diff --git a/WEB-INF/web.xml b/WEB-INF/web.xml new file mode 100644 index 0000000..87c4aa6 --- /dev/null +++ b/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + + + org.springframework.web.context.ContextLoaderListener + + + + + + + diff --git a/chatbotbackend.iml b/chatbotbackend.iml new file mode 100644 index 0000000..d0d10d3 --- /dev/null +++ b/chatbotbackend.iml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config.properties b/config.properties index ef5659e..aa9d2b4 100644 --- a/config.properties +++ b/config.properties @@ -1,24 +1,53 @@ -test_var=1111 + +# qa问答地址 qa_url=http://192.168.1.78:59000/game +# 中控url cc_url=http://localhost:8070/api/update/data -//condition_backend=http://192.168.1.82 +# condition后台url +condition_backend_url=http://192.168.1.82:6636/api + +# 数据模型url +automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train + +# action生成指定的后台地址 +service_url=http://192.168.1.178:8081/bot/dialog + +# +#qa_url=http://localhost:59100/game +#cc_url=http://localhost:8070/api/update/data +#condition_backend_url=http://localhost:6636/api +#automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train +#service_url=http://localhost:8081/bot/dialog + + +bot_backup_dir=tmp/ +config_dir=config/ unknown_text=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧 location_hint=请到%s game_start_hint=请说开始剧情或者继续剧情 +game_welcome_text=欢迎来到%s,请说继续剧情或者重新开始 game_module_error=游戏模块出错 +program_error=程序出现异常 +intent_not_understand=我不理解 # -------------------------------游戏生成--------------------------- +token_time_out=token超时了 +game_bot_category=游戏 delete_old_config_term_error=删除旧数据config失败 delete_old_variable_error=删除旧变量失败 delete_old_category_error=删除旧类别失败 -# ---------------------------------------------------------------- +name_mission_error=没找到bot名? +log_path=/var/www/html/logs/ + + +# ---------------------------------------------------------------- unknown_text_description=对于无法识别的问题做出的回答 game_step_description=QA问答游戏进度 @@ -41,6 +70,7 @@ plot_status=剧情%s状态 # --------------------------------------------------- plot_generation_error=剧情接口处理出现异常 +action_text_generate_error=action生成失败 默认condition default_condition=yaobuyao @@ -74,26 +104,64 @@ task_description_slot=[任务描述]" find_item_owner=[物品名]在[人名]身上 #---------------------------------------------- -# ---------------------文本解析--------------------- -text_parse_error=文本解析出错 -automatch_threshold=0.5 -game_condition_category=97 -service_url=http://192.168.1.178:8081/bot/dialog +#--------------------condition文本默认配置-------------------------- + options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat -automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train -idlelimit=180000 -condition_generate_url=http://192.168.1.178:1111/conditionProcess -condition_backend_url=http://192.168.1.82:6636/api -style=interrupt,multimatchvalues,bothvalue -fellow=pivot_httppost + +idle_limit=180000 +condition_fellow=pivot_httppost +automatch_threshold=0.5 +default_style=style=interrupt,bothvalue,multimatchvalues post_style1=style=httppost,bothvalue,multimatchvalues post_style2=style=httppost,multimatchvalues -post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s +# ---------------------condition解析生成--------------------- +bot_info_not_exist=bot信息不存在 +conditon_backend_error=condition后台报错 +text_parse_error=文本解析出错 + +game_condition_category=97 -# ----------------------condition增删改查异常---------------------------- +post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s\r\n + update_keyword_error=更新关键词单元失败 delete_user_data_error=删除用户数据失败 -game_condition_category_id=123 -platform_sql_init_error=新平台获取sql连接失败 \ No newline at end of file +platform_sql_init_error=新平台获取sql连接失败 + +json_format_error=json格式有误 +condition_insert_error=condition插入失败 +condition_update_error=condition更新失败 + +condition_name_dumplicate=condition名字重复 +update_error=更新失败 + + +# --------------------------配置文件增删改查----------------------------------- +config_pattern=%s|%s|%s|=>|%s|nextStep=%s|status=%s|configId=%s +config_delete_error=删除配置文件失败 +condition_name_update_error=更新语义关系名字失败 +config_insert_error=插入配置文件失败 +config_file_not_found=没有找到配置文件 + + +# -------------------------配置文件类别操作------------------------------------- +category_update_conflict="不可将父分组设为了当前分组的子分组" +category_update_error="类别更新失败" +category_insert_error="新建类别失败" +category_delete_error="类别删除失败" +category_query_error="类别查询失败" + + +# -------------------------变量操作------------------------------------------ +variable_name_dumplicate=变量名重复 +varibale_insert_error=变量插入失败 +variable_delete_error=变量删除失败 +variable_update_error=变量更新失败 +variable_sql_delete_error=从数据库删除变量失败 +variable_save_format=-varInitial-|%s|%s\n +extra_info_format=-extraInfo-|%s|%s\n +variable_update_format=%s---%s + +# ---------------------------数据库连接获取失败-------------------------------- +sql_connection_error=数据库连接获取失败 diff --git a/keywords2.txt b/keywords2.txt new file mode 100644 index 0000000..c42da21 --- /dev/null +++ b/keywords2.txt @@ -0,0 +1,202 @@ + + +# ------------------------------------------------------------------------------ +# 第一块,意图|相关的语义关系名 +意图语义关系名 + +# 第二块, 意图|语义关系名|关键词 + + +# ------------------------------------------------------------------------------ +WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + +WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +SURROUNDING_NPC|know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 +SURROUNDING_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 +SURROUNDING_NPC_CLASS|know_exist_what|+周围:name+附近:name +SURROUNDING_ITEM|know_exist_what|+周围:name+附近:name +SURROUNDING_PLACE|know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 +SURROUNDING_ITEM_CLASS|know_exist_what|+周围:name+附近:name + +WHAT_ITEM_I_HAVE|know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 +WHO_IN_THERE|shishui|+谁:里面+里面:人 + +GO_TO|yaobuyao|+去:name+到:name + +WHO_TO_FIND_NPC|xxx|+找到:name + +WHO_ARE_YOU|zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 +TASK_IS_WHAT|shishenme|+是什么:任务+qiwu:任务 + +FIND_NPC_LOCATION|xxx|+哪里:name+哪:name+地方:name+地点:name +FIND_ITEM_LOCATION|xxx|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +WHAT_NPC_IN_LOCATION|xxx|地点 +WAHT_ITEM_IN_LOCATION|xxx|地点 +WHAT_THINGS_IN_LOCATION|xxx|地点 + + + + + +# -------------------------------------------------------------------------- +# 地图在哪里 +map_zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +map_wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + + +# 能去哪里 +map_choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +# 周围有什么人 +people_know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 + +# 周围有什么物品 +item_know_exist_what|+周围:物品+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西 + +# 我有什么东西 +item_rencheng|+qiwu:东西 + +# 我有什么 +we_have_know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 + +# 里面的是谁 +inner_shishui|+谁:里面+里面:人 + +# 去某个地方 +map_yaobuyao|+去:name+到:name + +# 你是谁 +talker_zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 + +# 任务是什么 +task_shishenme|+是什么:任务+qiwu:任务 + +# 周围有什么 +things|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 + +# 周围有什么地方 +place_know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 + +# 周围有什么npc类名 +npc_class_pattern|+周围:name+附近:name + +# 周围有什么item类名 +item_class_pattern|+周围:name+附近:name + +# 怎么找到xxx +find_pattern|+找到:name + +# npc在哪里 +npc_location_pattern|+哪里:name+哪:name+地方:name+地点:name + +# 物品在哪里 +item_location_pattern|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +# 某地点有什么 +things_in_place_xxxx|+地点:什么 + +# 地点有什么人 +NPC_in_place_xxx|+地点:什么 + +# 地点有什么物品 +items_in_place_xxx|+地点:什么 + +# =====================================new add============================================ +people_rencheng|+机器人:谁+那个人:谁+人:谁+机器人:干嘛 + + + + + + +# ------------------------------------------------------------------------------ +# 格式 +# 意图|语义关系名字|关键词 +# name表示可以替换的名字,如物品名、角色名 +# attrName是属性名 +# qiwu就是玩家“我” + + + +# ------------------------------------------------------------------------------ +# 我在哪里 +WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + +# 我能去哪里 +WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +# 周围有什么人 +AROUND_NPC|know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 + +# 周围有什么npc类别 +AROUND_NPC_CLASS|know_exist_what|+周围:name+附近:name + +# 周围有什么 +AROUND_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 + +# 周围有什么物品 +AROUND_ITEM|know_exist_what|+周围:物品+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西 + +# 周围有什么地方 +AROUND_PLACE|know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 + +# 周围有什么物品类别 +AROUND_ITEM_CLASS|know_exist_what|+周围:name+附近:name + +# 我有什么 +WHAT_ITEM_I_HAVE|know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 + +# 里面有谁 +WHO_IN_THERE|shishui|+谁:里面+里面:人 + +# 去xx +GO_TO|yaobuyao|+去:name+到:name + +# 怎么找到NPC +HOW_TO_FIND_NPC|xxx|+找到:name + + +# 你是谁 +WHO_YOU_ARE|zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 + +# 任务是什么 +TASK_IS_WHAT|shishenme|+是什么:任务+qiwu:任务 + +# npc在哪里 +NPC_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name + +# 物品在哪里 +ITEM_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +# 怎么找到npc +HOW_FIND_NPC|want_know_zenmezuo|+找到:name +#怎么找到物品 +HOW_FIND_ITEM|want_know_zenmezuo|+找到:name + +# 沙滩上有什么人 +WHAT_NPC_IN_LOCATION|xxx|地点 + +# xx上有什么东西 +WAHT_ITEM_IN_LOCATION|xxx|地点 + +# 地点上有什么 +WHAT_THINGS_IN_LOCATION|xxx|地点 + +# npc的属性是多少 +NPC_ATTR|nums|+name:attrName +NPC_ATTR|shishenme|+name:attrName + +# 物品的属性是多少 +ITEM_ATTR|nums|+name:attrName +ITEM_ATTR|shishenme|+name:attrName + +# 周围有什么物品类别 +AOURND_NPC_CLASS|know_exist_what|+周围:name+附近:name + +# 怎么去XXX +HOW_TO_THERE|want_know_zenmezuo|默认 + diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/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 +# +# http://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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@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 http://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% diff --git a/pom.xml b/pom.xml index 438dd0f..48c5c1c 100644 --- a/pom.xml +++ b/pom.xml @@ -98,6 +98,12 @@ 1.5.0 + + commons-io + commons-io + 2.5 + + diff --git a/src/db/DBCPUtils.java b/src/db/DBCPUtils.java deleted file mode 100644 index 4746731..0000000 --- a/src/db/DBCPUtils.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.qiwu.chatbotbackend.db; - - -import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory; - -import javax.sql.DataSource; -import java.io.File; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - - -public class DBCPUtils { - private static DataSource ds;//定义一个连接池对象 - - static { - try { - Properties pro = new Properties(); - File file = new File("dbcpconfig.properties"); - pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties")); - ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象 - } catch (Exception e) { - e.printStackTrace(); - //throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); - } - } - - //从池中获取一个连接 - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - public static void closeAll(ResultSet rs, Statement stmt, Connection conn) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - if (conn != null) { - try { - conn.close();//关闭 - } catch (SQLException e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/src/db/DBUtils.java b/src/db/DBUtils.java deleted file mode 100644 index 5dc4aaa..0000000 --- a/src/db/DBUtils.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.qiwu.chatbotbackend.db; - -public class DBUtils { -} diff --git a/src/entity/AnswerNextStep.java b/src/entity/AnswerNextStep.java deleted file mode 100644 index ecc898d..0000000 --- a/src/entity/AnswerNextStep.java +++ /dev/null @@ -1,44 +0,0 @@ -package entity; - - -/** - * 包含后台返回数据的实体类。 - */ -public class AnswerNextStep { - int status = 0; - String answer; - String next; - - public String getAnswer() { - return answer; - } - - public int getStatus() { - return status; - } - - - - public void setAnswer(String answer) { - this.answer = answer; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - public AnswerNextStep(int status, String answers, String next){ - this.answer = answers; - this.next = next; - this.status = status; - } - public AnswerNextStep(){} -} diff --git a/src/entity/ChatCache3.java b/src/entity/ChatCache3.java deleted file mode 100644 index a0ce10a..0000000 --- a/src/entity/ChatCache3.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.processing.ChatCacheController; -import org.springframework.beans.factory.DisposableBean; - - -import javax.annotation.PreDestroy; - -public class ChatCache3 implements DisposableBean { - - -// private String chatKey = "不知道"; - private String chatKey = ""; - private String botAccount = ""; - - private Map infoPoint = null; - private GameEnv gameEnv = null; - private boolean reloading = false; - - - public String getBotAccount() { - return botAccount; - } - - public void setBotAccount(String botAccount) { - this.botAccount = botAccount; - } - - public boolean isReloading() { - return reloading; - } - - - public void setReloading(boolean reloading) { - this.reloading = reloading; - } - - public Map getInfoPoint() { - return infoPoint; - } - - public void setInfoPoint(Map infoPoint) { - this.infoPoint = infoPoint; - } - - public GameEnv getGameEnv() { - return gameEnv; - } - - public void setGameEnv(GameEnv gameEnv) { - this.gameEnv = gameEnv; - } - - public ChatCache3(String chatKey, GameEnv gameEnv, Map infoPoint) { - this.chatKey = chatKey; - this.gameEnv = gameEnv; - this.infoPoint = infoPoint; - } - - - @Override - public void destroy() throws IOException { - } - - public ChatCache3(UserInfo userInfo) throws Exception { - try { - gameEnv = new GameEnv(userInfo.botAccount); - } catch (Exception e) { - System.out.println("游戏平台初始化失败"); - e.printStackTrace(); - } - - String k; - this.botAccount = userInfo.botAccount; - infoPoint = new HashMap(); - Iterator iit = userInfo.varInitialMap.keySet().iterator(); - while (iit.hasNext()) { - k = iit.next(); - infoPoint.put(k, userInfo.varInitialMap.get(k)); - } - infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - - } - - -} diff --git a/src/entity/Condition.java b/src/entity/Condition.java deleted file mode 100644 index bc78ed4..0000000 --- a/src/entity/Condition.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; - - -/** - * 保存配置文件每一行(单行)解析后的信息的实体类。 - * 独立于引擎的另一种condition - */ -public class Condition { - public int priority = -1; - public int activePriority = 0; //如果本condition被其他condition激活 - public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 - public HashSet keywordSet = new HashSet(); - public HashMap> historyPremise = new HashMap>(); - public HashMap> currentPremise = new HashMap>(); - public HashMap updateKnowledge = new LinkedHashMap(); - public String[] answer = {"",}; - public String nextStep = ""; - public HashMap featureMap = new HashMap(); - public String indexName = ""; - public int id = 0; - public String configName = ""; - public String status = "waiting"; - //public ArrayList indexName = new ArrayList(); - - public Condition(int priority) { - this.priority = priority; - this.activePriority = priority; - } - - public Condition(Condition originCondition, int basePriority, int baseAuxiliaryPriority) { - this.priority = originCondition.priority; - this.keywordSet = originCondition.keywordSet; - this.historyPremise = originCondition.historyPremise; - this.currentPremise = originCondition.currentPremise; - this.answer = originCondition.answer; - this.nextStep = originCondition.nextStep; - this.featureMap = originCondition.featureMap; - this.updateKnowledge = originCondition.updateKnowledge; - this.indexName = originCondition.indexName; - this.id = originCondition.id; - this.configName = originCondition.configName; - this.status = originCondition.status; - this.activePriority = originCondition.activePriority + basePriority; - this.auxiliaryPriority = originCondition.auxiliaryPriority + baseAuxiliaryPriority; - } - - public Condition() { - } - -} diff --git a/src/entity/ConfigTerm.java b/src/entity/ConfigTerm.java deleted file mode 100644 index a1f3725..0000000 --- a/src/entity/ConfigTerm.java +++ /dev/null @@ -1,531 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class ConfigTerm implements Cloneable{ - - ThreadLocal iterNum=new ThreadLocal() { - protected Integer initialValue() { - return 0; - } - }; - ThreadLocal> conditionCount = new ThreadLocal>(){ - protected Map initialValue(){ - return new HashMap(); - }; - }; - - - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - - - private String curPremise = ""; - private String hisPremise = ""; - private String feature = ""; - private String reply = ""; - private String nextStep = ""; - private String updateKnowledge = ""; - private String nextStepStatus = "return"; - private String configName = ""; - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - public String getFeature() { - return feature; - } - - public void setFeature(String feature) { - this.feature = feature; - } - - public String getCurPremise() { - return curPremise; - } - - public String getNextStep() { - return nextStep; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName, Boolean append) { - - if(append) { - - iterNum.set(iterNum.get() + 1); - - //iterNum++; - this.configName = configName + "_" + iterNum.get(); - }else{ - this.configName = configName; - } - } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - - public void setCurPremise(String curPremise) { - this.curPremise = curPremise; - } - - public String getHisPremise() { - return hisPremise; - } - - public void setHisPremise(String hisPremise) { - this.hisPremise = hisPremise; - } - - public String getReply() { - return reply; - } - - public void setReply(String reply) { - this.reply = reply; - } - - public String getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public String getStatus() { - return status; - } - - public String getNextStepStatus() { - return nextStepStatus; - } - - public String getUpdateKnowledge() { - return updateKnowledge; - } - - public void setUpdateKnowledge(String updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - - static Map statusMap = new HashMap() { - { - put("return", "return"); - put("return-1", "back"); - put("return-0", "stay"); - put("activate", "activate"); - put("activate:after", "activate:after"); - } - }; - - public void setStatus(String status) { - this.status = status; - } - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public void setNextStepStatus(String nextStepStatus) { - this.nextStepStatus = nextStepStatus; - } - - public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - if (!updateKnowledge.equals("")) - this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); - //if (!updateKnowledge.equals("")) - // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - - public ConfigTerm(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { - this.curPremise = appendPremiseStr(curPremise, extraCP); - this.hisPremise = appendPremiseStr(hisPremise, extraHP); - this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; - this.auxiliaryPriority = auxiliaryPriority; - } - - public String appendPremiseStr(List premises, String extraPremise) { - StringBuffer sb = new StringBuffer(); - String premiseStr = "", conditionName; - Map nameCount = new HashMap(); - - for (Premise premise : premises){ - //设置初始值 - //System.out.println("nameCount" + nameCount); - conditionName = premise.getConditionName(); - - nameCount.putIfAbsent(conditionName, 0); - - //nameCount加一 - nameCount.put(conditionName, nameCount.get(conditionName) + 1); - - //在conditionName后添加count - if(nameCount.get(conditionName) > 1) { - premise.setConditionName(conditionName + nameCount.get(conditionName)); - } - - - - sb.append(","); - sb.append(premise.getConditionName()); - sb.append("::"); - sb.append(premise.getCmpType()); - sb.append("-"); - sb.append(premise.getOperator()); - sb.append("="); - sb.append(premise.getKeyword()); - } - if (sb.length() > 0) - sb.deleteCharAt(0); //删除第一个逗号 - - - if (!extraPremise.equals("")) { - if (sb.length() == 0) - sb.append(extraPremise); - else - sb.append("," + extraPremise); - } else if (sb.length() == 0) { - sb.append(" "); - } - premiseStr = sb.toString(); - - return premiseStr; - } - - public String appendKnowledgeStr(Map knowledge, String extraKL) { - StringBuffer sb = new StringBuffer(); - String varName = "", varValue = "", knowledgeStr; - Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 - String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; - - while (iit.hasNext()) { - varName = iit.next(); - varValue = knowledge.get(varName); - - if(varValue.startsWith("updateFollowerLocation")){ - delayUpdateFollowerLocation = true; - delayUpdateFollowerLocationKey = varName; - delayUpdateFollowerLocationValue = varValue; - continue; - } - sb.append("-<-").append(varName).append(":").append(varValue); - - } - if (!extraKL.equals("")) { - sb.append("-<-" + extraKL); - } - - if(delayUpdateFollowerLocation){ - sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); - } - - if (sb.length() > 0) - knowledgeStr = "updateKnowledge" + sb.toString(); - else - knowledgeStr = ""; - - return knowledgeStr; - } - - - public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { - //System.out.println(premise); - - String pair1[] = premise.split("=", 2); - String key = pair1[0]; - - String keywords = pair1[1]; - String pair2[] = key.split("::"); - String conditionName = pair2[0]; - String pair3[] = pair2[1].split("-"); - String cmpType = pair3[0]; - String operator = ""; - if (pair3.length > 1) - operator = pair3[1]; - - String question = ""; - if (conditionDescription.get(conditionName) != null) - question = conditionDescription.get(conditionName); - - JSONObject premiseJ = new JSONObject(); - premiseJ.put("keywords", keywords); - premiseJ.put("actionName", conditionName); - premiseJ.put("cmpType", cmpType); - premiseJ.put("question", question); - premiseJ.put("operator", operator); - - premiseList.add(premiseJ); - - } - - public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { - String pair[] = knowledge.split(":", 2); - - if (knowledge.equals("") || pair.length < 2) - return; - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - JSONObject knowledgeJ = new JSONObject(); - knowledgeJ.put("variableName", pair[0]); - knowledgeJ.put("keyword", pair[1]); - - knowledgeList.add(knowledgeJ); - } - - public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { - String pair[] = next.split("-"); - JSONObject nextStepJ = new JSONObject(); - JSONArray exceptJ = new JSONArray(); - - for (int i = 1; i < pair.length; i++) - exceptJ.add(pair[i]); - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - nextStepJ.put("nextStep", pair[0]); - nextStepJ.put("except", exceptJ); - nextStepJ.put("nextStepText", question); - nextStepList.add(nextStepJ); - } - - public JSONObject toJson(Map conditionDescription) { - JSONObject data = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - JSONArray hisPremiseList = new JSONArray(); - - //添加当前对话内容 - for (String premise : curPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise, conditionDescription); - } - data.put("currentPremiseList", curPremiseList); - - //添加已知信息的内容 - for (String premise : hisPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise, conditionDescription); - } - data.put("historyPremiseList", hisPremiseList); - - //添加下一步状态 - - - //添加configName - data.put("configName", configName); - - //添加config状态 - data.put("configStatus", jStatus); - - - boolean doPost = false; - String postURL = "", postType = "all", pair[]; - - for (String feat : feature.split(",")) { - if (feat.startsWith("post")) { - doPost = true; - pair = feat.substring(0, feat.length() - 1).split("\\(", 2); - postURL = pair[1]; - postType = pair[0].split("::")[1]; - }else if(feat.equals("return-0")){ - nextStepStatus = "return-0"; - }else if(feat.equals("activate")){ - nextStepStatus = "activate"; - }else if(feat.equals("activate:after")){ - nextStepStatus = "activate:after"; - } - } - - - data.put("nextStepStatus", statusMap.get(nextStepStatus)); - //添加post参数 - data.put("doPost", doPost); - data.put("postURL", postURL); - data.put("postType", postType); - - //添加回答 - data.put("reply", reply); - - //添加config类别id - data.put("categoryId", 0); - - //添加辅助优先级 - data.put("auxiliaryPriority", auxiliaryPriority); - - //添加更新答案处的信息 - JSONArray knowledgeList = new JSONArray(); - if (!updateKnowledge.equals("")) { - for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge, conditionDescription); - } - } - data.put("updateKnowledge", knowledgeList); - - //添加下一步 - JSONArray nextStepList = new JSONArray(); - for (String next : nextStep.split(",")) { - appendJNextStep(nextStepList, next, conditionDescription); - } - data.put("nextStepList", nextStepList); - - return data; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - - sb.append(curPremise).append("|"); - sb.append(hisPremise); - sb.append("|").append(feature).append(","); - sb.append(updateKnowledge).append(","); - sb.append(nextStepStatus).append( "|"); - sb.append("auxiliaryPriority="); - sb.append(auxiliaryPriority).append("|").append("configName="); - sb.append(configName); - sb.append("|=>|").append(reply); - sb.append("|").append("nextStep="); - sb.append(nextStep).append("|"); - sb.append("status=").append(status); - sb.append("|").append("configId="); - - return sb.toString(); - } - - public Object clone() { - Object o=null; - try{ - o= super.clone(); - }catch(CloneNotSupportedException e){ - System.out.println(e.toString()); - } - return o; - } - - - public static void activateCopy(ConfigTerm configTerm, List configTermList, String name){ - - configTerm.setReply(configTerm.getReply() + "{临时变量reply-2}"); - - - ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); - - if(configTerm2.getUpdateKnowledge().equals("")) - configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); - else - configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - configTerm2.setConfigName(name, true); - - configTermList.add(configTerm2); - - } - - - public ConfigTerm simpleCopy(ConfigTerm configTerm){ - - ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); - - return configTerm2; - } -} diff --git a/src/entity/ConfigurationItem.java b/src/entity/ConfigurationItem.java deleted file mode 100644 index be8bdb6..0000000 --- a/src/entity/ConfigurationItem.java +++ /dev/null @@ -1,5 +0,0 @@ -package entity; - -public class ConfigurationItem { - -} diff --git a/src/entity/Goods.java b/src/entity/Goods.java deleted file mode 100644 index 8a36aa2..0000000 --- a/src/entity/Goods.java +++ /dev/null @@ -1,4 +0,0 @@ -package entity; - -public class Goods { -} diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java deleted file mode 100644 index be49382..0000000 --- a/src/entity/JConfig.java +++ /dev/null @@ -1,495 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class JConfig implements Cloneable{ - - static int iterNum = 0; - - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - - - private String curPremise = ""; - private String hisPremise = ""; - private String feature = ""; - private String reply = ""; - private String nextStep = ""; - private String updateKnowledge = ""; - private String nextStepStatus = "return"; - private String configName = ""; - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - public String getFeature() { - return feature; - } - - public void setFeature(String feature) { - this.feature = feature; - } - - public String getCurPremise() { - return curPremise; - } - - public String getNextStep() { - return nextStep; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName, Boolean append) { - - if(append) { - iterNum++; - this.configName = configName + iterNum; - }else{ - this.configName = configName; - } - } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - - public void setCurPremise(String curPremise) { - this.curPremise = curPremise; - } - - public String getHisPremise() { - return hisPremise; - } - - public void setHisPremise(String hisPremise) { - this.hisPremise = hisPremise; - } - - public String getReply() { - return reply; - } - - public void setReply(String reply) { - this.reply = reply; - } - - public String getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public String getStatus() { - return status; - } - - public String getNextStepStatus() { - return nextStepStatus; - } - - public String getUpdateKnowledge() { - return updateKnowledge; - } - - public void setUpdateKnowledge(String updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - - static Map statusMap = new HashMap() { - { - put("return", "return"); - put("return-1", "back"); - put("return-0", "stay"); - put("activate", "activate"); - put("activate:after", "activate:after"); - } - }; - - public void setStatus(String status) { - this.status = status; - } - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public void setNextStepStatus(String nextStepStatus) { - this.nextStepStatus = nextStepStatus; - } - - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - if (!updateKnowledge.equals("")) - this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); - //if (!updateKnowledge.equals("")) - // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - - public JConfig(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { - this.curPremise = appendPremiseStr(curPremise, extraCP); - this.hisPremise = appendPremiseStr(hisPremise, extraHP); - this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; - this.auxiliaryPriority = auxiliaryPriority; - } - - public String appendPremiseStr(List premises, String extraPM) { - StringBuffer sb = new StringBuffer(); - String premiseStr = ""; - - for (String premise : premises) - sb.append("," + premise); - if (sb.length() > 0) - sb.deleteCharAt(0); //删除第一个逗号 - - - if (!extraPM.equals("")) { - if (sb.length() == 0) - sb.append(extraPM); - else - sb.append("," + extraPM); - } else if (sb.length() == 0) { - sb.append(" "); - } - premiseStr = sb.toString(); - - return premiseStr; - } - - public String appendKnowledgeStr(Map knowledge, String extraKL) { - StringBuffer sb = new StringBuffer(); - String varName = "", varValue = "", knowledgeStr; - Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; - String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; - - while (iit.hasNext()) { - varName = iit.next(); - varValue = knowledge.get(varName); - - if(varValue.startsWith("updateFollowerLocation")){ - delayUpdateFollowerLocation = true; - delayUpdateFollowerLocationKey = varName; - delayUpdateFollowerLocationValue = varValue; - continue; - } - sb.append("-<-").append(varName).append(":").append(varValue); - - } - if (!extraKL.equals("")) { - sb.append("-<-" + extraKL); - } - - if(delayUpdateFollowerLocation){ - sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); - } - - if (sb.length() > 0) - knowledgeStr = "updateKnowledge" + sb.toString(); - else - knowledgeStr = ""; - - return knowledgeStr; - } - - - public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { - //System.out.println(premise); - - String pair1[] = premise.split("=", 2); - String key = pair1[0]; - - String keywords = pair1[1]; - String pair2[] = key.split("::"); - String conditionName = pair2[0]; - String pair3[] = pair2[1].split("-"); - String cmpType = pair3[0]; - String operator = ""; - if (pair3.length > 1) - operator = pair3[1]; - - String question = ""; - if (conditionDescription.get(conditionName) != null) - question = conditionDescription.get(conditionName); - - JSONObject premiseJ = new JSONObject(); - premiseJ.put("keywords", keywords); - premiseJ.put("actionName", conditionName); - premiseJ.put("cmpType", cmpType); - premiseJ.put("question", question); - premiseJ.put("operator", operator); - - premiseList.add(premiseJ); - - } - - public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { - String pair[] = knowledge.split(":", 2); - - if (knowledge.equals("") || pair.length < 2) - return; - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - JSONObject knowledgeJ = new JSONObject(); - knowledgeJ.put("variableName", pair[0]); - knowledgeJ.put("keyword", pair[1]); - - knowledgeList.add(knowledgeJ); - } - - public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { - String pair[] = next.split("-"); - JSONObject nextStepJ = new JSONObject(); - JSONArray exceptJ = new JSONArray(); - - for (int i = 1; i < pair.length; i++) - exceptJ.add(pair[i]); - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - nextStepJ.put("nextStep", pair[0]); - nextStepJ.put("except", exceptJ); - nextStepJ.put("nextStepText", question); - nextStepList.add(nextStepJ); - } - - public JSONObject toJson(Map conditionDescription) { - JSONObject data = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - JSONArray hisPremiseList = new JSONArray(); - - //添加当前对话内容 - for (String premise : curPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise, conditionDescription); - } - data.put("currentPremiseList", curPremiseList); - - //添加已知信息的内容 - for (String premise : hisPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise, conditionDescription); - } - data.put("historyPremiseList", hisPremiseList); - - //添加下一步状态 - - - //添加configName - data.put("configName", configName); - - //添加config状态 - data.put("configStatus", jStatus); - - - boolean doPost = false; - String postURL = "", postType = "all", pair[]; - - for (String feat : feature.split(",")) { - if (feat.startsWith("post")) { - doPost = true; - pair = feat.substring(0, feat.length() - 1).split("\\(", 2); - postURL = pair[1]; - postType = pair[0].split("::")[1]; - }else if(feat.equals("return-0")){ - nextStepStatus = "return-0"; - }else if(feat.equals("activate")){ - nextStepStatus = "activate"; - }else if(feat.equals("activate:after")){ - nextStepStatus = "activate:after"; - } - } - - - data.put("nextStepStatus", statusMap.get(nextStepStatus)); - //添加post参数 - data.put("doPost", doPost); - data.put("postURL", postURL); - data.put("postType", postType); - - //添加回答 - data.put("reply", reply); - - //添加config类别id - data.put("categoryId", 0); - - //添加辅助优先级 - data.put("auxiliaryPriority", auxiliaryPriority); - - //添加更新答案处的信息 - JSONArray knowledgeList = new JSONArray(); - if (!updateKnowledge.equals("")) { - for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge, conditionDescription); - } - } - data.put("updateKnowledge", knowledgeList); - - //添加下一步 - JSONArray nextStepList = new JSONArray(); - for (String next : nextStep.split(",")) { - appendJNextStep(nextStepList, next, conditionDescription); - } - data.put("nextStepList", nextStepList); - - return data; - } - - public String toString() { - - String text = curPremise + "|" + - hisPremise + "|" + - feature + "," + updateKnowledge + "," + nextStepStatus + "|" + - "auxiliaryPriority=" + auxiliaryPriority + "|" + - "configName=" + configName + "|=>|" + - reply + "|" + - "nextStep=" + nextStep + "|" + - "status=" + status + "|" + - "configId="; - - return text; - } - - public Object clone() { - Object o=null; - try{ - o= super.clone(); - }catch(CloneNotSupportedException e){ - System.out.println(e.toString()); - } - return o; - } - - - public static void activateCopy(JConfig jConfig, List jConfigList, String name){ - - jConfig.setReply(jConfig.getReply() + "{临时变量reply-2}"); - - - JConfig jConfig2 = (JConfig) jConfig.clone(); -// if(jConfig.getHisPremise().equals(" ")) -// jConfig.setHisPremise("临时变量condition::match-Include=+null"); -// else -// jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); -// jConfig.setConfigName(name, true); - - if(jConfig2.getUpdateKnowledge().equals("")) - jConfig2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); - else - jConfig2.setUpdateKnowledge(jConfig2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - jConfig2.setConfigName(name, true); - - - //jConfigList.add(jConfig); - jConfigList.add(jConfig2); - - } - - - public static JConfig simpleCopy(JConfig jConfig){ - - JConfig jConfig2 = (JConfig) jConfig.clone(); - - return jConfig2; - } -} diff --git a/src/entity/Npc.java b/src/entity/Npc.java deleted file mode 100644 index dda10d9..0000000 --- a/src/entity/Npc.java +++ /dev/null @@ -1,4 +0,0 @@ -package entity; - -public class Npc { -} diff --git a/src/entity/QuestionKeyWord.java b/src/entity/QuestionKeyWord.java deleted file mode 100644 index c1b9ca6..0000000 --- a/src/entity/QuestionKeyWord.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - - -/** - * 暂时没用 - */ -public class QuestionKeyWord { - private String actionName; - private String chatKey; - private String keyWord; - - public String getActionName() { - return actionName; - } - - public String getChatKey() { - return chatKey; - } - - public String getKeyWord() { - return keyWord; - } - - public void setActionName(String actionName) { - this.actionName = actionName; - } - - public void setChatKey(String chatKey) { - this.chatKey = chatKey; - } - - public void setKeyWord(String keyWord) { - this.keyWord = keyWord; - } -} diff --git a/src/entity/World.java b/src/entity/World.java deleted file mode 100644 index a4e8059..0000000 --- a/src/entity/World.java +++ /dev/null @@ -1,36 +0,0 @@ -package entity; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class World { - - public List queryAroundAllBySite(String site){ return new ArrayList<>();}; // 返回所有模块下的实例名称列表 - public List queryAroundNpcBySite(String site){ return new ArrayList<>();}; // 返回npcname 字符串列表 - public List queryAroundGoodsBySite(String site){ return new ArrayList<>();}; // 返回goodsname 字符串列表 - public List queryCanGoBySite(String site){ return new ArrayList<>();}; //地点名称的列表 - public List queryPathBySite(String start, String destination){ return new ArrayList<>();}; // 返回一条,地点名称的列表 - - - public boolean addGoodsBase(String categoryName, String instanceName, String goodsIntro){ return true;};; // 添加成功为 true,否则false - public boolean deleteGoods(String categoryName, String instanceName){ return true;};; // 删除成功为 true,否则false - public boolean updateGoodsBase(String categoryName, String instanceName, String goodsIntro){ return true;};; // 更新成功为 true,否则false - public String queryGoodsIntro(String name, String site){ return "";};; // 返回一个物品简介 - public String queryAttrByGoodsName(String name, String attrName, String site){ return "";}; // - public List queryAllAttrByGoodsName(String name, String site){ return new ArrayList<>();}; // 获得所有属性名称列表 - public boolean updateAttrByGoodsName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 更新成功为 true,否则false - public boolean addAttrByGoodsName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 添加成功为 true,否则false - public boolean deleteAttrByGoodsName(String categoryName, String instanceName, String attrName){ return true;}; // 删除成功为 true,否则false - - - public boolean addNpc(String categoryName, String instanceName, String npcIntro){ return true;}; // 添加成功为 true,否则false - public boolean deleteNpc(String categoryName, String instanceName){ return true;}; // 删除成功为 true,否则false - public boolean updateNpc(String categoryName, String instanceName, String npcIntro){ return true;}; // 更新成功为 true,否则false - public String queryNpcIntro(String categoryName, String instanceName){ return "";}; // 返回一个npc简介 - public String queryAttrByNPCName(String categoryName, String instanceName, String attrName){ return "沙滩";}; // 返回npc属性值 - public boolean updateLocationByNPCName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 更新成功为 true,否则false - public boolean addAttrByNPCName(String categoryName, String instanceName, String attrName,String value){ return true;}; // 添加成功为 true,否则false - public boolean deleteAttrByNPCName(String categoryName, String instanceName, String attrName){ return true;}; // 删除成功为 true,否则false - -} diff --git a/src/gameDesign/GameUtil.java b/src/gameDesign/GameUtil.java deleted file mode 100644 index cb04909..0000000 --- a/src/gameDesign/GameUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.processing.LogWriter; -import com.qiwu.chatbotbackend.processing.WorldController; - -import java.util.Map; - -public class GameUtil { - - public GameEnv gameEnv = null; - public Map curInfoPoint = null; - public Map historyInfoPoint = null; - public WorldController worldController = null; - - public GameUtil(GameEnv gameEnv, WorldController worldController, Map curInfoPoint, Map historyInfoPoint) { - this.gameEnv = gameEnv; - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; - this.worldController = worldController; - } - - public void gamePreprocessing(LogWriter logWriter){ - - } - - public void gamePostprocessing(LogWriter logWriter){ - - } -} diff --git a/src/gameDesign/MapConstructor2.java b/src/gameDesign/MapConstructor2.java deleted file mode 100644 index 8e57a13..0000000 --- a/src/gameDesign/MapConstructor2.java +++ /dev/null @@ -1,560 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -public class MapConstructor2 extends ElementConstructor { - - String nickname = "qiwu"; - int[][] matrix; - int locationNum; - HashMap id2j = new HashMap(); - Map question2keyword = new HashMap(); - Map> name2nickname = new HashMap>(); - JSONArray locations = null; - - Map script = null; //话术模板 - - - - public MapConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - - public void constructGreph(JSONArray locations) { - - JSONObject jobj = null; - int locationId, index; - String locationName, taskLineName = ""; - - locationNum = locations.size(); - StringBuffer nameSet = null; - keywordMap.putIfAbsent("site_list", new StringBuffer()); - - for (int i = 0; i < locationNum; i++) { - jobj = locations.getJSONObject(i); - jobj.put("index", i); - locationName = (String) jobj.get("name"); - keywordMap.get("site_list").append("+").append(locationName); - - - taskLineName = String.format(PlotConstructor.TASK_LINE, locationName); - - - if (!varInitialMap.containsKey(taskLineName)) { - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, ""); - } - - nameSet = new StringBuffer(); - nameSet.append(locationName); - name2nickname.putIfAbsent(locationName, new ArrayList<>()); - POS.append("=" + locationName + "|地名\r\n"); - if(jobj.containsKey("nickname")){ - - for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ - if(!nickname.equals("")) { - nameSet.append("+").append(nickname); - POS.append("=").append(nickname).append("|地名\r\n"); - name2nickname.get(locationName).add(nickname); - } - } - } - jobj.put("nameSet", nameSet.toString()); - - locationId = (Integer) jobj.get("id"); - id2j.put(locationId, jobj); - } - - //邻接矩阵初始化 - matrix = new int[locationNum][locationNum]; - for (int i = 0; i < locationNum; i++) { - for (int j = 0; j < locationNum; j++) { - matrix[i][j] = Integer.MAX_VALUE; - } - } - - for (int i = 0; i < locationNum; i++) { - List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); - for (int neighbourId : neighbours) { - JSONObject neighbourObject = id2j.get(neighbourId); - System.out.println(neighbourObject); - index = (Integer) neighbourObject.get("index"); - matrix[i][index] = 1; - matrix[index][i] = 1; - } - } - } - - - public void construct(JSONObject gameElements, UserInfo userinfo) { - - try { - - conditionDescription.put("site", "当前地点"); - - JSONObject map = gameElements.getJSONObject("map"); - Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); - script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); - - if(!script.containsKey("PATH_AT")) - script.put("PATH_AT", "你已经在[地点名]了"); - if(!script.containsKey("WHERE_I_AM")) - script.put("WHERE_I_AM", "在[地点名]"); - if(!script.containsKey("PATH_ADJOINT")) - script.put("PATH_ADJOINT", "就在附近哦"); - if(!script.containsKey("PATH_EXIST")) - script.put("PATH_EXIST", "通过[途径]可以到达[目的地]"); - if(!script.containsKey("PATH_NOT_EXIST")) - script.put("PATH_NOT_EXIST", "不可到达"); - if(!script.containsKey("CAN_GO_SITES")) - script.put("CAN_GO_SITES", "你可以去[可去列表]"); - if(!script.containsKey("CAN_GO_NOWHERE")) - script.put("CAN_GO_NOWHERE", "没什么地方可去的,继续玩吧"); - if(!script.containsKey("SITE_NOT_ACTIVE")) - script.put("SITE_NOT_ACTIVE", "你来到了[地点名]"); - if(!script.containsKey("SITE_NOT_ADJOINT")) - script.put("SITE_NOT_ADJOINT", "通过[途径]可以到达[目的地]"); - if(!script.containsKey("AROUND_PEOPLE")) - script.put("AROUND_PEOPLE", "周围有[人物列表]"); - if(!script.containsKey("AROUND_ITEMS")) - script.put("AROUND_ITEMS", "周围有[物品列表]"); - if(!script.containsKey("AROUND_THINGS")) - script.put("AROUND_THINGS", "周围有[人物物品列表]"); - if(!script.containsKey("FIND_ITEM_LOCATION")) - script.put("FIND_ITEM_LOCATION", "[物品名]在[地点]"); - if(!script.containsKey("FIND_NPC_LOCATION")) - script.put("FIND_NPC_LOCATION", "[人名]在[地点]"); - if(!script.containsKey("AROUND_PLACE")) - script.put("AROUND_PLACE", "周围有[地点列表]"); - if(!script.containsKey("FIND_ITEM_WAY")) - script.put("FIND_ITEM_WAY", "[人名]在[地点]"); - if(!script.containsKey("FIND_NPC_WAY")) - script.put("FIND_NPC_WAY", "[物品名]在[地点]"); - if(!script.containsKey("GET_ITEM_ATTR")) - script.put("GET_ITEM_ATTR", "[物品名]的[属性名]是[属性值]"); - if(!script.containsKey("WE_HAVE")) - script.put("WE_HAVE", "我们有[物品列表]"); - if(!script.containsKey("GET_NPC_ATTR")) - script.put("GET_NPC_ATTR", "[人名]的[属性名]是[属性值]"); - if(!script.containsKey("INNER_PEOPLE")) - script.put("INNER_PEOPLE", "里面有[人物列表]"); - if(!script.containsKey("WHO_YOU_ARE")) - script.put("WHO_YOU_ARE", "我是[人名]"); - if(!script.containsKey("TASK_DESCRIPTION")) - script.put("TASK_DESCRIPTION", "我们的任务是[任务描述]"); - - - if(script == null){ - throw new Exception("话术不存在"); - } - JSONArray locations = map.getJSONArray("locations"); - String userName = (String) gameElements.get("userName"); - this.locations = locations; - this.question2keyword = question2keyword; - //通过邻接表构造邻接矩阵 - constructGreph(locations); - - //用弗洛伊德算法求最短路径 - Floyd floyd = new Floyd(); - floyd.findShortestPath(matrix, locationNum); - floyd.printPath(matrix, locationNum); - generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereIam(gameElements, userName, keywordMap); - generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateSurroundingItem(keywordMap); - generateSurroundingPeople(keywordMap); - generateSurroundThings(keywordMap); - generateSurroundPlace(keywordMap); - generateWeHave(keywordMap); - generateInnerPeople(keywordMap); - generateTaskDescription(keywordMap); - - - } catch(Exception e){ - operationStatus = 0; - e.printStackTrace(); - message = "地图处理出现异常:"; - return; - } - - } - - /** - * 生成‘我在哪里’所需要的配置文件 - */ - public void generateWhereIam(JSONObject gameElements, String botAccount, Map keywordMap) { - String conditionNameList[] = {"zainali", "wenzainali"}; - String conditionKeywords = ""; - - - for(String condition:conditionNameList) { - - conditionKeywords = keywordMap.get("map_" + condition).toString(); - - jConfig = new JConfig( - condition + "::match-Include=" + conditionKeywords, " ", - "match", "", "yaobuyao", - "map_query:queryWhereIam:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - } - - - } - - - - /** - * 生成‘怎么去哪里’所需要的配置文件 - */ - public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String conditionName = "want_know_zenmezuo"; - StringBuffer placeKeywords = new StringBuffer(); - - String nameSet; - - - for (int i = 0; i < locationNum; i++) { - nameSet = (String) locations.getJSONObject(i).get("nameSet"); - placeKeywords.append("+").append(nameSet); - } - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", - " " , - "match,return-0", - "", - " ", - "map_query:queryPathAdjoin:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=2", - " " , - "match,return-0", - "", - " ", - "map_query:queryHowToPathBySite:" + conditionName - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - } - - - /** - * 生成‘我能去哪里’所需要的配置文件 - */ - public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String conditionName = "choose_gowhere"; - String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); - - String placeA, placeB, pathNode; - - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryCanGoBySite:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘我要去那里’所需要的配置文件 - */ - public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply; - String conditionName = "yaobuyao"; - String conditionKeywords = "地点"; - String start = (String) gameElements.get("start"); - String placeKeywords; - - //包含去xx的所有地点的关键词集合 - StringBuffer toAllSiteskeywords = new StringBuffer(); - - //包含去xx这个特定地点的关键词的集合(包含别名) - StringBuffer toSitekeywords = new StringBuffer(); - - - String goRelateConditions[] = {"yaobuyao"}; - String gotoMapptern = keywordMap.get("map_" + goRelateConditions[0]).toString(), gotoSite = ""; - - - for (int i = 0; i < locationNum; i++) { - toSitekeywords.setLength(0); - placeA = (String) locations.getJSONObject(i).get("name"); - gotoSite = gotoMapptern.replace("name", placeA); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - for (String nickname : name2nickname.get(placeA)) { - gotoSite = gotoMapptern.replace("name", nickname); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - } - - lastTaskCondition = String.format(PlotConstructor.TASK_CONDITION, placeA); - lastTaskReply = String.format(PlotConstructor.TASK_REPLY, placeA); - - - //地点任务和地点回答的初始化 - if (!varInitialMap.containsKey(lastTaskCondition)) { - varInitialMap.put(lastTaskCondition, goRelateConditions[0]); - varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); - conditionDescription.put(lastTaskCondition, lastTaskCondition); - conditionDescription.put(lastTaskReply, lastTaskReply); - } - - - /** - * 要去某个地方,并且该地点相邻或者可以直接到达 - */ - conditionName = goRelateConditions[0]; - jConfig = new JConfig( - conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", - - " ", - "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" - - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - //上一个配置文件激活时的默认选项 - jConfig = new JConfig( - " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA - + "-<-npc_update:updateFollowerLocation:" + placeA - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + placeA + "_doudi", false); - jConfig.setjStatus(1); - jConfigList.add(jConfig); - - - } - - /** - * 要去的地方就在当前地点 - */ - jConfig = new JConfig( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - /** - * 要去的地方要经过几个地点才能到达 - */ - jConfig = new JConfig( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=2", - " ", - "match,return-0", - "", - " ", - "map_query:queryToDoPathBySite:" + conditionName - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - } - - - - /** - * 生成‘周围有什么人’所需要的配置文件 - */ - public void generateSurroundingPeople(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("people_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundNpcBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘周围有什么物品’所需要的配置文件 - */ - public void generateSurroundingItem(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("item_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundGoodsBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘周围有什么(包含人和物品)’所需要的配置文件 - */ - public void generateSurroundThings(Map keywordMap){ - String conditionName = "know_exist_what_mohu"; - String conditionKeywords = keywordMap.get("things_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundAllBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘周围有什么地点’所需要的配置文件 - */ - public void generateSurroundPlace(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("place_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryAroundPlace:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘我们有什么’所需要的配置文件 - */ - public void generateWeHave(Map keywordMap){ - String conditionName = "know_exist_what_mohu"; - String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "goods_query:queryPlayerItems:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘里面有什么人’所需要的配置文件 - */ - public void generateInnerPeople(Map keywordMap){ - - - //与里面有谁相关的condition - String innerNPCRelateConditions[] = {"shishui"}; - - keywordMap.putIfAbsent("inner_shishui", new StringBuffer()); - String conditionName = "shishui"; - String conditionKeywords = keywordMap.get("inner_" + conditionName).toString(); - - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryInnerNpcBySite:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘我们的任务是什么’所需要的配置文件 - */ - public void generateTaskDescription(Map keywordMap){ - - - //与里面有谁相关的condition - String innerNPCRelateConditions[] = {}; - - keywordMap.putIfAbsent("task_shishenme", new StringBuffer()); - String conditionName = "shishenme"; - String conditionKeywords = keywordMap.get("task_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryTaskDescription:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - -} \ No newline at end of file diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java deleted file mode 100644 index 9537a9f..0000000 --- a/src/gameDesign/PlotConstructor.java +++ /dev/null @@ -1,790 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.io.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - - -public class PlotConstructor extends ElementConstructor { - - public static String ASSISTANT = "globalVariable_智能助手"; - public static String ASSISTANT_EMOTION = "正常"; - public static String TASK_DESCRIPTION = "globalVariable_任务"; - - public static String TALKER_PATTERN = "【%s@%s】"; - String GAME_STEP_FORMAT = "%s_plot_%s"; - - JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); - private HashMap plotIndex = new HashMap(); - private HashMap plotTextIndex = new HashMap(); - HashMap visited = new HashMap(); - - - public static String TASK_LINE = "任务线_%s进度"; - public static String TASK_CONDITION = "任务线%s最后一个condition"; - public static String TASK_REPLY = "任务线%s最后的回答"; - - - public PlotConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - try { - addGameStartPlot(jsonObject, keywordMap); - - JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"), startCondition; - JSONObject returnMessage = null; - - - - - this.plots = plots; - constructAdjList(plots); - - if (plotIndex.containsKey(start)) { - String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; - conditionDescription.put(taskLineName, taskLineName); - - if(jsonObject.get("firstUnknownText") == null) - varInitialMap.put("unknownText", "你说啥?"); - else - varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - - - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - conditionDescription.put("game_step", "QA问答游戏进度"); - - BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); - - varInitialMap.put(start, "1"); - - - } else { - System.out.println("start剧情不存在"); - operationStatus = 0; - message = "开始剧情不存在,请到剧情列表设置"; - return; - } - - - - } catch(Exception e){ - operationStatus = 0; - message = "剧情接口处理出现异常"; - e.printStackTrace(); - return; - } - } - - //根据id构造邻接表 - public void constructAdjList(JSONArray plots) { - int length = plots.size(), branchSize; - String id = "", nextPlotId = "", nextPlotText; - JSONObject plot = null; - JSONArray branch = null; - - for (int i = 0; i < length; i++) { - plot = plots.getJSONObject(i); - id = (String) plot.get("id"); - plot.put("index", i); - - if (adjList.get(id) == null) { - adjList.put(id, new ArrayList<>()); - } - - //添加branch中的下一个plot - branch = plot.getJSONArray("branch"); - branchSize = branch.size(); - for (int j = 0; j < branchSize; j++) { - nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); - nextPlotText = branch.getJSONObject(j).getString("reply"); - plotTextIndex.put(nextPlotId, nextPlotText); - if (revAdjList.get(nextPlotId) == null) { - revAdjList.put(nextPlotId, new ArrayList<>()); - } - varSlotFilt(branch.getJSONObject(j), keywordMap); - adjList.get(id).add(nextPlotId); - revAdjList.get(nextPlotId).add(id); - - } - plotIndex.put(id, plot); - } - } - - /** - * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 - * @param branchNode - */ - public static void varSlotFilt(JSONObject branchNode, Map keywordMap){ - - - String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; - Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); - Matcher m = replacePattern.matcher(branchNode.getString("reply")); - while (m.find()) { - npcName = m.group(1); - //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 - //System.out.println("npcName" + npcName); - //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); - if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { - varSlot = m.group(3); - middleText = m.group(2); - branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); - } - - } - } - - - - /** - * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 - * 加上剧情计数器, null时未激活,大于等于1时表示已激活 - * @param root - * @param userinfo - */ - public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { - String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, nextGameStep, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation, extraBeforeJumpUK; - JSONObject node = null, branchNode = null, adjNode = null; - StringBuffer skipText = new StringBuffer(); - String extraHP = "", extraUK = "", extraFT = ""; - JSONArray branch = null; - - - int branchSize; - - List curPremiseList, historyPremiseList; - - root.put("nextUnknownText", varInitialMap.get("unknownText")); - root.put("parentId", "null"); - jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); - - if(root.get("conditionName") != null && !root.get("conditionName").equals("")) - conditionName = (String)root.get("conditionName"); - else{ - conditionName = "yaobuyao"; - root.put("conditionName", conditionName); - } - - - - String startPlace = ((String)root.get("place")).split("\\+")[0]; - String startTaskLine = String.format(PlotConstructor.TASK_LINE, startPlace); - String startTaskCondition = String.format(PlotConstructor.TASK_CONDITION, startPlace); - String startTaskReply = String.format(PlotConstructor.TASK_REPLY, startPlace); - varInitialMap.put("site", startPlace); - varInitialMap.put(startTaskLine, rootId); - varInitialMap.put(startTaskCondition, ""); - varInitialMap.put(startTaskReply, ""); - conditionDescription.put(startTaskLine, startTaskLine); - conditionDescription.put(startTaskCondition,startTaskCondition); - conditionDescription.put(startTaskReply, startTaskReply); - - - - //generateStartGame(root, jsonObject, startPlace, conditionName); - Queue queue = new LinkedList(); - Map autoJumpUpdateKnowledge = new HashMap(); - - queue.add(root); - - while (!queue.isEmpty()) { - node = queue.remove(); - id = (String) node.get("id"); - location = ((String) node.get("place")).split("\\+")[0]; - conditionName = (String) node.get("conditionName"); - curUnknownText = (String) node.get("nextUnknownText"); - taskLineName = String.format(PlotConstructor.TASK_LINE, location); - conditionDescription.put(id, "剧情" + id + "状态"); - varInitialMap.put(id ,""); - - //本任务线的最后一个condition和本任务线的最后一个回答 - - - - - branch = node.getJSONArray("branch"); - branchSize = branch.size(); - - - - for (int i = 0; i < branchSize; i++) { - - System.out.println("branch:" + i); - skipText.setLength(0); - - branchNode = branch.getJSONObject(i); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - - //System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString()); - - nextUnknownText = updateKnowledge.get("unknownText"); - //System.out.println(id + "分支内" +nextUnknownText); - nextId = (String)branchNode.get("nextPlotId"); - //skipText.append(); - - - if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ - nextId = id + "_end"; - branchNode.put("nextPlotId", nextId); - createEndNode(node, id, nextId, curUnknownText); - } - - //保留下一步剧情的地点 - beforeJumpLocatin = ((String)plotIndex.get(nextId).get("place")).split("\\+")[0]; - autoJumpUpdateKnowledge.clear(); - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ - nextId = (String)branchNode.get("nextPlotId"); - JSONObject jumpNextNode = plotIndex.get(nextId); - JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); - - skipText.append((String)branchNode.get("reply")); - branchNode.put("reply", jumpBranchNode.get("reply")); - Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); - autoJumpUpdateKnowledge.putAll(newUpdateKnowledge); - - nextUnknownText = (String)newUpdateKnowledge.get("unknownText"); - System.out.println("循环内" +nextUnknownText); - //updateKnowledge.putAll(newUpdateKnowledge); - - - jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); - - //如果下一步剧情存在 - if(jumpNextNextId != null && !jumpNextNextId.equals("") && plotIndex.containsKey(jumpNextNextId)){ - System.out.println(jumpNextNextId); - System.out.println(plotIndex.get(jumpNextNextId)); - jumpNextNextLocation = (String)plotIndex.get(jumpNextNextId).get("place"); - - autoJumpUpdateKnowledge.put("site", jumpNextNextLocation); - autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); - branchNode.put("autoJump", jumpBranchNode.get("autoJump")); - - }else { - jumpNextNextId = nextId + "_end"; - jumpBranchNode.put("nextPlotId", jumpNextNextId); - createEndNode(node, nextId, jumpNextNextId, curUnknownText); - branchNode.put("autoJump", false); - - } - - branchNode.put("nextPlotId", jumpNextNextId); - } - - - nextId = (String) branchNode.get("nextPlotId"); - - reply = (String)branchNode.get("reply"); - if(reply.equals("")) - reply = curUnknownText; - - - - //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - nextCondition = (String) plotIndex.get(nextId).get("conditionName"); - if(nextCondition.equals("")) - nextCondition = "yaobuyao"; - - nextLocation = ((String) plotIndex.get(nextId).get("place")).split("\\+")[0]; - - //任务线 - nTaskLineName = String.format(TASK_LINE, nextLocation); - //任务线最后一个condition - lastTaskCondition = String.format(TASK_CONDITION, nextLocation); - lastTaskReply = String.format(TASK_REPLY, nextLocation); - - - /** - * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: - * 1: 将剧情停留在最后一步剧情 - * 2. 设一个专门的剧情表示剧情的结尾 - */ - - //现在暂时放开下一步剧情未发生过的限制条件 - //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; - extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText; - - if(!beforeJumpLocatin.equals(nextLocation)) { - //extraBeforeJumpUK = - } - if(nextId.endsWith("_end")) - nextGameStep = id; - else - nextGameStep = nextId; - - - /** - * 1. 主角是否随剧情移动 - * 如果随剧情移动,则更新地点和game_step - * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 - * - * 2. 当前条件是否为空 - * 如果当前条件为空,则提交qa激活并进入下一步剧情 - * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 - * - * 3. 下一部剧情是否为空 - * - * - * 4. 有没有说去XX - * - * 主角不随剧情移动+当前条件为空+去沙滩 - * 1、沙滩无剧情 - * 2、沙滩有剧情 - * - * 5. 地点变化 - * 1. 当前所处地点 - * 2. 下一步剧情所处地点(包含自动跳转的情况) - * 3. 自动跳转完成后的地点 - */ - - /** - * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) - * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) - * 2. 自动跳转剧情文本保存到beforeJumpTaskReply - * 3. 当前剧情和下一步剧情更新状态 - */ - - String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin); - String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin); - String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; - - if(branchNode.containsKey("activateExtraPlot")) { - //激活除了下一步剧情以外的剧情 - beforeJumpUK = extraActivatedPlot(beforeJumpUK, nextLocation, JSONArray.parseArray(branchNode.getJSONArray("activateExtraPlot").toJSONString(), String.class)); - } - - - //如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新 - if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) { - extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep); - - - - - //自动跳转剧情如果有更新属性,这些数据也需要更新 - updateKnowledge.putAll(autoJumpUpdateKnowledge); - - }else { - - //任务线最后一个condition - - - - - /** - * 注意,比较的是当前地点和跳转前的地点 - * 地点更新为跳转后的地点 - */ - //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!location.equals(beforeJumpLocatin)){ - //System.out.println(id + "报异常" + curUnknownText); - if(curUnknownText.equals("")) { - reply = "请到" + beforeJumpLocatin; - //如果当前地点和下一步剧情地点不同,要提示 - }else { - reply = curUnknownText; - } - - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - - - jConfig = new JConfig( - "yaobuyao::match-Keyword=+" + beforeJumpLocatin, - "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1, - "match", (String)branchNode.get("reply"), (String) nextCondition, - extraUK + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep) - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation, autoJumpUpdateKnowledge - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + beforeJumpLocatin + "_" + id,false); - jConfig.setjStatus(1); - - jConfigList.add(jConfig); - - - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - updateKnowledge.remove("unknownText"); - updateKnowledge.remove("site"); - extraUK = beforeJumpUK; - - //如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说 - skipText.setLength(0); - - //必须在上一个jConfig添加完之后 - //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); - - } - } - - - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); - - - - extraFT = ""; - //是否将当前识别到的数据加入到已知数据列表 - if((Boolean)branchNode.get("includeCurInfo")){ - extraFT += ",includeCurInfo"; - } - - if(branchNode.get("extraFeature") != null){ - extraFT += "," + branchNode.getString("extraFeature"); - } - - jConfig = new JConfig( - curPremiseList, - historyPremiseList, - updateKnowledge, - "", extraHP, extraUK, - "match"+extraFT, reply, (String) nextCondition, "1" - ); - - - //当剧情没有条件限制时的操作 - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){ - unconditionalPlotProcess(jConfig, nextCondition); - } - if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) - jConfig.setAuxiliaryPriority("3"); - jConfigList.add(jConfig); - - - - //将子结点加入队列 - adjId = (String) branchNode.get("nextPlotId"); - if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { - visited.put(adjId, true); - adjNode = plotIndex.get(adjId); - - adjNode.put("parentId", id); - //System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText); - adjNode.put("nextUnknownText", nextUnknownText); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); - varInitialMap.put(adjId, ""); - } - - - } - - - } - - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 不设剧情不设条件时的处理 - * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 - * 2. 如果qa返回小于90则只回答剧情文本 - * 3. 如果qa返回not_found则只回答剧情文本 - * 4. 无论哪种情况都会跳下一步剧情 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 待激活列表,用于qa问答 - */ - - //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - jConfig.setNextStepStatus("active"); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - //--------------------------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------------------------- - - - /** - * ---------------------------------------------------------------------------------------------------- - * 用于存档 - */ - jConfig = new JConfig( - "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" - ); - jConfig.setAuxiliaryPriority("4"); - jConfigList.add(jConfig); - - - } - - /** - * 游戏开始的配置 - */ - public void generateStartGame(JSONObject root, JSONObject jsonObject, String startPlace, String conditionName){ - - //用于开始游戏的配置 - jConfig = new JConfig( - "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - (String)jsonObject.get("plotStartText"), - conditionName, - "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - "请说开始游戏或者继续游戏", - "start_options", - "" - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - } - - @Override - public void postProcessing(List idList, int categoryId){ - } - - public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ - - String condition = (String) node.get("conditionName"); - String location = ((String) node.get("place")).split("\\+")[0]; - - String nextCondition = condition; - String nextLocation = location; - String nTaskLineName = String.format(TASK_LINE, nextCondition); - - - JSONObject endNode = new JSONObject(); - endNode.put("place", location); - endNode.put("conditionName", condition); - endNode.put("id", nextId); - endNode.put("reply", nextUnknownText); - endNode.put("includeCurInfo", true); - endNode.put("updateKnowledge", new ArrayList()); - - - plotIndex.put(nextId, endNode); - visited.put(nextId, true); - - } - - void addGameStartPlot(JSONObject gameElements, Map keywordMap){ - - - File file = null; - FileReader fr = null; - BufferedReader br = null; - try { - file = new File("gameconfig.txt"); - fr = new FileReader(file); - - br = new BufferedReader(fr); - String jsonStr = br.readLine(); - - jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); - jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); - jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); - jsonStr = jsonStr.replace("startId", gameElements.getString("start")); - jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); - JSONObject config = JSONObject.parseObject(jsonStr); - - System.out.println(config.toJSONString()); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); - gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); - gameElements.put("start", "start1"); - gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); - - - br.close(); - fr.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - - //如果是无条件剧情,那么需要跟着一个激活操作 - public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); - jConfig.setNextStep("queryskip*,map*,item*,npc*"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - jConfig.setNextStepStatus("active"); - } - - public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ - int strLen = premiseStr.length(); - - - if(strLen == 0 || strLen == 1){ - premiseStr = new StringBuffer(); - }else{ - premiseStr.append(","); - } - - premiseStr.append(conditionName); - premiseStr.append("::"); - premiseStr.append(cmpType); - premiseStr.append("-"); - premiseStr.append(operator); - premiseStr.append("="); - premiseStr.append(value); - - } - - public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ - knowledgeStr.append("-<-"); - knowledgeStr.append(key); - knowledgeStr.append(":"); - knowledgeStr.append(value); - - } - - public String extraActivatedPlot(String updateKnowledge, String nextPlotLocation, List activateExtraPlot){ - JSONObject plot = null; - String location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = ""; - StringBuffer newUK = new StringBuffer(updateKnowledge); - for(String plotId:activateExtraPlot){ - plot = plotIndex.get(plotId); - conditionName = plot.getString("conditionName"); - location = plot.getString("location"); - plotText = plotTextIndex.get(plotId); - - lastTaskCondition = String.format(TASK_CONDITION, location); - lastTaskReply = String.format(TASK_REPLY, location); - - newUK.append("-<-").append(lastTaskCondition).append(":").append(conditionName).append("-<-").append(lastTaskReply).append(":").append(plotText); - - } - - return newUK.toString(); - - } - - - -} diff --git a/src/gameDesign/PlotConstructor3.java b/src/gameDesign/PlotConstructor3.java deleted file mode 100644 index 4d20473..0000000 --- a/src/gameDesign/PlotConstructor3.java +++ /dev/null @@ -1,573 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.FormsPoster; -import org.apache.http.message.BasicNameValuePair; -import com.qiwu.chatbotbackend.processing.MyFunc; - -import java.io.UnsupportedEncodingException; -import java.util.*; - -import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL; - - -public class PlotConstructor3 extends ElementConstructor { - - public static String ASSISTANT = "globalVariable_默认_智能助手"; - public static String TASK_DESCRIPTION = "globalVariable_默认_任务"; - - public static String TALKER_PATTERN = "【%s】"; - String GAME_STEP_FORMAT = "%s_plot_%s"; - - JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); - private HashMap id2j = new HashMap(); - HashMap visited = new HashMap(); - - - - public static String TASK_LINE = "任务线_%s进度"; - public static String TASK_CONDITION = "任务线%s最后一个condition"; - public static String TASK_REPLY = "任务线%s最后的回答"; - - public HashMap getId2j() { - return id2j; - } - - public PlotConstructor3(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - try { - JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"), startCondition; - JSONObject returnMessage = null; - - this.plots = plots; - constructAdjList(plots); - - if (id2j.containsKey(start)) { - String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; - conditionDescription.put(taskLineName, taskLineName); - - if(jsonObject.get("firstUnknownText") == null) - varInitialMap.put("unknownText", "你说啥?"); - else - varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - - - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id"))); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - conditionDescription.put("game_step", "QA问答游戏进度"); - - - BFSGenerate4(id2j.get(start), userinfo, jsonObject); - - varInitialMap.put(start, "1"); - - - - - - } else { - System.out.println("start剧情不存在"); - operationStatus = 0; - message = "开始剧情不存在,请到剧情列表设置"; - return; - } - - - - } catch(Exception e){ - operationStatus = 0; - message = "剧情接口处理出现异常"; - e.printStackTrace(); - return; - } - } - - //根据id构造邻接表 - public void constructAdjList(JSONArray plots) { - int length = plots.size(), branchSize; - String id = "", nextPlotId = ""; - JSONObject plot = null; - JSONArray branch = null; - - for (int i = 0; i < length; i++) { - plot = plots.getJSONObject(i); - id = (String) plot.get("id"); - plot.put("index", i); - - if (adjList.get(id) == null) { - adjList.put(id, new ArrayList<>()); - } - - //添加branch中的下一个plot - branch = plot.getJSONArray("branch"); - branchSize = branch.size(); - for (int j = 0; j < branchSize; j++) { - nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); - if (revAdjList.get(nextPlotId) == null) { - revAdjList.put(nextPlotId, new ArrayList<>()); - } - adjList.get(id).add(nextPlotId); - revAdjList.get(nextPlotId).add(id); - - } - id2j.put(id, plot); - } - } - - - - /** - * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 - * 加上剧情计数器, 每一步分为三个状态 - * @param root - * @param userinfo - */ - public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { - String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", extraFT, nextTaskName, keywordOptions, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, jumpLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - Boolean newBranch, manyParent, autoJump, includeCurInfo; - JSONObject node = null, branchNode = null, adjNode = null; - StringBuffer skipText = new StringBuffer(); - JSONArray branch = null; - - - List adjNodeList = null; - int priority, taskStep, nextPriority, nextTaskStep, branchSize; - - List curPremiseList, historyPremiseList; - - root.put("nextUnknownText", varInitialMap.get("unknownText")); - root.put("parentId", "null"); - jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); - - if(root.get("conditionName") != null && !root.get("conditionName").equals("")) - conditionName = (String)root.get("conditionName"); - - - String startPlace = ((String)root.get("place")).split("\\+")[0]; - varInitialMap.put("site", startPlace); - varInitialMap.put("任务线" + startPlace + "最后一个condition", ""); - varInitialMap.put("任务线" + startPlace + "最后的回答", ""); - conditionDescription.put("任务线" + startPlace + "最后一个condition","任务线" + startPlace + "最后一个condition"); - conditionDescription.put("任务线" + startPlace + "最后的回答", "任务线" + startPlace + "最后的回答"); - - - - //用于开始游戏的配置 - jConfig = new JConfig( - "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - (String)jsonObject.get("plotStartText"), - conditionName, - "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - "请说开始游戏或者继续游戏", - "start_options", - "" - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - - - Queue queue = new LinkedList(); - - queue.add(root); - - while (!queue.isEmpty()) { - node = queue.remove(); - id = (String) node.get("id"); - parentId = (String) node.get("parentId"); - location = ((String) node.get("place")).split("\\+")[0]; - jumpLocation = location; - conditionName = (String) node.get("conditionName"); - curUnknownText = (String) node.get("nextUnknownText"); - taskLineName = "任务线_" + location + "进度"; - conditionDescription.put(id, "剧情" + id + "状态"); - varInitialMap.put(id ,""); - nextUnknownText = ""; - skipText = new StringBuffer(); - //本任务线的最后一个condition和本任务线的最后一个回答 - - - - if (!varInitialMap.containsKey(taskLineName)) { - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, ""); - } - - //初始化 - newBranch = false; - manyParent = false; - - adjNodeList = adjList.get(id); - visited.put(id, true); - - - branch = node.getJSONArray("branch"); - branchSize = branch.size(); - //当两次出现unknown时给用户一下候选项 - keywordOptions = ""; - - String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation; - - - for (int i = 0; i < branchSize; i++) { - - branchNode = branch.getJSONObject(i); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - beforeJumpLocatin = (String)branchNode.get("place"); - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ - nextId = (String)branchNode.get("nextPlotId"); - JSONObject jumpNextNode = id2j.get(nextId); - JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); - - skipText.append((String)jumpBranchNode.get("reply")); - Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); - updateKnowledge.putAll(newUpdateKnowledge); - - - jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); - - if(jumpNextNextId != null && !jumpNextNextId.equals("")){ - jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place"); - - jumpLocation = jumpNextNextLocation; - updateKnowledge.put("site", jumpNextNextLocation); - updateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); - - } - - branchNode.put("autoJump", jumpBranchNode.get("autoJump")); - branchNode.put("nextPlotId", jumpNextNextId); - - } - - nextId = (String) branchNode.get("nextPlotId"); - reply = (String)branchNode.get("reply"); - - if(updateKnowledge.containsKey("unknownText")) - nextUnknownText = updateKnowledge.get("unknownText"); - else - nextUnknownText = "unknown"; - - - //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - if (id2j.get(nextId) != null) { - nextCondition = (String) id2j.get(nextId).get("conditionName"); - if(nextCondition.equals("")) - nextCondition = "yaobuyao"; - nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0]; - nTaskLineName = "任务线_" + nextLocation + "进度"; - } else { - //如果不存在下一剧情,就将condition设为空,任务线进度不变 - - nextId = id; - nTaskLineName = taskLineName; - nextLocation = location; - nextCondition = "yaobuyao"; - branchNode.put("reply", curUnknownText); - reply = curUnknownText; - branchNode.put("moveWithPlot", false); - } - - lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; - lastTaskReply = "任务线" + nextLocation + "最后的回答"; - - - /** - * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: - * 1: 将剧情停留在最后一步剧情 - * 2. 设一个专门的剧情表示剧情的结尾 - */ - - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; - if(!id.equals(nextId)){ - extraHP += "," + nextId + "::match-Include=null"; - } - - extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; - - - /** - * 1. 主角是否随剧情移动 - * 如果随剧情移动,则更新地点和game_step - * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 - * - * 2. 当前条件是否为空 - * 如果当前条件为空,则提交qa激活并进入下一步剧情 - * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 - * - * 3. 下一部剧情是否为空 - * 如果下一部剧情为空,剧情编号、任务线、地点、不变,condition改为yaobuyao,reply改为当前unknown文本,主角不随剧情移动 - * - * 4. 有没有说去XX - * - * 主角不随剧情移动+当前条件为空+去沙滩 - * 1、沙滩无剧情 - * 2、沙滩有剧情 - * - * 5. 地点变化 - * 1. 当前所处地点 - * 2. 下一步剧情所处地点(包含自动跳转的情况) - * 3. 自动跳转完成后的地点 - */ - - //如果主角的位置随着剧情移动 - if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) { - extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId); - - }else { - - //如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!jumpLocation.equals(nextLocation)){ - if(curUnknownText.equals("")) - reply = "请到" + nextLocation; - //如果当前地点和下一步剧情地点不同,要提示 - else - reply = curUnknownText; - - - - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - - - jConfig = new JConfig( - "yaobuyao::match-Keyword=+" + nextLocation, - "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1 - + "," + nextId + "::number-BiggerOrEqual=" + 1, - "match", (String)branchNode.get("reply") + skipText , (String) nextCondition, - "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId) - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + nextLocation + "_" + id,false); - jConfig.setjStatus(1); - - jConfigList.add(jConfig); - - - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - updateKnowledge.remove("unknownText"); - - //必须在上一个jConfig添加完之后 - //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); - - } - } - - - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); - - includeCurInfo = (Boolean)branchNode.get("includeCurInfo"); - if((Boolean)branchNode.get("includeCurInfo")){ - extraFT = ",includeCurInfo"; - }else{ - extraFT = ""; - } - - jConfig = new JConfig( - curPremiseList, - historyPremiseList, - updateKnowledge, - "", extraHP, extraUK, - "match"+extraFT, reply + skipText, (String) nextCondition, "1" - ); - - - //没有当前条件的限制, - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); - jConfig.setNextStep("queryskip*,map*,item*,npc*"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - jConfig.setNextStepStatus("active"); - } - - - - - jConfigList.add(jConfig); - - - if (branchNode.get("nextPlotId") != null) { - adjId = (String) branchNode.get("nextPlotId"); - if (visited.get(adjId) == null) { - if (id2j.get(adjId) != null) { - adjNode = id2j.get(adjId); - - adjNode.put("parentId", id); - adjNode.put("nextUnknownText", nextUnknownText); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); - varInitialMap.put(adjId, ""); - } - } - } - } - - - } - - - /** - * ---------------------------------------------------------------------------------------------------- - * 不设剧情不设条件时的处理 - * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 - * 2. 如果qa返回小于90则只回答剧情文本 - * 3. 如果qa返回not_found则只回答剧情文本 - * 4. 无论哪种情况都会跳下一步剧情 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 待激活列表,用于qa问答 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - //--------------------------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------------------------- - - - /** - * ---------------------------------------------------------------------------------------------------- - * 用于处理开始游戏或者继续游戏 - * - * - */ - - - } - - @Override - public void postProcessing(List idList, int categoryId){ - if (idList.size() != 0) { - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + QA_URL+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - jConfig.setNextStepStatus("active"); - JSONObject json = jConfig.toJson(this.getConditionDescription()); - helper.insertConfigByBotId(botId, json, idList, categoryId); - jConfigList.add(jConfig); - } - } - - - -} diff --git a/src/gameDesign/Scene.java b/src/gameDesign/Scene.java deleted file mode 100644 index 845fd2e..0000000 --- a/src/gameDesign/Scene.java +++ /dev/null @@ -1,5 +0,0 @@ -package gameDesign; - -public class Scene { - -} diff --git a/src/gameDesign/SceneConstructor.java b/src/gameDesign/SceneConstructor.java deleted file mode 100644 index 213dca5..0000000 --- a/src/gameDesign/SceneConstructor.java +++ /dev/null @@ -1,4 +0,0 @@ -package gameDesign; - -public class SceneConstructor { -} diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000..3fd3a09 --- /dev/null +++ b/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: com.qiwu.chatbotbackend.ChatbotBackendApplication + diff --git a/src/ChatbotBackendApplication.java b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java similarity index 91% rename from src/ChatbotBackendApplication.java rename to src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java index d31e972..4d7ab2f 100644 --- a/src/ChatbotBackendApplication.java +++ b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java @@ -3,9 +3,11 @@ package com.qiwu.chatbotbackend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ServletComponentScan +@ComponentScan public class ChatbotBackendApplication { public static void main(String[] args) { diff --git a/src/Config/Config.java b/src/main/java/com/qiwu/chatbotbackend/Config/Config.java similarity index 75% rename from src/Config/Config.java rename to src/main/java/com/qiwu/chatbotbackend/Config/Config.java index 3da8bd0..172e7b8 100644 --- a/src/Config/Config.java +++ b/src/main/java/com/qiwu/chatbotbackend/Config/Config.java @@ -5,19 +5,38 @@ import org.springframework.stereotype.Component; @Component public class Config { - public static String TEXT_PARSE_ERROR = null; + //url public static String CONDITION_URL = null; - public static String TEST_VAR = null; public static String QA_URL = null; public static String CC_URL = null; - public static String UNKNOWN_TEXT = null; - public static String LOCATION_HINT = null; - public static String GAME_START_HINT = null; + + //名字,地址 + public static String GAME_BOT_CATEGORY = null; + + //错误信息 + public static String UPDATE_ERROR = null; + + //游戏生成 + public static String BOT_INFO_NOT_EXIST = null; + public static String INTENT_NOT_UNDERSTAND = null; + public static String PROGRAM_ERROR = null; + public static String NAME_MISSING_ERROR = null; + public static String LOG_PATH = null; + + public static String TEXT_PARSE_ERROR = null; public static String GAME_MODULE_ERROR = null; public static String DELETE_OLD_CONFIG_TERM_ERROR = null; public static String DELETE_OLD_VARIABLE_ERROR = null; public static String DELETE_OLD_CATEGORY_ERROR = null; + + + public static String UNKNOWN_TEXT = null; + public static String LOCATION_HINT = null; + public static String GAME_START_HINT = null; + public static String GAME_WELCOME_TEXT = null; + + public static String UNKNOWN_TEXT_DESCRIPTION = null; public static String GAME_STEP_DESCRIPTION = null; public static String START_PLOT_NOT_EXIST = null; @@ -50,8 +69,11 @@ public class Config { public static int SIZE = 12; }; + //condition增删改查 + public static String CONDITION_UPDATE_ERROR = null; + public static String CONDITION_INSERT_ERROR = null; - public static String POST_ACTION_ERROR = null; + public static String CONDITION_BACKEND_ERROR = null; public static String TOKEN_TIME_OUT = null; public static String ENCODE_ERROR = null; @@ -84,14 +106,15 @@ public class Config { //生成action + public static String ACTION_TEXT_GENERATE_ERROR = null; + public static String CONDITION_NAME_DUMPLICATE = null; + public static String CONDITION_NAME_UPDATE_ERROR = null; public static String GAME_CONDITION_CATEGORY = null; public static String AUTOMATCH_THRESHOLD = null; public static String IDLE_LIMIT = null; public static String CONDITION_BACKEND_URL = null; - public static String CONDITION_GENERATE_URL= null; public static String OPTIONS = null; - public static String STYLE = null; - public static String AUTOMATCH_URL = null; + public static String DEFAULT_STYLE = null; public static String SERVICE_URL = null; public static String FELLOW = null; @@ -108,4 +131,42 @@ public class Config { public static String DELETE_USER_DATA_ERROR = null; + public static String PLATFORM_SQL_INIT_ERROR = null; + + public static String CATEGORY_UPDATE_CONFLICT = null; + public static String CATEGORY_UPDATE_ERROR = null; + + public static String CATEGORY_DELETE_ERROR = null; + public static String CATEGORY_INSERT_ERROR = null; + public static String CATEGORY_QUERY_ERROR = null; + + public static String JSON_FORMAT_ERROR = null; + + //配置文件增删改查异常 + public static String CONFIG_FILE_NOT_FOUND = null; + public static String CONFIG_DELETE_ERROR = null; + public static String CONFIG_INSERT_ERROR = null; + + //变量 + public static String VARIABLE_NAME_DUMPLICATE = null; + public static String VARIABLE_INSERT_ERROR = null; + public static String VARIABLE_SAVE_FORMAT = null; + public static String VARIABLE_UPDATE_FORMAT = null; + public static String EXTRA_INFO_FORMAT = null; + + public static String VARIABLE_DELETE_ERROR = null; + public static String VARIABLE_SQL_DELETE_ERROR = null; + + public static String VARIABLE_UPDATE_ERROR = null; + + public static String SQL_CONNECTION_ERROR = null; + + public static String BOT_BACKUP_DIR = null; + public static String CONFIG_DIR = null; + + public static String BACKUP_PATH = null; + + + + } diff --git a/src/Config/ConfigInitializer.java b/src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java similarity index 100% rename from src/Config/ConfigInitializer.java rename to src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java diff --git a/src/GameEnvironment/C3p0Utils.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java similarity index 100% rename from src/GameEnvironment/C3p0Utils.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java diff --git a/src/GameEnvironment/DBUtil.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java similarity index 100% rename from src/GameEnvironment/DBUtil.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java diff --git a/src/GameEnvironment/GameEnv.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java similarity index 100% rename from src/GameEnvironment/GameEnv.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java diff --git a/src/GameEnvironment/ObjectFileUtil.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/ObjectFileUtil.java similarity index 100% rename from src/GameEnvironment/ObjectFileUtil.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/ObjectFileUtil.java diff --git a/src/GameEnvironment/Util.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/Util.java similarity index 100% rename from src/GameEnvironment/Util.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/Util.java diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Attr.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Attr.java new file mode 100644 index 0000000..075474d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Attr.java @@ -0,0 +1,26 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; + +public class Attr implements Serializable{ + private static final long serialVersionUID = 1L; + private String name; + private String value; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + @Override + public String toString() { + return "Attr [name=" + name + ", value=" + value + "]"; + } + +} diff --git a/src/GameEnvironment/bean/GoodsClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsClass.java similarity index 100% rename from src/GameEnvironment/bean/GoodsClass.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsClass.java diff --git a/src/GameEnvironment/bean/GoodsInstance.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java similarity index 100% rename from src/GameEnvironment/bean/GoodsInstance.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java diff --git a/src/GameEnvironment/bean/Nickname.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java similarity index 100% rename from src/GameEnvironment/bean/Nickname.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java diff --git a/src/GameEnvironment/bean/NpcClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java similarity index 100% rename from src/GameEnvironment/bean/NpcClass.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java diff --git a/src/GameEnvironment/bean/NpcInstance.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java similarity index 100% rename from src/GameEnvironment/bean/NpcInstance.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java diff --git a/src/GameEnvironment/bean/Place.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java similarity index 100% rename from src/GameEnvironment/bean/Place.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java diff --git a/src/GameEnvironment/bean/PlaceLink.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java similarity index 100% rename from src/GameEnvironment/bean/PlaceLink.java rename to src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java new file mode 100644 index 0000000..54d9e5e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java @@ -0,0 +1,53 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.List; + +public class SuperClass implements Serializable{ + private static final long serialVersionUID = 1L; + private String name; + private String intro; + private List attrs; + private List goodsInstances; + private List npcInstances; + + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAttrs() { + return attrs; + } + public void setAttrs(List attrs) { + this.attrs = attrs; + } + @Override + public String toString() { + int goodsInstanceSize = 0; + if(goodsInstances!=null) { + goodsInstanceSize = goodsInstances.size(); + } + return "SuperClass [name=" + name + ", intro=" + intro + "goodsInstancesSize="+goodsInstanceSize+", attrs=" + attrs + "]"; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java new file mode 100644 index 0000000..8686840 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java @@ -0,0 +1,185 @@ +package com.qiwu.chatbotbackend.actiongenerate.DB; + +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.EngineUnit; +import com.qiwu.chatbotbackend.db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EngineUtils { + + private Connection conn = null; + + + public EngineUtils() throws SQLException { + conn = C3p0Utils.getEngineConnection(); + } + + + public void destroy() { + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + + + public String queryKeywordUnitText(int botId){ + String sql = "select text from units where user_id = ? and name = 'keywords'"; + String keywordText = ""; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + keywordText = (rs.getString("text")); + } + + ps.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return keywordText; + } + + public Boolean updateKeywordUnitText(int botId, String keywordText){ + Boolean b = true; + String sql = "update units set text = ? where user_id = ? and name = 'keywords'"; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, keywordText); + ps.setInt(2,botId); + + b = ps.executeUpdate() == 1; + ps.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return b; + } + + + + public Boolean updateWelcomeText(int botId, String welcome){ + boolean b; + + try { + String sql = "update users set welcome = ? where id=?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, welcome + "#welcome"); + ps1.setInt(2, botId); + + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + + + public Map queryConditionPatternText(int botId, List patternRelationList){ + String sql = "select user_id, text from `users` join `units` on users.id = units.user_id where users.username in ('" + Joiner.on("','").join(patternRelationList)+ "') and units.name = 'actions'"; + String keywordText = ""; + Map patternTextMap = new HashMap(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + //ps.setString(1, Joiner.on(",").join(patternRelationList)); + ResultSet rs = ps.executeQuery(); + + + + while(rs.next()){ + patternTextMap.put(rs.getInt("user_id"), rs.getString("text")); + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return patternTextMap; + } + + public Map queryUnitsByIdList(List idList){ + String sql = "select user_id, name, text from units where user_id in (" + Joiner.on(",").join(idList) + ") and name in ('actions','keywords')"; + + Integer id; + Map id2unit= new HashMap(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + //ps.setArray(1, idList.toArray()); + ResultSet rs = ps.executeQuery(); + + while(rs.next()){ + id = rs.getInt("user_id"); + if(id2unit.get(id) == null){ + id2unit.put(id, new EngineUnit()); + } + switch(rs.getString("name")){ + case "actions": + id2unit.get(id).setActions(rs.getString("text")); + break; + case "keywords": + id2unit.get(id).setKeywords(rs.getString("text")); + break; + } + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return id2unit; + } + + + public String queryBotAccountByBotId(int botId){ + String sql = "select username from users where id= ?"; + String botAccount = ""; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + botAccount = rs.getString("username"); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return botAccount; + } + + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java new file mode 100644 index 0000000..8cd2e5d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java @@ -0,0 +1,56 @@ +package com.qiwu.chatbotbackend.actiongenerate.DB; + +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class PlatformUtils { + + private Connection conn = null; + + + public PlatformUtils() throws SQLException { + conn = C3p0Utils.getPlatformConnection(); + } + + + public void destroy() { + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + public List queryConditionIdByTypetreeId(List typetreeIdList){ + String sql = "select conditionId from typetreeNcondition where typetreeId in (?)"; + String keywordText = ""; + List idList = new ArrayList(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,Joiner.on(",").join(typetreeIdList)); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + idList.add(rs.getInt("conditionId")); + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return idList; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java new file mode 100644 index 0000000..cdcde08 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java @@ -0,0 +1,113 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONArray; + +public class ActionPostElem { + String botName = ""; + String actionText = ""; + String authorization = ""; + Integer botId = 0; + String categoryName = ""; + JSONArray conditionIdPair = new JSONArray(); + String botType = ""; + + public ActionPostElem(String actionText, Integer botId, String botName, String categoryName, String authorization) { + this.botId = botId; + this.botName = botName; + this.actionText = actionText; + this.categoryName = categoryName; + this.authorization = authorization; + } + + + public ActionPostElem(String actionText, Integer botId, String botName, String categoryName, String authorization, String botType) { + this.botId = botId; + this.botName = botName; + this.actionText = actionText; + this.categoryName = categoryName; + this.authorization = authorization; + + if(botType != null) + this.botType = botType; + + } + + + + public ActionPostElem(Integer botId, String botName, String authorization) { + this.authorization = authorization; + this.botId = botId; + this.botName = botName; + } + + + public ActionPostElem(Integer botId, String botName, String actionText, String authorization, String categoryName, JSONArray conditionIdPair) { + this.botName = botName; + this.actionText = actionText; + this.authorization = authorization; + this.botId = botId; + this.categoryName = categoryName; + this.conditionIdPair = conditionIdPair; + } + + public String getBotName() { + return botName; + } + + public void setBotName(String botName) { + this.botName = botName; + } + + public String getActionText() { + return actionText; + } + + public void setActionText(String actionText) { + this.actionText = actionText; + } + + public String getAuthorization() { + return authorization; + } + + public void setAuthorization(String authorization) { + this.authorization = authorization; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + + public Integer getBotId() { + return botId; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public JSONArray getConditionIdPair() { + return conditionIdPair; + } + + public void setConditionIdPair(JSONArray conditionIdPair) { + this.conditionIdPair = conditionIdPair; + } + + + public String getBotType() { + return botType; + } + + public void setBotType(String botType) { + this.botType = botType; + } +} + + + diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java new file mode 100644 index 0000000..64df68a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java @@ -0,0 +1,91 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import java.util.List; + +public class Backup { + + int botId; + String botName; + String botCategoryName; + List conditionList =null; + List configTermList = null; + List categoryList = null; + List variableList = null; + BotInfo botInfo = null; + + public Backup(int botId, String botName, String botCategoryName, + List conditionList, List configTermList, List categoryList, List variableList, BotInfo botInfo) { + this.botId = botId; + this.botName = botName; + this.botCategoryName = botCategoryName; + this.conditionList = conditionList; + this.configTermList = configTermList; + this.categoryList = categoryList; + this.variableList = variableList; + this.botInfo = botInfo; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public String getBotName() { + return botName; + } + + public void setBotName(String botName) { + this.botName = botName; + } + + public String getBotCategoryName() { + return botCategoryName; + } + + public void setBotCategoryName(String botCategoryName) { + this.botCategoryName = botCategoryName; + } + + public List getConditionList() { + return conditionList; + } + + public void setConditionList(List conditionList) { + this.conditionList = conditionList; + } + + public List getConfigTermList() { + return configTermList; + } + + public void setConfigTermList(List configTermList) { + this.configTermList = configTermList; + } + + public List getCategoryList() { + return categoryList; + } + + public void setCategoryList(List categoryList) { + this.categoryList = categoryList; + } + + public List getVariablesList() { + return variableList; + } + + public void setVariablesList(List variableList) { + this.variableList = variableList; + } + + public BotInfo getBotInfo() { + return botInfo; + } + + public void setBotInfo(BotInfo botInfo) { + this.botInfo = botInfo; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java new file mode 100644 index 0000000..27a2ee7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java @@ -0,0 +1,80 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class BotInfo { + Integer botId; + String welcomeText; + String goodbyeText; + String postURL; + String defaultConfigCategory; + String bothValue; + String queryTextTransfer; + + public BotInfo(Integer botId, String welcomeText, String goodbyeText, + String postURL, String defaultConfigCategory, + String bothValue, String queryTextTransfer) { + this.botId = botId; + this.welcomeText = welcomeText; + this.goodbyeText = goodbyeText; + this.postURL = postURL; + this.defaultConfigCategory = defaultConfigCategory; + this.bothValue = bothValue; + this.queryTextTransfer = queryTextTransfer; + } + + + public Integer getBotId() { + return botId; + } + + public String getWelcomeText() { + return welcomeText; + } + + public String getGoodbyeText() { + return goodbyeText; + } + + public String getPostURL() { + return postURL; + } + + public String getDefaultConfigCategory() { + return defaultConfigCategory; + } + + public String getBothValue() { + return bothValue; + } + + public String getQueryTextTransfer() { + return queryTextTransfer; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public void setWelcomeText(String welcomeText) { + this.welcomeText = welcomeText; + } + + public void setGoodbyeText(String goodbyeText) { + this.goodbyeText = goodbyeText; + } + + public void setPostURL(String postURL) { + this.postURL = postURL; + } + + public void setDefaultConfigCategory(String defaultConfigCategory) { + this.defaultConfigCategory = defaultConfigCategory; + } + + public void setBothValue(String bothValue) { + this.bothValue = bothValue; + } + + public void setQueryTextTransfer(String queryTextTransfer) { + this.queryTextTransfer = queryTextTransfer; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java new file mode 100644 index 0000000..10a57db --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java @@ -0,0 +1,58 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Category { + int botId; + int categoryId; + int parentId; + String name; + String status = "avaliable"; + + public Category(int botId, int categoryId, int parentId, String name) { + this.botId = botId; + this.categoryId = categoryId; + this.parentId = parentId; + this.name = name; + } + + public Category(int botId, int parentId, String name) { + this.botId = botId; + this.parentId = parentId; + this.name = name; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public int getParentId() { + return parentId; + } + + public void setParentId(int parentId) { + this.parentId = parentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java new file mode 100644 index 0000000..ceac338 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java @@ -0,0 +1,86 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Condition { + + int botId; + int conditionId; + String conditionJsonText; + String actionText; + String category; + String active; + Integer displayOrder = 999; + + public Condition(int botId, int conditionId, String conditionJsonText, String actionText, String category, String active, Integer displayOrder) { + this.botId = botId; + this.conditionId = conditionId; + this.conditionJsonText = conditionJsonText; + this.actionText = actionText; + this.category = category; + this.active = active; + this.displayOrder = displayOrder; + } + + public Condition(int botId, String conditionJsonText, String actionText, String category, String active) { + this.botId = botId; + this.conditionJsonText = conditionJsonText; + this.actionText = actionText; + this.category = category; + this.active = active; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getConditionId() { + return conditionId; + } + + public void setConditionId(int conditionId) { + this.conditionId = conditionId; + } + + public String getConditionJsonText() { + return conditionJsonText; + } + + public void setConditionJsonText(String conditionJsonText) { + this.conditionJsonText = conditionJsonText; + } + + public String getActionText() { + return actionText; + } + + public void setActionText(String actionText) { + this.actionText = actionText; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public Integer getDisplayOrder() { + return displayOrder; + } + + public void setDisplayOrder(Integer displayOrder) { + this.displayOrder = displayOrder; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java new file mode 100644 index 0000000..ba1f1a0 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java @@ -0,0 +1,72 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONObject; + +public class ConfigTerm { + int botId; + int configId; + int categoryId; + String configJsonText; + String configName = ""; + String configTerm = "waiting"; + + public ConfigTerm(int botId, int configId, + int categoryId, String configJsonText, String configName) { + this.botId = botId; + this.configId = configId; + this.categoryId = categoryId; + this.configJsonText = configJsonText; + this.configName = configName; + } + + public ConfigTerm(int botId, int configId, int categoryId, JSONObject configData) { + this.botId = botId; + this.configId = configId; + this.categoryId = categoryId; + this.configJsonText = configData.toJSONString(); + + if(configData.containsKey("configName")){ + this.configName = configData.getString("configName"); + } + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getConfigId() { + return configId; + } + + public void setConfigId(int configId) { + this.configId = configId; + } + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public String getConfigJsonText() { + return configJsonText; + } + + public void setConfigJsonText(String configJsonText) { + this.configJsonText = configJsonText; + } + + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java new file mode 100644 index 0000000..2daad27 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java @@ -0,0 +1,34 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class EngineUnit { + Integer conditionid; + String keywords; + String actions; + + public EngineUnit() { + } + + public Integer getConditionid() { + return conditionid; + } + + public void setConditionid(Integer conditionid) { + this.conditionid = conditionid; + } + + public String getKeywords() { + return keywords; + } + + public void setKeywords(String keywords) { + this.keywords = keywords; + } + + public String getActions() { + return actions; + } + + public void setActions(String actions) { + this.actions = actions; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java new file mode 100644 index 0000000..aeabcd9 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java @@ -0,0 +1,33 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class IntervalStatus { + int status = 1; + String message = ""; + Object extraData = null; + + + public IntervalStatus(int status, String message, Object extraData) { + this.status = status; + this.message = message; + this.extraData = extraData; + } + + public IntervalStatus(int status, String message) { + this.status = status; + this.message = message; + } + + public int getStatus() { + return status; + } + + public String getMessage() { + return message; + } + + public Object getExtraData() { + return extraData; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java new file mode 100644 index 0000000..df58c7e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java @@ -0,0 +1,8 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONObject; + +public class Solution { + int status = 0; + JSONObject payload = null; +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java new file mode 100644 index 0000000..a5d0052 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java @@ -0,0 +1,81 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Variable { + + Integer botId; + Integer variableId; + Integer categoryId = 0; + String description; + String name; + String value; + + public Variable(Integer botId, Integer categoryId, String name, String description, String value) { + this.botId = botId; + + if(categoryId != null) + this.categoryId = categoryId; + this.description = description; + this.name = name; + this.value = value; + } + + public Variable(Integer botId, Integer variableId, Integer categoryId, String name, String description, String value) { + this.botId = botId; + this.variableId = variableId; + if(categoryId != null) + this.categoryId = categoryId; + this.description = description; + this.name = name; + this.value = value; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public void setVariableId(Integer variableId) { + this.variableId = variableId; + } + + public void setCategoryId(Integer categoryId) { + this.categoryId = categoryId; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } + + public Integer getBotId() { + return botId; + } + + public Integer getVariableId() { + return variableId; + } + + public Integer getCategoryId() { + return categoryId; + } + + public String getDescription() { + return description; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java new file mode 100644 index 0000000..188fc27 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java @@ -0,0 +1,149 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "ActionServlet", urlPatterns = {"/condition"}) +public class ActionServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botName = ""; + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + + if(receiveParameters.getString("botId").equals("undefined")) + botId = -1; + else + botId = receiveParameters.getInteger("botId"); + botName = receiveParameters.getString("botName_yhm"); + + + try { + EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + ActionUtils actionUtils = new ActionUtils(engine, helper); + + + switch(operationType) { + case "query_bot_info": + actionUtils.queryBotInfo(receiveParameters); + break; + case "bot_init": + actionUtils.createBot(receiveParameters, auth); + break; + case "query_category": + actionUtils.queryCategory(receiveParameters); + break; + case "query_condition": + actionUtils.queryCondition(receiveParameters); + break; + case "update_condition_display_order": + actionUtils.updateConditionDisplayOrder(receiveParameters); + break; + case "update_bot_info": + actionUtils.updateBotInfo(receiveParameters); + break; + case "update_goodbye": + actionUtils.updateGoodbye(receiveParameters); + break; + + default: + + //condition的增删改都需要先查询condition的信息 + actionUtils.getBotConditionInfo(botId, botName, auth); + switch(operationType) { + case "insert_condition": + actionUtils.insertCondition(receiveParameters); + break; + case "delete_condition": + actionUtils.deleteCondition(receiveParameters, auth); + break; + case "update_condition": + actionUtils.updateCondition(receiveParameters); + break; + case "change_active": + actionUtils.changeActive(receiveParameters); + break; + case "detect_template_update": + actionUtils.updateRelation(receiveParameters); + break; + case "update_condition_name": + actionUtils.updateConditionName(receiveParameters); + break; + } + if(actionUtils.intervalStatus.getStatus() == 1) + actionUtils.query4post(receiveParameters); + + + + } + helper.destroy(); + engine.destroy(); + + switch (actionUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", actionUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", actionUtils.intervalStatus.getMessage()); + } + + + } catch (SQLException e) { + e.printStackTrace(); + } + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java new file mode 100644 index 0000000..1cf3a7f --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java @@ -0,0 +1,150 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.CategoryUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; +import static com.qiwu.chatbotbackend.Config.Config.SQL_CONNECTION_ERROR; + +@WebServlet(name = "BackupServlet", urlPatterns = {"/save2file"}) +public class BackupServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + IntervalStatus intervalStatus = new IntervalStatus(1, ""); + ServletContext context = request.getServletContext(); + + + //读取并解析json数据 + String operationType = "", botName = "", botCategoryName; + String jsonStr = SimpleUtil.readJSONString(request), fileData; + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId = 0, categoryIndex; + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + + try { + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + JSONObject backupFile = new JSONObject(); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + botName = receiveParameters.getString("botName_yhm"); + botCategoryName = receiveParameters.getString("catName"); + + + EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + BotInfo botInfo = null; + List conditionList = new ArrayList(); + List configTermList = new ArrayList(); + List childCategoryIds = new ArrayList(); + List childCategories = new ArrayList(); + List variablesList = new ArrayList(); + + ActionUtils actionUtils = new ActionUtils(engine, helper); + CategoryUtils categoryUtils = new CategoryUtils(helper); + ConfigTermUtils configUtils = new ConfigTermUtils(botName, helper, context); + //actionUtils. + + //如果需要保存condition,查询所有condition + if (receiveParameters.containsKey("saveCondition") && receiveParameters.getBoolean("saveCondition")){ + conditionList = helper.queryConditionAll(botId); + } + + //如果需要保存配置文件,则从根目录开始保存配置文件 + if(receiveParameters.containsKey("saveConfig") && receiveParameters.getBoolean("saveConfig")){ + + categoryIndex = receiveParameters.getInteger("indexCategory"); + //查询某个类别下的所有类别 + childCategoryIds = categoryUtils.findChildCategoryIds(botId, categoryIndex, childCategories); + //查询属于以上类别列表的所有配置条目 + configTermList = helper.queryConfigByCategoryIdList(botId, childCategoryIds); + + } + + if(!receiveParameters.containsKey("saveVariable") || receiveParameters.getBoolean("saveVariable")){ + variablesList = helper.queryVariableAll(botId); + } + + botInfo = helper.queryBotInfo(botId); + + Backup backup = new Backup(botId, botName, botCategoryName, conditionList, configTermList, childCategories, variablesList, botInfo); + + //; + //backupFile.put("botId"); + + + + try { + writeFile(BOT_BACKUP_DIR + botId + ".backup",JSON.toJSONString(backup)); +// ReadFile("D:\\8.json"); + System.out.println(); + } catch (IOException e) { + e.printStackTrace(); + } + + helper.destroy(); + engine.destroy(); + + + } catch (SQLException e) { + intervalStatus = new IntervalStatus(0, SQL_CONNECTION_ERROR); + } + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append( + botId + ".backup"); + out.flush(); + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + /** + * 写文件到.Json + * @param filePath + * @param sets + * @throws IOException + */ + public static void writeFile(String filePath, String sets) + throws IOException { + FileWriter fw = new FileWriter(filePath); + PrintWriter out = new PrintWriter(fw); + out.write(sets); + out.println(); + fw.close(); + out.close(); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java new file mode 100644 index 0000000..4db6edc --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java @@ -0,0 +1,154 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.utils.CategoryUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "ConfigTermServlet", urlPatterns = {"/config"}) +public class ConfigTermServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //读取并解析json数据 + String botAccount = "", operationType = "",auth = request.getHeader("authorization"); + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + + System.out.println(jsonStr); + + Integer botId; + CategoryUtils categoryUtils = null; + JSONObject responseJSONObject = new JSONObject(); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); + receiveParaneters.put("Authorization", auth); + + operationType = receiveParaneters.getString("type"); + botId = receiveParaneters.getInteger("botId"); + + + try { + //EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + EngineUtils engine = null; + ConfigTermUtils configUtils = null; + + IntervalStatus intervalStatus = null; + + if(operationType.equals("query_config") || operationType.equals("query_sleeping_config")){ + configUtils = new ConfigTermUtils(helper); + switch(operationType){ + case "query_config": + + configUtils.queryConfig(receiveParaneters); + intervalStatus = configUtils.intervalStatus; + break; + case "query_sleeping_config": + configUtils.querySleepingConfig(receiveParaneters); + break; + } + intervalStatus = configUtils.intervalStatus; + + } + else if(operationType.endsWith("config")){ + engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + System.out.println("botAccount" + botAccount); + configUtils = new ConfigTermUtils(botAccount, helper, context); + switch (operationType){ + case "insert_config": + configUtils.insertConfigTerm(receiveParaneters); + break; + case "update_config": + configUtils.updateConfig(receiveParaneters); + break; + case "delete_config": + configUtils.deleteConfig(receiveParaneters); + break; + } + intervalStatus = configUtils.intervalStatus; + engine.destroy(); + }else{ + categoryUtils = new CategoryUtils(helper); + switch(operationType) { + case "query_category": + categoryUtils.queryCategory(receiveParaneters); + break; + case "insert_category": + categoryUtils.insertCategory(receiveParaneters); + break; + case "update_category": + categoryUtils.updateCategory(receiveParaneters); + break; + case "delete_category": + categoryUtils.deleteCategory(receiveParaneters); + break; + + } + intervalStatus = categoryUtils.intervalStatus; + } + helper.destroy(); + + + + switch (intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", intervalStatus.getMessage()); + break; + } + + + } catch (SQLException e) { + + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", "0"); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java new file mode 100644 index 0000000..c8dc570 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java @@ -0,0 +1,36 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@Component +public class CorsFilter implements Filter { + + //解决跨域问题 + + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + HttpServletResponse response = (HttpServletResponse) res; + + HttpServletRequest reqs = (HttpServletRequest) req; + + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); + + chain.doFilter(req, res); + } + + public void init(FilterConfig filterConfig) { + } + + public void destroy() { + } +} \ No newline at end of file diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java new file mode 100644 index 0000000..23087c4 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java @@ -0,0 +1,59 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; + +@WebServlet(name = "GetBackupServlet", urlPatterns = {"/download"}) +public class GetBackupServlet extends HttpServlet { + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String filename = request.getParameter("filename"); + try{ + response.reset();// 清空输出流 + + String resultFileName = filename; + resultFileName = URLEncoder.encode(resultFileName,"UTF-8"); + response.setCharacterEncoding("UTF-8"); + response.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头 + response.setContentType("application/msexcel");// 定义输出类型 + //输入流:本地文件路径 + DataInputStream in = new DataInputStream( + new FileInputStream(new File(BOT_BACKUP_DIR + filename))); + //输出流 + OutputStream out = response.getOutputStream(); + //输出文件 + int bytes = 0; + byte[] bufferOut = new byte[1024]; + while ((bytes = in.read(bufferOut)) != -1) { + out.write(bufferOut, 0, bytes); + } + out.close(); + in.close(); + } catch(Exception e){ + e.printStackTrace(); + response.reset(); + try { + OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + String data = ""; + writer.write(data); + writer.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + doPost(request, response); + } +} diff --git a/src/servlet/ReloadChatCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java similarity index 63% rename from src/servlet/ReloadChatCacheServlet.java rename to src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java index 20af7a3..5b4f423 100644 --- a/src/servlet/ReloadChatCacheServlet.java +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java @@ -1,4 +1,4 @@ -package com.qiwu.chatbotbackend.servlet; +package com.qiwu.chatbotbackend.actiongenerate.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; @@ -6,14 +6,22 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import java.io.PrintWriter; -@WebServlet(name = "ReloadChatCacheServlet", urlPatterns = {"/reloadChatCache"}) -public class ReloadChatCacheServlet extends HttpServlet { +@WebServlet(name = "GetNextstepExceptionServlet", urlPatterns = {"/getNextStepException"}) +public class GetNextstepExceptionServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + response.setHeader("Access-Control-Allow-Origin", "*"); + + PrintWriter out = response.getWriter(); + out.append("active known"); //在有多个下一步时,可以选择已被激活跳过或者是答案已知跳过 + out.flush(); } } diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java new file mode 100644 index 0000000..28764c7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java @@ -0,0 +1,97 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "MacroServlet", urlPatterns = {"/macro"}) +public class MacroServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botAccount = ""; + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + System.out.println("xxx"); + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + + + try { + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + VariableUtils variableUtils = null; + + helper.destroy(); + + switch (variableUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getMessage()); + break; + } + + + } catch (SQLException e) { + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java new file mode 100644 index 0000000..22a41d7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java @@ -0,0 +1,224 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.SimpleUtil; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.sql.SQLException; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +@WebServlet(name = "RecoveryServlet") +public class RecoveryServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + ServletContext context = request.getServletContext(); + //读取并解析json数据 + String operationType = "", botName = "", conditionName = "", botAccount; + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(), configTermJson, conditionJson; + JSONArray conditionIdPair = new JSONArray(), idPair; + Boolean flag = true; + Integer botId = 0, newCategoryId = 0, len, id; + IntervalStatus intervalStatus = new IntervalStatus(1, ""); + StringBuffer completeConfigText = new StringBuffer(); + ActionPostElem ape = null; + System.out.println(jsonStr); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + JSONObject data = receiveParameters.getJSONObject("data"); + botId = receiveParameters.getInteger("botId"); + botAccount = receiveParameters.getString("botName"); + botName = receiveParameters.getString("botName_yhm"); + + + + + + try { + Map idReplaceMap = new HashMap(); + + + ConfigTermText configTermText = null; + Set variableNameSet1, variableNameSet2, conditionNameSet1, conditionNameSet2; + List actionTextList = new ArrayList(); + //List originConditionList = null; + //List<> + List categoryList = data.getJSONArray("categoryList").toJavaList(Category.class); + List originConditionList = null, conditionList = data.getJSONArray("conditionList").toJavaList(Condition.class); + List configTermList = data.getJSONArray("configTermList").toJavaList(ConfigTerm.class); + List originVariableList, variableList = data.getJSONArray("variablesList").toJavaList(Variable.class); + BotInfo botInfo = data.getJSONObject("botInfo").toJavaObject(BotInfo.class); + + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + + ActionUtils actionUtils = new ActionUtils(engine, helper); + VariableUtils variableUtils = new VariableUtils(helper); + ConfigTermUtils configTermUtils = new ConfigTermUtils(helper); + + + //是否删除之前的数据 + if (!data.containsKey("dataOverride") || data.getBoolean("dataOverride")) { + //清空数据 + helper.deleteUserData(botId); + } + + originConditionList =helper.queryConditionAll(botId); + originVariableList = helper.queryVariableAll(botId); + conditionNameSet1 = actionUtils.getConditionNameSet(originConditionList); + conditionNameSet2 = actionUtils.getConditionNameSet(conditionList); + variableNameSet1 = variableUtils.getVariableNameSet(originVariableList); + variableNameSet2 = variableUtils.getVariableNameSet(variableList); + + variableNameSet1.retainAll(variableNameSet2); + conditionNameSet1.retainAll(conditionNameSet2); + //监测是否重名 + //求交集,如果交集大于0,则说明重复,返回重复列表 + if(conditionNameSet1.size() > 0){ + intervalStatus = new IntervalStatus(0, "dumplicate", JSONArray.toJSON(conditionNameSet1)); + }else if(variableNameSet1.size() > 0){ + intervalStatus = new IntervalStatus(0, "dumplicate", JSONArray.toJSON(variableNameSet1)); + }else{ + + for(Category category:categoryList){ + category.setBotId(botId); + + if(idReplaceMap.containsKey(category.getParentId())){ + category.setParentId(idReplaceMap.get(category.getParentId())); + } + + newCategoryId = helper.insertCategoryByBotId(category); + idReplaceMap.put(category.getCategoryId(), newCategoryId); + } + + + //修改botid,并批量插入condition + len = conditionList.size(); + //替换配置文件相应类别的id + for(int i =0;i < len;i++){ + conditionList.get(i).setBotId(botId); + conditionJson = JSON.parseObject(conditionList.get(i).getConditionJsonText()); + if(conditionList.get(i).getActive().equals("1")){ + completeConfigText.append(String.format(EXTRA_INFO_FORMAT, "activeAction", conditionJson.getString("conditionName"))); + } + idPair = new JSONArray(); + idPair.add(conditionJson.getInteger("originConditionId")); + idPair.add(conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0")); + conditionIdPair.add(idPair); + actionTextList.add(conditionList.get(i).getActionText()); + + } + helper.batchInsertCondition(conditionList); + + + len = variableList.size(); + //替换变量相应的botid + for(int i =0;i < len;i++){ + variableList.get(i).setBotId(botId); + + completeConfigText.append(String.format(VARIABLE_SAVE_FORMAT, variableList.get(i).getName(), variableList.get(i).getValue())); + } + helper.batchInsertVariable(botId, variableList); + + + + len = configTermList.size(); + //替换配置文件相应类别的id + for(ConfigTerm configTerm:configTermList){ + if(idReplaceMap.containsKey(configTerm.getCategoryId())){ + configTerm.setCategoryId(idReplaceMap.get(configTerm.getCategoryId())); + }else{ + configTerm.setCategoryId(0); + } + + configTermJson = JSON.parseObject(configTerm.getConfigJsonText()); + configTermText = configTermUtils.configPreprocessing(configTermJson); + id = helper.insertConfig(botId, configTermJson, configTerm.getCategoryId()); + completeConfigText.append(configTermText.toString()).append(id).append("\n"); + + + } + //helper.batchInsertConfig(botId, configTermList); + + batchUpdate(botAccount, completeConfigText.toString(), context, true); + ape = new ActionPostElem(botId, botName, actionUtils.generateCompleteActionText(receiveParameters, actionTextList), auth, GAME_BOT_CATEGORY,conditionIdPair); + actionUtils.postAction(ape); + + intervalStatus = actionUtils.intervalStatus; + + + } + engine.destroy(); + helper.destroy(); + + }catch (SQLException e){ + intervalStatus = new IntervalStatus(0, SQL_CONNECTION_ERROR); + } + + } + + + switch(intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", intervalStatus.getMessage()); + break; + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + public void batchUpdate(String userName, String data, ServletContext context, Boolean writeFile) throws IOException { + BufferedReader br = new BufferedReader(new StringReader(data)); + UserInfo userinfo = new UserInfo(userName); + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + System.out.println("batchupdate"); + + if(writeFile){ + UserInfoController.writeConfigText(userName, userinfo); + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java new file mode 100644 index 0000000..2b60693 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java @@ -0,0 +1,128 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "VariableServlet", urlPatterns = {"/variable"}) +public class VariableServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botAccount = ""; + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + System.out.println("xxx"); + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + + + try { + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + VariableUtils variableUtils = null; + + + if(operationType.equals("query_variable")){ + variableUtils = new VariableUtils(helper); + variableUtils.queryVariable(receiveParameters); + }else{ + variableUtils = new VariableUtils(botAccount, helper, context); + switch (operationType){ + + case "insert_variable": + variableUtils.insertVariable(receiveParameters); + break; + case "delete_variable": + variableUtils.deleteVairiable(receiveParameters); + break; + case "update_variable": + variableUtils.updateVariable(receiveParameters); + break; + } + } + + switch(operationType) { + case "query_variable": + variableUtils.queryVariable(receiveParameters); + break; + + + } + + + switch (variableUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getMessage()); + break; + } + + helper.destroy(); + engine.destroy(); + + + } catch (SQLException e) { + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java new file mode 100644 index 0000000..100e51d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java @@ -0,0 +1,129 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.Arrays; + +public class ActionParser { + public static JSONObject parse(String actionText){ + String name; + JSONObject action = new JSONObject(); + + + for(String line:actionText.split("\r\n")){ + name = line.trim().split("=")[0]; + + if(name.equals("") || name.equals("#actions")){ + // + }else{ + + switch(name) { + case "name": + //parseName(line, action); + break; + case "status": + parseStatus(line, action); + break; + case "condition": + parseCondition(line, action); + break; + case "style": + parseStyle(line, action); + break; + case "action": + parseAction(line, action); + break; + case "conflict": + + break; + case "process": + break; + default: + ; + } + } + } + + if(!action.containsKey("styleList")){ + action.put("styleList", new JSONArray()); + } + + return action; + + } + + public static void parseName(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("actionName", elem[1]); + } + + public static void parseAction(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("actionType", elem[1]); + } + public static void parseStatus(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("status", elem[1]); + } + public static void parseStyle(String text, JSONObject action){ + String elem[] = text.split("="); + String subElem[] = elem[1].split(","); + action.put("styleList", new JSONArray(Arrays.asList(subElem))); + } + + public static void parseConflict(String text, JSONObject action){ + // + } + + public static void parseCondition(String text, JSONObject action){ + String elem[] = text.split("\\|", 4); + String condition = elem[0]; + String relation = elem[1]; + String questionText = elem[2]; + String repeatStr = elem[3]; + String conditionName = "", relationList[], questionElem[]; + JSONArray questionList = new JSONArray(); + JSONArray repeatList = new JSONArray(); + + String conditionElem[] = condition.split("="); + conditionElem = conditionElem[1].split(":"); + + action.put("conditionName", conditionElem[0]); + if(conditionElem.length >=2) + action.put("dataType", conditionElem[1]); + + relationList = relation.split(","); + action.put("relationHead", relationList[0]); + action.put("relationName", relationList[1]); + action.put("relationTail", relationList[2]); + + + for(String question:questionText.split("~")){ + questionElem = question.split(":"); + JSONObject iterDict = new JSONObject(); + iterDict.put("que_start_time",questionElem[0]); + iterDict.put("que_stop_time" ,questionElem[1]); + iterDict.put("que_sen" ,questionElem[2]); + + if(questionElem.length == 4 && questionElem[3].equals("base")) + iterDict.put("base", 1); + else + iterDict.put("base", 0); + + questionList.add(iterDict); + } + + action.put("questionList", questionList); + + for(String repeat:repeatStr.split("~")){ + JSONObject repeatDict = new JSONObject(); + elem = repeat.split("=", 2); + repeatDict.put("repeatString", elem[0]); + repeatDict.put("repeatKeywords", elem[1]); + repeatList.add(repeatDict); + } + action.put("repeatList", repeatList); + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java new file mode 100644 index 0000000..157eede --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java @@ -0,0 +1,1065 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.DB.PlatformUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import java.io.UnsupportedEncodingException; +import java.sql.SQLException; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class ActionUtils { + EngineUtils engine = null; + SqlHelper helper = null; + String activeCondition = ""; + ActionPostElem ape = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public ActionUtils(EngineUtils engine, SqlHelper helper){ + this.engine = engine; + this.helper = helper; + } + + public void insertCondition(JSONObject parameters){ + + String conditionName = "", text = "", categoryStr, conditionJsonStr = "", isActive = ""; + Integer count = 0; + JSONObject conditionJson = null; + Condition condition = null; + List conditionList = new ArrayList(); + Boolean insertFlag = false; + JSONArray conditions = parameters.getJSONArray("conditionData"); + Integer botId = parameters.getInteger("botId"); + List actionTextList = helper.queryActionTextList(botId); + Set conditionNameSet = new HashSet(); + + + for(String actionText:actionTextList){ + //从action文本取出condition的名字 + //System.out.println("--" + actionText.trim().substring(100).split("\r\n")[0] + "---"); + conditionName = actionText.trim().split("\r\n")[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + } + + count = conditions.size(); + if(count > 0){ + + for(int i =0; i < count;i++){ + conditionJson = conditions.getJSONObject(i); + conditionName = conditionJson.getString("conditionName"); + + //condition名字已存在 + if(conditionNameSet.contains(conditionName)){ + for(int j =2;j < 100 && conditionNameSet.contains(conditionName);j++){ + + conditionName = conditionJson.getString("conditionName") + j; + } + conditionJson.put("conditionName", conditionName); + } + + text = generateSingleActionText(conditionName, conditionJson); + actionTextList.add(text); + if(conditionJson.getBoolean("active")) + isActive = "1"; + else + isActive = "0"; + categoryStr = conditionJson.getString("conditionCategory"); + conditionJson.put("displayOrder", 999); //展示顺序为condition的展示顺序,越小排在越前面 + conditionJsonStr = JSONObject.toJSONString(condition); + + + + condition = new Condition(botId, conditionJson.toJSONString(), text, categoryStr, isActive); + conditionList.add(condition); + + insertIdElemIfNotExist(conditionJson.getInteger("originConditionId"), conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0")); + + } + insertFlag = helper.batchInsertCondition(conditionList); + } + if(insertFlag) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, "插入失败"); + } + + public void insertIdElemIfNotExist(Integer originConditionId, String relationName){ + int len = 0; + Boolean exist = false; + if(ape.getConditionIdPair() != null){ + len = ape.getConditionIdPair().size(); + } + for(int i = 0;i < len;i++){ + if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ + exist = true; + break; + } + } + + if(!exist){ + ape.getConditionIdPair().add(new JSONArray(){{add(originConditionId);add(relationName);}}); + } + } + + public void deleteIdElemIfExist(Integer originConditionId){ + int len = 0; + Boolean exist = false; + if(ape.getConditionIdPair() != null){ + len = ape.getConditionIdPair().size(); + } + for(int i = 0;i < len;i++){ + if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ + ape.getConditionIdPair().remove(i); + } + } + } + + public String generateSingleActionText(String conditionName, JSONObject condition){ + + StringBuffer sb = new StringBuffer(); + String listeningText = ""; + StringBuffer actionText = new StringBuffer(); + + + appendActionHead(conditionName, actionText, "waiting"); + appendCondition(conditionName, actionText, condition); + appendProcess(conditionName, actionText, condition); + + + + listeningText = actionText.toString().replace("name=" + conditionName, "name=" +conditionName + "_listening"); + listeningText = listeningText.replace("status=waiting", "states=listening"); + actionText.append(listeningText); + + return actionText.toString(); + } + + public String generateCompleteActionText(JSONObject parameters, List actionTextList){ + Integer botId = parameters.getInteger("botId"); + BotInfo botInfo = helper.queryBotInfo(botId); + Boolean bothValue = true; + String styleText = "", serviceURL = "", elements[], conditionName; + Set conditionNameSet = new HashSet(); + StringBuffer postActionText = null, processText = new StringBuffer(), fullActionText = new StringBuffer(); + + if(botInfo == null){ + styleText = POST_STYLE1; + serviceURL = SERVICE_URL; + }else{ + if(botInfo.getBothValue().equals("1")){ + styleText = POST_STYLE1; + }else{ + styleText = POST_STYLE2; + } + if(!botInfo.getPostURL().equals("")){ + serviceURL = botInfo.getPostURL(); + }else{ + serviceURL = SERVICE_URL; + } + } + + postActionText = new StringBuffer(String.format(POST_ACTION_HEAD, styleText, serviceURL)); + + for(String text:actionTextList){ + + for(String line:text.split("\r\n")){ + if(line.startsWith("condition")){ + //System.out.println("line====" + line); + line = line.replace("condition", "reference"); + postActionText.append(line); + postActionText.append("\r\n"); + + elements = line.trim().split("\\|"); + + + conditionName = elements[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + break; + + } + } + } + + for(String name:conditionNameSet){ + postActionText.append("process=nextStep="); + postActionText.append(name); + postActionText.append("|"); + postActionText.append(name); + postActionText.append("=active|\r\n"); + } + + + for(String actionText:actionTextList){ + postActionText.append(actionText); + } + + postActionText.append("\r\n\r\n"); + + return postActionText.toString(); + } + + + public void appendProcess(String conditionName, StringBuffer actionText, JSONObject condition){ + + } + + /** + * + * 构建action的头部信息,包括name、status、style、fellow等信息 + * 其中addition_element,就是前段传的一些参数 + * + * @param actionText + * @param actionStatus + */ + public void appendActionHead(String conditionName, StringBuffer actionText, String actionStatus){ + + actionText.append("\r\n\r\n"); + actionText.append("name=").append(conditionName).append("\r\n"); + actionText.append("status=").append(actionStatus).append("\r\n"); + actionText.append("action=select\r\n"); + + if(AUTOMATCH_THRESHOLD != null && !AUTOMATCH_THRESHOLD.equals("")) + actionText.append("automatchthreshold=").append(AUTOMATCH_THRESHOLD).append("\r\n"); + + actionText.append(DEFAULT_STYLE).append("\r\n"); + actionText.append("fellow=pivot_httppost\r\n"); + + } + + public void queryCondition(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String category = parameters.getString("category"); + String queryType = parameters.getString("queryType"); + List conditionList = null; + JSONObject data = new JSONObject(){ + { + put("conditionList", new JSONArray()); + } + }; + + JSONObject conditionJson = null; + + if(queryType != null && queryType.equals("category")){ + conditionList = helper.queryConditionByCategory(botId, category); + }else{ + conditionList = helper.queryConditionAll(botId); + } + + for(Condition condition:conditionList){ + conditionJson = JSON.parseObject(condition.getConditionJsonText()); + conditionJson.put("conditionId", condition.getConditionId()); + data.getJSONArray("conditionList").add(conditionJson); + } + + intervalStatus = new IntervalStatus(1, "", data); + + + + } + + public void queryCategory(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String[] categoryChain; + + List conditionCategories = helper.queryConditionCategoriesById(botId); + JSONObject categoryTree = new JSONObject(), categoryTreeJson = new JSONObject(), finalCategory = new JSONObject(); + + if(conditionCategories.size() != 0 ){ + for(String category:conditionCategories){ + categoryChain = category.split("-"); + for(String node: categoryChain){ + categoryTree.putIfAbsent(node, new JSONObject()); //设置默认子节点 + categoryTree = categoryTree.getJSONObject(node); //进入子节点 + } + } + + categoryTreeJson.putIfAbsent("-1", new JSONObject(){ + { + put("children", new JSONArray()); + } + }); + constructCategoryTreeJson(categoryTree, categoryTreeJson, "-1"); + + finalCategory.put("category", categoryTreeJson.getJSONObject("-1").getJSONArray("children")); + + }else{ + finalCategory.put("category", new JSONArray()); + } + + intervalStatus = new IntervalStatus(1, "", finalCategory); + + } + + public void query4post(JSONObject parameters){ + + Integer activedConditionId = -1; + + String finalText = ""; + JSONObject conditionJson = null; + int botId = parameters.getInteger("botId"); + List conditionList = helper.queryConditionAll(botId); + List conditionTextList = new ArrayList(); + + + for(Condition condition:conditionList){ + if(condition.getActive().equals("1")) + activedConditionId = condition.getConditionId(); + + conditionTextList.add(condition.getActionText()); + } + + if(activedConditionId == -1 && conditionList.size() >= 1){ + conditionTextList.set(0, conditionTextList.get(0).replace("status=waiting","status=active")); + } + finalText = generateCompleteActionText(parameters, conditionTextList); + ape.setActionText(finalText); + + postAction(ape); + + } + + public void constructCategoryTreeJson(JSONObject categoryTree, JSONObject categoryTreeJson, String root){ + String namePair[]; + JSONObject node = categoryTreeJson.getJSONObject(root); + JSONObject childNode = null; + for(String key:categoryTree.keySet()){ + namePair = key.split(":"); //id:名字 + childNode = new JSONObject(); + childNode.put("value", namePair[0]); + childNode.put("label", namePair[1]); + categoryTreeJson.put(namePair[0], node); + if(!node.containsKey("children")) + node.put("children", new JSONArray()); + + node.getJSONArray("children").add(childNode); + constructCategoryTreeJson(categoryTree.getJSONObject(key), categoryTreeJson, namePair[0]); + } + } + + + /** + * 将某个condition设为初始问题 + * 将某个condition改成active, 将之前active的condition改成waiting + */ + public void changeActive(JSONObject parameters){ + Boolean flag = true; + int botId = parameters.getInteger("botId"); + int activeConditionId = parameters.getInteger("activeConditionId"); + List conditionList = new ArrayList(); + + Condition oldActiveCondition = helper.queryActiveCondition(botId); + + if(oldActiveCondition != null){ + + oldActiveCondition.setActionText(oldActiveCondition.getActionText().replace("status=active", "status=waiting")); + oldActiveCondition.setConditionJsonText(oldActiveCondition.getConditionJsonText().replace("\"active\": true", "\"active\": false")); + oldActiveCondition.setActive("0"); + conditionList.add(oldActiveCondition); + } + + Condition newActiveCondition = helper.queryConditionByConditionId(botId, activeConditionId); + newActiveCondition.setActive("1"); + newActiveCondition.setActionText(newActiveCondition.getActionText().replace("status=waiting","status=active")); + newActiveCondition.setConditionJsonText(newActiveCondition.getConditionJsonText().replace( "\"active\": false", "\"active\": true")); + conditionList.add(newActiveCondition); + + flag = helper.batchUpdateCondition(botId, conditionList); + + } + + + + public void appendCondition(String conditionName, StringBuffer actionText, JSONObject condition){ + int count = 0; + String relationHead = "", relationName = "", relationTail; + String iteration = "1", finalText; + JSONObject questionElem = null, repeatElem = null; + StringBuffer questionText = new StringBuffer(), repeatText = new StringBuffer(), processText = new StringBuffer(); + + + String conditionPattern = "condition=%s:%s:%s|%s,%s,%s|%s|%s\r\n"; + + relationHead = condition.getString("relationHead"); + if(relationHead.equals("")) + relationHead = "#visitorname"; + relationTail = condition.getString("relationTail"); + if(relationTail.equals("")) + relationTail = "#visitorname"; + relationName = condition.getString("relationName"); + + //condition的属性 number、string、location + String dataType = condition.getString("dataType"); + + if(dataType != null && ! dataType.equals("")) + dataType = dataType; + else + dataType = ""; + + //解析问题的开始轮次等 + JSONArray questionList = condition.getJSONArray("questionList"); + count = questionList.size(); + for(int i = 0;i < count;i++){ + + if(i != 0) + questionText.append("~"); + + questionElem = questionList.getJSONObject(i); + questionText.append(questionElem.getString("que_start_time")).append(":").append(questionElem.getString("que_stop_time")); + questionText.append(":").append(questionElem.getString("que_sen")); + //添加base问题 + if(questionElem.getInteger("base") == 1){ + questionText.append(":base"); + } + } + + //添加复述列表 + JSONArray repeatList = condition.getJSONArray("repeatList"); + count = repeatList.size(); + for(int i = 0;i < count;i++) { + if(i != 0) + repeatText.append("~"); + + + repeatElem = repeatList.getJSONObject(i); + if(!repeatElem.getString("repeatKeywords").startsWith("+")) + repeatElem.put("repeatKeywords", "+" + repeatElem.getString("repeatKeywords")); + + repeatText.append(repeatElem.getString("repeatString")).append("=").append(repeatElem.getString("repeatKeywords")); + processText.append("process=").append(conditionName).append("=").append(repeatElem.getString("repeatKeywords").split("-")[0]).append("|pivot_httppost=active|\r\n"); + } + processText.append("process=").append(conditionName).append("=unknown|pivot_httppost=active|\r\n"); + processText.append("process=completed=true|pivot_httppost=active|\r\n"); + finalText = String.format(conditionPattern, conditionName, dataType, iteration, + relationHead, relationName, relationTail, questionText.toString(), repeatText.toString()); + + actionText.append(finalText); + actionText.append(processText.toString()); + + } + + + /** + * 更新rule并且监测condition模板中的base问题和style是否发生变化 + * @param parameters + */ + public void updateRelation(JSONObject parameters){ + int botId = parameters.getInteger("botId"), len, baseIdx1 = 0, baseIdx2 = 0, originConditionId; + Boolean updateFlag = false; + JSONObject conditionJson = new JSONObject(), patternConditionJson, questionDict; + String relation = ""; + List conditionList = helper.queryConditionAll(botId); + List conditionRelationList = new ArrayList(); + List conditionJsonList = new ArrayList(); + + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); + + if(intervalStatus.getStatus() == 1) { + for (Condition condition : conditionList) { + conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + conditionJson.put("conditionId", condition.getConditionId()); + relation = conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); + conditionRelationList.add(relation); + conditionJsonList.add(conditionJson); + } + + Map patternTextMap = engine.queryConditionPatternText(botId, conditionRelationList); + + + for (JSONObject condtiionJson : conditionJsonList) { + originConditionId = conditionJson.getInteger("originConditionId"); + updateFlag = false; + + if (patternTextMap.get(originConditionId) != null && intervalStatus.getStatus() == 1) { + + patternConditionJson = ActionParser.parse(patternTextMap.get(originConditionId)); + + //分别找到condition的base问题 + len = conditionJson.getJSONArray("questionList").size(); + for (int i = 0; i < len; i++) { + questionDict = conditionJson.getJSONArray("questionList").getJSONObject(i); + if (questionDict.getInteger("base") == 1) { + baseIdx1 = i; + break; + } + + } + + len = patternConditionJson.getJSONArray("questionList").size(); + for (int i = 0; i < len; i++) { + questionDict = patternConditionJson.getJSONArray("questionList").getJSONObject(i); + if (questionDict.getInteger("base") == 1) { + baseIdx2 = i; + break; + } + + } + + //如果关于base问题的两个json数据不一样,就更新数据 + if (!conditionJson.getJSONArray("questionList").getJSONObject(baseIdx1).equals(patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2))) { + conditionJson.getJSONArray("questionList").set(baseIdx1, patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2)); + updateFlag = true; + } + + //如果关于style的json数据不一致,就更新styleList + if (!conditionJson.getJSONArray("styleList").equals(patternConditionJson.getJSONArray("styleList"))) { + conditionJson.put("styleList", patternConditionJson.getJSONArray("styleList")); + updateFlag = true; + } + + if (updateFlag) { + parameters.put("conditionData", conditionJson); + intervalStatus = updateCondition(parameters); + } + } + } + } + + } + + + + /** + * 更新关键词单元, + * @param botId + * @param extraKeyword 额外需要更新的关键词 + * @param appendMacro 在宏定义中添加关键词 + * @param POS + */ + public IntervalStatus updateKnowledgeUnit(int botId, Map extraKeyword, Map appendMacro, String POS){ + StringBuffer newKeywords = new StringBuffer(); + IntervalStatus intervalStatus = null; + Boolean flag; + String keywordUnitText = engine.queryKeywordUnitText(botId), keywordPair[]; + + for(String line:keywordUnitText.split("\r\n")){ + if (line.startsWith("options|") || line.trim().equals("") || line.startsWith("idlelimit")) + continue; + + newKeywords.append(line); + if(line.startsWith("++")){ + keywordPair = line.split("\\|"); + if(appendMacro != null && appendMacro.containsKey(keywordPair[0])){ + newKeywords.append("+").append(appendMacro.get(keywordPair[0]).toString()); + } + } + newKeywords.append("\r\n"); + } + + if(extraKeyword != null) { + for (String key : extraKeyword.keySet()) { + newKeywords.append(key).append("|").append(extraKeyword.get(key)); + + if (key.equals("options")) { + BotInfo botInfo = helper.queryBotInfo(botId); + //是否将用户回答传给后台 + if (botInfo.getQueryTextTransfer().equals("1")) + newKeywords.append(",query_text_transfer"); + } + newKeywords.append("\r\n"); + } + } + + if(POS != null){ + newKeywords.append(POS); + } + + flag = engine.updateKeywordUnitText(botId, newKeywords.toString()); + + + if(flag || keywordUnitText.equals(newKeywords.toString())) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, UPDATE_KEYWORD_ERROR); + + return intervalStatus; + + } + + public void createBot(JSONObject data, String authorization){ + //新建bot + ActionPostElem ape = new ActionPostElem("", -1, data.getString("botName_yhm"), data.getString("catName"), authorization, data.getString("botType")); + + + postAction(ape); + + if(intervalStatus.getStatus() == 1){ + ((JSONObject)intervalStatus.getExtraData()).put("botId", ape.getBotId()); + ((JSONObject)intervalStatus.getExtraData()).put("botAccount", engine.queryBotAccountByBotId(ape.getBotId())); + BotInfo botInfo = new BotInfo(ape.getBotId(), "", "", "", "", "1", "1"); + helper.insertBotInfo(botInfo); + } + + } + + + public void queryBotInfo(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + BotInfo botInfo = helper.queryBotInfo(botId); + JSONArray returnList = new JSONArray(); + + if(botInfo != null) { + //List returnList = new ArrayList(); + returnList.add(new JSONArray(){{ + add("bothValue"); + add("将三元组两边的值都传给后台"); + add(botInfo.getBothValue()); + }}); + + returnList.add(new JSONArray(){{ + add("queryTextTransfer"); + add("将问句传给后台"); + add(botInfo.getQueryTextTransfer()); + }}); + + intervalStatus = new IntervalStatus(1, "", returnList); + }else{ + intervalStatus = new IntervalStatus(0, "查询失败"); + } + + + + } + + public IntervalStatus deleteCondition(JSONObject data, String authorization){ + int conditionId = data.getInteger("conditionId"); + int botId = data.getInteger("botId"); + IntervalStatus intervalStatus = null; + + Condition condition = helper.queryConditionByConditionId(botId, conditionId); + JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + Boolean flag = helper.deleteConditionBy2Id(botId, conditionId); + + if(flag){ + deleteIdElemIfExist(conditionJson.getInteger("originConditionId")); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, "删除失败"); + } + + return intervalStatus; + } + + public IntervalStatus updateCondition(JSONObject parameters){ + IntervalStatus intervalStatus = null; + Integer botId = parameters.getInteger("botId"), conditionId, displayOrder; + String categoryStr, actionText, conditionName, conditionJsonText, active; + Boolean flag; + + + JSONObject conditionData = parameters.getJSONObject("conditionData"); + + conditionId = conditionData.getInteger("conditionId"); + conditionName = conditionData.getString("conditionName"); + categoryStr = conditionData.getString("conditionCategory"); + displayOrder = conditionData.getInteger("displayOrder"); + active = conditionData.getBoolean("active") ? "1":"0"; + + conditionJsonText = conditionData.toJSONString(); + + + actionText = generateSingleActionText(conditionName, conditionData); + + Condition condition = new Condition(botId, conditionId, conditionJsonText, actionText, categoryStr, active, displayOrder); + flag = helper.updateConditionById(condition); + + if(!flag){ + condition = helper.queryConditionByConditionId(botId, conditionId); + if(condition != null && condition.getConditionJsonText().equals(conditionJsonText)){ + flag = true; + } + } + + + if(flag){ + intervalStatus = new IntervalStatus(1, "success"); + }else{ + intervalStatus = new IntervalStatus(0, "修改失败"); + } + + return intervalStatus; + } + + + + /** + * 将生成的action文本提交到周志宇处 + * @param ape + * @return + */ + public void postAction(ActionPostElem ape){ + String url = CONDITION_BACKEND_URL + "/post/actions"; + JSONObject retData = null; + Integer statusCode = 0; + + + JSONObject postData = new JSONObject(); + postData.put("botname", ape.getBotName()); + postData.put("actions", ape.getActionText()); + postData.put("catName", ape.getCategoryName()); + postData.put("cdt_name_ls", ape.getConditionIdPair()); + postData.put("id", ape.getBotId()); + + + //新建bot时不传botId + if(ape.getBotId() == -1){ + postData.remove("id"); + } + if(!ape.getBotType().equals("")) + postData.put("project", ape.getBotType()); + + + try { + retData = SimpleUtil.postJSON(url, postData, ape.getAuthorization()); + }catch (UnsupportedEncodingException e){ + retData = new JSONObject(){ + { + put("status_code", -1); + } + }; + } + //System.out.println(retData.toJSONString()); + + switch(retData.getInteger("status_code")){ + case 200: + switch(retData.getString("status")){ + case "Success": + ape.setBotId(retData.getInteger("id")); + intervalStatus = new IntervalStatus(1, "", new JSONObject()); + break; + case "Fail": + intervalStatus = new IntervalStatus(0, retData.getString("reason")); + break; + } + break; + case 401: + intervalStatus = new IntervalStatus(0, TOKEN_TIME_OUT); + break; + default: + intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR); + } + + } + + + public void gamePlotInit(String botName, int botId, String auth, JSONObject parameters, String startCondition, Map> conditionExtraKeywords){ + Boolean flag = true; + String elem[], postfix, conditionName, keywordPosition, actionText, relationName, finalText, activeFlag; + PlatformUtils platformUtils = null; + JSONObject patternConditionJson = null, conditionJson = null; + List idList = new ArrayList(); + List actionTextList = new ArrayList(); + List conditionList = new ArrayList(); + JSONArray conditionData = new JSONArray(), conditionPostPair = new JSONArray(); + Map id2unit = null; + Map macroMap = null, macroAppendMap = new HashMap(); + + try{ + platformUtils = new PlatformUtils(); + + helper.deleteUserData(botId); + + idList = platformUtils.queryConditionIdByTypetreeId(parameters.getJSONArray("conditionCategories")); + + id2unit = engine.queryUnitsByIdList(idList); + + for(Integer id:id2unit.keySet()){ + + patternConditionJson = ActionParser.parse(id2unit.get(id).getActions()); + patternConditionJson.put("originConditionId", id); + patternConditionJson.put("active", false); + patternConditionJson.put("conditionCategory", "0:默认"); + relationName = patternConditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); + + for(int i = 1;i < 10;i++){ + //给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样 + if(i == 1) + postfix = ""; + else + postfix = String.valueOf(i); + + activeFlag = "0"; + + conditionJson = (JSONObject) patternConditionJson.clone(); + conditionName = conditionJson.getString("conditionName") + postfix; + + if(!conditionExtraKeywords.containsKey(conditionName + "_tail")){ //如果没有用到这个condition,就跳过 + break; + } + + conditionJson.put("conditionName", conditionName); + + if(conditionJson.getString("relationHead").equals("?")) + keywordPosition = "left"; + else + keywordPosition = "right"; + + + + flag = conditionAppendKeyword(conditionName, conditionJson, conditionExtraKeywords, macroAppendMap); + + if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition)) + conditionJson.put("active", false); + + + actionText = generateSingleActionText(conditionName, conditionJson); + if(startCondition.equals(conditionName)) { + conditionJson.put("active", true); + actionText = actionText.replace("status=waiting", "status=active"); + activeFlag = "1"; + } + + conditionList.add(new Condition(botId, conditionJson.toJSONString(), actionText, conditionJson.getString("conditionCategory"), activeFlag)); + + actionTextList.add(actionText); + conditionData.add(conditionJson); + + String finalRelationName = relationName; + conditionPostPair.add(new JSONArray(){ + { + add(id); + add(finalRelationName); + } + }); + } + } + parameters.put("conditionData", conditionData); + finalText = generateCompleteActionText(parameters, actionTextList); + ape = new ActionPostElem(botId, botName, finalText, auth, "", conditionPostPair); + postAction(ape); + + if(intervalStatus.getStatus() == 1) { + helper.batchInsertCondition(conditionList); + //insertCondition(parameters); + + + if (intervalStatus.getStatus() == 1) { + engine.updateWelcomeText(botId, parameters.getString("welcome")); + updateKnowledgeUnit(botId, new HashMap() {{ + put("options", OPTIONS); + put("idlelimit", IDLE_LIMIT); + }}, macroAppendMap, parameters.getString("POS")); + } + } + + platformUtils.destroy(); + + + }catch (SQLException e){ + intervalStatus = new IntervalStatus(0, ACTION_TEXT_GENERATE_ERROR); + System.out.println(e.getMessage()); + } + + } + + public void getBotConditionInfo(int botId, String botName, String auth){ + String url = CONDITION_BACKEND_URL + "/get/actions/" + String.valueOf(botId); + Integer statusCode; + JSONObject receiveData = SimpleUtil.getMethod(url, auth); + IntervalStatus intervalStatus = null; + ape = new ActionPostElem(botId, botName, auth); + + statusCode = receiveData.getInteger("status_code"); + //System.out.println(receiveData.toJSONString()); + + switch(statusCode){ + case 200: + ape.setCategoryName(receiveData.getString("catName")); + ape.setConditionIdPair(receiveData.getJSONArray("cdt_name_ls")); + intervalStatus = new IntervalStatus(1, ""); + break; + case 401: + intervalStatus = new IntervalStatus(0,"token过期了"); + break; + default: + intervalStatus = new IntervalStatus(0, "condition后台报错"); + break; + } + } + + public Boolean conditionAppendKeyword(String conditionName, JSONObject conditionJson, Map> conditionExtraKeywords, Map macroAppendMap ){ + + String relationHead = conditionJson.getString("relationHead"); + String repeatKeywords = conditionJson.getJSONArray("repeatList").getJSONObject(0).getString("repeatKeywords").split("-")[0]; + + String extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_head")); + if(relationHead.startsWith("++")){ + if(macroAppendMap.containsKey(relationHead)){ + macroAppendMap.get(relationHead).append(extraKeywords); + }else{ + macroAppendMap.put(relationHead, new StringBuffer(extraKeywords)); + } + } + conditionJson.put("relationHead", extraKeywords); + + + extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_tail")); + if(repeatKeywords.startsWith("++")){ + if(macroAppendMap.containsKey(repeatKeywords)){ + macroAppendMap.get(repeatKeywords).append(extraKeywords); + }else{ + macroAppendMap.put(repeatKeywords, new StringBuffer(extraKeywords)); + } + } + conditionJson.getJSONArray("repeatList").getJSONObject(0).put("repeatKeywords", extraKeywords); + + + return true; + } + + public Set getConditionNameSet(List conditionList){ + String elements[]; + String conditionName; + Set conditionNameSet = new HashSet(); + for(Condition condition:conditionList){ + + for(String line:condition.getActionText().split("\r\n")){ + if(line.startsWith("condition")){ + + elements = line.trim().split("\\|"); + + conditionName = elements[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + break; + } + } + } + + return conditionNameSet; + } + public String getConditionName(Condition condition){ + String elements[]; + String conditionName = ""; + + for(String line:condition.getActionText().split("\r\n")){ + if(line.startsWith("condition")){ + + elements = line.trim().split("\\|"); + + conditionName = elements[0].split("=")[1].split(":")[0]; + break; + } + } + + + return conditionName; + } + + + /** + * 更新condition的名字 + * @param parameters + * @return + */ + public String updateConditionName(JSONObject parameters){ + + + int botId = parameters.getInteger("botId"); + int conditioId = parameters.getInteger("conditionId"); + Boolean flag = true; + String conditionName = parameters.getString("conditionName"), actionText = ""; + + Condition condition = helper.queryConditionByConditionId(botId, conditioId); + JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + List conditionList = helper.queryConditionAll(botId); + Set conditionNameSet = getConditionNameSet(conditionList); + + + if(conditionNameSet.contains(conditionName)){ + intervalStatus = new IntervalStatus(0, CONDITION_NAME_DUMPLICATE); + }else{ + conditionJson.put("conditionName", conditionName); + actionText = generateSingleActionText(conditionName, conditionJson); + condition.setActionText(actionText); + condition.setConditionJsonText(conditionJson.toJSONString()); + flag = helper.updateConditionById(condition); + + if(!flag){ + intervalStatus = new IntervalStatus(0, CONDITION_NAME_UPDATE_ERROR); + }else{ + intervalStatus = new IntervalStatus(1, ""); + } + + } + + return ""; + } + + + public void updateGoodbye(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String goodbyeText = parameters.getString("sayGoodBye"); + + + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);put("sayGoodbye", goodbyeText);}}, null, null); + + } + + /** + * 修改conditiond的显示顺序 + * @param parameters + */ + public void updateConditionDisplayOrder(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + int conditioId = parameters.getInteger("conditionId"); + int order = parameters.getInteger("order"); + Boolean flag = true; + + Condition condition = helper.queryConditionByConditionId(botId, conditioId); + + condition.setDisplayOrder(order); + if(helper.updateConditionById(condition)){ + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, CONDITION_UPDATE_ERROR); + } + + + } + + public void updateBotInfo(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + Boolean updateFlag = true; + + String option = parameters.getString("option"); + String value = parameters.getString("value"); + + BotInfo botInfo = helper.queryBotInfo(botId); + + if(botInfo != null) { + + switch (option) { + case "welcomeText": + botInfo.setWelcomeText(value); + break; + case "postURL": + botInfo.setPostURL(value); + break; + case "bothValue": + botInfo.setBothValue(value); + break; + case "queryTextTransfer": + botInfo.setQueryTextTransfer(value); + break; + } + updateFlag = helper.updateBotInfo(botInfo); + if(updateFlag){ + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, UPDATE_ERROR); + } + }else{ + intervalStatus = new IntervalStatus(0, BOT_INFO_NOT_EXIST); + } + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java new file mode 100644 index 0000000..9207e17 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java @@ -0,0 +1,206 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.entity.BotInfo; +import com.qiwu.chatbotbackend.actiongenerate.entity.Category; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.db.SqlHelper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class CategoryUtils { + SqlHelper helper = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public CategoryUtils(SqlHelper helper){ + this.helper = helper; + } + + public void insertCategory(JSONObject parameters){ + int id = 0; + Category category = new Category(parameters.getInteger("botId"), parameters.getInteger("categoryParentId"), parameters.getString("categoryName")); + + id = helper.insertCategoryByBotId(category); + + if(id != 0) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, CATEGORY_INSERT_ERROR); + + } + + public void updateCategory(JSONObject parameters){ + Boolean updateFlag = true; + List childIds = null; + Category category = new Category(parameters.getInteger("botId"), parameters.getInteger("categoryId"), + parameters.getInteger("newParentId"), parameters.getString("newCategoryName")); + + childIds = findChildCategoryIds(category.getBotId(), category.getCategoryId()); + + + if(childIds.contains(category.getParentId())){ + intervalStatus = new IntervalStatus(0, CATEGORY_UPDATE_CONFLICT); + }else{ + updateFlag = helper.updateCategory(category); + if(updateFlag) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, CATEGORY_UPDATE_ERROR); + } + + } + + public List findChildCategoryIds(int botId, int rootId){ + List categories = helper.queryCategoryAll(botId); + List idList = new ArrayList(){ + { + add(rootId); + } + }; + + if(rootId == -1) //0和-1表示所有类别 + idList.add(0); + + for(Category category:categories){ + if(idList.contains(category.getParentId())){ + idList.add(category.getCategoryId()); + } + + } + + return idList; + } + + + public List findChildCategoryIds(int botId, int rootId, List childCategories){ + List categories = helper.queryCategoryAll(botId); + List idList = new ArrayList(){ + { + add(rootId); + } + }; + + if(rootId == -1) //0和-1表示所有类别 + idList.add(0); + + for(Category category:categories){ + if(idList.contains(category.getParentId())){ + idList.add(category.getCategoryId()); + } + if(idList.contains(category.getCategoryId())){ + childCategories.add(category); + } + } + + return idList; + } + + + public void queryCategory(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + String categoryId, parentId, defaultCategoryName = "默认"; + List defaultCategoryPath = new ArrayList(); + + List categories = helper.queryCategoryAll(botId); + Map categoryMap = new HashMap(); + BotInfo botInfo = helper.queryBotInfo(botId); + JSONObject finalJson = new JSONObject(); + + /** + * 结构是 + * { + * |--- -1 (根目录) + * | |----0 默认类别 + * | |----其他用户新建类别 + * } + */ + JSONObject categoryTree = new JSONObject(); + categoryTree.put("0", new JSONObject(){{ + put("value", 0); + put("label", "默认"); + put("children", new JSONArray()); + }} + ); + categoryTree.put("-1", new JSONObject(){{ + put("value", -1); + put("label", "root"); + put("children", new JSONArray()); + }} + ); + categoryTree.getJSONObject("-1").getJSONArray("children").add(categoryTree.getJSONObject("0")); + + + for(Category category:categories){ + categoryMap.put(category.getBotId(), category); + } + + + //默认类别路径格式:"[一级类别,二级类别, 三级类别..]" + if(botInfo.getDefaultConfigCategory().equals("") || !botInfo.getDefaultConfigCategory().startsWith("[")){ + //默认路径是从0开始 + defaultCategoryPath.add(0); + }else{ + defaultCategoryPath = JSONArray.parseArray(botInfo.getDefaultConfigCategory(), Integer.class); + } + + + for(Category category:categories){ + categoryId = String.valueOf(category.getCategoryId()); + parentId = String.valueOf(category.getParentId()); + + categoryTree.put(categoryId, new JSONObject(){ + { + put("value", category.getCategoryId()); + put("label", category.getName()); + } + }); + + categoryTree.putIfAbsent(parentId, new JSONObject()); + if(categoryTree.getJSONObject(parentId).getJSONArray("children") == null){ + categoryTree.getJSONObject(parentId).put("children", new JSONArray()); + } + + //将当年类别id的引用放在父id下 + categoryTree.getJSONObject(parentId).getJSONArray("children").add(categoryTree.getJSONObject(categoryId)); + + if(category.getCategoryId() == defaultCategoryPath.get(defaultCategoryPath.size()-1)){ + defaultCategoryName = category.getName(); + } + + } + + finalJson.put("category", categoryTree.getJSONObject("-1").getJSONArray("children")); + finalJson.put("defaultId", JSONArray.parseArray(JSON.toJSONString(defaultCategoryPath))); + finalJson.put("defaultIdName", defaultCategoryName); + + intervalStatus = new IntervalStatus(1, "", finalJson); + + + } + + public void deleteCategory(JSONObject parameters){ + + Boolean flag1, flag2; + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + + ListidList = findChildCategoryIds(botId, categoryId); + flag1 = helper.deleteCategoryByCategoryIds(botId, idList); + if(flag1) { + helper.deleteConfigByCategories(botId, idList); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, CATEGORY_DELETE_ERROR); + } + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java new file mode 100644 index 0000000..ccc932e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java @@ -0,0 +1,324 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.ConfigTerm; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.Premise; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.CONFIG_INSERT_ERROR; + + + +public class ConfigTermUtils { + + SqlHelper helper = null; + String botAccount = ""; + ServletContext context = null; + UserInfo userInfo = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public ConfigTermUtils(String botAccount, SqlHelper helper, ServletContext context) throws IOException, SQLException { + this.helper = helper; + this.context = context; + this.botAccount = botAccount; + + UserInfoController uiController = new UserInfoController(); + this.userInfo = uiController.userInfoQuery(botAccount, context); + } + + public ConfigTermUtils(SqlHelper helper){ + this.helper = helper; + } + + + public void insertConfigTerm(JSONObject parameters) throws IOException { + Boolean insertFlag = true; + List configList = new ArrayList(); + List idList = new ArrayList(); + + + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + + + //处理特殊字符 + ConfigTermText configText = configPreprocessing(parameters.getJSONObject("configData")); + configList.add(parameters.getJSONObject("configData")); + + insertFlag = helper.batchInsertConfigByBotId(botId, configList, idList, categoryId); + + + //generateSingleConfigText(); + if(insertFlag){ + UserInfoController.insertConfig(botAccount, String.valueOf(idList.get(0)), configText.toString() + idList.get(0), context); + UserInfoController.writeConfigText(botAccount, userInfo); + intervalStatus = new IntervalStatus(1,""); + }else{ + intervalStatus = new IntervalStatus(0, CONFIG_INSERT_ERROR); + } + + } + + + /** + * 数据预处理 + * @param configJson + */ + public ConfigTermText configPreprocessing(JSONObject configJson){ + int premiseNum = 0, knowledgeNum = 0, nextStepNum; + Premise premise = null; + String reply, auxiliaryPriority = "0", nextStepStatus, configName; + StringBuffer nextStepText = new StringBuffer(), featureText = new StringBuffer(); + JSONObject premiseJson = null, knowledgeJson = null, nextStep; + + ConfigTermText configTermText = null; + + List curPremiseList = new ArrayList(); + List hisPremiseList = new ArrayList(); + Map updateKnowledge = new HashMap(); + Map punctReplaceMap = new HashMap(){ + { + put(",", ","); + put("|", ""); + put("\r\n", ""); + put("\n", ""); + put("\t", ""); + } + }; + + + //解析当前信息的前置条件 + premiseNum = configJson.getJSONArray("currentPremiseList").size(); + for(int i = 0;i < premiseNum;i++){ + premiseJson = configJson.getJSONArray("currentPremiseList").getJSONObject(i); + premise = new Premise(premiseJson.getString("actionName"), premiseJson.getString("cmpType"), + premiseJson.getString("operator"), premiseJson.getString("keywords")); + + if(!premise.getConditionName().equals("") || !premise.getKeyword().equals("")){ + + premise.setKeyword(textReplace(premise.getKeyword(), punctReplaceMap)); + curPremiseList.add(premise); + + } + premiseJson.put("keywords", textReplace(premiseJson.getString("keywords"), punctReplaceMap)); + } + + //解析已知信息的前置条件 + premiseNum = configJson.getJSONArray("historyPremiseList").size(); + for(int i = 0;i < premiseNum;i++){ + premiseJson = configJson.getJSONArray("historyPremiseList").getJSONObject(i); + premise = new Premise(premiseJson.getString("actionName"), premiseJson.getString("cmpType"), + premiseJson.getString("operator"), premiseJson.getString("keywords")); + + if(!premise.getConditionName().equals("") || !premise.getKeyword().equals("")){ + + premise.setKeyword(textReplace(premise.getKeyword(), punctReplaceMap)); + hisPremiseList.add(premise); + } + premiseJson.put("keywords", textReplace(premiseJson.getString("keywords"), punctReplaceMap)); + } + + //获得辅助优先级 + if(configJson.get("auxiliaryPriority") != null){ + auxiliaryPriority = String.valueOf(configJson.getInteger("auxiliaryPriority")); + } + + //获得回答 + reply = textReplace(configJson.getString("reply"), punctReplaceMap); + configJson.put("reply", textReplace(configJson.getString("reply"), punctReplaceMap)); + + //获得更新知识单元 + if(configJson.getJSONArray("updateKnowledge") != null) { + knowledgeNum = configJson.getJSONArray("updateKnowledge").size(); + for (int i = 0; i < knowledgeNum; i++) { + knowledgeJson = configJson.getJSONArray("updateKnowledge").getJSONObject(i); + + updateKnowledge.put(knowledgeJson.getString("variableName"), textReplace(knowledgeJson.getString("keyword"), punctReplaceMap)); + knowledgeJson.put("keyword", textReplace(knowledgeJson.getString("keyword"), punctReplaceMap)); + } + } + + //多个下一步激活问题的处理 + + if(configJson.get("nextStepList") != null){ + nextStepNum = configJson.getJSONArray("nextStepList").size(); + + for(int i = 0;i < nextStepNum;i++){ + if(i != 0) + nextStepText.append(","); + nextStep = configJson.getJSONArray("nextStepList").getJSONObject(i); + nextStepText.append(nextStep.getString("nextStep")); + if(nextStep.get("except") != null && nextStep.getJSONArray("except").size() != 0){ + nextStepText.append(":").append(Joiner.on("-").join(nextStep.getJSONArray("except"))); + } + + } + } + + if(curPremiseList.size() != 0 || hisPremiseList.size() != 0) + //match表示需要条件匹配 + featureText.append("match"); + + //是否提交表单 + if(configJson.getBoolean("doPost")){ + featureText.append("post::").append(configJson.getString("postType")); + featureText.append("(").append(configJson.getString("postURL")).append(")"); + + } + + //判断下一步是选择新的问题,还是留在原来的问题,或是返回上一个问题 + if(!configJson.containsKey("nextStepStatus")) + featureText.append(",return-0"); + else{ + nextStepStatus = configJson.getString("nextStepStatus"); + switch(nextStepStatus){ + case "stay": + featureText.append(",return-0"); + break; + case "back": + featureText.append(",return-1"); + break; + case "return": + case "jump": + //存在多个下一步 + if(configJson.get("nextStepList") != null && configJson.getJSONArray("nextStepList").size() > 1){ + featureText.append(",newNext"); + } + break; + case "activate": + //下一步激活,且激活不为空 + if(configJson.get("nextStepList") != null && !configJson.getJSONArray("nextStepList").getJSONObject(0).getString("nextStep").equals("")){ + featureText.append(",activate"); + } + break; + } + } + + configTermText = new ConfigTermText(curPremiseList, hisPremiseList, updateKnowledge, "", "", "", featureText.toString(), reply, nextStepText.toString(), auxiliaryPriority); + + configName = configJson.getString("configName"); + if(configName != null && !configName.equals("")) { + configTermText.setConfigName(configName, false); + } + + return configTermText; + + + + } + + public void deleteConfig(JSONObject parameters) throws IOException { + Boolean deleteFlag = true; + int botId = parameters.getInteger("botId"); + int configId = parameters.getInteger("configId"); + + deleteFlag = helper.deleteConfigByConfigId(botId, configId); + + if(deleteFlag){ + UserInfoController.deleteConfig(botAccount, String.valueOf(configId), "", context); + UserInfoController.writeConfigText(botAccount, userInfo); + } + + } + + public void updateConfig(JSONObject parameters) throws IOException { + Boolean updateFlag = true; + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + int configId = parameters.getInteger("configId"); + + ConfigTermText configText = configPreprocessing(parameters.getJSONObject("configData")); + + ConfigTerm configTerm = helper.queryConfigByConfigId(botId, configId); + + updateFlag = helper.updateConfig(new ConfigTerm(botId, configId, categoryId, parameters.getJSONObject("configData"))); + if(!updateFlag){ + if(parameters.getJSONObject("configData").toJSONString().equals(configTerm.getConfigJsonText())){ + updateFlag = true; + } + } + + if(updateFlag){ + //更新配置条目 + UserInfoController.deleteConfig(botAccount, String.valueOf(configId), "", context); + UserInfoController.insertConfig(botAccount, String.valueOf(configId), configText.toString() + configId, context); + UserInfoController.writeConfigText(botAccount, userInfo); + } + + } + + + public void queryConfig(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + JSONArray configDataList = new JSONArray(); + JSONObject configJson = null; + + List configTermList = helper.queryConfigByCategoryId(botId, categoryId); + + for(ConfigTerm configTerm:configTermList){ + configJson = JSONObject.parseObject(configTerm.getConfigJsonText()); + configJson.put("configId", configTerm.getConfigId()); + configJson.put("categoryId", configTerm.getCategoryId()); + + configDataList.add(configJson); + } + + intervalStatus = new IntervalStatus(1, "", configDataList); + } + + public void querySleepingConfig(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + JSONArray sleepingConfigs = new JSONArray(); + JSONObject configJson = null; + + List configTermList = helper.querySleepingConfig(botId); + + for(ConfigTerm configTerm:configTermList){ + sleepingConfigs.add(new JSONArray(){ + { + add(configTerm.getConfigId()); + add(configTerm.getConfigName()); + } + }); + } + + intervalStatus = new IntervalStatus(1, "", sleepingConfigs); + } + + /** + * 将文本中的一些特殊字符过滤掉 + * @param text + * @param replaceMap + * @return + */ + public String textReplace(String text, Map replaceMap){ + for(String key:replaceMap.keySet()){ + text = text.replace(key, replaceMap.get(key)); + } + + return text; + } + + public void generateSingleConfigText(JSONObject configJson){ + + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java new file mode 100644 index 0000000..36b8686 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java @@ -0,0 +1,4 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +public class MacroUtils { +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java new file mode 100644 index 0000000..259e624 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java @@ -0,0 +1,159 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.entity.Variable; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class VariableUtils { + SqlHelper helper = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + String botAccount = ""; + ServletContext context = null; + UserInfo userInfo = null; + + public VariableUtils(String botAccount, SqlHelper helper, ServletContext context) throws IOException, SQLException { + this.helper = helper; + this.context = context; + this.botAccount = botAccount; + + UserInfoController uiController = new UserInfoController(); + this.userInfo = uiController.userInfoQuery(botAccount, context); + } + + + + + public VariableUtils(SqlHelper helper) { + this.helper = helper; + } + + public void queryVariable(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + List variables = null; + JSONArray varList = new JSONArray(); + + variables = helper.queryVariableAll(botId); + + for(Variable variable:variables){ + varList.add(new JSONObject(){ + { + put("id", variable.getVariableId()); + put("categoryId", variable.getCategoryId()); + put("name", variable.getName()); + put("description", variable.getDescription()); + put("default", variable.getValue()); + } + }); + } + + intervalStatus = new IntervalStatus(1, "", varList); + + } + + public void insertVariable(JSONObject parameters) throws IOException { + int botId = parameters.getInteger("botId"); + int variableId = 0; + + Variable variable = new Variable(parameters.getInteger("botId"), parameters.getInteger("categoryId"), + parameters.getString("varName"), parameters.getString("varDescription"), + parameters.getString("varDefaultValue")); + + if(helper.queryVariableByName(variable.getBotId(), variable.getName()) != null){ + intervalStatus = new IntervalStatus(0, VARIABLE_NAME_DUMPLICATE); + }else{ + variableId = helper.insertVariable(variable); + + if(variableId != 0){ + + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + //修改配置文件 + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_INSERT_ERROR); + } + + + } + } + + public void deleteVairiable(JSONObject parameters) throws IOException { + int botId = parameters.getInteger("botId"); + int variableId = parameters.getInteger("varId"); + Boolean deleteFalg = true; + + //从delete + //deleteFalg = + Variable variable = helper.queryVariableByVariableId(botId, variableId); + + if(deleteFalg) { + deleteFalg = helper.deleteVariable(botId, variableId); + + System.out.println("deleteFlag" + deleteFalg); + + if(deleteFalg){ + intervalStatus = new IntervalStatus(1, ""); + UserInfoController.deleteVariable(botAccount, "", variable.getName(), context); + UserInfoController.writeConfigText(botAccount, userInfo); + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_SQL_DELETE_ERROR); + } + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_DELETE_ERROR); + } + } + + public void updateVariable(JSONObject parameters) throws IOException { + Boolean updateFlag = true; + Variable variable = new Variable(parameters.getInteger("botId"), parameters.getInteger("varId"), + parameters.getInteger("categoryId"), parameters.getString("varName"), + parameters.getString("varDescription"), parameters.getString("varDefaultValue")); + + Variable variable2 = helper.queryVariableByName(variable.getBotId(), variable.getName()); + + if(variable2 != null && variable.getVariableId() == variable2.getVariableId()){ + intervalStatus = new IntervalStatus(0, VARIABLE_NAME_DUMPLICATE); + }else{ + updateFlag = helper.updateVariable(variable); + + if(updateFlag){ + intervalStatus = new IntervalStatus(1, ""); + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + }else{ + + if(variable.getCategoryId() == variable2.getCategoryId() && variable.getBotId() == variable2.getBotId() + && variable.getValue().equals(variable2.getValue()) && variable.getName().equals(variable2.getValue()) + && variable.getDescription().equals(variable2.getDescription())){ + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + intervalStatus = new IntervalStatus(1, ""); + }else { + intervalStatus = new IntervalStatus(0, VARIABLE_UPDATE_ERROR); + } + } + } + + } + + public Set getVariableNameSet(List variableList){ + Set variableNameSet = new HashSet(); + for(Variable variable:variableList){ + variableNameSet.add(variable.getName()); + } + + return variableNameSet; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java b/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java new file mode 100644 index 0000000..8e3df58 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.controller; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ResourceLoader; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; + +@RestController +@ResponseBody +public class BackupController { + + @Autowired + ResourceLoader loader; + + + @GetMapping("/sayhi2") + public ResponseEntity getFile(@PathVariable("name") String name){ + System.out.println("---" + name); + String filePath = BOT_BACKUP_DIR + name; + byte[] body = null; + + try { + body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream()); + }catch (Exception e){ + e.printStackTrace(); + } + + + String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length()); + HttpHeaders headers=new HttpHeaders(); + headers.add("Content-Disposition", "attachment;filename="+fileName); + + return new ResponseEntity(body, headers, HttpStatus.OK); + } + + @RequestMapping("/sayhi1") + public ResponseEntity getFile2(){ + System.out.println("---"); + String filePath = BOT_BACKUP_DIR; + byte[] body = null; + + try { + body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream()); + }catch (Exception e){ + e.printStackTrace(); + } + + + String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length()); + HttpHeaders headers=new HttpHeaders(); + headers.add("Content-Disposition", "attachment;filename="+fileName); + + return new ResponseEntity(body, headers, HttpStatus.OK); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java b/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java new file mode 100644 index 0000000..555f8e4 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java @@ -0,0 +1,13 @@ +package com.qiwu.chatbotbackend.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Hello { + + @RequestMapping("/sayhi") + public String sayHi() { + return "hello: "; + } +} diff --git a/src/db/C3p0Utils.java b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java similarity index 90% rename from src/db/C3p0Utils.java rename to src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java index cccd088..cc630ea 100644 --- a/src/db/C3p0Utils.java +++ b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java @@ -15,7 +15,8 @@ public class C3p0Utils { //通过标识名来创建相应连接池 static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); //通过标识名来创建相应连接池 - static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("mysql2"); + static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("engine"); + static ComboPooledDataSource dataSource3 = new ComboPooledDataSource("platform"); //从连接池中取用一个连接 public static Connection getConnection() throws SQLException { @@ -39,6 +40,17 @@ public class C3p0Utils { } } + //从连接池中取用一个连接 + public static Connection getPlatformConnection() throws SQLException { + try { + return dataSource3.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + //释放连接回连接池 public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { if (rs != null) { diff --git a/src/db/DB.java b/src/main/java/com/qiwu/chatbotbackend/db/DB.java similarity index 100% rename from src/db/DB.java rename to src/main/java/com/qiwu/chatbotbackend/db/DB.java diff --git a/src/db/SqlHelper.java b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java similarity index 59% rename from src/db/SqlHelper.java rename to src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java index a3020ff..9ec475d 100644 --- a/src/db/SqlHelper.java +++ b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java @@ -1,8 +1,8 @@ package com.qiwu.chatbotbackend.db; import com.alibaba.fastjson.JSONObject; -import com.qiwu.actiongenerate.entity.BotInfo; -import com.qiwu.actiongenerate.entity.Condition; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; @@ -37,6 +37,524 @@ public class SqlHelper { } } + + + + //---------------------------------------变量的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + public List queryVariableAll(int botId){ + String sql = "select * from chatbot_variable where botId= ?"; + List variables = new ArrayList(); + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + variables.add(variable); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variables; + } + + public Variable queryVariableByName(int botId, String name){ + String sql = "select * from chatbot_variable where botId= ? and name= ?"; + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setString(2, name); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variable; + } + + + public Variable queryVariableByVariableId(int botId, int variableId){ + String sql = "select * from chatbot_variable where botId= ? and variableId= ?"; + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, variableId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variable; + } + + public Integer insertVariable(Variable variable) { + String sql = "insert into chatbot_variable (botId, categoryId, name, description, defaultValue) VALUES (?, ?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + int id = 0; + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setInt(1, variable.getBotId()); + ps.setInt(2, variable.getCategoryId()); + ps.setString(3, variable.getName()); + ps.setString(4, variable.getDescription()); + ps.setString(5, variable.getValue()); + + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + public Integer insertBotInfo(BotInfo botInfo) { + String sql = "insert into bot_info (botId, defaultConfigCategory, welcomeText, goodbyeText, postURL, queryTextTransfer) VALUES (?, ?, ?, ?, ?, 1)"; + String userName = ""; + String result = "empty"; + int id = 0; + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setInt(1, botInfo.getBotId()); + ps.setString(2, botInfo.getDefaultConfigCategory()); + ps.setString(3, botInfo.getWelcomeText()); + ps.setString(4, botInfo.getGoodbyeText()); + ps.setString(5, botInfo.getPostURL()); + + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + public boolean deleteVariable(int botId, int variableId) { + String sql = "delete from chatbot_variable where botId= ? and variableId = ?"; + String userName = ""; + String result = "empty"; + boolean b = false; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setInt(2, variableId); + + b = ps.executeUpdate() == 1; + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + + + public Boolean updateVariable(Variable variable){ + boolean b = false; + + try { + String sql = "update chatbot_variable set categoryId = ?, name = ?, description = ?, defaultValue = ? where botId = ? and variableId = ?"; + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, variable.getCategoryId()); + ps.setString(2, variable.getName()); + ps.setString(3, variable.getDescription()); + ps.setString(4, variable.getValue()); + ps.setInt(5, variable.getBotId()); + ps.setInt(6, variable.getVariableId()); + + b = ps.executeUpdate() == 1; + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + //----------------------------------------配置条目类别的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + + public boolean deleteCategoryByCategoryIds(int botId, List idList) { + String sql = "delete from config_categories where botId= ? and categoryId in (?)"; + + boolean b = false; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setString(2, Joiner.on(",").join(idList)); + b = ps.executeUpdate() == 1; + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CATEGORY_ERROR); + e.printStackTrace(); + return false; + } + } + + + public Integer insertCategoryByBotId(Category category) { + String sql = "INSERT INTO config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + boolean b = false; + int id = 0; + try { + conn.setAutoCommit(false); + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setInt(1, category.getBotId()); + ps.setInt(2, category.getParentId()); + ps.setString(3, category.getName()); + ps.setString(4, category.getStatus()); + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + + + public List queryCategoryAll(int botId){ + String sql = "select * from config_categories where botId= ?"; + List categories = new ArrayList(); + Category category = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + category = new Category(rs.getInt("botId"), rs.getInt("categoryId"), + rs.getInt("categoryParentId"), rs.getString("categoryName")); + categories.add(category); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return categories; + } + + public Boolean updateCategory(Category category){ + boolean b = false; + + try { + String sql = "update config_categories set categoryName = ?, categoryParentId = ? where botId = ? and categoryId = ?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1,category.getName()); + ps1.setInt(2, category.getParentId()); + ps1.setInt(3, category.getBotId()); + ps1.setInt(4, category.getCategoryId()); + + b = ps1.executeUpdate() ==1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + //----------------------------------------配置条目的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + public boolean deleteConfigByCategories(int botId, List idList) { + boolean b = false; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ? and categoryId in (?)"); + ps1.setInt(1, botId); + ps1.setString(2, Joiner.on(",").join(idList)); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + public boolean deleteConfigByConfigId(int botId, int configId) { + boolean b = false; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ? and configId = ?"); + ps1.setInt(1, botId); + ps1.setInt(2, configId); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + public List queryConfigByCategoryId(int botId, int configId){ + String sql = "select * from chatbot_config where botId= ? and categoryId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, configId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + + public List querySleepingConfig(int botId){ + String sql = "select * from chatbot_config where configName != '' and botId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + + public List queryConfigByCategoryIdList(int botId, List categoryIdList){ + String sql = "select * from chatbot_config where botId= ? and categoryId in (" + Joiner.on(",").join(categoryIdList) + ")"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + //ps.setString(2, Joiner.on(",").join(categoryIdList)); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + public ConfigTerm queryConfigByConfigId(int botId, int configId){ + String sql = "select * from chatbot_config where botId= ? and configId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, configId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + //actionTextList.add(rs.getString("actionText")); + //configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTerm; + } + + public int insertConfig(int botId, JSONObject configData, int categoryId) { + boolean insertFlag = true; + Boolean b = false; + int id = 0; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, configData.toJSONString()); + ps.setString(4, (String)configData.get("configName")); + + + b = ps.executeUpdate() == 1; + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + return id; + } + + public Boolean updateConfig(ConfigTerm configTerm){ + boolean b = false; + + try { + String sql = "update chatbot_config set configData = ? ,categoryId = ?, configName = ? where botId=? and configId=?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, configTerm.getConfigJsonText()); + ps1.setInt(2, configTerm.getCategoryId()); + ps1.setString(3, configTerm.getConfigName()); + ps1.setInt(4, configTerm.getBotId()); + ps1.setInt(5, configTerm.getConfigId()); + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + + + //----------------------------------------condition操作--------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------ @@ -53,15 +571,23 @@ public class SqlHelper { PreparedStatement ps1 = conn.prepareStatement(sql1); ps1.setInt(1, botId); b1 = ps1.execute(); + ps1.close(); + PreparedStatement ps2 = conn.prepareStatement(sql2); ps2.setInt(1, botId); - b2 = ps1.execute(); + b2 = ps2.execute(); + ps2.close(); + PreparedStatement ps3 = conn.prepareStatement(sql3); ps3.setInt(1, botId); - b3 = ps1.execute(); + b3 = ps3.execute(); + ps3.close(); + PreparedStatement ps4 = conn.prepareStatement(sql4); ps4.setInt(1, botId); - b4 = ps1.execute(); + b4 = ps4.execute(); + ps4.close(); + } catch (SQLException e) { System.out.println(DELETE_USER_DATA_ERROR); e.printStackTrace(); @@ -71,7 +597,7 @@ public class SqlHelper { } - public Boolean batchInsertCondition(List insertList){ + public Boolean batchInsertCondition(List conditionList){ int count[]; boolean insertFlag = true; String sql = "", varName, varValue, description; @@ -84,12 +610,12 @@ public class SqlHelper { sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - for(String[] elements:insertList){ - ps.setString(1, elements[0]); - ps.setString(2, elements[1]); - ps.setString(3, elements[2]); - ps.setString(4, elements[3]); - ps.setString(5, elements[4]); + for(Condition condition:conditionList){ + ps.setInt(1, condition.getBotId()); + ps.setString(2, condition.getConditionJsonText()); + ps.setString(3, condition.getCategory()); + ps.setString(4, condition.getActionText()); + ps.setString(5, condition.getActive()); ps.addBatch(); } @@ -131,6 +657,9 @@ public class SqlHelper { actionTextList.add(rs.getString("actionText")); } + ps.close(); + rs.close(); + }catch(Exception e){ @@ -142,18 +671,22 @@ public class SqlHelper { public Condition queryActiveCondition(int botId){ Condition condition = null; - String sql = "select * from chatbot_condition where active= 1"; + String sql = "select * from chatbot_condition where active= 1 and botId = ?"; String pre_name = ""; List actionTextList = new ArrayList(); try{ PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); ResultSet rs = ps.executeQuery(); if(rs.next()){ condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); } + ps.close(); + rs.close(); + }catch(Exception e){ @@ -162,10 +695,29 @@ public class SqlHelper { return condition; } + public boolean deleteConditionBy2Id(int botId, int conditionId) { + boolean b; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_condition where botId= ? and conditionId=?"); + ps1.setInt(1, botId); + ps1.setInt(2, conditionId); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + public List queryConditionCategoriesById(int botId){ - String sql = "select categoryStr from chatbot_condition where botId= ?"; + String sql = "select categoryInfo from chatbot_condition where botId= ?"; String pre_name = ""; List categoryList = new ArrayList(); try{ @@ -173,9 +725,12 @@ public class SqlHelper { ps.setInt(1,botId); ResultSet rs = ps.executeQuery(); while(rs.next()){ - categoryList.add(rs.getString("categoryStr")); + categoryList.add(rs.getString("categoryInfo")); } + ps.close(); + rs.close(); + }catch(Exception e){ @@ -195,10 +750,13 @@ public class SqlHelper { ps.setInt(1,botId); ResultSet rs = ps.executeQuery(); if(rs.next()){ - botInfo = new BotInfo(rs.getInt("botId"), rs.getString("welcomText"), rs.getString("goodbyeText"), rs.getString("postURL"), rs.getString("defaultConfigCategory"), + botInfo = new BotInfo(rs.getInt("botId"), rs.getString("welcomeText"), rs.getString("goodbyeText"), rs.getString("postURL"), rs.getString("defaultConfigCategory"), rs.getString("bothValue"), rs.getString("queryTextTransfer")); } + ps.close(); + rs.close(); + }catch(Exception e){ e.printStackTrace(); @@ -206,6 +764,36 @@ public class SqlHelper { return botInfo; } + public Boolean updateBotInfo(BotInfo botInfo){ + boolean b; + + try { + String sql = "update bot_info set welcomeText = ?, goodbyeText = ?, postURL = ?, defaultConfigCategory = ?, bothValue = ?, queryTextTransfer = ? where botId = ?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, botInfo.getWelcomeText()); + ps1.setString(2, botInfo.getGoodbyeText()); + ps1.setString(3, botInfo.getPostURL()); + ps1.setString(4, botInfo.getDefaultConfigCategory()); + ps1.setString(5, botInfo.getBothValue()); + ps1.setString(6, botInfo.getQueryTextTransfer()); + ps1.setInt(7, botInfo.getBotId()); + + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + public Boolean updateConditionById(Condition condition){ boolean b; @@ -219,7 +807,7 @@ public class SqlHelper { ps1.setInt(5, condition.getBotId()); ps1.setInt(6, condition.getConditionId()); - b = ps1.execute(); + b = ps1.executeUpdate() == 1; ps1.close(); return b; @@ -283,35 +871,6 @@ public class SqlHelper { } - public List queryConditionByCategory(String category){ - boolean b; - List conditionList = new ArrayList(); - Condition condition = null; - - try { - String sql = "query chatbot_condition wher botId = ? where categoryStr = ?"; - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, category); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - conditionList.add(condition); - } - ps.close(); - rs.close(); - - - return conditionList; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return conditionList; - } - } - public List queryConditionByCategory(int botId, String category){ @@ -320,7 +879,7 @@ public class SqlHelper { Condition condition = null; try { - String sql = "select * from chatbot_condition wher botId = ? and categoryStr = ?"; + String sql = "select * from chatbot_condition wher botId = ? and categoryInfo = ? order by displayOrder asc"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, botId); ps.setString(2, category); @@ -328,7 +887,7 @@ public class SqlHelper { while(rs.next()){ condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); conditionList.add(condition); } ps.close(); @@ -350,7 +909,7 @@ public class SqlHelper { Condition condition = null; try { - String sql = "select * from chatbot_condition wher botId = ? and conditionId = ?"; + String sql = "select * from chatbot_condition where botId = ? and conditionId = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, botId); ps.setInt(2, conditionId); @@ -358,7 +917,7 @@ public class SqlHelper { if(rs.next()){ condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); } ps.close(); rs.close(); @@ -367,7 +926,7 @@ public class SqlHelper { return condition; } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + System.out.println(CONFIG_DELETE_ERROR); e.printStackTrace(); return condition; } @@ -380,14 +939,14 @@ public class SqlHelper { Condition condition = null; try { - String sql = "select * from chatbot_condition wher botId = ? where botId = ?"; + String sql = "select * from chatbot_condition where botId = ? order by displayOrder asc"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, botId); ResultSet rs = ps.executeQuery(); while(rs.next()){ condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); conditionList.add(condition); } ps.close(); @@ -397,7 +956,7 @@ public class SqlHelper { return conditionList; } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + System.out.println(CONFIG_DELETE_ERROR); e.printStackTrace(); return conditionList; } @@ -405,7 +964,8 @@ public class SqlHelper { - + //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------ @@ -472,7 +1032,7 @@ public class SqlHelper { try { PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); ps1.setString(1, String.valueOf(botId)); - b = ps1.execute(); + b = ps1.executeUpdate() == 1; ps1.close(); return b; @@ -491,7 +1051,7 @@ public class SqlHelper { try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(botId)); - b = ps.execute(); + b = ps.executeUpdate() == 1; ps.close(); @@ -512,7 +1072,7 @@ public class SqlHelper { try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(botId)); - b = ps.execute(); + b = ps.executeUpdate() == 1; ps.close(); @@ -582,6 +1142,47 @@ public class SqlHelper { } + public boolean batchInsertVariable(int botId, List variableList) { + + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; + PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for(Variable variable:variableList){ + ps2.setInt(1, botId); + ps2.setString(2, variable.getName()); + ps2.setString(3, variable.getDescription()); + ps2.setString(4, variable.getValue()); + ps2.addBatch(); + } + + count = ps2.executeBatch(); + + conn.commit(); + ps2.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + public boolean batchInsertConfigByBotId(int botId, List jsonList, List idList, int categoryId) { int count[]; boolean insertFlag = true; @@ -635,6 +1236,52 @@ public class SqlHelper { return insertFlag; } + public boolean batchInsertConfig(int botId, List configTermList) { + int count[]; + boolean insertFlag = true; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for (ConfigTerm configTerm : configTermList) { + ps.setInt(1, botId); + ps.setInt(2, configTerm.getCategoryId()); + ps.setString(3, configTerm.getConfigJsonText()); + ps.setString(4, configTerm.getConfigName()); + + ps.addBatch(); + } + + count = ps.executeBatch(); + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + ps.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + } + public boolean batchInsertCategoryByBotId(int botId, Map categoryMap) { @@ -756,7 +1403,7 @@ public class SqlHelper { ps.setString(2, variableName); ps.setString(3, description); ps.setString(4, defaultValue); - b = ps.execute(); + b = ps.executeUpdate() == 1; ps.close(); conn.commit(); @@ -924,4 +1571,5 @@ public class SqlHelper { + } diff --git a/src/entity/Action.java b/src/main/java/com/qiwu/chatbotbackend/entity/Action.java similarity index 100% rename from src/entity/Action.java rename to src/main/java/com/qiwu/chatbotbackend/entity/Action.java diff --git a/src/entity/ArchiveInfo.java b/src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java similarity index 100% rename from src/entity/ArchiveInfo.java rename to src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java diff --git a/src/entity/ChatCache.java b/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java similarity index 100% rename from src/entity/ChatCache.java rename to src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java diff --git a/src/entity/ConfigTermText.java b/src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java similarity index 77% rename from src/entity/ConfigTermText.java rename to src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java index 2a2dfa2..6abebde 100644 --- a/src/entity/ConfigTermText.java +++ b/src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java @@ -16,18 +16,7 @@ public class ConfigTermText implements Cloneable{ } }; - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - private String curPremise = ""; private String hisPremise = ""; @@ -40,10 +29,14 @@ public class ConfigTermText implements Cloneable{ private String auxiliaryPriority = "1"; private String status = "waiting"; + static HashMap StatusMap = new HashMap(){ + { + put("waiting", 0); + put("sleeping", 1); + } + }; + - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } public String getFeature() { return feature; } @@ -73,8 +66,6 @@ public class ConfigTermText implements Cloneable{ iterNum.set(iterNum.get() + 1); - System.out.println("iterNum:" + iterNum.get()); - //iterNum++; this.configName = configName + "_" + iterNum.get(); }else{ this.configName = configName; @@ -90,58 +81,6 @@ public class ConfigTermText implements Cloneable{ } - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - public void setCurPremise(String curPremise) { this.curPremise = curPremise; } @@ -414,7 +353,7 @@ public class ConfigTermText implements Cloneable{ data.put("configName", configName); //添加config状态 - data.put("configStatus", jStatus); + data.put("configStatus", statusMap.get(status)); boolean doPost = false; diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java b/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java new file mode 100644 index 0000000..4f334de --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java @@ -0,0 +1,53 @@ +package com.qiwu.chatbotbackend.entity; + +public class Macro { + int botId; + int macroId; + String name; + String value; + + public Macro(int botId, int macroId, String name, String value) { + this.botId = botId; + this.macroId = macroId; + this.name = name; + this.value = value; + } + + public Macro(int botId, String name, String value) { + this.botId = botId; + this.name = name; + this.value = value; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getMacroId() { + return macroId; + } + + public void setMacroId(int macroId) { + this.macroId = macroId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/src/entity/Premise.java b/src/main/java/com/qiwu/chatbotbackend/entity/Premise.java similarity index 85% rename from src/entity/Premise.java rename to src/main/java/com/qiwu/chatbotbackend/entity/Premise.java index f15c76e..864c854 100644 --- a/src/entity/Premise.java +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Premise.java @@ -7,10 +7,26 @@ public class Premise { private String keyword = ""; public Premise(String conditionName, String cmpType, String operator, String keyword) { + this.conditionName = conditionName; this.cmpType = cmpType; this.operator = operator; this.keyword = keyword; + + if(cmpType == null){ + this.cmpType = "match"; + }else{ + this.cmpType = cmpType; + } + + if(operator == null){ + this.operator = "Include"; + }else{ + this.operator = operator; + } + if(cmpType.equals("any")){ + this.operator = "Include"; + } } public String getConditionName() { diff --git a/src/entity/Solution.java b/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java similarity index 100% rename from src/entity/Solution.java rename to src/main/java/com/qiwu/chatbotbackend/entity/Solution.java diff --git a/src/entity/UserInfo.java b/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java similarity index 100% rename from src/entity/UserInfo.java rename to src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java diff --git a/src/gameDesign/CharacterConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java similarity index 100% rename from src/gameDesign/CharacterConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java diff --git a/src/gameDesign/ElementConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java similarity index 100% rename from src/gameDesign/ElementConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java diff --git a/src/gameDesign/Floyd.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java similarity index 100% rename from src/gameDesign/Floyd.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java similarity index 100% rename from src/gameDesign/GlobalVariableConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java diff --git a/src/gameDesign/ItemConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java similarity index 100% rename from src/gameDesign/ItemConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java diff --git a/src/gameDesign/ListeningConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java similarity index 100% rename from src/gameDesign/ListeningConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java diff --git a/src/gameDesign/MapConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java similarity index 97% rename from src/gameDesign/MapConstructor.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java index ab1a547..b610e65 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java @@ -315,7 +315,6 @@ public class MapConstructor extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("plot_" + placeA + "_doudi", false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -327,7 +326,6 @@ public class MapConstructor extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("plot_" + placeA + "_doudi2", false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); diff --git a/src/gameDesign/PlotConstructor2.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java similarity index 97% rename from src/gameDesign/PlotConstructor2.java rename to src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java index a1e084c..557d929 100644 --- a/src/gameDesign/PlotConstructor2.java +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java @@ -284,14 +284,6 @@ public class PlotConstructor2 extends ElementConstructor { - - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - - if(reply.equals("")) reply = curUnknownText; @@ -543,7 +535,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("queryskip1",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -554,7 +545,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("queryskip2",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -564,7 +554,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("queryskip3",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -591,7 +580,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("unknown1",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -603,7 +591,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("unknown2",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -615,7 +602,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("unknown3",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -626,7 +612,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("unknown4",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); @@ -638,7 +623,6 @@ public class PlotConstructor2 extends ElementConstructor { ); configTermText.setStatus("sleeping"); configTermText.setConfigName("common_answer",false); - configTermText.setjStatus(1); configTermText.setAuxiliaryPriority("0"); configTermTextList.add(configTermText); //--------------------------------------------------------------------------------------------------------------- diff --git a/src/processing/ActionMatcher.java b/src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java similarity index 80% rename from src/processing/ActionMatcher.java rename to src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java index bcd031f..17339d5 100644 --- a/src/processing/ActionMatcher.java +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java @@ -129,55 +129,6 @@ public class ActionMatcher { } } - - -// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) -// || action.featureMap.get("activate") != null){ -// if(conditionSatisfy(action)){ -// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { -// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 -// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); -// } -// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { -// bestMatch = action; -// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); -// logWriter.writeln(); -// } -// -// -// } -// -// }else { -// logWriter.record("-----------------------------------优先级不足,跳过", 0); -// logWriter.record(userinfo.id2config.get(action.id), 1); -// } -// } -// -// -// -// -// -// if (action.status.equals("waiting")){ -// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) -// || action.featureMap.get("activate") != null){ -// if(conditionSatisfy(action)){ -// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { -// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 -// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); -// } -// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { -// bestMatch = action; -// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); -// logWriter.writeln(); -// } -// -// -// } -// -// }else { -// logWriter.record("-----------------------------------优先级不足,跳过", 0); -// logWriter.record(userinfo.id2config.get(action.id), 1); -// } } } } @@ -336,19 +287,17 @@ public class ActionMatcher { } - - /** * 单个条件的匹配,判断是否满足条件 * 比较类型分为 match、number、time、variable, * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 * - * @param keyword + * @param variableValue 变量的值或者condition识别到的关键字 * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 + * @param keywordSet 限定值域 * @return 返回匹配或者不匹配 */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { + public boolean premiseSatisfy(String variableValue, String cmpType, HashSet keywordSet) { boolean flag = true; String operator = ""; @@ -361,60 +310,74 @@ public class ActionMatcher { if (cmpType.equals("match")) { - if(operator.equals("Keyword") || operator.equals("Include")) { - if (!keywordSet.contains(keyword)) { + if(operator.equals("Keyword") || operator.equals("Include")) { //识别到的关键词 属于预先设定的值域 + if (!keywordSet.contains(variableValue)) { flag = false; } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); + if (flag == false && variableValue.contains(":")) { + String ks[] = variableValue.split(":"); for (String k : ks) { if (keywordSet.contains(k)) flag = true; } } } else if(operator.equals("Exclude")) { - if(keyword.contains(":")){ - String ks[] = keyword.split(":", 2); + if(variableValue.contains(":")){ + String ks[] = variableValue.split(":", 2); if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) flag = false; }else { - if (keywordSet.contains(keyword)) { + if (keywordSet.contains(variableValue)) { flag = false; } } - }else if(operator.equals("Have")){ + }else if(operator.equals("Have")) { //变量的值包含了某些关键词 + for (String key : keywordSet) { + if (key.equals("")) + continue; + if (!variableValue.contains(key)) { + flag = false; + break; + } + } + + }else if(operator.equals("NotHave")){ for(String key:keywordSet){ if(key.equals("")) continue; - if(!keyword.contains(key)){ + if(variableValue.contains(key)){ flag = false; break; } } + }else if(operator.equals("Any")){ + + if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + flag = false; }else{ flag = false; } - } else if (cmpType.equals("number") && !keyword.equals("")) { + } else if (cmpType.equals("number") && !variableValue.equals("")) { int candidateA = 0; int candidateB = 0; - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); + if (variableValue.contains(":")) { + String ks[] = variableValue.split(":"); for (String k : ks) { if(StringUtils.isNumeric(k)) - keyword = k; + variableValue = k; } } - if(!StringUtils.isNumeric(keyword)){ + if(!StringUtils.isNumeric(variableValue)){ return false; } - candidateA = Integer.parseInt(keyword); + candidateA = Integer.parseInt(variableValue); for (String k : keywordSet) { if (!k.equals("")) { candidateB = Integer.parseInt(k); @@ -436,16 +399,16 @@ public class ActionMatcher { long candidateA, candidateB = 0; - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); + if (variableValue.contains(":")) { + String ks[] = variableValue.split(":"); for (String k : ks) { if(k.contains("年") && k.contains("月") && k.contains("日")) - keyword = k; + variableValue = k; } } - candidateA = SimpleUtil.transferToMillisecond(keyword); + candidateA = SimpleUtil.transferToMillisecond(variableValue); for (String k : keywordSet) { if (!k.equals("")) { @@ -482,10 +445,10 @@ public class ActionMatcher { */ flag = false; if(operator.equals("Equal")){ - flag = keyword.equals(conditionValue2); + flag = variableValue.equals(conditionValue2); - }else if(keyword.contains(":") && conditionValue2.contains(":")){ - String relPair1[] = keyword.split(":", 2), keyword1 = ""; + }else if(variableValue.contains(":") && conditionValue2.contains(":")){ + String relPair1[] = variableValue.split(":", 2), keyword1 = ""; String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; boolean similar = false; @@ -539,9 +502,9 @@ public class ActionMatcher { // 操作符为等于时可以比较两个字符串是否相同 } } - }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ - if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ - int candidateA = Integer.parseInt(keyword); + }else if(!variableValue.contains(":") && !conditionValue2.contains(":")){ + if(StringUtils.isNumeric(variableValue) && StringUtils.isNumeric(conditionValue2)){ + int candidateA = Integer.parseInt(variableValue); int candidateB = Integer.parseInt(conditionValue2); @@ -558,9 +521,9 @@ public class ActionMatcher { else if (operator.equals("NotEqual")) flag = candidateA != candidateB; - } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") + } else if(variableValue.contains("年") && variableValue.contains("月") && variableValue.contains("日") && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ - long candidateA = SimpleUtil.transferToMillisecond(keyword); + long candidateA = SimpleUtil.transferToMillisecond(variableValue); long candidateB = SimpleUtil.transferToMillisecond(conditionValue2); if (operator.equals("Bigger")) @@ -584,7 +547,7 @@ public class ActionMatcher { } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 flag = false; } else { @@ -592,22 +555,19 @@ public class ActionMatcher { } } catch (IndexOutOfBoundsException e) { System.out.println("配置文件格式有误"); - logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); flag = false; - e.printStackTrace(); } catch (ParseException e) { System.out.println("时间解析错误"); - historyInfoPoint.put("error_message", "解析出错:" + keyword); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); - e.printStackTrace(); + historyInfoPoint.put("error_message", "解析出错:variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); flag = false; } catch (Exception e) { System.out.println("操作符有误"); - logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); - e.printStackTrace(); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); flag = false; } @@ -1100,9 +1060,7 @@ public class ActionMatcher { try { configId = originAction.getId(); - newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); - //action = ActionMatcher.buildCondition(action, configStr); @@ -1110,10 +1068,7 @@ public class ActionMatcher { if (activatedMap.containsKey(configId)) { if(higherPriority(newAction, activatedMap.get(configId))) activatedMap.put(configId, newAction); -// if(newAction.getAuxiliaryPriority() > activatedMap.get(configId).getAuxiliaryPriority()) -// activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; -// if(newAction.priority > activatedMap.get(configId).priority) -// activatedMap.get(configId).priority = newAction.priority; + } else if (!activatedMap.containsKey(configId)) { activatedMap.put(configId, newAction); activatedQueue.add(newAction); @@ -1141,10 +1096,6 @@ public class ActionMatcher { Queue activatedQueue = new LinkedList(); Solution bestMatch = oldBestMatch; Action newAction1 = ansAction, newAction2; -// activateCondition(activatedQueue, userinfo.botAccount, ansAction.priority, ansAction.auxiliaryPriority, ansAction.nextStep, context); -// ansAction = activatedQueueMatching(ansAction, activatedQueue, context); -// -// bestMatch = getSolution(ansAction, context, userinfo); diff --git a/src/processing/ChatCacheController.java b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java similarity index 88% rename from src/processing/ChatCacheController.java rename to src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java index 56e83b2..7d84210 100644 --- a/src/processing/ChatCacheController.java +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java @@ -54,33 +54,23 @@ public class ChatCacheController { - try { - chatCache = chatCacheMap.get(userKey); + chatCache = chatCacheMap.get(userKey); - //如果用户之前没有玩过或者有一段时间没有玩 - if(chatCache == null){ + //如果用户之前没有玩过或者有一段时间没有玩 + if(chatCache == null){ + chatCache = new ChatCache(userinfo, userKey, randKey, botType); + chatCacheMap.put(userKey, chatCache); + //用户几分钟前还在玩 + } else { + if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 + //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { + ChatCacheController.saveChatCache(chatCache, null); + } chatCache = new ChatCache(userinfo, userKey, randKey, botType); chatCacheMap.put(userKey, chatCache); - //用户几分钟前还在玩 - } else { - if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { - ChatCacheController.saveChatCache(chatCache, null); - } - chatCache = new ChatCache(userinfo, userKey, randKey, botType); - chatCacheMap.put(userKey, chatCache); - } } - //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - } catch (Exception e) { - //可整合 - e.printStackTrace(); - - //chatCache = new ChatCache(userinfo, userKey, randKey); - //chatCacheMap.put(userKey, chatCache); - } System.out.println(chatCache.getGameEnv()); @@ -138,7 +128,6 @@ public class ChatCacheController { } catch (Exception e) { System.out.println("游戏存档时发生异常"); - e.printStackTrace(); opFlag = false; } @@ -158,33 +147,27 @@ public class ChatCacheController { String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; Map infoPoints = new HashMap(); - try { - File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - if (file.exists()){ - gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - }else{ - throw new IOException("环境存档不存在"); - } + File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + if (file.exists()){ + gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + }else{ + throw new IOException("环境存档不存在"); + } - file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); - FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - String jsonStr = br.readLine(); - infoPoint = (Map)JSON.parseObject(jsonStr); - - chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); - chatCache.setGameStart(true); - - br.close(); - fr.close(); + file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String jsonStr = br.readLine(); + infoPoint = (Map)JSON.parseObject(jsonStr); + chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); + chatCache.setGameStart(true); + br.close(); + fr.close(); - } catch (IOException e) { - System.out.println(e.toString()); - } return chatCache; } @@ -194,7 +177,7 @@ public class ChatCacheController { /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ - public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { + public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo){ String sessionKey; ChatCache chatCache = null; SqlHelper helper = null; @@ -289,7 +272,7 @@ public class ChatCacheController { } catch (Exception e) { e.printStackTrace(); - return false; + findFlag = false; } return findFlag; diff --git a/src/processing/FormsPoster.java b/src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java similarity index 100% rename from src/processing/FormsPoster.java rename to src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java diff --git a/src/processing/LogWriter.java b/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java similarity index 100% rename from src/processing/LogWriter.java rename to src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java diff --git a/src/processing/MyFunc.java b/src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java similarity index 76% rename from src/processing/MyFunc.java rename to src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java index bb0e51d..d1cfc67 100644 --- a/src/processing/MyFunc.java +++ b/src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java @@ -6,6 +6,8 @@ import com.qiwu.chatbotbackend.entity.Solution; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; @@ -23,7 +25,7 @@ import java.util.Date; import java.util.List; -public class MyFunc { +public class SimpleUtil { /** * 将后台返回的数据转成json格式 @@ -64,6 +66,57 @@ public class MyFunc { return json.toString(); } + + public static JSONObject getMethod(String url, String auth){ + CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse resp = null; + String respContent = null; + String keyName = null; + JSONObject jobj = new JSONObject(); + + + try { + HttpGet httpGet = new HttpGet(url); + + if(auth != null){ + httpGet.setHeader("Authorization", auth); + } + resp = client.execute(httpGet); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + jobj.put("get_status", 1); + jobj.put("status_code", 200); + + } else { + jobj.put("get_status", 0); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); + jobj.put("parameter", "接收请求的程序出现异常"); + } + } catch (Exception e) { + e.printStackTrace(); + jobj.put("status_code", 0); + jobj.put("get_status", 0); + + }finally { + try { + if (resp != null) { + resp.close(); + } + if (client != null) { + client.close(); + } + }catch(IOException e){ + e.printStackTrace(); + } + } + + return jobj; + } + + + /** * 通过get方法传递参数时需要对参数的编码进行转换 */ @@ -134,18 +187,22 @@ public class MyFunc { try { HttpResponse resp = client.execute(httpPost); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); jobj = JSONObject.parseObject(respContent); jobj.put("post_status", 1); - + jobj.put("status_code", 200); } else { jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常"); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); + jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); } } catch (Exception e) { + jobj.put("status_code", 0); + jobj.put("post_status", 0); e.printStackTrace(); } @@ -181,12 +238,11 @@ public class MyFunc { } else { jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常"); + jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); } } catch (Exception e) { - e.printStackTrace(); + jobj.put("error_message", "提交表单时出错:" + e.getMessage()); jobj.put("post_status", 0); - } return jobj; diff --git a/src/processing/UserInfoController.java b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java similarity index 71% rename from src/processing/UserInfoController.java rename to src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java index 7f58522..afb1f05 100644 --- a/src/processing/UserInfoController.java +++ b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java @@ -5,15 +5,13 @@ import com.qiwu.chatbotbackend.entity.UserInfo; import javax.servlet.ServletContext; import java.io.*; -import java.sql.SQLException; import java.util.*; +import static com.qiwu.chatbotbackend.Config.Config.CONFIG_DIR; import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; public class UserInfoController { - static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; - static String FILE_ERROR = ".txt文件有误"; @@ -24,9 +22,8 @@ public class UserInfoController { String line; - System.out.println("configDir"+ CONFIG_DIR); - File dir = new File(CONFIG_DIR); + File dir = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR); if (!dir.exists()) dir.mkdir(); for (File configFile : dir.listFiles()) { @@ -36,13 +33,8 @@ public class UserInfoController { String fileName = configFile.getName(); UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); reader.close(); br.close(); @@ -50,38 +42,37 @@ public class UserInfoController { } - public static void userConfigInit(String botAccount, ServletContext context) throws IOException { + public static UserInfo userConfigInit(String botAccount, ServletContext context) throws IOException { String line; - File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt"); + UserInfo userInfo = null; + File userFile = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR + botAccount + ".txt"); + - System.out.println(userFile.getAbsolutePath()); + + System.out.println("配置文件地址:" + userFile.getAbsolutePath()); if (!userFile.exists()) { BufferedReader br = new BufferedReader(new StringReader("")); - UserInfo userinfo = new UserInfo(botAccount); - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } + userInfo = new UserInfo(botAccount); + + userInfo = buildUserInfo(br, userInfo, true); + context.setAttribute(userInfo.botAccount, userInfo); } else { FileReader reader = new FileReader(userFile); BufferedReader br = new BufferedReader(reader); UserInfo userinfo = new UserInfo(botAccount); - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } + userInfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + + reader.close(); br.close(); + + } + return userInfo; } @@ -97,12 +88,6 @@ public class UserInfoController { try { - text = line.split("---"); - - line = text[0]; - if(text.length > 1 && text[1].startsWith("<-")) - line += "---" + text[1]; - element = line.replace("\n", "").split("\\|=\\>\\|"); premises = element[0].split("\\|"); feature = premises[2]; @@ -165,13 +150,8 @@ public class UserInfoController { insertPremise(action.getHistoryPremise(), history_premises); //满足条件越多,优先级越大 action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); - //action.activePriority = action.priority; - /* - for(String premise:cur_premises){ - pair = premise.split("="); - action.indexName.add(pair[0]); - } - */ + + firstCnditionName = cur_premises[0]; if (firstCnditionName.equals(" ")) action.setIndexName("emptySet"); @@ -193,8 +173,8 @@ public class UserInfoController { * @return * @throws IOException */ - public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { - String line, infoName, extraElements[]; + public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide){ + String line = "", infoName, extraElements[]; HashMap> conditionTable = null; //是否覆盖原有的数据 @@ -213,8 +193,8 @@ public class UserInfoController { List actionList = null; - while ((line = br.readLine()) != null) { - try { + try{ + while ((line = br.readLine()) != null) { if (line.trim().equals("")) continue; line = line.replace("\n", ""); @@ -235,7 +215,7 @@ public class UserInfoController { actionList.add(action); conditionTable.put(action.getIndexName(), actionList); if (action.getId() != 0) { - if(!action.getConfigName().equals("")){ + if (!action.getConfigName().equals("")) { userinfo.name2condition.put(action.getConfigName(), action); } userinfo.id2config.put(action.getId(), line); @@ -243,16 +223,17 @@ public class UserInfoController { } } - } catch (ArrayIndexOutOfBoundsException e) { - System.out.println(TEXT_PARSE_ERROR); - - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - System.out.println(line); } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(TEXT_PARSE_ERROR); + + //e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + System.out.println(line); } + userinfo.conditionTable = conditionTable; return userinfo; @@ -292,26 +273,15 @@ public class UserInfoController { * @param bot_name 用户名 * @return 用户信息 */ - public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { - /*根据数据库得到botAccount改为直接得到 - SqlHelper helper = new SqlHelper(); - String botAccount = helper.querybotAccountByKey(chat_key); - */ + public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException { + String botAccount = bot_name; UserInfo userinfo = null; if (context.getAttribute(botAccount) == null) { - userConfigInit(botAccount, context); - } - if (context.getAttribute(botAccount) == null) { - - return null; - //userinfo = new UserInfo(botAccount); - //userinfo.conditionTable = new HashMap>(); + userinfo = userConfigInit(botAccount, context); } else { userinfo = (UserInfo) context.getAttribute(botAccount); } - //helper.destroy(); - return userinfo; } @@ -321,7 +291,6 @@ public class UserInfoController { int id = Integer.parseInt(configId); Action action = new Action(); UserInfoController userInfoController = new UserInfoController(); - //data=configLine+"---"+conditionNameList String conditionNameList[] = data.split(","); String conditionName = ""; @@ -333,12 +302,8 @@ public class UserInfoController { if (userInfo.id2config.containsKey(id)) { Action oldAction = userInfo.id2condition.get(id); //------------------- - try { + conditionName = oldAction.getIndexName(); - conditionName = oldAction.getIndexName(); - } catch (Exception e) { - e.printStackTrace(); - } if (userInfo.conditionTable.get(conditionName) != null) { @@ -363,18 +328,14 @@ public class UserInfoController { } public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { - Action action = new Action(); String conditionName = ""; for (int configId : idGroup) { if (userInfo.id2config.containsKey(configId)) { Action oldAction = userInfo.id2condition.get(configId); - try { - conditionName = oldAction.getIndexName(); - } catch (Exception e) { - e.printStackTrace(); - } + conditionName = oldAction.getIndexName(); + if (userInfo.conditionTable.get(conditionName) != null) { @@ -403,13 +364,13 @@ public class UserInfoController { public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { Action action = new Action(); - //data=configLine+"---"+conditionNameList String dataPair[] = data.split("---"); String configLine = dataPair[0]; - String conditionNameList[]; UserInfoController userInfoController = new UserInfoController(); int id = Integer.parseInt(configId); + + action = userInfoController.buildCondition(action, configLine); if (context.getAttribute(userName) == null) { @@ -487,29 +448,28 @@ public class UserInfoController { } - public static String writeConfigText(String userName, UserInfo userinfo) throws IOException { + public static String writeConfigText(String userName, UserInfo userinfo){ + String path = System.getProperty("user.dir") + "/" + CONFIG_DIR + userName + ".txt"; + String returnMessage = "success"; + FileWriter fw = null; + BufferedWriter bw = null; - String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText; - String path = CONFIG_DIR + "/" + userName + ".txt"; + try { + File file = new File(path); + File dir = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR); - File file = new File(path); - File dir = new File(System.getProperty("user.dir") + "/config"); - System.out.println(userName); - System.out.println("config_dir" + dir.getAbsolutePath()); - String returnMessage = "success"; + if (!dir.exists()) + dir.mkdir(); + if (!file.exists()) { + file.createNewFile(); + } - if (!dir.exists()) - dir.mkdir(); - if (!file.exists()) { - file.createNewFile(); - } + fw = new FileWriter(file); + bw = new BufferedWriter(fw); - FileWriter fw = new FileWriter(file); - BufferedWriter bw = new BufferedWriter(fw); - try { Iterator keyIter = userinfo.extraInfo.keySet().iterator(); while (keyIter.hasNext()) { String info = keyIter.next(); @@ -533,8 +493,13 @@ public class UserInfoController { e.printStackTrace(); returnMessage = "config file write error"; } finally { - bw.close(); - fw.close(); + try { + bw.close(); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } return returnMessage; diff --git a/src/processing/WorldController.java b/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java similarity index 100% rename from src/processing/WorldController.java rename to src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java diff --git a/src/servlet/FindCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java similarity index 100% rename from src/servlet/FindCacheServlet.java rename to src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java diff --git a/src/servlet/GameDesignServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java similarity index 76% rename from src/servlet/GameDesignServlet.java rename to src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java index af68997..2b0e3c2 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java @@ -1,6 +1,10 @@ package com.qiwu.chatbotbackend.servlet; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; @@ -21,7 +25,8 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; -import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL; +import static com.qiwu.chatbotbackend.Config.Config.GAME_CONDITION_CATEGORY; +import static com.qiwu.chatbotbackend.Config.Config.GAME_WELCOME_TEXT; @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) @@ -74,157 +79,152 @@ public class GameDesignServlet extends HttpServlet { try { helper = new SqlHelper(); - } catch (SQLException e) { - e.printStackTrace(); - } - //读取并解析json数据 - String jsonStr = SimpleUtil.readJSONString(request); + //读取并解析json数据 + String jsonStr = SimpleUtil.readJSONString(request); - if (jsonStr != null && !jsonStr.equals("")) { - JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); - dataId = (Integer) receiveParaneters.get("id"); - JSONObject gameElements = helper.queryGameElementsByBotId(dataId); + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); + dataId = (Integer) receiveParaneters.get("id"); - gameElements.put("auth", request.getHeader("authorization")); - //System.out.println(gameElements.toJSONString()); - botId = (Integer)gameElements.get("botId"); - botAccount = (String) gameElements.get("botAccount"); - userName = (String)gameElements.get("userName"); - botName = (String)gameElements.get("botName"); + JSONObject gameElements = helper.queryGameElementsByBotId(dataId); + gameElements.put("auth", request.getHeader("authorization")); + //System.out.println(gameElements.toJSONString()); + botId = (Integer)gameElements.get("botId"); + botAccount = (String) gameElements.get("botAccount"); + userName = (String)gameElements.get("userName"); + botName = (String)gameElements.get("botName"); - //假设重建用户信息 - if (context.getAttribute(botAccount) == null) { - UserInfoController.userConfigInit(botAccount, context); - } - UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + //假设重建用户信息 + if (context.getAttribute(botAccount) == null) { + UserInfoController.userConfigInit(botAccount, context); + } + + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - //清空之前生成的配置条目 - try { + //清空之前生成的配置条目 flag = botInit(botId, botAccount, userinfo, helper); - } catch (SQLException e) { - System.out.println("清空旧数据失败"); - e.printStackTrace(); - } - StringBuffer mergedConfigText = new StringBuffer(); - int skipCount = 0; + StringBuffer mergedConfigText = new StringBuffer(); + int skipCount = 0; + + + //从文件中读取condition相关的关键词 + readKeywords(keywordMap, KEYWORD_DIR); + + + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n,预处理之后:").append(now); + String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; + for(String moduleName: moduleList){ + + switch (moduleName) { + case "map": + moduleName2 = "地图"; + constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "plots": + moduleName2 = "剧情"; + constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + + root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); + break; + case "goods": + moduleName2 = "物品"; + constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "globalVariable": + moduleName2 = "全局变量"; + constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "npc": + moduleName2 = "NPC"; + constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + default: + continue; + + } + if (constructor.getOperationStatus() == 1) { - //从文件中读取condition相关的关键词 - System.out.println("----------------------read-------------------------/r------------------------------------------------------"); - readKeywords(keywordMap, KEYWORD_DIR); + //先清空再插入 + idList.clear(); + helper.batchInsertVariableByBotId(botId, constructor); + List jsonList = new ArrayList(); + for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ + json = configTermText.toJson(constructor.getConditionDescription()); + constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); + jsonList.add(json); + } - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n,预处理之后:").append(now); - String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; - for(String moduleName: moduleList){ - switch (moduleName) { - case "map": - moduleName2 = "地图"; - constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - case "plots": - moduleName2 = "剧情"; - constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); + helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); + constructor.postProcessing(idList, categoryMap.get(moduleName2)); + constructor.generateConfigText(idList); - root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); - break; - case "goods": - moduleName2 = "物品"; - constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - case "globalVariable": - moduleName2 = "全局变量"; - constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); + mergedConfigText.append(constructor.getConfigText()); + }else { + returnStatus = 0; + returnMessage = constructor.getMessage(); break; - case "npc": - moduleName2 = "NPC"; - constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - default: - continue; - - } - if (constructor.getOperationStatus() == 1) { - - System.out.println(moduleName); - //先清空再插入 - idList.clear(); - helper.batchInsertVariableByBotId(botId, constructor); - - List jsonList = new ArrayList(); - for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ - json = configTermText.toJson(constructor.getConditionDescription()); - constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); - jsonList.add(json); } + ldt = LocalDateTime.now(); + now = ldt.format(dtf); + timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); - helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); - constructor.postProcessing(idList, categoryMap.get(moduleName2)); - constructor.generateConfigText(idList); - - mergedConfigText.append(constructor.getConfigText()); - }else { - returnStatus = 0; - returnMessage = constructor.getMessage(); - break; } - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); - - } - - if(returnStatus == 1) { - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求预处理:").append(now); - StringReader sr = new StringReader(mergedConfigText.toString()); - BufferedReader br = new BufferedReader(sr); - //System.out.println(mergedConfigText.toString()); - UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(botAccount, userinfo); - UserInfoController.writeConfigText(botAccount, userinfo); - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求前:").append(now); - String postResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS); - - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求后:").append(now); - - if(!postResult.equals("success")){ - returnStatus = 0; - returnMessage = postResult; + if(returnStatus == 1) { + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求预处理:").append(now); + StringReader sr = new StringReader(mergedConfigText.toString()); + BufferedReader br = new BufferedReader(sr); + //System.out.println(mergedConfigText.toString()); + UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(botAccount, userinfo); + UserInfoController.writeConfigText(botAccount, userinfo); + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求前:").append(now); + IntervalStatus generateResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS, helper); + + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求后:").append(now); + + if(generateResult.getStatus() != 1){ + returnStatus = 0; + returnMessage = generateResult.getMessage(); + } } - } - helper.destroy(); + helper.destroy(); - }else { - returnStatus = 0; - returnMessage = "请求解析失败"; + }else { + returnStatus = 0; + returnMessage = "请求解析失败"; + } + } catch (SQLException e) { + e.printStackTrace(); } @@ -269,47 +269,65 @@ public class GameDesignServlet extends HttpServlet { return deleteConfigFlag && deleteVariableFlag; } - public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS){ - String startCondition, POS2 = ""; - String botName = (String)gameElements.get("botName"); + + /** + * 重新生成action文本 + * @param root + * @param gameElements + * @param userInfo + * @param additionalKeywords + * @param exceptRelation + * @param POS + * @return + */ + public IntervalStatus actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS, SqlHelper helper){ + String startCondition, POS2 = "", botName = gameElements.getString("botName"); + System.out.println(botName); JSONObject returnMessage = null; + EngineUtils engine = null; + IntervalStatus intervalStatus = new IntervalStatus(1, ""); JSONObject actionPostData = new JSONObject(); - //System.out.println("root"+ root.toJSONString()); + startCondition = (String)root.get("conditionName"); actionPostData.put("startCondition", "start_options"); - actionPostData.put("botName_yhm", (String)gameElements.get("botName")); - actionPostData.put("botName", botName); - actionPostData.put("botId", (Integer)gameElements.get("botId")); - actionPostData.put("type", "game_plot_init"); - actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始"); + actionPostData.put("welcome", String.format(GAME_WELCOME_TEXT, gameElements.getString("botName"))); actionPostData.put("relationKeywords", additionalKeywords); - actionPostData.put("auth", gameElements.get("auth")); + actionPostData.put("botId", gameElements.getInteger("botId")); + + if(gameElements.getJSONArray("conditionCategoryIdList") != null){ + actionPostData.put("conditionCategories", gameElements.getJSONArray("conditionCategoryIdList")); + }else{ + actionPostData.put("conditionCategories", new JSONArray(){ + { + add(GAME_CONDITION_CATEGORY); + } + }); + } if (gameElements.containsKey("POS")) POS2 = (String)gameElements.get("POS"); - actionPostData.put("POS", POS.toString() + POS2); System.out.println(actionPostData.toJSONString()); - - userInfo.extraInfo.put("activeAction", startCondition); try { - returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth")); - } catch (UnsupportedEncodingException e) { + engine = new EngineUtils(); + ActionUtils actionUtils = new ActionUtils(engine, helper); + actionUtils.gamePlotInit(botName, gameElements.getInteger("botId"), gameElements.getString("auth"), actionPostData, startCondition, additionalKeywords); + intervalStatus = actionUtils.intervalStatus; + }catch(Exception e){ e.printStackTrace(); + intervalStatus = new IntervalStatus(0, "action生成失败"); + }finally { + engine.destroy(); } - if(returnMessage.getInteger("post_status") == 1 && returnMessage.getInteger("status") != null && returnMessage.getInteger("status") == 1 ) { - return "success"; - }else { - System.out.println(returnMessage.get("parameter")); - System.out.println("语义关系生成失败"); - return (String)returnMessage.get("parameter"); - } + userInfo.extraInfo.put("activeAction", startCondition); + + return intervalStatus; } @@ -356,7 +374,4 @@ public class GameDesignServlet extends HttpServlet { } - - - } diff --git a/src/servlet/GetAnswerServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java similarity index 84% rename from src/servlet/GetAnswerServlet.java rename to src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java index eb6abcd..58d9609 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java @@ -1,5 +1,6 @@ package com.qiwu.chatbotbackend.servlet; +import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.Solution; @@ -16,13 +17,12 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; -import java.sql.SQLException; import java.text.ParseException; import java.util.HashMap; import java.util.Map; +import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2; -import static com.qiwu.chatbotbackend.Config.Config.TEST_VAR; @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) @@ -31,15 +31,14 @@ public class GetAnswerServlet extends HttpServlet { * GetAnswerServlet就是处理post请求并返回答案的入口 */ - String NAME_MISSING_ERROR = "没找到bot名?"; - String LOG_PATH = "/var/www/html/logs/"; + //String LOG_PATH = "/home/hxw/source/logs/"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Map receiveParamters = new HashMap<>(request.getParameterMap()); Map curInfoPoint = new HashMap(); - //Map historyInfoPoint = null; + Solution bestMatch = null; BasicBotUtil botUtil = null; Action ansAction = null; @@ -60,148 +59,144 @@ public class GetAnswerServlet extends HttpServlet { userKey = chatKeys[0]; randKey = chatKeys[1]; } + receiveParamters.put("userKey", new String[]{userKey}); receiveParamters.put("randKey", new String[]{randKey}); - LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); - - UserInfo userinfo = null; - UserInfoController uiController = new UserInfoController(); try { - //userinfo = process.userInfoQuery(chatKey,context); - //从servlet根据用户名查询用户信息 - userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); + LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); - } catch (SQLException e) { - state = NAME_MISSING_ERROR; - e.printStackTrace(); - } + UserInfo userinfo = null; + UserInfoController uiController = new UserInfoController(); + userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); - if(userinfo != null) { - //获得用户历史信息 - ChatCache chatCache = null; - Boolean loadCacheStatus = Boolean.valueOf(false); + if (userinfo != null) { + //获得用户历史信息 + ChatCache chatCache = null; + Boolean loadCacheStatus = Boolean.valueOf(false); - if(userinfo.varInitialMap.get("botType") != null) - botType = userinfo.varInitialMap.get("botType"); + if (userinfo.varInitialMap.get("botType") != null) + botType = userinfo.varInitialMap.get("botType"); - try { chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); - if(chatCache == null){ - throw(new Exception("chatCache初始化失败")); + if (chatCache == null) { + throw (new Exception("chatCache初始化失败")); } - } catch (Exception e) { - System.out.println(e.getMessage()); - //e.printStackTrace(); - } - /** - * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) - * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 - */ - //historyInfoPoint = chatCache.getInfoPoint(); + /** + * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) + * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 + */ + //historyInfoPoint = chatCache.getInfoPoint(); + switch (botType) { + case "game": + WorldController worldController = new WorldController(logWriter, userinfo); + botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController); + break; + default: + botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); + break; + } - switch(botType){ - case "game": - WorldController worldController = new WorldController(logWriter,userinfo); - botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController); - break; - default: - botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); - break; - } - - //针对不同游戏类型对信息点做预处理 - debugFlag = botUtil.preprocessing(receiveParamters, context); - + //针对不同游戏类型对信息点做预处理 + debugFlag = botUtil.preprocessing(receiveParamters, context); - //信息点预处理 - ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil); + //信息点预处理 + ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil); - /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/ - ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); - if (state.equals("") && ansAction.getPriority()== -1) - state = "我不理解,"; - if (state.equals("")) { - try { - bestMatch = matcher.getSolution(ansAction, context, userinfo); + /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/ + ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); + if (state.equals("") && ansAction.getPriority() == -1) + state = INTENT_NOT_UNDERSTAND; + if (state.equals("")) { + try { + bestMatch = matcher.getSolution(ansAction, context, userinfo); - if(!botUtil.getChatCache().getReload()) { - //读档成功不应该再激活 - //if(matcher.) - if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { - //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); + if (!botUtil.getChatCache().getReload()) { + //读档成功不应该再激活 + //if(matcher.) + if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); + } + } else { + //跳过 + botUtil.getChatCache().setReload(false); //清楚标识 } - }else{ - //跳过 - botUtil.getChatCache().setReload(false); //清楚标识 - } - } catch (ParseException e) { - e.printStackTrace(); + } catch (ParseException e) { + e.printStackTrace(); + } + } else { + bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction")); } - } else { - bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction")); - } - //针对不同bot类型做后处理 - botUtil.postprocessing(chatKey, context, bestMatch); + //针对不同bot类型做后处理 + botUtil.postprocessing(chatKey, context, bestMatch); - botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); - if (debugFlag) { - matcher.appendDebugInfo(bestMatch, context); - } + botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); + if (debugFlag) { + matcher.appendDebugInfo(bestMatch, context); + } - //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) - matcher.infoTransfer(bestMatch, context, debugFlag); + //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) + matcher.infoTransfer(bestMatch, context, debugFlag); - ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); - //清理超时的用户数据 - if (context.getAttribute("cacheUpdateTime") == null) - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { - ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - } + ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); + //清理超时的用户数据 + if (context.getAttribute("cacheUpdateTime") == null) + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { + ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + } + ansJ = SimpleUtil.toJson(bestMatch); + } else { + ansJ = CONFIG_FILE_NOT_FOUND; + } + out.write(ansJ.getBytes()); + + logWriter.writeln(); + logWriter.writeln(); + logWriter.record("-----------------------------------------对话处理结束", 0); + logWriter.writeln(); + logWriter.writeln(); + logWriter.close(); + }catch (Exception e){ + JSONObject errorData = new JSONObject(){ + { + put("solution", PROGRAM_ERROR); + put("status", 1); + } + }; + e.printStackTrace(); + out.write(errorData.toJSONString().getBytes()); - ansJ = SimpleUtil.toJson(bestMatch); - } else { - ansJ = "找不到配置文件"; } - System.out.println(TEST_VAR); - - logWriter.writeln(); - logWriter.writeln(); - logWriter.record("-----------------------------------------对话处理结束", 0); - logWriter.writeln(); - logWriter.writeln(); - logWriter.close(); - System.out.println(ansJ); - out.write(ansJ.getBytes()); + out.flush(); } diff --git a/src/servlet/GetConfigServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java similarity index 100% rename from src/servlet/GetConfigServlet.java rename to src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java diff --git a/src/servlet/SaveChatCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java similarity index 100% rename from src/servlet/SaveChatCacheServlet.java rename to src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java diff --git a/src/task/utils/BasicBotUtil.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java similarity index 100% rename from src/task/utils/BasicBotUtil.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java diff --git a/src/task/utils/ContextDestroyListener.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java similarity index 100% rename from src/task/utils/ContextDestroyListener.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java diff --git a/src/task/utils/ContextInitialListener.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java similarity index 100% rename from src/task/utils/ContextInitialListener.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java diff --git a/src/task/utils/DataDeliver.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java similarity index 100% rename from src/task/utils/DataDeliver.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java diff --git a/src/task/utils/FileFinder.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java similarity index 100% rename from src/task/utils/FileFinder.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java diff --git a/src/task/utils/GameBotUtil.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java similarity index 98% rename from src/task/utils/GameBotUtil.java rename to src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java index 7cdcbb1..81ed988 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java @@ -75,6 +75,7 @@ public class GameBotUtil extends BasicBotUtil{ } + @Override public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ @@ -144,6 +145,7 @@ public class GameBotUtil extends BasicBotUtil{ return true; } + @Override public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ String keyword = ""; String nameSeries[] = actionName.split("_"); @@ -328,7 +330,7 @@ public class GameBotUtil extends BasicBotUtil{ } - private void loading(ArchiveInfo archiveInfo, Solution solution){ + private void loading(ArchiveInfo archiveInfo, Solution solution) throws Exception { String keyword = "", site; ChatCache loadCache = null; @@ -342,13 +344,7 @@ public class GameBotUtil extends BasicBotUtil{ chatCache.getInfoPoint().put("common_answer", ""); - try { - loadCache = ChatCacheController.loadChatCache(archiveInfo); - } catch (Exception e) { - System.out.println("从本地加载存档失败"); - solution.setAnswer("从本地加载存档失败"); - e.printStackTrace(); - } + loadCache = ChatCacheController.loadChatCache(archiveInfo); //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties new file mode 100644 index 0000000..454e52a --- /dev/null +++ b/src/main/resources/application-dev.properties @@ -0,0 +1,11 @@ +server.port=8081 +server.servlet.context-path=/bot +#启用shutdown +# management.endpoints.web.exposure.include=info, health, shutdown +# management.endpoint.shutdown.enabled=true +# spring.security.user.name=hxw +# spring.security.user.password=123 +qa.url2=http://192.168.1.87:59100/game +qa.url=http://aliyun-hz1.chewrobot.com:59100/game +test.var=111122223333 +TEST_VAR=11111 diff --git a/src/main/resources/application-pro.properties b/src/main/resources/application-pro.properties new file mode 100644 index 0000000..f266626 --- /dev/null +++ b/src/main/resources/application-pro.properties @@ -0,0 +1,8 @@ +server.port=8081 +server.servlet.context-path=/bot +#启用shutdown +# management.endpoints.web.exposure.include=info, health, shutdown +# management.endpoint.shutdown.enabled=true +# spring.security.user.name=hxw +# spring.security.user.password=123 +qa.url=http://aliyun-hz1.chewrobot.com:59100/game \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..4ad66bd --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.profiles.active=@profiles.active@ +test.var=111122223333 +TEST_VAR=11111 \ No newline at end of file diff --git a/src/main/resources/dev/c3p0-config.xml b/src/main/resources/dev/c3p0-config.xml new file mode 100644 index 0000000..4d32655 --- /dev/null +++ b/src/main/resources/dev/c3p0-config.xml @@ -0,0 +1,63 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/chatCN?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/platform?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 2 + 30 + 8 + 2 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/log4j.properties b/src/main/resources/dev/log4j.properties similarity index 100% rename from src/log4j.properties rename to src/main/resources/dev/log4j.properties diff --git a/src/main/resources/pro/c3p0-config.xml b/src/main/resources/pro/c3p0-config.xml new file mode 100644 index 0000000..f6916a5 --- /dev/null +++ b/src/main/resources/pro/c3p0-config.xml @@ -0,0 +1,65 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/chatCN?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/platform?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 3 + 30 + 10 + 3 + 200 + + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/pro/log4j.properties b/src/main/resources/pro/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/pro/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/resources/static/js/jquery-3.3.1.min.js b/src/main/resources/static/js/jquery-3.3.1.min.js new file mode 100644 index 0000000..4d9b3a2 --- /dev/null +++ b/src/main/resources/static/js/jquery-3.3.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w(" + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

+
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/templates/index.jsp b/src/main/resources/templates/index.jsp new file mode 100644 index 0000000..330092e --- /dev/null +++ b/src/main/resources/templates/index.jsp @@ -0,0 +1,16 @@ +<%-- + Created by IntelliJ IDEA. + User: hxw + Date: 18-5-8 + Time: 下午1:47 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + $Title$ + + +$END$ + + diff --git a/src/main/resources/templates/update.html b/src/main/resources/templates/update.html new file mode 100644 index 0000000..e102286 --- /dev/null +++ b/src/main/resources/templates/update.html @@ -0,0 +1,97 @@ + + + + 配置文件 v2.2.4 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

+
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/templates/update3.html b/src/main/resources/templates/update3.html new file mode 100644 index 0000000..3165695 --- /dev/null +++ b/src/main/resources/templates/update3.html @@ -0,0 +1,85 @@ + + + + 配置文件 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

关键词替换:

+

 

+ +
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/c3p0-config.xml b/src/main/resources/test/c3p0-config.xml similarity index 93% rename from src/c3p0-config.xml rename to src/main/resources/test/c3p0-config.xml index 4287ee0..39d0885 100644 --- a/src/c3p0-config.xml +++ b/src/main/resources/test/c3p0-config.xml @@ -13,10 +13,10 @@ com.mysql.jdbc.Driver - jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 root - admin + 3g9^pWQs#ft7 10 30 50 diff --git a/src/main/resources/test/log4j.properties b/src/main/resources/test/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/test/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/processing/ChatCacheController2.java b/src/processing/ChatCacheController2.java deleted file mode 100644 index 860cfed..0000000 --- a/src/processing/ChatCacheController2.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ArchiveInfo; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import javax.servlet.ServletContext; -import java.io.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class ChatCacheController2 { - - public static long TIME_OUT = 300000; - - - private static String CHAT_CACHE_DIR = "ChatCache/"; - - private static String ARCHIVE_NAME = "%s-%s-%s"; - private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; - private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; - private static String ENV_POSTFIX = "-env.data"; - private static String INFO_POSTFIX = "-info.data"; - - public static String COMBINE_PUNC1 = "@@@"; - public static String COMBINE_PUNC2 = "@@@@"; - - - - /** - * 通过chat_key获得后台保存的历史信息点 - * chatCache:存储了chatKye相对应的对话记录(历史信息点) - * - * @return 历史信息点,对话过程中引擎提取的用户信息 - */ - public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { - Map chatCacheMap = null; - ChatCache chatCache = null; - - if (context.getAttribute("chatCache") == null) { - chatCacheMap = new HashMap(); - //chatCacheMap.put(chatKey, new ChatCache(userinfo)); - context.setAttribute("chatCache", chatCacheMap); - } else { - chatCacheMap = (Map) context.getAttribute("chatCache"); - } - - - - try { - chatCache = chatCacheMap.get(userKey); - - - //如果用户之前没有玩过或者有一段时间没有玩 - if(chatCache == null){ - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - //用户几分钟前还在玩 - } else { - if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 - saveChatCache(chatCache, null); - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - } - } - //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - } catch (Exception e) { - //可整合 - e.printStackTrace(); - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - - } - - return chatCache; - } - - - - public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); - String nowTime = now .format(format); - Boolean opFlag; - - - String userKey = chatCache.getUserKey(); - String site = chatCache.getInfoPoint().get("site"); - String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); - - try { - - if(helper == null){ - helper = new SqlHelper(); - } - - File dir = new File(CHAT_CACHE_DIR); - if (!dir.exists()) - dir.mkdir(); - - - - - - ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); - - - File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); - FileWriter fw = new FileWriter(file); - - String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); - fw.write(jsonString); - fw.close(); - - - opFlag = helper.insertArchiveInfo(archiveName, userKey, site); - - } catch (Exception e) { - System.out.println("游戏存档时发生异常"); - e.printStackTrace(); - opFlag = false; - } - - return opFlag; - } - - - - public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; - Map infoPoint = null; - String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); - keys[1] = keys[1].split("-")[0]; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; - Map infoPoints = new HashMap(); - try { - File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - if (file.exists()){ - gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - }else{ - throw new IOException("环境存档不存在"); - } - - - file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); - FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - String jsonStr = br.readLine(); - infoPoint = (Map)JSON.parseObject(jsonStr); - - chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); - chatCache.setReloading(true); - - br.close(); - fr.close(); - - - - - } catch (IOException e) { - System.out.println(e.toString()); - } - - return chatCache; - } - - - - /** - * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 - */ - public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { - String sessionKey; - ChatCache chatCache = null; - SqlHelper helper = null; - long lastChatTime, now; - Map history = new HashMap(); - Map chatCacheMap = (Map) context.getAttribute("chatCache"); - - try { - - Iterator it = chatCacheMap.keySet().iterator(); - while (it.hasNext()) { - sessionKey = it.next(); - if (sessionKey.equals(userKey)) { - saveChatCache(chatCacheMap.get(sessionKey),null); - continue; - } - history = chatCacheMap.get(sessionKey).getInfoPoint(); - lastChatTime = Long.valueOf(history.get("lastUpdateTime")); - now = System.currentTimeMillis(); - if (now - lastChatTime > ChatCacheController2.TIME_OUT) { - chatCache = chatCacheMap.get(sessionKey); - - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { - saveChatCache(chatCache, null); - } - System.out.println("移除" + sessionKey); - it.remove(); - } - } - }catch (Exception e){ - e.printStackTrace(); - } - context.setAttribute("chatCache", chatCacheMap); - } - - /** - * 根据chatKey更新chatCache的数据,并修改最后更新时间 - */ - public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { - historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - Map keyCacheMap = (Map) context.getAttribute("chatCache"); - ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); - chatCache.setInfoPoint(historyInfoPoint); - chatCache.setGameEnv(gameEnv); - context.setAttribute("chatCache", keyCacheMap); - } - - - public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; - ArchiveInfo archiveInfo = null; - Map infoPoint = null; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; - SqlHelper helper; - Map infoPoints = new HashMap(); - try { - - helper = new SqlHelper(); - archiveInfo = helper.queryUserLastGameArchive(userKey); - - - } catch(Exception e){ - e.printStackTrace(); - return false; - } - - return archiveInfo != null; - } - - - public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { - try { - System.out.println("移除----------------------------"); - HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); - chatCacheHashMap.remove(chatKey); - - } catch(Exception e){ - e.printStackTrace(); - return false; - } - - return true; - } - - - - - - - - - -} diff --git a/src/processing/ProcessQuestion.java b/src/processing/ProcessQuestion.java deleted file mode 100644 index 9c4a77a..0000000 --- a/src/processing/ProcessQuestion.java +++ /dev/null @@ -1,852 +0,0 @@ -package processing; - -import entity.Solution; -import entity.Condition; -import entity.UserInfo; -import net.sf.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import javax.servlet.ServletContext; -import java.io.*; -import java.sql.SQLException; -import java.text.ParseException; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class ProcessQuestion { - - static Map activatedMap = new HashMap(); - - - - static String POST_DATA_ERROR = "post数据有误"; - static String POST_ERROR = "数据post时出错了"; - static String API_ERROR = "api处理过程中出错了"; - static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; - Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); - -/* - public void updateDB(QuestionKeyWord qkw) throws SQLException { - SqlHelper helper = new SqlHelper(); - String result = helper.queryActionByKey(qkw.getChatKey()); - if(result != "empty") - //待添加 - //qkw.setActionName(result+"+"+qkw.getActionName()); - helper.updateAction(qkw); - else - helper.insertAction(qkw); - helper.destroy(); - } -*/ - - - - - public boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, StringBuffer curInfoRecord){ - - String return_str = "", k ; - boolean debugFlag = false; - - - - //输出所有actionName的值 - Iterator iit = curInfoPoint.keySet().iterator(); - while(iit.hasNext()){ - k = iit.next(); - // - System.out.print(k+": "); - - if(k.equals("debug_mode")) - debugFlag = true; - - String values[] = curInfoPoint.get(k); - - for(String v:values) { - System.out.print(v + " "); - } - System.out.println(); - if(values[0].equals(":")){ - values[0] = ""; - curInfoPoint.put(k, values); - } - - } - - //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown - iit = curInfoPoint.keySet().iterator(); - boolean unknown_flag = true; - while(iit.hasNext()){ - k = iit.next(); - String values[] = curInfoPoint.get(k); - if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name") || k.equals("emptySet")) - continue; - if(values != null && !values[0].equals("")) { - unknown_flag = false; - break; - } - } - - String currentAction = ""; - if(historyInfoPoint.containsKey("currentAction")) - currentAction = historyInfoPoint.get("currentAction"); - else if(userinfo.extraInfo.containsKey("activeAction")) { - currentAction = userinfo.extraInfo.get("activeAction"); - historyInfoPoint.put("currentAction", currentAction); - }else - currentAction = " "; - - - curInfoPoint.put("emptySet", new String[]{" ",}); - if(historyInfoPoint.get("activeList") == null){ - historyInfoPoint.put("activeList", currentAction); - } - - if(unknown_flag && !currentAction.equals("")){ - String i[] = {"unknown",}; - curInfoPoint.put(currentAction,i); - } - - return debugFlag; - } - - - /** - * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 - * @return bestMatch 状态表中满足条件最多的一条 - */ - public Condition getBestMatch(Map curInfoPoint,Map historyInfoPoint,HashMap> conditionTable, ServletContext context) throws IOException { - - Integer configId = 0; - List conditionList = null; - Condition bestMatch = new Condition(-1),iterCon; - Iterator it = curInfoPoint.keySet().iterator(); - Queue activatedQueue = new LinkedList(); - Queue activatedCondition = new LinkedList(); - - - while (it.hasNext()) { - String conditionName = it.next(); - String[] keywords = curInfoPoint.get(conditionName); - String keyword = null; - - if (keywords != null && !keywords[0].equals("")) - keyword = keywords[0]; - - if (keyword != null && conditionTable.get(conditionName) != null) { - conditionList = conditionTable.get(conditionName); - for (Condition condition : conditionList) { - if(condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ - - if(condition.featureMap.get("instantPost") != null){ - - - } - //Post后还是可以激活 - - if(condition.featureMap.get("activate") != null){ - bestMatch = condition; - - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); - } else if((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) - bestMatch = condition; - } - } - } - } - - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); - - - - return bestMatch; - } - - public Condition activatedQueueMatching(Condition bestMatch,Queue activatedQueue, Map curInfoPoint,Map historyInfoPoint, ServletContext context){ - Condition condition; - //待激活配置条目被激活后的匹配 - while(!activatedQueue.isEmpty()){ - condition = activatedQueue.remove(); - activatedMap.remove(condition.id); - - if(conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ - if(condition.featureMap.containsKey("activate")){ - bestMatch = condition; - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); - } else if((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)){ - bestMatch = condition; - } - } - - } - - return bestMatch; - - } - - /** - * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 - * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @param condition 配置文件(状态表)的一行 - * @return 满足条件就为True,不满足就为False - */ - public boolean conditionSatisfy(Map curInfoPoint,Map historyInfoPoint,Condition condition){ - boolean flag = true; - String actionName,keywords[],keyword,comparePair[],cmpType,premiseStr; - HashSet keywordSet = null; - - if(condition.featureMap.containsKey("match")){ - Iterator it = condition.currentPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - keywords = curInfoPoint.get(actionName); - if (keywords == null) { - flag = false; - break; - } - keyword = keywords[0]; - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; - - keywordSet = condition.currentPremise.get(premiseStr); - if(!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - } - - it = condition.historyPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - keyword = historyInfoPoint.get(actionName); - - if(keyword == null){ - flag = false; - break; - } - - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; - - keywordSet = condition.historyPremise.get(premiseStr); - if(!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - } - } - - return flag; - - } - - /** - * 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) - * @param keyword - * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 - * @return 返回匹配或者不匹配 - */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet){ - boolean flag = true; - String operator = ""; - - try { - String splitPair[] = cmpType.split("-"); - if (splitPair.length > 1) { - operator = splitPair[1]; - cmpType = splitPair[0]; - } - - - if (cmpType.equals("match")) { - if (!keywordSet.contains(keyword)) { - flag = false; - } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if (keywordSet.contains(k)) - flag = true; - } - } - - } else if (cmpType.equals("number") && !keyword.equals("") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - - } else if (cmpType.equals("time")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - if (operator.equals("Early")) - flag = candidateA < candidateB; - else if (operator.equals("Later")) - flag = candidateA > candidateB; - - - } - //-------------------------------------------------------------------- - //为兼容旧数据 - else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA > candidateB; - - } else if (cmpType.equals("numberBiggerOrEqual") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA >= candidateB; - - } else if (cmpType.equals("numberSmaller") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA < candidateB; - - } else if (cmpType.equals("numberSmallerOrEqual") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA <= candidateB; - - } else if (cmpType.equals("timeEarly")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - flag = candidateA < candidateB; - - } else if (cmpType.equals("timeLater")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - flag = candidateA > candidateB; - - } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 - flag = false; - - } else { - flag = false; - } - } catch (IndexOutOfBoundsException e){ - System.out.println("配置文件格式有误"); - e.printStackTrace(); - }catch (Exception e){ - System.out.println("操作符有误"); - e.printStackTrace(); - flag = false; - } - - return flag; - } - - /** - * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @return 返回给引擎的数据 - */ - public Solution getSolution(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, reply, variable; - Solution ans = new Solution(0, "", ""); - - - - //如果一条配置文件有多个答案,则随 - // 机选择一个答案 - int randNum = (int) (Math.random() * ansCondition.answer.length); - ans.setAnswer(ansCondition.answer[randNum]); - //System.out.println(ans.getAnswer()); - - //post关键字 - if(ansCondition.featureMap.containsKey("post")){ - ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); - - //nextNext关键字 - }else if(ansCondition.featureMap.containsKey("newNext")){ - ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); - //上一步 - }else if (ansCondition.featureMap.containsKey("return-1")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - //停留 - }else if (ansCondition.featureMap.containsKey("return-0")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - //激活 - }else if (ansCondition.featureMap.containsKey("activate")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - } - - //updateKnowledge关键字 - if (ansCondition.featureMap.containsKey("updateKnowledge")){ - updateKnowledge(ansCondition, historyInfoPoint); - } - - if(ans.getNext().equals("")){ - ans.setNext("nextStep=" + ansCondition.nextStep); - } - - - try { - - /* - it = historyInfoPoint.keySet().iterator(); - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - if(curInfoPoint.get(actionName) != null) { - keyword1 = curInfoPoint.get(actionName)[0]; - ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里 - } - - keyword2 = historyInfoPoint.get(actionName); - ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2)); - - } - */ - - - - - //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 - reply = ans.getAnswer(); - Matcher m = replacePattern.matcher(reply); - while(m.find()){ - variable = m.group(1).substring(1, m.group(1).length()-3); - if(m.group(1).endsWith("-1}")){ - if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals("")) - reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]); - }else if(m.group(1).endsWith("-2}")){ - if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")) - reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); - } - } - ans.setAnswer(reply); - - }catch(Exception e){ - e.printStackTrace(); - } - - return ans; - } - - public void infoTransition(Map curInfoPoint, Map historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag){ - //将当前信息点更新至历史信息点 - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, lastReply; - String next = ans.getNext().split("=")[1]; - - //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx - historyInfoPoint.put("currentAction",next); - historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); - - if(debugFlag) - lastReply = ans.getAnswer().split(")")[2]; - else - lastReply = ans.getAnswer(); - historyInfoPoint.put("lastReply", lastReply); - - try { - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - keyword1 = curInfoPoint.get(actionName)[0]; - keyword2 = historyInfoPoint.get(actionName); - if (keyword2 == null) - historyInfoPoint.put(actionName, keyword1); - else if (keyword2 != null && !keyword1.equals("")) - historyInfoPoint.put(actionName, keyword1); - } - - - ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); - //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); - - - }catch(Exception e){ - e.printStackTrace(); - } - } - - - /** - * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 - * @param ans 最终返回的数据 - * @param curInfoPoint 当前对话识别到的信息点 - * @param historyInfoPoint 在当前对话之前采集到的所有用户信息点 - * @param context - */ - public void appendDebugInfo(Solution ans, Map curInfoPoint, Map historyInfoPoint, ServletContext context) { - Iterator it = null; - String key, values[], value; - - HashSet skipSet = new HashSet(){ - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("bot_name"); - add("action_name"); - add("chat_key"); - add("lastReply"); - } - }; - - it = curInfoPoint.keySet().iterator(); - String debugInfo = ""; - debugInfo += "(识别:"; - - while(it.hasNext()) { - key = it.next(); - values = curInfoPoint.get(key); - if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key)) - debugInfo += (" " + key + ":\'" + values[0] + "\' "); - } - - debugInfo += ")(已知:"; - it = historyInfoPoint.keySet().iterator(); - while(it.hasNext()){ - - key = it.next(); - value = historyInfoPoint.get(key); - if(value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key)) - debugInfo += (" " + key + ":\'" + value + "\' "); - - } - ans.setAnswer( debugInfo + ")" + ans.getAnswer()); - } - - - /** - * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) - * @param ans 返回给用户的数据 - * @param ansCondition 满足条件最多的condition(配置文件的某一行) - */ - public Solution postToServer(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint) throws IOException { - String url = null,elem[], subElem[], key, postType = "all"; - Map infoMap = new HashMap(); - List pairList = new ArrayList(); - Iterator k_iter = null; - - elem = ansCondition.featureMap.get("post").split("\\|"); - url = elem[0]; - postType = elem[1]; - - //提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 - if(postType.equals("all")){ - k_iter = curInfoPoint.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next(); - if(curInfoPoint.get(key)[0] != "") - //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); - pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); - } - - k_iter = historyInfoPoint.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next(); - if(historyInfoPoint.get(key) != "") - //infoMap.put(key + "_his", historyInfoPoint.get(key)); - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - } - - //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 - }else if(postType.equals("term")){ - k_iter = ansCondition.currentPremise.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next().split("::")[0]; - if(curInfoPoint.get(key)[0] != "") - pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); - } - - k_iter = ansCondition.historyPremise.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next().split("::")[0]; - if(historyInfoPoint.get(key) != "") - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - //infoMap.put(key + "_his", historyInfoPoint.get(key)); - } - } - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); - entity.setContentType("application/x-www-form-urlencoded"); - httpPost.setEntity(entity); - - try { - HttpResponse resp = client.execute(httpPost); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - JSONObject jobj = JSONObject.fromString(respContent); - Iterator kit = jobj.keys(); - while (kit.hasNext()) { - keyName = kit.next(); - if (keyName.equals("process")) { - ans.setNext((String)jobj.get(keyName)); - historyInfoPoint.put("process", (String)jobj.get(keyName)); - } else if (keyName.equals("solution")) { - ans.setAnswer((String) jobj.get(keyName)); - } else { - historyInfoPoint.put(keyName, jobj.getString(keyName)); - } - } - } else { - ans.setAnswer(API_ERROR); - } - }catch (Exception e){ - e.printStackTrace(); - - ans.setNext(POST_ERROR + url); - } - - return ans; - - } - - public Solution findNewNext(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint){ - String nextOptions[] = ansCondition.nextStep.split(","); - String conditionName,premises[],cpPair[]; - boolean flag = true; - - String activeList = historyInfoPoint.get("activeList"); - - for(String option: nextOptions){ - flag = true; - cpPair = option.split(":"); - conditionName = cpPair[0]; - if(cpPair.length == 1){ - ans.setNext("nextStep="+conditionName); - break; - } - premises = cpPair[1].split("-"); - for(String premise:premises) { - if(premise.equals("known")) { - //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 - boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName)[0].equals("") && !curInfoPoint.get(conditionName)[0].equals("unknown"); - boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown"); - - //只有前两者都为假时,conditionExist才为真 - boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); - - if (conditionExist) - flag = false; - } - - if(premise.equals("active")){ - boolean isActive = activeList.contains(conditionName); - if (isActive) - flag = false; - } - } - - if(flag){ - ans.setNext("nextStep="+conditionName); - break; - } - - } - return ans; - - } - - public void updateKnowledge(Condition condition, Map historyInfoPoint) throws ParseException { - String keyword, variableName, updateValue; - - Iterator iit = condition.updateKnowledge.keySet().iterator(); - while(iit.hasNext()){ - - variableName = iit.next(); - updateValue = condition.updateKnowledge.get(variableName); - keyword = historyInfoPoint.get(variableName); - - try { - //做数字加法 - if (updateValue.startsWith("+")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("-")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(4); - //做字符串删除 - } else if (updateValue.startsWith("str-")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(4), ""); - } - }catch (Exception e){ - e.printStackTrace(); - continue; - } - historyInfoPoint.put(variableName, updateValue); - } - - - - } - - - public void activateCondition(Queue activatedQueue, String userName, int basePriority, String activateList, ServletContext context){ - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - String configStr = ""; - Integer configId; - Condition newCondition, originCondition; - - for(String configIdStr:activateList.split(",")){ - if (!StringUtils.isNumeric(configIdStr)) - continue; - configId = Integer.parseInt(configIdStr); - - configStr = userinfo.id2config.get(configId); - if(configStr != null) { - originCondition = userinfo.id2condition.get(configId); - newCondition = new Condition(originCondition, basePriority); - //condition = ProcessQuestion.buildCondition(condition, configStr); - - if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { - activatedMap.get(configId).activePriority = newCondition.activePriority; - } else if (!activatedMap.containsKey(configId)) { - activatedMap.put(configId, newCondition); - activatedQueue.add(newCondition); - } - } - } - - - } - - public Solution postActivate(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - Queue activatedQueue = new LinkedList(); - Solution bestMatch = null; - activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context); - ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); - - bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); - - return bestMatch; - - - } - - - - -} diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java deleted file mode 100644 index 6211686..0000000 --- a/src/processing/QuestionMatcher.java +++ /dev/null @@ -1,1056 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Condition; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.http.message.BasicNameValuePair; - -import javax.servlet.ServletContext; -import java.io.IOException; -import java.text.ParseException; -import java.util.*; - - -public class QuestionMatcher { - - Map activatedMap = new HashMap(); - - - static String POST_DATA_ERROR = "post数据有误"; - static String POST_ERROR = "数据post时出错了"; - static String API_ERROR = "api处理过程中出错了"; - - - - - public LogWriter logWriter = null; - public UserInfo userinfo = null; - public ServletContext context = null; - public GameEnv gameEnv = null; - public Map curInfoPoint = null; - public Map historyInfoPoint = null; - public WorldController worldController = null; - BasicBotUtil botUtil = null; - - public QuestionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; - this.logWriter = logWriter; - this.userinfo = userinfo; - this.context = context; - this.gameEnv = gameEnv; - this.worldController = new WorldController(logWriter, userinfo); - this.botUtil = botUtil; - } - - - public QuestionMatcher(){ - - } - - - - - /** - * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch - * - * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 - * @return bestMatch 状态表中满足条件最多的一条 - */ - public Condition getBestMatch( HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { - - Integer configId = 0; - List conditionList = null; - Condition bestMatch = new Condition(-1), iterCon; - Iterator it = curInfoPoint.keySet().iterator(); - Queue activatedQueue = new LinkedList(); - Queue activatedCondition = new LinkedList(); - - - - while (it.hasNext()) { - String conditionName = it.next(); - String keywords = curInfoPoint.get(conditionName); - String keyword = null; - - if (keywords != null && !keywords.equals("")) - keyword = keywords; - - - if (keyword != null && conditionTable.get(conditionName) != null) { - conditionList = conditionTable.get(conditionName); - - - for (Condition condition : conditionList) { - - if (condition.status.equals("waiting")){ - if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority) - || condition.featureMap.get("activate") != null){ - if(conditionSatisfy(condition)){ - if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { - //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); - } - if((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)) { - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - } - - - } - - }else { - logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - } - } - } - } - - } - logWriter.record("----------------------匹配结束", 2); - - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); - - - return bestMatch; - } - - /** - * 在激活列表中选择满足匹配且优先级最高的一条配置条目 - * @param bestMatch - * @param activatedQueue - * @param context - * @return - * @throws IOException - */ - public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, ServletContext context) throws IOException { - Condition condition; - //待激活配置条目被激活后的匹配 - while (!activatedQueue.isEmpty()) { - condition = activatedQueue.remove(); - activatedMap.remove(condition.id); - - - if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority) - || condition.featureMap.get("activate") != null - || bestMatch.nextStep.contains(String.valueOf(condition.id)) || (!condition.configName.equals("") && bestMatch.nextStep.contains(condition.configName.substring(0,3)))){ - //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 - if(conditionSatisfy(condition)){ - if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); - } - - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - - - } - - } else { - logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - } - - - - - } - - return bestMatch; - - } - - /** - * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 - * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 - * - * @param condition 配置文件(状态表)的一行 - * @return 满足条件就为True, 不满足就为False - */ - public boolean conditionSatisfy(Condition condition) { - boolean flag = true; - String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; - HashSet keywordSet = null; - - logWriter.record("-----------------------------------检索到配置条目", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - - if (condition.featureMap.containsKey("match")) { - Iterator it = condition.currentPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - cmpType = comparePair[1]; - keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - keywordSet = condition.currentPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - - it = condition.historyPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - cmpType = comparePair[1]; - actionName = comparePair[0]; - //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, condition.featureMap.containsKey("includeCurInfo"), actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - - - keywordSet = condition.historyPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - } - - - return flag; - - } - - - - - /** - * 单个条件的匹配,判断是否满足条件 - * 比较类型分为 match、number、time、variable, - * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 - * - * @param keyword - * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 - * @return 返回匹配或者不匹配 - */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { - boolean flag = true; - String operator = ""; - - try { - String splitPair[] = cmpType.split("-", 2); - if (splitPair.length > 1) { - operator = splitPair[1]; - cmpType = splitPair[0]; - } - - - if (cmpType.equals("match")) { - if(operator.equals("Keyword") || operator.equals("Include")) { - if (!keywordSet.contains(keyword)) { - flag = false; - } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if (keywordSet.contains(k)) - flag = true; - } - } - } else if(operator.equals("Exclude")) { - if(keyword.contains(":")){ - String ks[] = keyword.split(":", 2); - if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) - flag = false; - }else { - if (keywordSet.contains(keyword)) { - flag = false; - } - } - }else if(operator.equals("Have")){ - for(String key:keywordSet){ - if(key.equals("")) - continue; - if(!keyword.contains(key)){ - flag = false; - break; - } - } - }else{ - flag = false; - } - - - } else if (cmpType.equals("number") && !keyword.equals("")) { - int candidateA = 0; - int candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(StringUtils.isNumeric(k)) - keyword = k; - - } - } - - if(!StringUtils.isNumeric(keyword)){ - return false; - - } - - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if (cmpType.equals("time")) { - - long candidateA, candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(k.contains("年") && k.contains("月") && k.contains("日")) - keyword = k; - - } - } - - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - if (operator.equals("Early")) - flag = candidateA < candidateB; - else if (operator.equals("Later")) - flag = candidateA > candidateB; - - } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { - String conditionName2 = "", conditionValue2 = ""; - for (String k : keywordSet) { - if (!k.equals("")) { - conditionName2 = k; - break; - } - } - - if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { - conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); - }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ - conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); - }else { - flag = false; - } - - - if(flag ){ - /** - * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true - */ - flag = false; - if(operator.equals("Equal")){ - flag = keyword.equals(conditionValue2); - - }else if(keyword.contains(":") && conditionValue2.contains(":")){ - String relPair1[] = keyword.split(":", 2), keyword1 = ""; - String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; - boolean similar = false; - - if(relPair1[0].equals(relPair2[0])){ - similar = true; - keyword1 = relPair1[1]; - keyword2 = relPair2[1]; - }else if (relPair1[1].equals(relPair2[1])){ - similar = true; - keyword1 = relPair1[0]; - keyword2 = relPair2[0]; - } - - if(similar){ - if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ - int candidateA = Integer.parseInt(keyword1); - int candidateB = Integer.parseInt(keyword2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") - && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword1); - long candidateB = MyFunc.transferToMillisecond(keyword2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ - if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ - int candidateA = Integer.parseInt(keyword); - int candidateB = Integer.parseInt(conditionValue2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") - && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword); - long candidateB = MyFunc.transferToMillisecond(conditionValue2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - } - - - - } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 - flag = false; - - } else { - flag = false; - } - } catch (IndexOutOfBoundsException e) { - System.out.println("配置文件格式有误"); - flag = false; - e.printStackTrace(); - } catch (ParseException e) { - System.out.println("时间解析错误"); - e.printStackTrace(); - flag = false; - } catch (Exception e) { - System.out.println("操作符有误"); - e.printStackTrace(); - flag = false; - } - - return flag; - } - - /** - * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 - * - * @return 返回给引擎的数据 - */ - public Solution getSolution(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, reply, variable; - Solution ans = new Solution(0, "", ""); - - - //如果一条配置文件有多个答案,则随 - // 机选择一个答案 - - //System.out.println(ans.getAnswer()); - - //post关键字 - if (ansCondition.featureMap.containsKey("post")) { - logWriter.record("---------------------进入表单结束",1); - ans = postToServer(ans, ansCondition); - logWriter.record("---------------------提交表单结束",1); - - //nextNext关键字 - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - //updateKnowledge关键字 - if (ansCondition.featureMap.containsKey("updateKnowledge")) { - logWriter.record("---------------------进入更新答案【略】",1); - updateKnowledge2(ansCondition); - logWriter.record("---------------------更新答案结束",1); - } - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ansCondition.featureMap.containsKey("newNext")) { - logWriter.record("---------------------进入判断下一步【略】",1); - ans = findNewNext(ans, ansCondition); - logWriter.record("---------------------判断下一步结束",1); - //上一步 - } else if (ansCondition.featureMap.containsKey("return-1")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - //停留 - } else if (ansCondition.featureMap.containsKey("return-0")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if(activeList.length > 0) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else - ans.setNext("nextStep= "); - //激活 - } else if (ansCondition.featureMap.containsKey("activate") || ansCondition.featureMap.containsKey("activate:after")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - } - - - - - - try { - - reply = MyFunc.randStr(ansCondition.answer); - reply = botUtil.varSlotReplace(reply); - reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter); - - ans.setAnswer(reply); - - botUtil.extraOperation(ansCondition, ans); - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ans.getNext().equals("")) { - ans.setNext("nextStep=" + ansCondition.nextStep); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return ans; - } - - /** - * 请求处理结束后台将当前信息的信息点转移到已知信息 - * @param ans - * @param context - * @param debugFlag - */ - public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { - //将当前信息点更新至历史信息点 - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, lastReply; - String next = ans.getNext().split("=", 2)[1]; - - //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx - historyInfoPoint.put("currentAction", next); - historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); - - logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); - - HashSet skipSet = new HashSet() { - { - add("chat_key"); - add("action_name"); - add("bot_name"); - add("emptySet"); - add("query_text"); - } - }; - - if (debugFlag) - lastReply = ans.getAnswer().split(")")[2]; - else - lastReply = ans.getAnswer(); - historyInfoPoint.put("lastReply", lastReply); - - try { - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - - if(skipSet.contains(actionName)) - continue; - - keyword1 = curInfoPoint.get(actionName); - keyword2 = historyInfoPoint.get(actionName); - if (keyword2 == null) { - historyInfoPoint.put(actionName, keyword1); - }else if (historyInfoPoint.get(actionName).equals("do_reset")){ - historyInfoPoint.put(actionName, ""); - }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) - historyInfoPoint.put(actionName, keyword1); - } - historyInfoPoint.put("临时变量reply", ""); - historyInfoPoint.put("临时变量condition", ""); - historyInfoPoint.put("临时变量3", ""); - - - - //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 - * - * @param ans 最终返回的数据 - * @param context - */ - public void appendDebugInfo(Solution ans, ServletContext context) { - Iterator it = null; - String key, values, value; - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("bot_name"); - add("action_name"); - add("lastReply"); - add("unknownTextList"); - add("finalUnknownText"); - add("unknownText"); - add("randKey"); - add("userKey"); - } - }; - - it = curInfoPoint.keySet().iterator(); - String debugInfo = ""; - debugInfo += "(识别:"; - - while (it.hasNext()) { - key = it.next(); - values = curInfoPoint.get(key); - if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { - if (key.endsWith("_backup")) { - key = key.substring(0, key.length() - 7); - } - debugInfo += (" " + key + ":\'" + values + "\' "); - } - } - - debugInfo += ")"; - if(curInfoPoint.containsKey("debug_mode")) { - debugInfo = debugInfo.replace("-)", ""); - debugInfo += "(已知:"; - it = historyInfoPoint.keySet().iterator(); - while (it.hasNext()) { - - key = it.next(); - value = historyInfoPoint.get(key); - if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition") && !key.startsWith("临时变量")) - debugInfo += (" " + key + ":\'" + value + "\' "); - - } - } - ans.setAnswer(debugInfo + ")" + ans.getAnswer()); - } - - - /** - * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) - * - * @param ans 返回给用户的数据 - * @param ansCondition 满足条件最多的condition(配置文件的某一行) - */ - public Solution postToServer(Solution ans, Condition ansCondition) throws IOException { - String url = null, elem[], subElem[], key,keys, postType = "all"; - Map infoMap = new HashMap(); - List pairList = new ArrayList(); - Iterator k_iter = null; - FormsPoster poster = new FormsPoster(logWriter); - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("lastReply"); - } - }; - - elem = ansCondition.featureMap.get("post").split("\\|"); - url = elem[0]; - postType = elem[1]; - - - if(postType.equals("all")){ - poster.postAll(curInfoPoint, historyInfoPoint, ans, url); - }else if(postType.equals("term")){ - poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansCondition, url); - }else if(postType.equals("gameQA")){ - poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); - } - - return ans; - - } - - public Solution findNewNext(Solution ans, Condition ansCondition) { - String nextOptions[] = ansCondition.nextStep.split(","); - String conditionName, premises[], cpPair[]; - boolean flag = true; - - String activeList = historyInfoPoint.get("activeList"); - - for (String option : nextOptions) { - flag = true; - cpPair = option.split(":"); - conditionName = cpPair[0]; - if (cpPair.length == 1) { - ans.setNext("nextStep=" + conditionName); - break; - } - premises = cpPair[1].split("-"); - for (String premise : premises) { - if (premise.equals("known")) { - //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 - boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); - boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); - - //只有前两者都为假时,conditionExist才为真 - boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); - - if (conditionExist) - flag = false; - } - - if (premise.equals("active")) { - boolean isActive = activeList.contains(conditionName); - if (isActive) - flag = false; - } - } - - if (flag) { - ans.setNext("nextStep=" + conditionName); - break; - } - - } - return ans; - - } - - - public void updateKnowledge2(Condition condition) throws ParseException { - String keyword, variableName, updateValue, returnStr = "1"; - - - - Iterator iit = condition.updateKnowledge.keySet().iterator(); - while (iit.hasNext()) { - - variableName = iit.next(); - - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); - updateValue = botUtil.knowledgeProcess(variableName, condition.updateKnowledge.get(variableName)); - - - try { - //做数字加法 - if (updateValue.startsWith("+")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("-")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(4); - //做字符串删除 - } else if (updateValue.startsWith("str-")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(4), ""); - - } else if (updateValue.startsWith("int+=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("int-=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(5); - //做字符串删除 - } else if (updateValue.startsWith("str-=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(5), ""); - - - //变量提取 - } else if (updateValue.startsWith("var=")) { - String conditionName = updateValue.substring(5, updateValue.length() - 3); - - if (updateValue.endsWith("-1}")) { - if (curInfoPoint.get(conditionName) != null) { - updateValue = curInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - } else if (updateValue.endsWith("-2}")) { - if (historyInfoPoint.get(conditionName) != null) { - updateValue = historyInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - - //提取配置条目的下一步 - } else if (updateValue.endsWith("nextStep-3}")) { - updateValue = condition.nextStep; - //提取配置条目的回答 - } else if (updateValue.endsWith("reply-3}")) { - updateValue = MyFunc.randStr(condition.answer); - } - //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue - if (variableName.startsWith("process-nextStep")) { - condition.nextStep = updateValue; - updateValue = ""; - } - - } - - - } catch (Exception e) { - e.printStackTrace(); - continue; - } - - - - if(updateValue.equals("")) { - curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 - // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 - curInfoPoint.put(variableName, ""); - } - - botUtil.putKeyword(variableName, updateValue); - - - } - - } - - - public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { - UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - String configStr = ""; - Integer configId; - Condition newCondition, originCondition; - List originConditionList = new ArrayList(); - - for (String configIdStr : activateList.split(",")) { - logWriter.record("------激活-------" + configIdStr + "-------
", 0); - try { - if (StringUtils.isNumeric(configIdStr)) { - configId = Integer.parseInt(configIdStr); - configStr = userinfo.id2config.get(configId); - originCondition = userinfo.id2condition.get(configId); - originConditionList.add(originCondition); - } else { - if (configIdStr.endsWith("*")) { - String prefix = configIdStr.substring(0, configIdStr.length()-1); - for(String name:userinfo.name2condition.keySet()){ - if (name.startsWith(prefix)){ - originConditionList.add(userinfo.name2condition.get(name)); - } - } - - } else { - originConditionList.add(userinfo.name2condition.get(configIdStr)); - } - - - } - } catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); - } - } - - for (Condition condition: originConditionList){ - originCondition = condition; - try { - - configId = originCondition.id; - - newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); - //condition = QuestionMatcher.buildCondition(condition, configStr); - - - - if (activatedMap.containsKey(configId)) { - if(newCondition.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) - activatedMap.get(configId).auxiliaryPriority = newCondition.auxiliaryPriority; - if(newCondition.activePriority > activatedMap.get(configId).activePriority) - activatedMap.get(configId).activePriority = newCondition.activePriority; - } else if (!activatedMap.containsKey(configId)) { - activatedMap.put(configId, newCondition); - activatedQueue.add(newCondition); - } - }catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------激活失败:" + condition.configName, 5); - } - - } - - - } - - /** - * 一个提交表单后在激活的操作 - * @param ansCondition - * @param context - * @param userinfo - * @return - * @throws IOException - * @throws ParseException - */ - public Solution postActivate(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - Queue activatedQueue = new LinkedList(); - Solution bestMatch = null; - activateCondition(activatedQueue, userinfo.botAccount, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); - ansCondition = activatedQueueMatching(ansCondition, activatedQueue, context); - - bestMatch = getSolution(ansCondition, context, userinfo); - - return bestMatch; - - - } - - -} diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java deleted file mode 100644 index c8d8226..0000000 --- a/src/processing/ResponseFilter.java +++ /dev/null @@ -1,208 +0,0 @@ -//package com.qiwu.chatbotbackend.processing; -// -//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -//import com.qiwu.chatbotbackend.entity.Action; -//import com.qiwu.chatbotbackend.entity.UserInfo; -//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; -// -//import java.util.*; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; -//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; -// -//public class ResponseFilter { -// -// static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, -// String reply, UserInfo userInfo, Action ansCondition, LogWriter logWriter){ -// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; -// -// -// if(botType == null || botType.equals("")){ -// return reply; -// -// }else if (botType.equals("game")){ -// -// String site = historyInfoPoint.get("site"); -// -// -// reply = SimpleUtil.randStr(reply.split("~")); -// -// if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 -// return reply; -// } -// -// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ -// return reply; -// } -// -// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ -// return appendTalker(reply, historyInfoPoint, gameEnv, worldController); -// }else if (reply.equals("") && ( -// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals("")) && !historyInfoPoint.get("common_answer").equals("no answer")) -// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) -// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) -// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) -// ){ -// return reply; -// } -// -// -// -// -// -// if(userInfo.varInitialMap.get("unknownTextList") != null){ -// List unknownList = new ArrayList(); -// -// String lastTalker = ""; -// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 -// -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { -// if(isOnlineText(ans, historyInfoPoint)) -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return SimpleUtil.randStr(unknownList); -// } -// -// } -// -// if(userInfo.varInitialMap.get("finalUnknownText") != null){ -// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); -// List finalUnknownList = new ArrayList(); -// -// -// for(String ans:finalUnknownText.split("~")){ -// if(ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// if(isOnlineText(ans, historyInfoPoint)) -// finalUnknownList.add(ans); -// //return ans; -// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ -// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if(finalUnknownList.size() > 0){ -// return SimpleUtil.randStr(finalUnknownList); -// -// } -// } -// -// } -// -// -// return "找不到匹配文本"; -// } -// -// -// -// static Matcher findTalker(String reply){ -// Pattern findTalker = Pattern.compile(TALKER); -// Matcher m = findTalker.matcher(reply); -// -// return m; -// } -// /** -// * 查看回答文本的说话这是否在当前地点 -// * 0:没有说话者 -// * 1:说话者在当前地点 -// * 2:说话者不在当前地点或者不能说话 -// * @param reply -// * @param curInfoPoint -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @param site -// * @param logWriter -// * @return -// */ -// static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ -// String npc, location; -// -// Matcher m = findTalker(reply); -// int flag = 1; -// if(m.find()) { -// npc = m.group(1); -// location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); -// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ -// if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ -// flag = 1; -// logWriter.record("\"" + reply + "\":匹配", 1); -// }else { -// flag = 2; -// logWriter.record(npc + "不能说话", 1); -// } -// -// }else { -// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); -// flag = 2; -// } -// }else{ -// logWriter.record("\"" + reply + "\":没有npc名",1 ); -// flag = 0; -// } -// return flag; -// -// } -// -// /** -// * 在头部没有【%s@%s】的文本加上【%s@%s】 -// * @param reply -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @return -// */ -// static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ -// -// List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); -// String npc = ""; -// List filtedNpcList = new ArrayList(); -// -// for(String npcName:npcList){ -// if(isOnlineMode(npcName, historyInfoPoint)) { -// filtedNpcList.add(npcName); -// }else{ -// System.out.println(npcName + "是离线模式"); -// } -// } -// if(filtedNpcList.size() != 0) -// npc = SimpleUtil.randStr(filtedNpcList); -// else -// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); -// -// -// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION) + reply; -// -// } -// -// static Boolean isOnlineMode(String npc, Map historyInfoPoint){ -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// } -// static Boolean isOnlineText(String text, Map historyInfoPoint){ -// Matcher m = findTalker(text); -// String npc = ""; -// if(m.find()) { -// npc = m.group(1); -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// }else{ -// System.out.println("竟然没找到npc"); -// return false; -// } -// } -// -//} diff --git a/src/processing/ResponseFilter3.java b/src/processing/ResponseFilter3.java deleted file mode 100644 index db46673..0000000 --- a/src/processing/ResponseFilter3.java +++ /dev/null @@ -1,260 +0,0 @@ -//package com.qiwu.chatbotbackend.processing; -// -//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -//import com.qiwu.chatbotbackend.entity.Condition; -//import com.qiwu.chatbotbackend.entity.UserInfo; -//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; -// -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; -//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; -// -//public class ResponseFilter3 { -// -// static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, -// String reply, UserInfo userInfo, Condition ansCondition, LogWriter logWriter){ -// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; -// -// -// if(botType == null || botType.equals("")){ -// return reply; -// -// }else if (botType.equals("game")){ -// -// String site = historyInfoPoint.get("site"); -// -// -// reply = MyFunc.randStr(reply.split("~")); -// -// if(reply.endsWith("开始游戏或者继续游戏")){ -// return reply; -// } -// -// -// //如果剧情跳转中包含了自动跳转的文本,那么不判断是否处于同一地点 -//// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ -//// return reply; -//// } -// -// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ -// return appendTalker(reply, historyInfoPoint, gameEnv, worldController); -// -// //如果回答为空但是有qa回答、地图物品npc查询结果则允许返回空文本,否则往下漏,取unknown文本 -// }else if (reply.equals("") && ( -// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals(""))) -// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) -// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) -// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) -// ){ -// return reply; -// } -// -// -// -// if(userInfo.varInitialMap.get("unknownTextList") != null){ -// List unknownList = new ArrayList(); -// -// String lastTalker = ""; -// Boolean onlyLastTalker = false; -// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 -// if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ -//// Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); -//// while(m.find()) { -//// //回答unknown文本的npc必须处于在线模式 -//// npc = m.group(1); -//// if(isOnlineMode(npc, historyInfoPoint)) { -//// //找到最后一个说话且处于离线模式的npc -//// lastTalker = npc; -//// }else{ -//// System.out.println(npc + "是离线模式"); -//// } -//// } -// lastTalker = findPlotLastTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)), site, historyInfoPoint, gameEnv, logWriter); -// if(!lastTalker.equals("") && userInfo.varInitialMap.get("unknownTextList").contains(lastTalker)) -// onlyLastTalker = true; -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (ans.contains(lastTalker) && onlyLastTalker) { -// -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return MyFunc.randStr(unknownList); -// } -// -// }else { -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { -// -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return MyFunc.randStr(unknownList); -// } -// } -// } -// -// -// //最终unknown文本 -// if(userInfo.varInitialMap.get("finalUnknownText") != null){ -// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); -// List finalUnknownList = new ArrayList(); -// -// -// for(String ans:finalUnknownText.split("~")){ -// if(ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// finalUnknownList.add(ans); -// //return ans; -// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ -// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if(finalUnknownList.size() > 0){ -// return MyFunc.randStr(finalUnknownList); -// -// } -// } -// -// } -// -// -// return "找不到匹配文本"; -// } -// -// -// -// static Matcher findTalker(String reply){ -// Pattern findTalker = Pattern.compile(TALKER); -// Matcher m = findTalker.matcher(reply); -// -// return m; -// } -// /** -// * 查看回答文本的说话这是否在当前地点 -// * 0:没有说话者 -// * 1:说话者在当前地点 -// * 2:说话者不在当前地点 -// * @param reply -// * @param curInfoPoint -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @param site -// * @param logWriter -// * @return -// */ -// static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter, Boolean needOnline){ -// String npc, location; -// -// Matcher m = findTalker(reply); -// int flag = 1; -// if(m.find()) { -// npc = m.group(1); -// flag = npcIsSameLocation(npc, site, reply, historyInfoPoint, gameEnv, logWriter); -// }else{ -// logWriter.record("\"" + reply + "\":没有npc名",1 ); -// flag = 0; -// } -// return flag; -// -// } -// -// static Integer npcIsSameLocation(String npc, String site, String reply, Map historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){ -// Integer flag; -// String location = gameEnv.queryNpcAttrByNpcName(npc, "location"); -// //String location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); -// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ -// if((gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能"))){ -// flag = 1; -// logWriter.record("\"" + reply + "\":匹配", 1); -// }else { -// flag = 2; -// logWriter.record(npc + "不能说话或者是离线模式", 1); -// } -// -// }else { -// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); -// flag = 2; -// } -// -// return flag; -// } -// -// /** -// * 在头部没有【%s@%s】的文本加上【%s@%s】 -// * @param reply -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @return -// */ -// static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ -// -// List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); -// String npc = ""; -// List filtedNpcList = new ArrayList(); -// -// for(String npcName:npcList){ -// if(isOnlineMode(npcName, historyInfoPoint)) { -// filtedNpcList.add(npcName); -// }else{ -// System.out.println(npcName + "是离线模式"); -// } -// } -// if(filtedNpcList.size() != 0) -// npc = MyFunc.randStr(filtedNpcList); -// else -// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); -// -// -// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION); -// -// } -// -// static Boolean isOnlineMode(String npc, Map historyInfoPoint){ -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// } -// -// public static String findPlotLastTalker(String text, String site, Map historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){ -// Matcher m = findTalker(text); -// String npc, lastTalker = ""; -// while(m.find()) { -// //回答unknown文本的npc必须处于在线模式 -// npc = m.group(1); -// //处于离线模式 可以说话 相同地点 -// if(isOnlineMode(npc, historyInfoPoint) && npcIsSameLocation(npc, site, npc, historyInfoPoint, gameEnv, logWriter) == 1) { -// //找到最后一个说话且处于离线模式的npc -// lastTalker = npc; -// }else{ -// System.out.println(npc + "是离线模式"); -// } -// } -// -// return lastTalker; -// } -// -//} diff --git a/src/processing/SimpleUtil.java b/src/processing/SimpleUtil.java deleted file mode 100644 index 1d9ecfa..0000000 --- a/src/processing/SimpleUtil.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.entity.Solution; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -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.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - - -public class SimpleUtil { - - /** - * 将后台返回的数据转成json格式 - */ - public static String toJson(Solution ans) { - JSONObject jobj = new JSONObject(); - jobj.put("solution", ans.getAnswer()); - jobj.put("status", ans.getStatus()); - jobj.put("process", ans.getNext()); - return jobj.toString(); - } - - public static String toJson(String returnStr) { - JSONObject jobj = new JSONObject(); - jobj.put("returnString", returnStr); - return jobj.toString(); - } - - /** - * 当请求中的数据是json格式时,该函数用于提取request中的json数据 - * - * @param request - * @return json字符串 - */ - public static String readJSONString(HttpServletRequest request) { - StringBuffer json = new StringBuffer(); - String line = null; - - try { - BufferedReader reader = request.getReader(); - while ((line = reader.readLine()) != null) { - json.append(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return json.toString(); - } - - /** - * 通过get方法传递参数时需要对参数的编码进行转换 - */ - public static String convert2Utf8(String s) { - if (s == null) return null; - try { - s = new String(s.getBytes("iso-8859-1"), "utf-8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return s; - } - - public static long transferToMillisecond(String keyword) throws ParseException { - long time; - - System.out.println(keyword); - - String timeSeries[] = {"时", "分", "秒"}; - for (String f : timeSeries) { - if (!keyword.contains(f)) - keyword += "0" + f; - } - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - time = format.parse(keyword).getTime(); - - return time; - } - - public static String transferToStandardTime(long time) throws ParseException { - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - - Date date = new Date(time); - return format.format(date); - - } - - public static boolean isInteger(String str){ - return true; - } - - - - public static JSONObject postJSON(String url, JSON data, String auth) throws UnsupportedEncodingException { - - JSONObject jobj = new JSONObject(); - - - - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - - StringEntity entity = new StringEntity(data.toJSONString(), "utf-8"); - - entity.setContentType("application/json; charset=utf-8"); - httpPost.setEntity(entity); - - if(auth != null){ - httpPost.setHeader("Authorization", auth); - } - - try { - HttpResponse resp = client.execute(httpPost); - jobj.put("status_code", resp.getStatusLine().getStatusCode()); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - jobj = JSONObject.parseObject(respContent); - jobj.put("post_status", 1); - } else { - jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return jobj; - - } - - - - - - public static JSONObject postFORM(String url, List pairList) throws UnsupportedEncodingException { - - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); - entity.setContentType("application/x-www-form-urlencoded"); - httpPost.setEntity(entity); - JSONObject jobj = new JSONObject(); - - try { - System.out.println("url为:" + url); - HttpResponse resp = client.execute(httpPost); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - jobj = JSONObject.parseObject(respContent); - jobj.put("post_status", 1); - - } else { - jobj.put("post_status", 0); - jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); - } - } catch (Exception e) { - jobj.put("error_message", "提交表单时出错:" + e.getMessage()); - jobj.put("post_status", 0); - } - - return jobj; - - } - - public static String randStr(String strList[]){ - String reply; - int randNum = (int) (Math.random() * strList.length); - reply = strList[randNum]; - - return reply; - } - - public static String randStr(List strList){ - String reply; - - int randNum = (int) (Math.random() * strList.size()); - reply = strList.get(randNum); - - return reply; - } - - -} \ No newline at end of file diff --git a/src/servlet/ContextDestroyListener.java b/src/servlet/ContextDestroyListener.java deleted file mode 100644 index 92eedbf..0000000 --- a/src/servlet/ContextDestroyListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; -import java.io.IOException; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.Map; - -@WebListener -public class ContextDestroyListener implements ServletContextListener { - - public void contextDestroyed(ServletContextEvent sce) { - System.out.println("destory context...."); - /** - * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 - */ - - String chatKey; - ServletContext servletContext = sce.getServletContext(); - Object obj = servletContext.getAttribute("chatCache"); - ChatCache cache = null; - SqlHelper helper = null; - - if(obj != null){ - Map chatCacheMap = (Map)obj; - - Iterator cacheIter = chatCacheMap.keySet().iterator(); - try { - helper = new SqlHelper(); - while (cacheIter.hasNext()) { - chatKey = cacheIter.next(); - cache = chatCacheMap.get(chatKey); - - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { - System.out.println(String.format("saving %s", chatKey)); - ChatCacheController.saveChatCache(cache, helper); - } - } - cacheIter.remove(); - helper.destroy(); - - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - -} diff --git a/src/servlet/MyListener.java b/src/servlet/MyListener.java deleted file mode 100644 index ebe10f8..0000000 --- a/src/servlet/MyListener.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; -import java.util.Iterator; -import java.util.Map; - -@WebListener -public class MyListener implements ServletContextListener { - - public void contextDestroyed(ServletContextEvent sce) { - System.out.println("destory context...."); - /** - * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 - */ - - String chatKey; - ServletContext servletContext = sce.getServletContext(); - Object obj = servletContext.getAttribute("chatCache"); - ChatCache cache = null; - SqlHelper helper = null; - - if(obj != null){ - Map chatCacheMap = (Map)obj; - - Iterator cacheIter = chatCacheMap.keySet().iterator(); - - - while(cacheIter.hasNext()){ - chatKey = cacheIter.next(); - cache = chatCacheMap.get(chatKey); - try { - helper = new SqlHelper(); - System.out.println(String.format("saving %s", chatKey)); - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if(cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { - ChatCacheController.saveChatCache(cache, helper); - } - }catch (Exception e){ - System.out.println(String.format("保存%s时出现异常", chatKey)); - } - cacheIter.remove(); - } - } - } - -} diff --git a/src/servlet/ReloadConfig.java b/src/servlet/ReloadConfig.java deleted file mode 100644 index 1e2912f..0000000 --- a/src/servlet/ReloadConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package servlet; - -import entity.UserInfo; -import processing.MyFunc; -import processing.ProcessQuestion; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - -@WebServlet(name = "ReloadConfig") -public class ReloadConfig extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String userName = request.getParameter("userName"); - boolean flag = true; - UserInfo userinfo = new UserInfo(userName); - File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt"); - ServletContext context = this.getServletContext(); - if(!configFile.exists()) { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("文件不存在: "+userName); - - }else{ - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - - try { - userinfo = ProcessQuestion.buildUserInfo(br, userinfo); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ - flag = false; - System.out.println(userinfo.userName + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - - if(!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + userName +".txt\\\n"); - - } - else{ - response.setCharacterEncoding("utf-8"); - response.setContentType( "text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新成功+ “ "); - out.flush(); - out.close(); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - - - } - - } - - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java deleted file mode 100644 index 7d6c8cb..0000000 --- a/src/servlet/ReloadConfigServlet.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - - -/** - * 发请求从本地文件夹重新加载某用户的配置文件 - */ -@WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"}) -public class ReloadConfigServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - String botAccount = request.getParameter("botAccount"); - boolean flag = true; - UserInfo userinfo = new UserInfo(botAccount); - File configFile = new File(System.getProperty("user.dir") + "/config/" + botAccount + ".txt"); - System.out.println(configFile.getAbsolutePath()); - ServletContext context = this.getServletContext(); - if (!configFile.exists()) { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("文件不存在: " + botAccount); - - } else { - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - - try { - userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - flag = false; - System.out.println(userinfo.botAccount + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - - if (!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - response.setStatus(111); - PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + botAccount + ".txt\\\n"); - - } else { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("重新加载成功"); - out.flush(); - out.close(); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - - - } - - } - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java deleted file mode 100644 index da89789..0000000 --- a/src/servlet/UpdateServlet.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.SimpleUtil; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -/** - * 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。 - */ -@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"}) -public class UpdateServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - //在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。 - request.setCharacterEncoding("UTF-8"); - String line, extraElements[]; - ArrayList errorList = new ArrayList(); - ServletContext context = this.getServletContext(); - String botAccount = request.getParameter("botAccount"); - - UserInfo userinfo = new UserInfo(botAccount); - userinfo.conditionTable = new HashMap>(); - - List actionList = null; - HashSet keyWordSet = null; - - BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string"))); - boolean flag = true; - String errorStr = ""; - - - while ((line = br.readLine()) != null) { - System.out.println(line); - - if (line.trim().equals("")) - continue; - line = line.replace("\n", ""); - //在用户信息中添加额外信息,如设为active的action - if (line.indexOf("-extraInfo-") != -1) { - extraElements = line.split("\\|"); - userinfo.extraInfo.put(extraElements[1], extraElements[2]); - userinfo.configStr += line + "\n"; - continue; - } - //line = SimpleUtil.convert2Utf8(line.trim()); - userinfo.configStr += line + "\n"; - Action action = new Action(); - try { - action = UserInfoController.buildCondition(action, line); - actionList = userinfo.conditionTable.get(action.getIndexName()); - if (actionList == null) - actionList = new ArrayList(); - actionList.add(action); - userinfo.conditionTable.put(action.getIndexName(), actionList); - /* - for(String name:action.indexName){ - userinfo.conditionTable.put() - } - */ - } catch (Exception e) { - System.out.println("配置文件有误!"); - flag = false; - errorList.add(line); - - - } - - } - br.close(); - if (!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - String returnStr = SimpleUtil.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); - out.println("更新失败,以下行有误: "); - for (String error : errorList) - out.println("---" + error); - out.flush(); - out.close(); - System.out.println("error"); - - } else { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新成功+ “ "); - out.flush(); - out.close(); - System.out.println("success"); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - context.setAttribute(botAccount, userinfo); - String path = System.getProperty("user.dir") + "/config/" + userinfo.botAccount + ".txt"; - File file = new File(path); - File dir = new File(System.getProperty("user.dir") + "/config"); - - if (!dir.exists()) - dir.mkdir(); - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fw = new FileWriter(file); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(userinfo.configStr); - bw.close(); - fw.close(); - - - } - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java deleted file mode 100644 index 372c0b2..0000000 --- a/src/servlet/UpdateSingleConfigServlet.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; - -@WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"}) -public class UpdateSingleConfigServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - ServletContext context = this.getServletContext(); - String userName = request.getParameter("userName"); - String processType = request.getParameter("type"); - String configId = request.getParameter("configId"); - String data = request.getParameter("configData"); - System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); - - if (context.getAttribute(userName) != null) { - switch (processType) { - case "insert_config": - UserInfoController.insertConfig(userName, configId, data, context); - break; - case "update_config": - UserInfoController.deleteConfig(userName, configId, data, context); - UserInfoController.insertConfig(userName, configId, data, context); - break; - case "delete_config": - UserInfoController.deleteConfig(userName, configId, data, context); - break; - case "insert_variable": - UserInfoController.updateVariable(userName, configId, data, context); - break; - case "delete_variable": - UserInfoController.deleteVariable(userName, configId, data, context); - break; - case "update_variable": - UserInfoController.updateVariable(userName, configId, data, context); - break; - case "extra_info": - UserInfoController.updateExtraInfo(userName, data, context); - break; - - case "batch_update": - batchUpdate(userName, data, context); - - } - writeConfig(userName, context); - response.setStatus(200); - - } else if (processType.equals("batch_update")) { - batchUpdate(userName, data, context); - writeConfig(userName, context); - response.setStatus(200); - } else { - response.setStatus(111); - } - - - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.write("success"); - out.flush(); - out.close(); - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } - - - public String writeConfig(String userName, ServletContext context) throws IOException { - String returnMessage = ""; - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - - returnMessage = UserInfoController.writeConfigText(userName, userinfo); - - return returnMessage; - } - - - public void batchUpdate(String userName, String data, ServletContext context) throws IOException { - BufferedReader br = new BufferedReader(new StringReader(data)); - UserInfo userinfo = new UserInfo(userName); - userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - System.out.println("batchupdate"); - } -}