Commit b4080f3e by 苗权威

7.6

parent a1fd2b1a
......@@ -7,20 +7,26 @@
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="dingdong" />
<module name="jdwhale" />
<module name="ruoqi" />
<module name="smartbox" />
<module name="spirit" />
<module name="xiaoai" />
<module name="xiaodu" />
<module name="xiaoya" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="rokid" target="1.8" />
<module name="RokidBox" target="1.8" />
</bytecodeTargetLevel>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="dingdong" options="-parameters" />
<module name="jdwhale" options="-parameters" />
<module name="rokid" options="-parameters" />
<module name="ruoqi" options="-parameters" />
<module name="spirit" options="-parameters" />
<module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" />
<module name="xiaoai" options="-parameters" />
<module name="xiaodu" options="-parameters" />
<module name="xiaoya" options="-parameters" />
......
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM">
<file url="file://$PROJECT_DIR$/RokidBox" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/dingdong" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jdwhale" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/rokid" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/ruoqi" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spirit" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoai" charset="UTF-8" />
......
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$/dingdong" />
<file type="web" url="file://$PROJECT_DIR$/jdwhale" />
<file type="web" url="file://$PROJECT_DIR$/RokidBox" />
<file type="web" url="file://$PROJECT_DIR$/spirit" />
<file type="web" url="file://$PROJECT_DIR$/xiaodu" />
<file type="web" url="file://$PROJECT_DIR$/xiaoya" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
......@@ -11,6 +19,8 @@
<option value="$PROJECT_DIR$/xiaoya/pom.xml" />
<option value="$PROJECT_DIR$/dingdong/pom.xml" />
<option value="$PROJECT_DIR$/ruoqi/pom.xml" />
<option value="$PROJECT_DIR$/rokid/pom.xml" />
<option value="$PROJECT_DIR$/jdwhale/pom.xml" />
</list>
</option>
</component>
......
......@@ -11,6 +11,7 @@
<groupId>ai.qiwu.dong</groupId>
<artifactId>dingdong</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>dingdong</name>
<description>Demo project for Spring Boot</description>
......@@ -22,6 +23,19 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>LATEST</version>
<scope>provided</scope>
</dependency>
<dependency>
......@@ -50,6 +64,7 @@
</dependencies>
<build>
<finalName>dingdong</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
......
......@@ -2,12 +2,18 @@ package ai.qiwu.dong.dingdong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DingdongApplication {
public class DingdongApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DingdongApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DingdongApplication.class);
}
}
......@@ -27,6 +27,7 @@ public interface Constants {
String RECOMMEND = "recommend";
String START_BY_ANSWER = "startByAnswer";
String END_BY_END = "endByEnd";
String ALL = "all";
}
interface Status {
......
package ai.qiwu.dong.dingdong.common;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-2 下午2:22
*/
@Getter
@Setter
public class Holder {
private volatile String word;
private volatile String lastAudioUrl;
}
......@@ -18,16 +18,16 @@ public class DingDongController {
private static final Logger logger = LoggerFactory.getLogger(ParseService.class);
// @Autowired
// private ParseServiceCompromise compromise;
@Autowired
private ParseService parseService;
private ParseServiceCompromise compromise;
// @Autowired
// private ParseService parseService;
@RequestMapping("/ding")
public @ResponseBody DingDongResponse dingdong(@RequestBody DingDongRequest request) {
logger.info("Request params : "+ request);
return parseService.getResponse(request);
return compromise.getResponse(request);
}
@RequestMapping("/ding/callback")
......
......@@ -3,6 +3,7 @@ package ai.qiwu.dong.dingdong.service;
import ai.qiwu.dong.dingdong.common.Constants;
import ai.qiwu.dong.dingdong.common.Constants.Intent;
import ai.qiwu.dong.dingdong.common.Constants.Status;
import ai.qiwu.dong.dingdong.common.Holder;
import ai.qiwu.dong.dingdong.model.request.DingDongRequest;
import ai.qiwu.dong.dingdong.model.request.user.User;
import ai.qiwu.dong.dingdong.model.response.DingDongResponse;
......@@ -23,6 +24,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author 苗权威
......@@ -33,6 +35,8 @@ public class ParseServiceCompromise {
private final static Logger logger = LoggerFactory.getLogger(ParseServiceCompromise.class);
private final static ConcurrentHashMap<String, Holder> USER_LAST_ALL_WORD_AudioUrl = new ConcurrentHashMap<>();
public DingDongResponse getResponse(DingDongRequest request) {
String userId = null;
User user = request.getUser();
......@@ -130,7 +134,8 @@ public class ParseServiceCompromise {
case Intent.END_BY_END : return parseWordInItsIntent(request, false, true, userId);
case Intent.XIAO_WU : return parseWordInItsIntent(request, true, true, userId);
case Intent.START_BY_ANSWER : return parseWordInItsIntent(request, true, true, userId);
case Intent.RECOMMEND : return parseWordInItsIntent(request, false, false, userId);
case Intent.RECOMMEND : return parseWordInItsIntent(request, true, false, userId);
case Intent.ALL : return parseWordInItsIntent(request, false, false, userId);
default: {
logger.info("没有匹配到任何已有意图,本次请求的意图名:"+intentKey);
return buildErrorResponse(request, userId);
......@@ -141,14 +146,17 @@ public class ParseServiceCompromise {
else if (slots.size() <= 1) {
logger.info("slots不为null,但是没有映射到任何意图");
return buildErrorResponse(request, userId);
} else if (slots.size() == 3 && slots.containsKey(Intent.RECOMMEND)) {
return requestQiWuInterface(userId, request);
} else {
logger.info("Intent请求slots大小>=3,预料之外");
logger.info("Intent请求slots大小>3,或是等于3但是没有recommend意图,预料之外");
return buildErrorResponse(request, userId);
}
}
private DingDongResponse parseWordInItsIntent(DingDongRequest request, boolean font, boolean needToCut, String userId) {
String word = request.getInput_text();
Holder holder = USER_LAST_ALL_WORD_AudioUrl.get(userId);
DingDongResponse response;
if (needToCut) {
if (font) {
......@@ -171,8 +179,40 @@ public class ParseServiceCompromise {
}
}
}
// 处理ALL意图
else if (!font) {
if (holder != null && word.equals(holder.getWord())) {
logger.info("本次ALL意图的话语与上次相同,认定是用户说的话");
} else {
if (holder == null) {
holder = new Holder();
USER_LAST_ALL_WORD_AudioUrl.put(userId, holder);
}
holder.setWord(word);
DingDongResponse forbidResponse;
if (holder.getLastAudioUrl() != null) {
logger.info("本次ALL意图的话语与上次不同,重复播放上次音频");
forbidResponse = buildResponse(request, userId);
forbidResponse.getDirective().getDirective_items().get(0).setContent(holder.getLastAudioUrl());
} else {
logger.info("本次ALL意图的话语与上次不同,提醒用户再说一遍");
forbidResponse = buildErrorResponse(request, userId);
}
return forbidResponse;
}
}
logger.info("此次解析得到的用户的话是:"+word);
response = requestQiWuInterface(userId, request);
String audioUrl = response.getDirective().getDirective_items().get(0).getContent();
if (holder == null) {
holder = new Holder();
holder.setLastAudioUrl(audioUrl);
USER_LAST_ALL_WORD_AudioUrl.put(userId, holder);
} else {
holder.setLastAudioUrl(audioUrl);
}
return response;
}
......@@ -210,11 +250,6 @@ public class ParseServiceCompromise {
}
private DingDongResponse dealLaunchIntent(DingDongRequest request, String userId) {
Map<String, String> slots = request.getSlots();
if (slots.containsKey(Intent.RECOMMEND)) {
request.setInput_text("推荐作品");
return requestQiWuInterface(userId, request);
}
DingDongResponse launchResponse = buildErrorResponse(request, userId);
launchResponse.getDirective().getDirective_items().get(0).setContent("欢迎,这里有海量的作品,希望您玩的开心");
return launchResponse;
......@@ -230,6 +265,8 @@ public class ParseServiceCompromise {
case Constants.DEV_SERVICE_RESP_PACK_ERROR: logger.info("status为NOTICE:开发者服务回包数据错误");break;
case Constants.NOTICE_OPEN_PLATFORM_ERROR: logger.info("status为NOTICE:开放平台系统异常");break;
}
if (USER_LAST_ALL_WORD_AudioUrl.remove(userId) != null) logger.info("非正常结束,平台发出NOTICE信息,在此处删除缓存成功");
return buildErrorResponse(request, userId);
}
......@@ -248,6 +285,8 @@ public class ParseServiceCompromise {
}
DingDongResponse response = buildErrorResponse(request, userId);
response.getDirective().getDirective_items().get(0).setContent("我们的作品库在不断扩充,欢迎下次再来玩");
if (USER_LAST_ALL_WORD_AudioUrl.remove(userId) != null) logger.info("平台发出END信息,代表技能退出,在此处删除缓存成功");
return response;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--控制台日志输出配置-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!--对输出日志进行格式化-->
<encoder>
<!-- %d日期,%p日志级别,%file文件名,%line所在行数,%m输出的信息,%n换行 -->
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<!--字符编码-->
<charset>UTF-8</charset><!--此处设置字符集-->
</encoder>
</appender>
<!--指定日志输出等级-->
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!--上述配置表名将 >=info级别的日志都输出到控制台-->
<!--日志文件配置-->
<appender name="dingdongLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--被写入的文件名,可以是相对目录,也可以是绝对目录,如果上级目录不存在会自动创建,没有默认值。-->
<File>/usr/mqw/logs/dingdong/</File>
<!--滚动记录文件:根据时间来制定滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/usr/mqw/logs/dingdong/base.log.%d.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<logger name="qi.qiwu.dingdong" level="DEBUG">
<appender-ref ref="dingdongLog" />
</logger>
</configuration>
\ No newline at end of file
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ai.qiwu.mqw</groupId>
<artifactId>jdwhale</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>jdwhale</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>LATEST</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>JDWhale</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package ai.qiwu.mqw.jdwhale;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class JdwhaleApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(JdwhaleApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(JdwhaleApplication.class);
}
}
package ai.qiwu.mqw.jdwhale.common;
/**
* @author 苗权威
* @dateTime 19-6-25 下午5:57
*/
public interface Constants {
String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat";
String SERVICE_NAME = "DINGDONG";
String CANCEL_INTENT = "Alpha.CancelIntent";
String HELP_INTENT = "Alpha.HelpIntent";
}
package ai.qiwu.mqw.jdwhale.common;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 苗权威
* @dateTime 19-6-26 下午2:59
*/
public class MqwLru<K, V> {
private static final int DEFAULT_SINGLE_SEGMENT_ENTRYS = 100;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final int DEFAULT_SEGMENT_ARRAY_LENGTH = 16;
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final int MAX_SEGMENT_ARRAY_LENGTH = 1 << 16;
final Segment[] segments;
public MqwLru(int arrCapacity, int loadFactor, int segementCapacity) {
int arrayLength = tableSizeFor(arrCapacity);
this.segments = new Segment[arrayLength];
for (int i = 0; i < arrayLength; i++) {
segments[i] = new Segment(segementCapacity, loadFactor);
}
}
private static int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
private static int hash(int h) {
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
static final class Entry<K,V> {
final K key;
volatile V value;
final int hash;
Entry<K,V> doubleLinkedBefore;
Entry<K,V> doubleLinkedAfter;
Entry(K key, V value, int hash) {
this.key = key;
this.value = value;
this.hash = hash;
}
}
static final class Segment<K, V> extends ReentrantLock {
volatile int count;
int threshold;
final float loadFactor;
final int maxCapacity;
volatile Entry<K,V> header;
volatile Entry<K,V> tail;
Segment(int segmentCapacity, float loadFactor) {
this.maxCapacity = segmentCapacity;
this.loadFactor = loadFactor;
this.threshold = (int) (maxCapacity*loadFactor);
}
V put(K key, V value, int hash) {
lock();
try {
int c = count;
//if (c++ >= threshold) rehash();
} finally {
unlock();
}
return null;
}
}
}
package ai.qiwu.mqw.jdwhale.controller;
import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse;
import ai.qiwu.mqw.jdwhale.service.ParseServiceWithoutLRU;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:51
*/
@RestController
public class DingDongController {
private static final Logger logger = LoggerFactory.getLogger(DingDongController.class);
@Autowired
private ParseServiceWithoutLRU serviceWithoutLRU;
@RequestMapping("/dingdong")
public @ResponseBody
DingDongResponse dingdong(@RequestBody DingDongRequest request) {
logger.info("Request params: "+request);
return serviceWithoutLRU.getResponse(request);
}
}
package ai.qiwu.mqw.jdwhale.model.RequestModel;
import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest;
import ai.qiwu.mqw.jdwhale.model.RequestModel.session.DingDongSession;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:30
*/
@Getter
@Setter
@ToString
public class DingDongRequest {
private String version;
private DingDongSession session;
private TripleRequest request;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.request;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:45
*/
@Getter
@Setter
@ToString
public class IntentRequestIntent {
private String name;
private String confirmResult;
private Map<String, IntentRequestSlot> map;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.request;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:46
*/
@Getter
@Setter
public class IntentRequestSlot {
private String name;
private String value;
private boolean matched;
private String confirmResult;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.request;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:49
*/
@Getter
@Setter
@ToString
public class SessionEndRequestReason {
private String type;
private String message;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.request;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:43
*/
@Getter
@Setter
@ToString
public class TripleRequest {
private String type;
private String requestId;
private Long timestamp;
private String dialogState;
private IntentRequestIntent intent;
private String original;
private SessionEndRequestReason reason;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.session;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:31
*/
@Getter
@Setter
@ToString
public class DingDongSession {
private boolean isNew;
private String sessionId;
private Object contexts;
private SessionApp application;
private SessionUser user;
private SessionDevice device;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.session;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:33
*/
@Getter
@Setter
@ToString
public class SessionApp {
private String applicationId;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.session;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:36
*/
@Getter
@Setter
@ToString
public class SessionDevice {
private String deviceId;
}
package ai.qiwu.mqw.jdwhale.model.RequestModel.session;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:34
*/
@Getter
@Setter
@ToString
public class SessionUser {
private String userId;
private String accessToken;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:52
*/
@Getter
@Setter
public class DingDongResponse {
private String version;
private boolean shouldEndSession;
private Map<String, String> contexts;
private OutputResponse response;
private List<AudioPlayerDirective> directives;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午5:08
*/
@Getter
@Setter
public class AudioPlayerDirective {
private String type;
private String playBehavior;
private AudioStream audioStream;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午5:10
*/
@Getter
@Setter
public class AudioStream {
private String name;
private String url;
private String token;
private Long offsetInMilliseconds;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel.response;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:58
*/
@Getter
@Setter
public class Output {
private String type;
private String text;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel.response;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:57
*/
@Getter
@Setter
public class OutputResponse {
private Output output;
private Reprompt reprompt;
}
package ai.qiwu.mqw.jdwhale.model.ResponseModel.response;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-6-25 下午4:59
*/
@Getter
@Setter
public class Reprompt {
private String type;
private String text;
}
package ai.qiwu.mqw.jdwhale.service;
import ai.qiwu.mqw.jdwhale.common.Constants;
import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest;
import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioStream;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Output;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Reprompt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author 苗权威
* @dateTime 19-6-25 下午5:13
*/
@Service("service")
public class ParseService {
private static final Logger logger = LoggerFactory.getLogger(ParseService.class);
private static final ConcurrentHashMap<String, DingDongResponse> userResponseMap = new ConcurrentHashMap<>();
public DingDongResponse getResponse(DingDongRequest request) {
String userId = request.getSession().getUser().getUserId();
if (userId == null) userId = request.getSession().getApplication().getApplicationId();
TripleRequest unknowRequest = request.getRequest();
switch (unknowRequest.getType()) {
case "LaunchRequest": return dealLaunchRequest();
case "IntentRequest": return dealIntentRequest(unknowRequest, userId);
case "SessionEndedRequest": dealSessionEndedRequest(unknowRequest, userId); return null;
default: logger.info("ERROR DIRECTIVE"); return dealLaunchRequest();
}
}
private DingDongResponse dealLaunchRequest() {
DingDongResponse response = new DingDongResponse();
buildResponse(response);
response.getResponse().getOutput().setText("欢迎来到有声互动小说,请说推荐作品");
response.getResponse().getReprompt().setText("请说推荐作品");
return response;
}
private DingDongResponse dealIntentRequest(TripleRequest request, String userId) {
// 处理Alpha.CancelIntent意图,该意图是平台默认的意图,用户说退出则退出技能,
// 我们这里需要对该意图进行判断处理.
// "request": {
// "dialogState": "STARTED",
// "intent": {
// "name": "Alpha.CancelIntent"
// },
// "requestId": "42d7d9f2-4134-4979-82fc-44dafe408171_6006_test",
// "timestamp": 1561510754347,
// "type": "IntentRequest"
// },
if (Constants.CANCEL_INTENT.equals(request.getIntent().getName())) {
dealSessionEndedRequest(request, userId);
return null;
}
if (Constants.HELP_INTENT.equals(request.getIntent().getName())) {
DingDongResponse response = new DingDongResponse();
buildResponse(response);
response.getResponse().setReprompt(null);
response.getResponse().getOutput().setText("请明确一些说帮或不帮");
return response;
}
DingDongResponse response = userResponseMap.get(userId);
if (response == null) {
response = buildResponseTemplate();
userResponseMap.put(userId, response);
}
String userWord = request.getOriginal();
requestQiWuInterface(userId, userWord, response);
return response;
}
private void dealSessionEndedRequest(TripleRequest request, String userId) {
DingDongResponse response = userResponseMap.remove(userId);
logger.info("用户:"+userId+" 的缓存删除成功, " + response);
}
private void requestQiWuInterface(String userId, String userWord, DingDongResponse response) {
String audioUrl = "";
String textContent = "请说推荐作品";
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
HashMap<String, String> params = new HashMap<>();
params.put("user_id", String.valueOf(userId));
params.put("text", userWord);
params.put("access",Constants.SERVICE_NAME);
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8");
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setEntity(body);
httpResponse = httpClient.execute(post);
HttpEntity responseBody = httpResponse.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
logger.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get("audio");
textContent = (String) responseJsonFormat.get("text");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) httpClient.close();
if (httpResponse != null) httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
addUrlAndTextToResponse(audioUrl, textContent, response);
}
private void addUrlAndTextToResponse(String url, String text, DingDongResponse response) {
//response.getResponse().getOutput().setText(text);
response.getDirectives().get(0).getAudioStream().setUrl(url);
}
private DingDongResponse buildResponseTemplate() {
DingDongResponse response = new DingDongResponse();
response.setVersion("1.0");
response.setShouldEndSession(true);
buildDirectives(response);
return response;
}
private void buildResponse(DingDongResponse response) {
response.setShouldEndSession(true);
response.setVersion("1.0");
OutputResponse outResponse = new OutputResponse();
Output output = new Output();
output.setType("PlainText");
outResponse.setOutput(output);
Reprompt reprompt = new Reprompt();
reprompt.setType("PlainText");
reprompt.setText("哈哈,是不是后悔刚才的选择了,下次可要好好考虑考虑哦");
outResponse.setReprompt(reprompt);
response.setResponse(outResponse);
}
private void buildDirectives(DingDongResponse response) {
AudioPlayerDirective audioDirective = new AudioPlayerDirective();
audioDirective.setType("AudioPlayer.Play");
audioDirective.setPlayBehavior("REPLACE_ALL");
AudioStream audioStream = new AudioStream();
audioStream.setToken("654987123");
audioDirective.setAudioStream(audioStream);
List<AudioPlayerDirective> directives = new ArrayList<>();
directives.add(audioDirective);
response.setDirectives(directives);
}
}
package ai.qiwu.mqw.jdwhale.service;
import ai.qiwu.mqw.jdwhale.common.Constants;
import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest;
import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioStream;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Output;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Reprompt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-6-26 下午4:09
*/
@Service("serviceWithoutLRU")
public class ParseServiceWithoutLRU {
private static final Logger logger = LoggerFactory.getLogger(ParseService.class);
public DingDongResponse getResponse(DingDongRequest request) {
String userId = request.getSession().getUser().getUserId();
if (userId == null) userId = request.getSession().getApplication().getApplicationId();
TripleRequest unknowRequest = request.getRequest();
switch (unknowRequest.getType()) {
case "LaunchRequest": return dealLaunchRequest();
case "IntentRequest": return dealIntentRequest(unknowRequest, userId);
case "SessionEndedRequest": dealSessionEndedRequest(userId); return null;
default: logger.info("ERROR DIRECTIVE"); return dealLaunchRequest();
}
}
private DingDongResponse dealLaunchRequest() {
DingDongResponse response = new DingDongResponse();
buildResponse(response);
response.getResponse().getOutput().setText("欢迎来到有声互动小说,请说推荐作品");
response.getResponse().getReprompt().setText("请说推荐作品");
return response;
}
private DingDongResponse dealIntentRequest(TripleRequest request, String userId) {
// 处理Alpha.CancelIntent意图,该意图是平台默认的意图,用户说退出则退出技能,
// 我们这里需要对该意图进行判断处理.
// "request": {
// "dialogState": "STARTED",
// "intent": {
// "name": "Alpha.CancelIntent"
// },
// "requestId": "42d7d9f2-4134-4979-82fc-44dafe408171_6006_test",
// "timestamp": 1561510754347,
// "type": "IntentRequest"
// },
if (Constants.CANCEL_INTENT.equals(request.getIntent().getName())) {
dealSessionEndedRequest(userId);
return null;
}
if (Constants.HELP_INTENT.equals(request.getIntent().getName())) {
DingDongResponse response = new DingDongResponse();
buildResponse(response);
response.getResponse().setReprompt(null);
response.getResponse().getOutput().setText("请明确一些说帮或不帮");
return response;
}
DingDongResponse response = buildResponseInTTS();
String userWord = request.getOriginal();
requestQiWuInterface(userId, userWord, response);
return response;
}
private void dealSessionEndedRequest(String userId) {
logger.info("用户 "+userId+" 会话结束");
}
private void requestQiWuInterface(String userId, String userWord, DingDongResponse response) {
String audioUrl = "";
String textContent = "请说推荐作品";
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
HashMap<String, String> params = new HashMap<>();
params.put("user_id", String.valueOf(userId));
params.put("text", userWord);
params.put("access",Constants.SERVICE_NAME);
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8");
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setEntity(body);
httpResponse = httpClient.execute(post);
HttpEntity responseBody = httpResponse.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
logger.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get("audio");
textContent = (String) responseJsonFormat.get("text");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) httpClient.close();
if (httpResponse != null) httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
addUrlAndTextToResponse(audioUrl, textContent, response);
}
private void addUrlAndTextToResponse(String url, String text, DingDongResponse response) {
response.getResponse().getOutput().setText(text);
response.getDirectives().get(0).getAudioStream().setUrl(url);
}
/**
* 语音指令调用该方法生成Response
* @return
*/
private DingDongResponse buildResponseInDirective() {
DingDongResponse response = new DingDongResponse();
response.setVersion("1.0");
response.setShouldEndSession(true);
buildDirectives(response);
return response;
}
/**
* TTS模式
* @return
*/
private DingDongResponse buildResponseInTTS() {
DingDongResponse response = new DingDongResponse();
buildResponse(response);
buildDirectives(response);
return response;
}
private void buildResponse(DingDongResponse response) {
response.setShouldEndSession(false);
response.setVersion("1.0");
OutputResponse outResponse = new OutputResponse();
Output output = new Output();
output.setType("PlainText");
outResponse.setOutput(output);
Reprompt reprompt = new Reprompt();
reprompt.setType("PlainText");
reprompt.setText("哈哈,是不是后悔刚才的选择了,下次可要好好考虑考虑哦");
outResponse.setReprompt(reprompt);
response.setResponse(outResponse);
}
private void buildDirectives(DingDongResponse response) {
AudioPlayerDirective audioDirective = new AudioPlayerDirective();
audioDirective.setType("AudioPlayer.Play");
audioDirective.setPlayBehavior("REPLACE_ALL");
AudioStream audioStream = new AudioStream();
audioStream.setToken("654987123");
audioDirective.setAudioStream(audioStream);
List<AudioPlayerDirective> directives = new ArrayList<>();
directives.add(audioDirective);
response.setDirectives(directives);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--控制台日志输出配置-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!--对输出日志进行格式化-->
<encoder>
<!-- %d日期,%p日志级别,%file文件名,%line所在行数,%m输出的信息,%n换行 -->
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<!--字符编码-->
<charset>UTF-8</charset><!--此处设置字符集-->
</encoder>
</appender>
<!--指定日志输出等级-->
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!--上述配置表名将 >=info级别的日志都输出到控制台-->
<!--日志文件配置-->
<appender name="whaleLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--被写入的文件名,可以是相对目录,也可以是绝对目录,如果上级目录不存在会自动创建,没有默认值。-->
<File>/usr/mqw/logs/jdWhale/</File>
<!--滚动记录文件:根据时间来制定滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/usr/mqw/logs/jdWhale/base.log.%d.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<logger name="qi.qiwu.mqw" level="DEBUG">
<appender-ref ref="whaleLog" />
</logger>
</configuration>
\ No newline at end of file
package ai.qiwu.mqw.jdwhale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JdwhaleApplicationTests {
@Test
public void contextLoads() {
}
}
......@@ -6,6 +6,7 @@
<groupId>ai.qiwu</groupId>
<artifactId>smartbox</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
......
......@@ -16,6 +16,16 @@
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<file.encoding>UTF-8</file.encoding>
<maven.test.skip>true</maven.test.skip>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<!-- dependency version -->
<commons_lang_version>2.6</commons_lang_version>
<codehaus_jackson_version>1.9.13</codehaus_jackson_version>
<google_code_gson_version>2.8.5</google_code_gson_version>
</properties>
<dependencies>
......@@ -29,6 +39,35 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons_lang_version}</version>
</dependency>
<!-- Json Parse -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${google_code_gson_version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
</dependencies>
<build>
......
package ai.qiwu.rokid.ruoqi.common;
/**
* @author 苗权威
* @dateTime 19-7-2 下午7:36
*/
public interface Constants {
String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat";
String SERVICE_NAME = "DINGDONG";
}
package ai.qiwu.rokid.ruoqi.common.exception;
public class ProtocolException extends Exception {
/**
*
*/
private static final long serialVersionUID = 8914106243553844621L;
public ProtocolException(String message) {
super(message);
}
public ProtocolException(String message, Throwable throwable) {
super(message, throwable);
}
public ProtocolException(Throwable throwable) {
super(throwable);
}
}
package ai.qiwu.rokid.ruoqi.common.exception;
import org.springframework.http.HttpStatus;
/**
* 通用异常情况
*
* @author Bassam
*
*/
public class RokidException extends Exception {
private static final long serialVersionUID = 9135801019232303753L;
// 默认提供了一定的错误定义///
public static final String ERROR_CODE_SUCCESS = HttpStatus.OK.name();// 成功
public static final String ERROR_CODE_NOTFOUND = "NotFound";// 没有找到
public static final String ERROR_CODE_DATABASE = "DatabaseError";// 数据库错误
public static final String ERROR_CODE_REDIS = "RedisError";// Redis错误
public static final String ERROR_CODE_REDISFOUND = "RedisNotFound";// Redis数据没有找到
public static final String ERROR_CODE_SECURITY = "SecurityError";// 安全检查错误
public static final String ERROR_CODE_INVALIDHEAD = "InvalidHead";// 请求头有误
public static final String ERROR_CODE_INVALIDBODY = "InvalidBody";// 请求数据有误
public static final String ERROR_CODE_INVALIDARGUMENT = "InvalidArgument";// 无效的参数
public static final String ERROR_CODE_RESONSE = "ResponseError";// 响应错误
public static final String ERROR_CODE_MISSINGARGUMENT = "MissingArgument";// 参数缺失
public static final String ERROR_CODE_METHODNOTALLOWED = "MethodNotAllowed";// 方法不支持
public static final String ERROR_CODE_INTERNAL = "InternalError";// 内部错误
public static final String ERROR_CODE_ACCESS = "AccessDenied";// 接入出错
private int httpStatusCode;// Http状态码
private String errorCode;// 操作码
public int getHttpStatusCode() {
return httpStatusCode;
}
public void setHttpStatusCode(int httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public RokidException(int httpStatusCode, String errorCode) {
super();
this.httpStatusCode = httpStatusCode;
this.errorCode = errorCode;
}
public RokidException(int httpStatusCode, String errorCode, String message) {
super(message);
this.httpStatusCode = httpStatusCode;
this.errorCode = errorCode;
}
public RokidException(int httpStatusCode, String errorCode, String message, Throwable throwable) {
super(message, throwable);
this.httpStatusCode = httpStatusCode;
this.errorCode = errorCode;
}
public RokidException(int httpStatusCode, String errorCode, Throwable throwable) {
super(throwable);
this.httpStatusCode = httpStatusCode;
this.errorCode = errorCode;
}
}
package ai.qiwu.rokid.ruoqi.common.exception;
/**
* 语音业务异常情况
*
* @author Bassam
*
*/
public class RokidSpeechletException extends RokidException {
private static final long serialVersionUID = 9135801019232303753L;
private String actionType;
private String actionName;
public RokidSpeechletException(int httpStatusCode, String errorCode, String message, Throwable throwable) {
super(httpStatusCode, errorCode, message, throwable);
}
public RokidSpeechletException(int httpStatusCode, String errorCode, String message) {
super(httpStatusCode, errorCode, message);
}
public RokidSpeechletException(int httpStatusCode, String errorCode, Throwable throwable) {
super(httpStatusCode, errorCode, throwable);
}
public RokidSpeechletException(int httpStatusCode, String errorCode) {
super(httpStatusCode, errorCode);
}
public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName) {
super(httpStatusCode, errorCode);
this.actionType = actionType;
this.actionName = actionName;
}
public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName,
Throwable throwable) {
super(httpStatusCode, errorCode, throwable);
this.actionType = actionType;
this.actionName = actionName;
}
public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName,
String message, Throwable throwable) {
super(httpStatusCode, errorCode, message, throwable);
this.actionType = actionType;
this.actionName = actionName;
}
public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName,
String message) {
super(httpStatusCode, errorCode, message);
this.actionType = actionType;
this.actionName = actionName;
}
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public String getActionName() {
return actionName;
}
public void setActionName(String actionName) {
this.actionName = actionName;
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import java.util.List;
import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException;
import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.confirm.ResConfirm;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.ResMedia;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.pickup.ResPickup;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.ResVoice;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item.ResVoiceItem;
import org.apache.commons.lang.StringUtils;
public class ActionUtils {
/**
*
* @param actionVersion
* @param actionType
* @param shouldEndSession
* @return
* @throws ProtocolException
*/
public static ResAction getEmptyAction(String actionVersion, String actionType, boolean shouldEndSession)
throws ProtocolException {
ResAction resAction = new ResAction();
if (StringUtils.isBlank(actionVersion)) {
throw new ProtocolException("actionVersion is isBlank");
}
resAction.setVersion(actionVersion);
if (StringUtils.isBlank(actionType) || (!ResAction.ACTION_TYPE_NORMAL.equals(actionType)
&& !ResAction.ACTION_TYPE_EXIT.equals(actionType))) {
throw new ProtocolException("actionType is error");
}
resAction.setType(actionType);
resAction.setShouldEndSession(shouldEndSession);
return resAction;
}
/**
* 构建Voice节点
*
* @param voiceAction
* 详见 ResVoice.VOICE_ACTION
* @param disableEvent
* 是否关闭Event事件
* @param itemId
* @param voiceContent
* @return
* @throws ProtocolException
*/
public static ResVoice getResVoice(String voiceAction, boolean disableEvent, String itemId, String voiceContent)
throws ProtocolException {
if (checkVoiceAction(voiceAction)) {
ResVoice resVoice = new ResVoice();
resVoice.setAction(voiceAction);
resVoice.setDisableEvent(disableEvent);
if (ResVoice.VOICE_ACTION_PLAY.equals(voiceAction)) {
if (StringUtils.isBlank(voiceContent)) {
throw new ProtocolException("voiceContent is isBlank");
}
ResVoiceItem voiceItem = new ResVoiceItem();
voiceItem.setItemId(itemId);
voiceItem.setTts(voiceContent);
resVoice.setItem(voiceItem);
}
return resVoice;
}
throw new ProtocolException("voiceAction is error");
}
/**
* 构建Confirm节点
*
* @param confirmIntent
* @param confirmSlot
* @param optionWords
* @return
* @throws ProtocolException
*/
public static ResConfirm getResConfirm(String confirmIntent, String confirmSlot, List<String> optionWords)
throws ProtocolException {
if (!StringUtils.isBlank(confirmIntent) && !StringUtils.isBlank(confirmSlot)) {
ResConfirm resConfirm = new ResConfirm();
resConfirm.setConfirmIntent(confirmIntent);
resConfirm.setConfirmSlot(confirmSlot);
resConfirm.setOptionWords(optionWords);
return resConfirm;
} else {
throw new ProtocolException("confirmIntent or confirmSlot isBlank");
}
}
/**
* 检查Voice的Action事件
*
* @param voiceAction
* @return
* @throws ProtocolException
*/
public static boolean checkVoiceAction(String voiceAction) throws ProtocolException {
if (StringUtils.isBlank(voiceAction)) {
throw new ProtocolException("Voice Directive's action is blank");
}
if (!ResVoice.VOICE_ACTION_PLAY.equals(voiceAction) && !ResVoice.VOICE_ACTION_PAUSE.equals(voiceAction)
&& !ResVoice.VOICE_ACTION_RESUME.equals(voiceAction)
&& !ResVoice.VOICE_ACTION_STOP.equals(voiceAction)) {
throw new ProtocolException("Voice Directive's action is error");
}
return true;
}
/**
* 构建 ResMedia节点
*
* @param mediaAction
* @param disableEvent
* @param itemId
* @param mediaToken
* @param mediaType
* @param mediaUrl
* @param mediaOffset
* @return
* @throws ProtocolException
*/
public static ResMedia getResMeida(String mediaAction, boolean disableEvent, String itemId, String mediaToken,
String mediaType, String mediaUrl, long mediaOffset) throws ProtocolException {
if (checkMediaAction(mediaAction)) {
ResMedia resMedia = new ResMedia();
resMedia.setDisableEvent(disableEvent);
resMedia.setAction(mediaAction);
if (ResMedia.MEDIA_ACTION_PLAY.equals(mediaAction)) {
ResMediaItem resMediaItem = new ResMediaItem();
if (StringUtils.isBlank(mediaUrl)) {
throw new ProtocolException("mediaUrl isBlank");
}
resMediaItem.setUrl(mediaUrl);
if (StringUtils.isBlank(mediaType) || (!ResMediaItem.MEDIA_TYPE_AUDIO.equals(mediaType)
&& !ResMediaItem.MEDIA_TYPE_VIDEO.equals(mediaType))) {
throw new ProtocolException("mediaType is error");
}
resMediaItem.setType(mediaType);
resMediaItem.setToken(mediaToken);
if (mediaOffset < 0) {
throw new ProtocolException("mediaOffset is error");
}
resMediaItem.setOffsetInMilliseconds(mediaOffset);
resMedia.setItem(resMediaItem);
}
}
throw new ProtocolException("Error mediaAction:" + mediaAction);
}
/**
* 检查VoiceAction
*
* @param mediaAction
* @return
* @throws ProtocolException
*/
public static boolean checkMediaAction(String mediaAction) throws ProtocolException {
if (StringUtils.isBlank(mediaAction)) {
throw new ProtocolException("Media Directive's action is blank");
}
if (!ResMedia.MEDIA_ACTION_PLAY.equals(mediaAction) && !ResMedia.MEDIA_ACTION_PAUSE.equals(mediaAction)
&& !ResMedia.MEDIA_ACTION_RESUME.equals(mediaAction)
&& !ResMedia.MEDIA_ACTION_STOP.equals(mediaAction)) {
throw new ProtocolException("Media Directive's action is error");
}
return true;
}
/**
* 获取ResPickUp节点
*
* @param enable
* @param durationInMilliseconds
* @return
* @throws ProtocolException
*/
public static ResPickup getResPickup(boolean enable, long durationInMilliseconds) throws ProtocolException {
ResPickup resPickup = new ResPickup();
resPickup.setEnable(enable);
if (durationInMilliseconds < 0) {
throw new ProtocolException("durationInMilliseconds is error");
}
resPickup.setDurationInMilliseconds(durationInMilliseconds);
return resPickup;
}
/**
* 检查Action类型
*
* @param actionType
* @return
* @throws ProtocolException
*/
public static boolean checkActionType(String actionType) throws ProtocolException {
if (ResAction.ACTION_TYPE_EXIT.equals(actionType) || ResAction.ACTION_TYPE_NORMAL.equals(actionType)) {
return true;
}
throw new ProtocolException("actionType is error");
}
/**
* 检查ResVoice的合法性
*
* @param resVoice
* @return
* @throws ProtocolException
*/
public static boolean checkVoice(ResVoice resVoice) throws ProtocolException {
if (resVoice != null) {
if (!checkVoiceAction(resVoice.getAction())) {
throw new ProtocolException("Voice Directive is error");
}
if (ResVoice.VOICE_ACTION_PLAY.equals(resVoice.getAction())) {
if (resVoice.getItem() == null) {
throw new ProtocolException("Voice Directive's action is play,but item is null");
}
if (StringUtils.isBlank(resVoice.getItem().getTts())) {
throw new ProtocolException("Voice Directive's action is play,but item's tts is blank");
}
}
}
return true;
}
/**
* 检查Media节点的合法性
*
* @param resMedia
* @return
* @throws ProtocolException
*/
public static boolean checkMedia(ResMedia resMedia) throws ProtocolException {
if (resMedia != null) {
if (!checkMediaAction(resMedia.getAction())) {
throw new ProtocolException("Media Directivei is error");
}
if (ResMedia.MEDIA_ACTION_PLAY.equals(resMedia.getAction())) {
if (resMedia.getItem() == null) {
throw new ProtocolException("Meida Directive's action is play,but item is null");
}
if (StringUtils.isBlank(resMedia.getItem().getUrl())) {
throw new ProtocolException("Meida Directive's action is play,but item's url is Blank");
}
if (resMedia.getItem().getOffsetInMilliseconds() < 0) {
throw new ProtocolException(
"Meida Directive's action is play,but item's OffsetInMilliseconds is <0");
}
}
}
return true;
}
/**
* 检查PickUp节点
*
* @param resPickup
* @return
* @throws ProtocolException
*/
public static boolean checkPickup(ResPickup resPickup) throws ProtocolException {
if (resPickup != null) {
if (resPickup.getDurationInMilliseconds() < 0) {
throw new ProtocolException("PickUp Directive's DurationInMilliseconds is <0");
}
}
return true;
}
/**
* 检查confirm节点
*
* @param resConfirm
* @return
* @throws ProtocolException
*/
public static boolean checkConfirm(ResConfirm resConfirm) throws ProtocolException {
if (resConfirm != null) {
if (StringUtils.isBlank(resConfirm.getConfirmIntent())
|| StringUtils.isBlank(resConfirm.getConfirmSlot())) {
throw new ProtocolException("Confirm Directive's Intent or slot is blank");
}
}
return true;
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException;
import ai.qiwu.rokid.ruoqi.common.exception.RokidException;
import ai.qiwu.rokid.ruoqi.model.response.ResResponse;
import org.springframework.http.HttpStatus;
public class ProtocolUtils {
/**
* 忽略事件,比如Voice.STARTED的EventRequest来的时候我们可以使用这个操作忽略这个请求
*
* @return
* @throws ProtocolException
*/
public static final ResResponse igonre() {
try {
return ResponseUtils.buildIngoreEventResponse();
} catch (ProtocolException e) {
e.printStackTrace();
return null;
}
}
/**
* 退出
*
* @举例 若琪停止播放
* @return
* @throws ProtocolException
*/
public static final ResResponse exit() throws RokidException {
try {
return ResponseUtils.buildExitNowResponse();
} catch (ProtocolException e) {
return null;
}
}
/**
* 从0开始播放音乐,并且停止TTS
*
* @param songId
* @param songUrl
* @return
* @throws RokidException
*/
public static final ResResponse playSongAndFinished(String songId, String songUrl) throws RokidException {
try {
return ResponseBuilder.build().audioPlay(songId, null, songUrl, 0).mediaEventDisable().afterFinish()
.create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
/**
* 暂停音乐
*
* @举例 若琪暂停播放
* @return
* @throws ProtocolException
*/
public static final ResResponse pauseMusic() throws RokidException {
try {
return ResponseBuilder.build().mediaPause().mediaEventDisable().create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
public static final ResResponse playTTs(String content) throws RokidException {
try {
return ResponseBuilder.build().voicePlay(null, content).sendChatCard(content).create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
/**
* 播放完tts退出示例
* @param content
* @return
* @throws RokidException
*/
public static final ResResponse playTts(String content) throws RokidException{
try {
return ResponseBuilder.build().voicePlay(null, content).sendChatCard(content).afterFinish().create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
/**
* 进入六十秒拾音状态
* @param content
* @return
* @throws RokidException
*/
public static final ResResponse pickUp(String content) throws RokidException{
try {
return ResponseBuilder.build().voicePlay(null, content).pickupOpen().sendChatCard(content).create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
/**
* 继续播放音乐
*
* @举例 若琪继续播放音乐
* @return
* @throws ProtocolException
*/
public static final ResResponse resumeMusic() throws RokidException {
try {
return ResponseBuilder.build().mediaResume().mediaEventDisable().afterFinish().create();
} catch (ProtocolException e) {
throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE,
e.getCause());
}
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
public class ReqBasicInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String protocolVersion;// 当前协议版本
private String requestId;// 请求ID
private String sessionId;// SessionId
private String appId;// 应用ID
private String deviceId;// 设备ID
private String deviceType;// 设备类型
private String deviceVendor;// 厂商ID
private String masterId;// 设备主人的ID
private String userId;// 用户id
private String locale;// 用户语言
private String actionType;// 操作类型
private String actionName;// 操作名称
private long timestamp;// 设备时间戳
private String voicetrigger;// 当前设备激活词
public String getProtocolVersion() {
return protocolVersion;
}
public String getRequestId() {
return requestId;
}
public String getSessionId() {
return sessionId;
}
public String getAppId() {
return appId;
}
public String getDeviceId() {
return deviceId;
}
public String getDeviceType() {
return deviceType;
}
public String getDeviceVendor() {
return deviceVendor;
}
public String getMasterId() {
return masterId;
}
public String getUserId() {
return userId;
}
public String getLocale() {
return locale;
}
public String getActionType() {
return actionType;
}
public String getActionName() {
return actionName;
}
public long getTimestamp() {
return timestamp;
}
public void setProtocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public void setDeviceVendor(String deviceVendor) {
this.deviceVendor = deviceVendor;
}
public void setMasterId(String masterId) {
this.masterId = masterId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setLocale(String locale) {
this.locale = locale;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public void setActionName(String actionName) {
this.actionName = actionName;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getVoicetrigger() {
return voicetrigger;
}
public void setVoicetrigger(String voicetrigger) {
this.voicetrigger = voicetrigger;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import java.util.HashMap;
import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException;
import ai.qiwu.rokid.ruoqi.model.request.ReqRequest;
import ai.qiwu.rokid.ruoqi.model.request.context.application.media.ReqApplicationMedia;
import ai.qiwu.rokid.ruoqi.model.request.context.application.voice.ReqApplicationVoice;
import ai.qiwu.rokid.ruoqi.model.request.context.device.location.ReqLocation;
import ai.qiwu.rokid.ruoqi.model.request.request.ReqRequestValue;
import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media.ReqExtraMedia;
import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice.ReqExtraVoice;
import ai.qiwu.rokid.ruoqi.model.request.request.content.slot.Slot;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* 请求处理工具类
*
* @author Bassam
*
*/
public class RequestUtils {
/**
* 获取ReqRequest对象
*
* @param resuest
* @return
* @throws ProtocolException
*/
public static ReqRequest getRequest(String resuest) throws ProtocolException {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
return gson.fromJson(resuest, ReqRequest.class);
}
/**
* 获得基本请求信息
*
* @param reqRequest
* @return
*/
public static ReqBasicInfo getBasicInfo(ReqRequest reqRequest) {
ReqBasicInfo reqBasicInfo = new ReqBasicInfo();
if (reqRequest != null) {
reqBasicInfo.setProtocolVersion(reqRequest.getVersion());
if (reqRequest.getSession() != null) {
reqBasicInfo.setSessionId(reqRequest.getSession().getSessionId());
}
if (reqRequest.getContext() != null) {
if (reqRequest.getContext().getApplication() != null) {
reqBasicInfo.setAppId(reqRequest.getContext().getApplication().getApplicationId());
}
if (reqRequest.getContext().getDevice() != null
&& reqRequest.getContext().getDevice().getBasic() != null) {
reqBasicInfo.setDeviceId(reqRequest.getContext().getDevice().getBasic().getDeviceId());
reqBasicInfo.setDeviceType(reqRequest.getContext().getDevice().getBasic().getDeviceType());
reqBasicInfo.setDeviceVendor(reqRequest.getContext().getDevice().getBasic().getVendor());
reqBasicInfo.setTimestamp(reqRequest.getContext().getDevice().getBasic().getTimestamp());
reqBasicInfo.setMasterId(reqRequest.getContext().getDevice().getBasic().getMasterId());
reqBasicInfo.setLocale(reqRequest.getContext().getDevice().getBasic().getLocale());
reqBasicInfo.setVoicetrigger(reqRequest.getContext().getDevice().getBasic().getVoicetrigger());
}
if (reqRequest.getContext().getUser() != null) {
reqBasicInfo.setUserId(reqRequest.getContext().getUser().getUserId());
}
}
if (reqRequest.getRequest() != null) {
reqBasicInfo.setRequestId(reqRequest.getRequest().getReqId());
reqBasicInfo.setActionType(reqRequest.getRequest().getReqType());
if (reqRequest.getRequest().getContent() != null) {
if (ReqRequestValue.REQTYPE_EVENT.equals(reqBasicInfo.getActionType())) {
reqBasicInfo.setActionName(reqRequest.getRequest().getContent().getEvent());
} else if (ReqRequestValue.REQTYPE_INTENT.equals(reqBasicInfo.getActionType())) {
reqBasicInfo.setActionName(reqRequest.getRequest().getContent().getIntent());
}
}
}
}
return reqBasicInfo;
}
/**
* 获得Media状态信息
*
* @param reqRequest
* @return
*/
public static ReqApplicationMedia getMediaState(ReqRequest reqRequest) {
ReqApplicationMedia reqApplicationMedia = null;
if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getApplication() != null) {
reqApplicationMedia = reqRequest.getContext().getApplication().getMedia();
}
if (reqApplicationMedia == null) {
reqApplicationMedia = new ReqApplicationMedia();
}
if (StringUtils.isBlank(reqApplicationMedia.getState())) {
reqApplicationMedia.setState(ReqApplicationMedia.STATE_IDLE);
}
return reqApplicationMedia;
}
/**
* 获得VoiceState
*
* @param reqRequest
* @return
*/
public static ReqApplicationVoice getVoiceState(ReqRequest reqRequest) {
ReqApplicationVoice reqApplicationVoice = null;
if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getApplication() != null) {
reqApplicationVoice = reqRequest.getContext().getApplication().getVoice();
}
if (reqApplicationVoice == null) {
reqApplicationVoice = new ReqApplicationVoice();
}
if (StringUtils.isBlank(reqApplicationVoice.getState())) {
reqApplicationVoice.setState(ReqApplicationVoice.STATE_IDLE);
}
return reqApplicationVoice;
}
/**
* 获取位置信息
*
* @param reqRequest
* @return
*/
public static ReqLocation getLocation(ReqRequest reqRequest) {
ReqLocation reqLocation = null;
if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getDevice() != null) {
reqLocation = reqRequest.getContext().getDevice().getLocation();
}
if (reqLocation == null) {
reqLocation = new ReqLocation();
}
return reqLocation;
}
/**
* 获取Media拓展信息
*
* @param reqRequest
* @return
*/
public static ReqExtraMedia getMediaExtra(ReqRequest reqRequest) {
ReqExtraMedia reqExtraMedia = null;
if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null
&& reqRequest.getRequest().getContent().getExtra() != null) {
reqExtraMedia = reqRequest.getRequest().getContent().getExtra().getMedia();
}
if (reqExtraMedia == null) {
reqExtraMedia = new ReqExtraMedia();
}
return reqExtraMedia;
}
/**
* 获取Voice拓展信息
*
* @param reqRequest
* @return
*/
public static ReqExtraVoice getVoiceExtra(ReqRequest reqRequest) {
ReqExtraVoice reqExtraVoice = null;
if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null
&& reqRequest.getRequest().getContent().getExtra() != null) {
reqExtraVoice = reqRequest.getRequest().getContent().getExtra().getVoice();
}
if (reqExtraVoice == null) {
reqExtraVoice = new ReqExtraVoice();
}
return reqExtraVoice;
}
/**
* 获取属性信息
*
* @param reqRequest
* @return
*/
public static HashMap<String, Object> getAttributes(ReqRequest reqRequest) {
HashMap<String, Object> attributes = null;
if (reqRequest != null && reqRequest.getSession() != null && reqRequest.getSession().getAttributes() != null) {
attributes = reqRequest.getSession().getAttributes();
}
if (attributes == null) {
attributes = new HashMap<>();
}
return attributes;
}
/**
* 获取Slots
*
* @param reqRequest
* @return
*/
public static HashMap<String, Slot> getSlots(ReqRequest reqRequest) {
HashMap<String, Slot> slots = null;
if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null) {
slots = reqRequest.getRequest().getContent().getSlots();
}
if (slots == null) {
slots = new HashMap<>();
}
return slots;
}
/**
* 获取Intent Request的ASR结果
*
* @param reqRequest
* @return
*/
public static String getSentence(ReqRequest reqRequest) {
String scentence = "";
if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null) {
scentence = reqRequest.getRequest().getContent().getSentence();
}
return scentence;
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException;
import ai.qiwu.rokid.ruoqi.model.response.ResResponse;
import ai.qiwu.rokid.ruoqi.model.response.response.ResResponseContent;
import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.confirm.ResConfirm;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.ResMedia;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.pickup.ResPickup;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.ResVoice;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item.ResVoiceItem;
import ai.qiwu.rokid.ruoqi.model.response.response.card.ResCard;
import ai.qiwu.rokid.ruoqi.model.response.response.card.chat.ResChatCard;
import ai.qiwu.rokid.ruoqi.model.response.session.ResSession;
import org.apache.commons.lang.StringUtils;
public class ResponseBuilder {
private ResResponse response;
private boolean shouldEndSession = false;// 执行完这个action完毕
private String actionType = ResAction.ACTION_TYPE_NORMAL;
private HashMap<String, Object> attributes;
private ResVoice resVoice;
private ResConfirm resConfirm;
private ResMedia resMedia;
private ResPickup pickup;
private ResCard card;
public static ResponseBuilder build() {
return new ResponseBuilder();
}
public ResponseBuilder() {
response = buildEmptyActionResponse(ResResponse.RES_VERSION_V2, null, ResAction.ACTION_VERSION_V2, actionType,
shouldEndSession);
}
/**
* 下一次请求原样带回的参数
*
* @param attributes
* @return
*/
public ResponseBuilder setAttributes(HashMap<String, Object> attributes) {
this.attributes = attributes;
return this;
}
/**
* 播放TTS
*
* @param voiceId
* @param voiceContent
* @return
*/
public ResponseBuilder voicePlay(String voiceId, String voiceContent) {
if (resVoice == null) {
resVoice = new ResVoice();
}
ResVoiceItem resVoiceItem = new ResVoiceItem();
resVoiceItem.setItemId(voiceId);
resVoiceItem.setTts(voiceContent);
resVoice.setAction(ResVoice.VOICE_ACTION_PLAY);
resVoice.setItem(resVoiceItem);
return this;
}
/**
* 暂停Media
*
* @return
*/
public ResponseBuilder voicePause() {
if (resVoice == null) {
resVoice = new ResVoice();
}
resVoice.setAction(ResVoice.VOICE_ACTION_PAUSE);
return this;
}
/**
* 继续播放TTS
*
* @return
*/
public ResponseBuilder voiceResume() {
if (resVoice == null) {
resVoice = new ResVoice();
}
resVoice.setAction(ResVoice.VOICE_ACTION_RESUME);
return this;
}
/**
* 停止播放TTS
*
* @return
*/
public ResponseBuilder voiceStop() {
if (resVoice == null) {
resVoice = new ResVoice();
}
resVoice.setAction(ResVoice.VOICE_ACTION_STOP);
return this;
}
/**
* 关闭Voice的EventRequest
*
* @return
*/
public ResponseBuilder voiceEventDisable() {
if (resVoice == null) {
resVoice = new ResVoice();
}
resVoice.setDisableEvent(true);
return this;
}
/**
* 发起confirm
*
* @param confirmIntent
* @param confirmSlot
* @param optionWords
* @return
*/
public ResponseBuilder confirmOpen(String confirmIntent, String confirmSlot, List<String> optionWords) {
if (resConfirm == null) {
resConfirm = new ResConfirm();
}
resConfirm.setConfirmSlot(confirmSlot);
resConfirm.setConfirmIntent(confirmIntent);
resConfirm.setOptionWords(optionWords);
return this;
}
/**
* 播放音频
*
* @param audioId
* @param audioToken
* @param audioUrl
* @param offsetInMilliseconds
* @return
*/
public ResponseBuilder audioPlay(String audioId, String audioToken, String audioUrl, long offsetInMilliseconds) {
return mediaPlay(audioId, audioToken, ResMediaItem.MEDIA_TYPE_AUDIO, audioUrl, offsetInMilliseconds);
}
/**
* 播放视频
*
* @param mediaId
* @param videoToken
* @param videoUrl
* @param offsetInMilliseconds
* @return
*/
public ResponseBuilder videoPlay(String mediaId, String videoToken, String videoUrl, long offsetInMilliseconds) {
return mediaPlay(mediaId, videoToken, ResMediaItem.MEDIA_TYPE_VIDEO, videoUrl, offsetInMilliseconds);
}
/**
* 播放Media
*
* @param mediaType
* @param mediaId
* @param mediaToken
* @param mediaUrl
* @param offsetInMilliseconds
* @return
*/
public ResponseBuilder mediaPlay(String mediaId, String mediaToken, String mediaType, String mediaUrl,
long offsetInMilliseconds) {
if (resMedia == null) {
resMedia = new ResMedia();
}
ResMediaItem resMediaItem = new ResMediaItem();
resMediaItem.setItemId(mediaId);
resMediaItem.setType(mediaType);
resMediaItem.setToken(mediaToken);
resMediaItem.setUrl(mediaUrl);
resMediaItem.setOffsetInMilliseconds(offsetInMilliseconds);
resMedia.setAction(ResMedia.MEDIA_ACTION_PLAY);
resMedia.setItem(resMediaItem);
return this;
}
/**
* 暂停Media
*
* @return
*/
public ResponseBuilder mediaPause() {
if (resMedia == null) {
resMedia = new ResMedia();
}
resMedia.setAction(ResMedia.MEDIA_ACTION_PAUSE);
return this;
}
/**
* 继续播放Meida
*
* @return
*/
public ResponseBuilder mediaResume() {
if (resMedia == null) {
resMedia = new ResMedia();
}
resMedia.setAction(ResMedia.MEDIA_ACTION_RESUME);
return this;
}
/**
* 停止播放TTS
*
* @return
*/
public ResponseBuilder mediaStop() {
if (resMedia == null) {
resMedia = new ResMedia();
}
resMedia.setAction(ResMedia.MEDIA_ACTION_STOP);
return this;
}
/**
* 关闭Voice的EventRequest
*
* @return
*/
public ResponseBuilder mediaEventDisable() {
if (resMedia == null) {
resMedia = new ResMedia();
}
resMedia.setDisableEvent(true);
return this;
}
/**
* 打开拾音
*
* @return
*/
public ResponseBuilder pickupOpen() {
return pickupOpen(null);
}
/**
* 打开识音,并且设置重复播报的TTS
*
* @param retryTts
* @return
*/
public ResponseBuilder pickupOpen(String retryTts) {
if (pickup == null) {
pickup = new ResPickup();
}
pickup.setEnable(true);
pickup.setDurationInMilliseconds(6000l);
if (StringUtils.isNotBlank(retryTts)) {
pickup.setRetryTts(retryTts);
}
return this;
}
/**
* 执行完毕以后退出应用
*
* @return
*/
public ResponseBuilder afterFinish() {
shouldEndSession = true;
return this;
}
/**
* 立即退出应用
*
* @return
*/
public ResponseBuilder finishNow() {
actionType = ResAction.ACTION_TYPE_EXIT;
shouldEndSession = true;
return this;
}
public ResponseBuilder sendChatCard(String content) {
card = new ResChatCard(content);
return this;
}
public ResResponse create() throws ProtocolException {
response.getSession().setAttributes(attributes);
List<ResDirective> directives = new ArrayList<>();
response.getResponse().getAction().setDirectives(directives);
response.getResponse().getAction().setShouldEndSession(shouldEndSession);
if (!ActionUtils.checkActionType(actionType)) {
throw new ProtocolException("actionType is error");
}
response.getResponse().getAction().setType(actionType);
if (!ActionUtils.checkVoice(resVoice)) {
throw new ProtocolException("resVoice is error");
}
if (resVoice != null) {
response.getResponse().getAction().getDirectives().add(resVoice);
}
if (!ActionUtils.checkMedia(resMedia)) {
throw new ProtocolException("resMedia is error");
}
if (resMedia != null) {
response.getResponse().getAction().getDirectives().add(resMedia);
}
if (!ActionUtils.checkConfirm(resConfirm)) {
throw new ProtocolException("resConfirm is error");
}
if (resConfirm != null) {
response.getResponse().getAction().getDirectives().add(resConfirm);
}
if (!ActionUtils.checkPickup(pickup)) {
throw new ProtocolException("resPickup is error");
}
if (pickup != null) {
response.getResponse().getAction().getDirectives().add(pickup);
}
if (card != null) {
response.getResponse().setCard(card);
}
return response;
}
private ResResponse buildEmptyActionResponse(String resVersion, HashMap<String, Object> attributes,
String actionVersion, String actionType, boolean shouldEndSession) {
ResResponse resResponse = new ResResponse();
resResponse.setVersion(resVersion);
ResSession resSession = new ResSession();
if (attributes != null && !attributes.isEmpty()) {
resSession.setAttributes(attributes);
}
resResponse.setSession(resSession);
ResResponseContent resResponseContent = new ResResponseContent();
ResAction resAction;
try {
resAction = ActionUtils.getEmptyAction(actionVersion, actionType, shouldEndSession);
resResponseContent.setAction(resAction);
} catch (ProtocolException e) {
e.printStackTrace();
}
resResponse.setResponse(resResponseContent);
return resResponse;
}
}
package ai.qiwu.rokid.ruoqi.common.utils;
import java.util.List;
import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException;
import ai.qiwu.rokid.ruoqi.model.response.ResResponse;
import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem;
import org.apache.commons.lang.StringUtils;
import com.google.gson.GsonBuilder;
/**
* @类描述 用于快速构造CloudApp的Response的工具类
* @对应结构以及命名 Response对应ResResponse:协议内容; response对应ResResponseContent:响应;
* action对应ResAction:事件; voice:文本; media:媒体; confirm:主动询问;
* confirmIntent:主动询问意图(比如询问歌手); confirmSlot:主动询问意图内容(比如歌手);
* optionWords:主动询问辅助信息; 场景化:scen;非场景化:cut
*/
public class ResponseUtils {
/**
* @方法 构造一个退出应用的协议内容
* @描述 客户端接收到该协议内容以后会立即退出应用
* @使用场景 当我们的应用需要退出的时候返回这个协议内容
* @注意 此协议内容的版本以及事件版本号都已经被固定为RES_VERSION_V2和ACTION_VERSION_V2,如协议版本变更,请自行修正一下;另外应用退出以后,nlp那边的session也会被清理
* @return
* @throws ProtocolException
*/
public static ResResponse buildExitNowResponse() throws ProtocolException {
return ResponseBuilder.build().finishNow().create();
}
/**
* @方法 构造一个空的协议内容,Voice以及Media继续保持原有执行状态
* @描述 客户端接收到该协议内容以后不会对当前的操作有任何的影响
* @使用场景 当我们的应用接受到不需要处理,需要忽略的Event请求是,我们可以返回该响应
* @注意 此协议内容的版本以及事件版本号都已经被固定为RES_VERSION_V2和ACTION_VERSION_V2,如协议版本变更,请自行修正一下,另外此协议内容会的shouldEndSession=false的
* @return
* @throws ProtocolException
*/
public static ResResponse buildIngoreEventResponse() throws ProtocolException {
return ResponseBuilder.build().create();
}
/**
* @方法 播报一句TTS,Media继续保持原有执行状态,并且有EventRequest
* @param voiceId
* tts的ID,可以为空
* @param voiceContent
* tts 内容
* @return
* @throws ProtocolException
*/
public static ResResponse buildVoicePlayResponse(String voiceId, String voiceContent) throws ProtocolException {
if (StringUtils.isBlank(voiceContent)) {
throw new ProtocolException("voiceContent Can not be null");
}
return ResponseBuilder.build().voicePlay(voiceId, voiceContent).create();
}
/**
* @方法 暂停播放Voice
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildVoicePauseResponse() throws ProtocolException {
return ResponseBuilder.build().voicePause().create();
}
/**
* @方法 继续播放Voice
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildVoiceResumeResponse() throws ProtocolException {
return ResponseBuilder.build().voiceResume().create();
}
/**
* @方法 停止播放Voice
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildVoiceStopResponse() throws ProtocolException {
return ResponseBuilder.build().voiceStop().create();
}
/**
* @方法 播放Media事件,TTS继续保持原有执行状态,
*
* @param mediaToken
* @param mediaType
* @param mediaUrl
* @param mediaOffset
* @return
*/
public static ResResponse buildMediaPlayResponse(String mediaId, String mediaToken, String mediaType,
String mediaUrl, long mediaOffset) throws ProtocolException {
if (StringUtils.isBlank(mediaUrl)) {
throw new ProtocolException("mediaUrl Can not be null");
}
if (mediaOffset < 0) {
throw new ProtocolException("mediaOffset Can not be < 0");
}
if (!ResMediaItem.MEDIA_TYPE_AUDIO.equals(mediaType) && ResMediaItem.MEDIA_TYPE_VIDEO.equals(mediaType)) {
throw new ProtocolException("mediaType is error");
}
return ResponseBuilder.build().mediaPlay(mediaId, mediaToken, mediaType, mediaUrl, mediaOffset).create();
}
/**
* @方法 暂停播放Media
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildMediaPauseResponse() throws ProtocolException {
return ResponseBuilder.build().mediaPause().create();
}
/**
* @方法 继续播放Media
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildMediaResumeResponse() throws ProtocolException {
return ResponseBuilder.build().mediaResume().create();
}
/**
* @方法 停止播放Media
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildMediaStopResponse() throws ProtocolException {
return ResponseBuilder.build().mediaStop().create();
}
/**
* @方法 暂停播放Media和Voice
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildPauseResponse() throws ProtocolException {
return ResponseBuilder.build().voicePause().mediaPause().create();
}
/**
* @方法 继续播放Voice和Meida
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildResumeResponse() throws ProtocolException {
return ResponseBuilder.build().voiceResume().mediaResume().create();
}
/**
* @方法 停止播放Voice和Media
*
* @return
* @throws ProtocolException
*/
public static ResResponse buildStopResponse() throws ProtocolException {
return ResponseBuilder.build().voiceStop().mediaStop().create();
}
/**
* 构造一个Confirm,并且把Media停止
*
* @param voiceContent
* @param confirmIntent
* 需要在平台上面定义过得intent,不能随便写
* @param confirmSlot
* 需要在平台上面定义过得slot,不能随便写
* @param confirmOptionWords
* @return
*/
public static ResResponse buildConfirmOpenResponse(String voiceContent, String confirmIntent, String confirmSlot,
List<String> confirmOptionWords) throws ProtocolException {
if (StringUtils.isBlank(voiceContent)) {
throw new ProtocolException("voiceContent Can not be null");
}
if (StringUtils.isBlank(confirmIntent)) {
throw new ProtocolException("confirmIntent Can not be null");
}
if (StringUtils.isBlank(confirmSlot)) {
throw new ProtocolException("confirmSlot Can not be null");
}
return ResponseBuilder.build().voicePlay(null, voiceContent).mediaStop()
.confirmOpen(confirmIntent, confirmSlot, confirmOptionWords).create();
}
/**
* 将ResResponse变成Json字符串
*
* @param response
* @return
*/
public static String responseToString(ResResponse response) {
if (response != null) {
return new GsonBuilder().disableHtmlEscaping().create().toJson(response);
} else {
return null;
}
}
}
package ai.qiwu.rokid.ruoqi.controller;
import ai.qiwu.rokid.ruoqi.model.request.ReqRequest;
import ai.qiwu.rokid.ruoqi.model.response.ResResponse;
import ai.qiwu.rokid.ruoqi.service.RokidRequestParse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 苗权威
* @dateTime 19-7-3 下午4:25
*/
@RestController
public class RokidController {
private static final Logger logger = LoggerFactory.getLogger(RokidController.class);
@Autowired
private RokidRequestParse requestParse;
@RequestMapping("/rokid")
public ResResponse chat(@RequestBody ReqRequest request) {
logger.info("请求消息:"+request.toString());
return requestParse.getResponse(request);
}
}
package ai.qiwu.rokid.ruoqi.model.request;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.context.ReqContext;
import ai.qiwu.rokid.ruoqi.model.request.request.ReqRequestValue;
import ai.qiwu.rokid.ruoqi.model.request.session.ReqSession;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
/**
*
*
*/
/**
* @类描述 CloudApp协议,Request对象
* @说明 Request主要包含四块内容 1、version:CloudApp协议版本; 2、session:当前的会话信息;
* 3、context:设备、用户、以及其他状态信息; 4、request:业务请求内容
* @param <>
* Slots对象
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = -490292141289020844L;
/**
*
*/
private String version;// 协议版本号,当前版本2.0.0
private ReqSession session;// 会话的信息
private ReqContext context;// 当前的设备信息,用户信息和应用状态
private ReqRequestValue request;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public ReqSession getSession() {
return session;
}
public void setSession(ReqSession session) {
this.session = session;
}
public ReqContext getContext() {
return context;
}
public void setContext(ReqContext context) {
this.context = context;
}
public ReqRequestValue getRequest() {
return request;
}
public void setRequest(ReqRequestValue request) {
this.request = request;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.context.application.ReqApplication;
import ai.qiwu.rokid.ruoqi.model.request.context.device.ReqDevice;
import ai.qiwu.rokid.ruoqi.model.request.context.user.ReqUser;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqContext implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5297187036481770538L;
private ReqApplication application; //ApplicationInfo对象,目前只有应用ID
private ReqDevice device;//此次请求发生时当前设备信息的描述
private ReqUser user;//展示了与当前设备绑定的用户信息,通常是设备对应手机应用的账号
public ReqApplication getApplication() {
return application;
}
public void setApplication(ReqApplication application) {
this.application = application;
}
public ReqDevice getDevice() {
return device;
}
public void setDevice(ReqDevice device) {
this.device = device;
}
public ReqUser getUser() {
return user;
}
public void setUser(ReqUser user) {
this.user = user;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.application;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.context.application.media.ReqApplicationMedia;
import ai.qiwu.rokid.ruoqi.model.request.context.application.voice.ReqApplicationVoice;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqApplication implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6035458330596077339L;
private String applicationId;// 当前的应用ID
private ReqApplicationMedia media;
private ReqApplicationVoice voice;
public String getApplicationId() {
return applicationId;
}
public ReqApplicationMedia getMedia() {
return media;
}
public ReqApplicationVoice getVoice() {
return voice;
}
public void setMedia(ReqApplicationMedia media) {
this.media = media;
}
public void setVoice(ReqApplicationVoice voice) {
this.voice = voice;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.application.media;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqApplicationMedia implements Serializable {
public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态
public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态
public static final String STATE_IDLE = "IDLE";// 当前播放器状态在闲置状态
public static final String STATE_UNKNOW = "UNKNOW";// 未知状态
/**
*
*/
private static final long serialVersionUID = -6035458330596077339L;
private String state;// "PLAYING / PAUSED / IDLE",
private String itemId;
private String token;
private Long progress;// 毫秒
private Long duration;// 毫秒
public String getState() {
return state;
}
public String getItemId() {
return itemId;
}
public String getToken() {
return token;
}
public Long getProgress() {
return progress;
}
public void setProgress(Long progress) {
this.progress = progress;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public void setState(String state) {
this.state = state;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public void setToken(String token) {
this.token = token;
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.application.voice;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqApplicationVoice implements Serializable {
public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态
public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态
public static final String STATE_IDLE = "IDLE";// 当前播放器状态在闲置状态
public static final String STATE_UNKNOW = "UNKNOW";// 未知状态
/**
*
*/
private static final long serialVersionUID = -6035458330596077339L;
private String state;// "PLAYING / PAUSED / IDLE",
private String itemId;
public String getState() {
return state;
}
public String getItemId() {
return itemId;
}
public void setState(String state) {
this.state = state;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.device;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.context.device.basic.ReqBasic;
import ai.qiwu.rokid.ruoqi.model.request.context.device.location.ReqLocation;
import ai.qiwu.rokid.ruoqi.model.request.context.device.media.ReqMedia;
import ai.qiwu.rokid.ruoqi.model.request.context.device.screen.ReqScreen;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqDevice implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3966116657482862685L;
private ReqBasic basic;// 展示了当前设备的基础信息,主要包含设备制造信息、时间信息、国家文字信息。
private ReqScreen screen;// 展示了当前设备的屏幕信息,主要包含屏幕的分辨率信息。
private ReqMedia media;// 向CloudApp表明当前设备上CloudAppClient中的MediaPlayer的状态信息。
private ReqMedia voice;// 向CloudApp表明当前设备上CloudAppClient中的Voice的状态信息。
private ReqLocation location;// 位置信息,现在只有一个经纬度
public ReqBasic getBasic() {
return basic;
}
public void setBasic(ReqBasic basic) {
this.basic = basic;
}
public ReqScreen getScreen() {
return screen;
}
public void setScreen(ReqScreen screen) {
this.screen = screen;
}
public ReqMedia getMedia() {
return media;
}
public void setMedia(ReqMedia media) {
this.media = media;
}
public ReqMedia getVoice() {
return voice;
}
public void setVoice(ReqMedia voice) {
this.voice = voice;
}
public ReqLocation getLocation() {
return location;
}
public void setLocation(ReqLocation location) {
this.location = location;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.device.basic;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqBasic implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String vendor;// 注册生产商ID
private String deviceType;// 该生产商设定的设备型号
private String deviceId;// 该型号下的设备ID
private String locale;// 国家及语言,标准locale格式
private Long timestamp;// 设备当前时间,unix timestamp
private String masterId;// 设备主人的Id;
private String voicetrigger;// 设备当前激活词
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getMasterId() {
return masterId;
}
public void setMasterId(String masterId) {
this.masterId = masterId;
}
public String getVoicetrigger() {
return voicetrigger;
}
public void setVoicetrigger(String voicetrigger) {
this.voicetrigger = voicetrigger;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.device.location;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqLocation implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7136610825306612078L;
private String longitude;// 经度
private String latitude;// 纬度
private String country;// 国家
private String state;// 州/省份
private String city;// 城市
private String area;// 区县
private String district;// 地区,行政
private String street;// 街道
private String timeZone;//时区
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.device.media;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 25/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqMedia implements Serializable {
public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态
public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态
public static final String STATE_IDLE = "IDLE";//当前播放器状态在闲置状态
public static final String STATE_UNKNOW = "UNKNOW";// 未知状态
/**
*
*/
private static final long serialVersionUID = -6588484011026696932L;
private String state;// PLAYING PAUSED IDLE
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public boolean isPlaying() {
return STATE_PLAYING.equals(state);
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.device.screen;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 25/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqScreen implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3108410377906776393L;
private String x;//X 方向上的像素大小
private String y;//Y 方向上的像素大小
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.context.user;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqUser implements Serializable {
/**
*
*/
private static final long serialVersionUID = 675958584565674347L;
private String userId;//用户ID
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.request.content.ReqRequestContent;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqRequestValue implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6876155972421972250L;
public static final String REQTYPE_INTENT = "INTENT";
public static final String REQTYPE_EVENT = "EVENT";
private String reqType;// 表明请求的类型: INTENT 和 EVENT 分别对应 IntentRequest 和
// EventRequest。
private String reqId;// 每次请求都会对应一个唯一ID用以区分每一次的请求。请求ID将会与返回ID一一对应。
private ReqRequestContent content;// IntentRequest 或 EventRequest的对象
public String getReqType() {
return reqType;
}
public void setReqType(String reqType) {
this.reqType = reqType;
}
public String getReqId() {
return reqId;
}
public void setReqId(String reqId) {
this.reqId = reqId;
}
public ReqRequestContent getContent() {
return content;
}
public void setContent(ReqRequestContent content) {
this.content = content;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content;
import java.io.Serializable;
import java.util.HashMap;
import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.ReqEventExtra;
import ai.qiwu.rokid.ruoqi.model.request.request.content.slot.Slot;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqRequestContent implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8296524576831663917L;
/**
* @see ai.qiwu.rokid.ruoqi.model.request.request.content.enums
*/
private String intent;// IntentRequest,CloudApp 对应的 nlp intent
private HashMap<String, Slot> slots;
private String sentence;// asr 语音内容
/**
* @see ai.qiwu.rokid.ruoqi.model.request.request.content.enums
*/
private String event; // EventRequest,事件类型
private ReqEventExtra extra;// EventRequest
public String getIntent() {
return intent;
}
public void setIntent(String intent) {
this.intent = intent;
}
public HashMap<String, Slot> getSlots() {
return slots;
}
public void setSlots(HashMap<String, Slot> slots) {
this.slots = slots;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public ReqEventExtra getExtra() {
return extra;
}
public void setExtra(ReqEventExtra extra) {
this.extra = extra;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.enums;
import org.apache.commons.lang.StringUtils;
public enum RokidEventCommonEnums {
// EVENT
SKILL_EXIT_EVENT("Skill.EXIT", "skillSuspendEvent", "EventRequest,event=Skill.EXIT"), // 当应用挂起的时候 TODO 需要修改名字
SKILL_SUSPEND_EVENT("Skill.SUSPEND", "skillSuspendEvent", "EventRequest,event=Skill.SUSPEND"), // 当应用挂起的时候的事件
SESSION_ENDED_EVENT("Session.ENDED", "sessionEndedEvent", "EventRequest,event=Session.ENDED");// 当Domain被切换到的时候的事件,可以用于关闭资源
private String event;
private String methodName;
private String cnHit; // 中文提示,仅作阅读代码的提示。
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCnHit() {
return cnHit;
}
public void setCnHit(String cnHit) {
this.cnHit = cnHit;
}
RokidEventCommonEnums(String event, String methodName, String cnHit) {
this.event = event;
this.methodName = methodName;
this.cnHit = cnHit;
}
public static RokidEventCommonEnums convert(String event) {
for (RokidEventCommonEnums v : RokidEventCommonEnums.values()) {
if (StringUtils.equals(v.event, event)) {
return v;
}
}
return null;
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.enums;
import org.apache.commons.lang.StringUtils;
public enum RokidEventMediaEnums {
// EVENT
MEDIA_STARTED_EVENT("Media.STARTED", "mediaStartedEvent", "EventRequest,event=Media.STARTED"), // 当MediaPlayer开始播放时发生。
MEDIA_FAILED_EVENT("Media.FAILED", "mediaFailedEvent", "EventRequest,event=Media.FAILED"), // 当MediaPlayer播放失败时发生。
MEDIA_PAUSED_EVENT("Media.PAUSED", "mediaPausedEvent", "EventRequest,event=Media.PAUSED"), // 当MediaPlayer中途停止时发生。
MEDIA_FINISHED_EVENT("Media.FINISHED", "mediaFinishedEvent", "EventRequest,event=Media.FINISHED");// 当播放内容结束时发生。
private String event;
private String methodName;
private String cnHit; // 中文提示,仅作阅读代码的提示。
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCnHit() {
return cnHit;
}
public void setCnHit(String cnHit) {
this.cnHit = cnHit;
}
RokidEventMediaEnums(String event, String methodName, String cnHit) {
this.event = event;
this.methodName = methodName;
this.cnHit = cnHit;
}
public static RokidEventMediaEnums convert(String event) {
for (RokidEventMediaEnums v : RokidEventMediaEnums.values()) {
if (StringUtils.equals(v.event, event)) {
return v;
}
}
return null;
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.enums;
import org.apache.commons.lang.StringUtils;
public enum RokidEventVoiceEnums {
// EVENT
VOICE_STARTED_EVENT("Voice.STARTED", "voiceStartedEvent", "EventRequest,event=Voice.STARTED"), // 当Voice开始播放时发生。
VOICE_FAILED_EVENT("Voice.FAILED", "voiceFailedEvent", "EventRequest,event=Voice.FAILED"), // 当Voice播放失败时发生。
VOICE_FINISHED_EVENT("Voice.FINISHED", "voiceFinishedEvent", "EventRequest,event=Voice.FINISHED"); // 当Voice播放内容结束时发生。
private String event;
private String methodName;
private String cnHit; // 中文提示,仅作阅读代码的提示。
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCnHit() {
return cnHit;
}
public void setCnHit(String cnHit) {
this.cnHit = cnHit;
}
RokidEventVoiceEnums(String event, String methodName, String cnHit) {
this.event = event;
this.methodName = methodName;
this.cnHit = cnHit;
}
public static RokidEventVoiceEnums convert(String event) {
for (RokidEventVoiceEnums v : RokidEventVoiceEnums.values()) {
if (StringUtils.equals(v.event, event)) {
return v;
}
}
return null;
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.enums;
import org.apache.commons.lang.StringUtils;
/**
* 系统级的Intent事件
*
* @author Bassam
*
*/
public enum RokidIntentCommonEnums {
WELECOME_INTENT("ROKID.INTENT.WELCOME", "appStartIntent", "打开应用事件"), // 通过激活词打开应用时会发送这个Intent
UNKONWN_INTENT("ROKID.INTENT.UNKNOWN", "unkonwnIntent", "未知意图的Intent事件"), // 未知意图的Intent事件,当Skill开启PickUp以后,用户三次处理都出错,会命中该Intent
EXIT_INTENT("ROKID.INTENT.EXIT", "appStopIntent", "退出应用事件");// Skill退出请求
private String intent;
private String methodName;
private String cnHit; // 中文提示,仅作阅读代码的提示。
public String getIntent() {
return intent;
}
public void setIntent(String intent) {
this.intent = intent;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCnHit() {
return cnHit;
}
public void setCnHit(String cnHit) {
this.cnHit = cnHit;
}
RokidIntentCommonEnums(String intent, String methodName, String cnHit) {
this.intent = intent;
this.methodName = methodName;
this.cnHit = cnHit;
}
public static RokidIntentCommonEnums convert(String intent) {
for (RokidIntentCommonEnums v : RokidIntentCommonEnums.values()) {
if (StringUtils.equals(v.intent, intent)) {
return v;
}
}
return null;
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.enums;
import org.apache.commons.lang.StringUtils;
/**
* 系统级的Intent事件
*
* @author Bassam
*
*/
public enum RokidIntentMediaEnums {
RESUME_INTENT("ROKID.INTENT.AUDIO_RESUME", "resumeIntent", "继续播放事件"),
PAUSE_INTENT("ROKID.INTENT.AUDIO_PAUSE", "pauseIntent", "暂停播放事件"),
STOP_INTENT("ROKID.INTENT.AUDIO_CANCEL", "stopIntent", "取消播放事件"),
LOOP_INTENT("ROKID.INTENT.AUDIO_LOOPON", "loopIntent", "循环播放事件"),
LOOPOFF_INTENT("ROKID.INTENT.AUDIO_LOOPOFF", "loopOffIntent", "取消循环播放事件"),
NEXT_INTENT("ROKID.INTENT.AUDIO_NEXT", "nextIntent", "下一首播放事件"),
PREVIOUS_INTENT("ROKID.INTENT.AUDIO_PREVIOUS", "previousIntent", "上一首播放事件"),
REPEAT_INTENT("ROKID.INTENT.AUDIO_REPEAT", "repeatIntent", "重复播放事件"),
STARTOVER_INTENT("ROKID.INTENT.AUDIO_STARTOVER", "startOverIntent", "重新播放事件"),
SHUFFLE_INTENT("ROKID.INTENT.AUDIO_SHUFFLEON", "shuffleIntent", "随机播放事件"),
SHUFFLEOFF_INTENT("ROKID.INTENT.AUDIO_SHUFFLEOFF", "shuffleOffIntent", "关闭随机播放事件");
private String intent;
private String methodName;
private String cnHit; // 中文提示,仅作阅读代码的提示。
public String getIntent() {
return intent;
}
public void setIntent(String intent) {
this.intent = intent;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getCnHit() {
return cnHit;
}
public void setCnHit(String cnHit) {
this.cnHit = cnHit;
}
RokidIntentMediaEnums(String intent, String methodName, String cnHit) {
this.intent = intent;
this.methodName = methodName;
this.cnHit = cnHit;
}
public static RokidIntentMediaEnums convert(String intent) {
for (RokidIntentMediaEnums v : RokidIntentMediaEnums.values()) {
if (StringUtils.equals(v.intent, intent)) {
return v;
}
}
return null;
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.extra;
import java.io.Serializable;
import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media.ReqExtraMedia;
import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice.ReqExtraVoice;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* Created by Bassam on 15/03/2017.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqEventExtra implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6312382694862019116L;
private ReqExtraMedia media;
private ReqExtraVoice voice;
public ReqExtraMedia getMedia() {
return media;
}
public void setMedia(ReqExtraMedia media) {
this.media = media;
}
public ReqExtraVoice getVoice() {
return voice;
}
public void setVoice(ReqExtraVoice voice) {
this.voice = voice;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqExtraMedia implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4201471138232339064L;
private String itemId;
private String token;
private String progress;
private String duration;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getProgress() {
return progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReqExtraVoice implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4975096988067404659L;
private String itemId;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package ai.qiwu.rokid.ruoqi.model.request.request.content.slot;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Slot implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8124321322315914064L;
private String type;
private String value;
public String getType() {
return type;
}
public String getValue() {
return value;
}
public void setType(String type) {
this.type = type;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment