Commit 21a106ae by hxw

上传完整文件夹

parent dff6f518
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
<facet type="web" name="Web">
<configuration>
<webroots />
<sourceRoots>
<root url="file://$MODULE_DIR$/src/main/java" />
<root url="file://$MODULE_DIR$/src/main/resources" />
</sourceRoots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.11.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.11.1" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.25" level="project" />
<orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.3.2" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.yaml:snakeyaml:1.23" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.9.7" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.9.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.9.7" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.7" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.7" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.7" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.12" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:9.0.12" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.12" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:6.0.13.Final" level="project" />
<orderEntry type="library" name="Maven: javax.validation:validation-api:2.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.3.2.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.4.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.1.2.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.1.0.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.1.0.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.1.0.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.4.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:5.0.4" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.11.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:2.23.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.9.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.9.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-library:1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.1.2.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.1.2.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.6.2" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.51" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.10" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.11" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.5" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat:tomcat-dbcp:9.0.12" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat:tomcat-juli:9.0.12" level="project" />
<orderEntry type="library" name="Maven: c3p0:c3p0:0.9.1.2" level="project" />
<orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.0.7" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-thymeleaf:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.thymeleaf:thymeleaf-spring5:3.0.11.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.thymeleaf:thymeleaf:3.0.11.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.attoparser:attoparser:2.0.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.unbescape:unbescape:1.1.6.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.1.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-actuator:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator-autoconfigure:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator:2.1.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-core:1.1.0" level="project" />
<orderEntry type="library" name="Maven: org.hdrhistogram:HdrHistogram:2.1.9" level="project" />
<orderEntry type="library" name="Maven: org.latencyutils:LatencyUtils:2.0.3" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:18.0" level="project" />
<orderEntry type="library" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
</component>
</module>
\ No newline at end of file
test_var=1111
# qa问答地址
qa_url=http://192.168.1.78:59000/game qa_url=http://192.168.1.78:59000/game
# 中控url
cc_url=http://localhost:8070/api/update/data 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=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧 unknown_text=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧
location_hint=请到%s location_hint=请到%s
game_start_hint=请说开始剧情或者继续剧情 game_start_hint=请说开始剧情或者继续剧情
game_welcome_text=欢迎来到%s,请说继续剧情或者重新开始
game_module_error=游戏模块出错 game_module_error=游戏模块出错
program_error=程序出现异常
intent_not_understand=我不理解
# -------------------------------游戏生成--------------------------- # -------------------------------游戏生成---------------------------
token_time_out=token超时了
game_bot_category=游戏
delete_old_config_term_error=删除旧数据config失败 delete_old_config_term_error=删除旧数据config失败
delete_old_variable_error=删除旧变量失败 delete_old_variable_error=删除旧变量失败
delete_old_category_error=删除旧类别失败 delete_old_category_error=删除旧类别失败
# ----------------------------------------------------------------
name_mission_error=没找到bot名?
log_path=/var/www/html/logs/
# ----------------------------------------------------------------
unknown_text_description=对于无法识别的问题做出的回答 unknown_text_description=对于无法识别的问题做出的回答
game_step_description=QA问答游戏进度 game_step_description=QA问答游戏进度
...@@ -41,6 +70,7 @@ plot_status=剧情%s状态 ...@@ -41,6 +70,7 @@ plot_status=剧情%s状态
# --------------------------------------------------- # ---------------------------------------------------
plot_generation_error=剧情接口处理出现异常 plot_generation_error=剧情接口处理出现异常
action_text_generate_error=action生成失败
默认condition 默认condition
default_condition=yaobuyao default_condition=yaobuyao
...@@ -74,26 +104,64 @@ task_description_slot=[任务描述]" ...@@ -74,26 +104,64 @@ task_description_slot=[任务描述]"
find_item_owner=[物品名]在[人名]身上 find_item_owner=[物品名]在[人名]身上
#---------------------------------------------- #----------------------------------------------
# ---------------------文本解析--------------------- #--------------------condition文本默认配置--------------------------
text_parse_error=文本解析出错
automatch_threshold=0.5
game_condition_category=97
service_url=http://192.168.1.178:8081/bot/dialog
options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat
automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train
idlelimit=180000 idle_limit=180000
condition_generate_url=http://192.168.1.178:1111/conditionProcess condition_fellow=pivot_httppost
condition_backend_url=http://192.168.1.82:6636/api automatch_threshold=0.5
style=interrupt,multimatchvalues,bothvalue default_style=style=interrupt,bothvalue,multimatchvalues
fellow=pivot_httppost
post_style1=style=httppost,bothvalue,multimatchvalues post_style1=style=httppost,bothvalue,multimatchvalues
post_style2=style=httppost,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=更新关键词单元失败 update_keyword_error=更新关键词单元失败
delete_user_data_error=删除用户数据失败 delete_user_data_error=删除用户数据失败
game_condition_category_id=123 platform_sql_init_error=新平台获取sql连接失败
platform_sql_init_error=新平台获取sql连接失败
\ No newline at end of file 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=数据库连接获取失败
# ------------------------------------------------------------------------------
# 第一块,意图|相关的语义关系名
意图语义关系名
# 第二块, 意图|语义关系名|关键词
# ------------------------------------------------------------------------------
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|默认
#!/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 "$@"
@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%
...@@ -98,6 +98,12 @@ ...@@ -98,6 +98,12 @@
<version>1.5.0</version> <version>1.5.0</version>
</dependency> </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies> </dependencies>
......
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
package com.qiwu.chatbotbackend.db;
public class DBUtils {
}
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(){}
}
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<String, String> 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<String, String> getInfoPoint() {
return infoPoint;
}
public void setInfoPoint(Map<String, String> infoPoint) {
this.infoPoint = infoPoint;
}
public GameEnv getGameEnv() {
return gameEnv;
}
public void setGameEnv(GameEnv gameEnv) {
this.gameEnv = gameEnv;
}
public ChatCache3(String chatKey, GameEnv gameEnv, Map<String, String> 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<String, String>();
Iterator<String> 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()));
}
}
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<String> keywordSet = new HashSet<String>();
public HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, String> updateKnowledge = new LinkedHashMap<String, String>();
public String[] answer = {"",};
public String nextStep = "";
public HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = "";
public int id = 0;
public String configName = "";
public String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>();
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() {
}
}
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<Integer> iterNum=new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
ThreadLocal<Map<String, Integer>> conditionCount = new ThreadLocal<Map<String, Integer>>(){
protected Map<String, Integer> initialValue(){
return new HashMap<String, Integer>();
};
};
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<String, String> statusMap = new HashMap<String, String>() {
{
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<String, String> 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<Premise> curPremise, List<Premise> hisPremise, Map<String, String> 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<Premise> premises, String extraPremise) {
StringBuffer sb = new StringBuffer();
String premiseStr = "", conditionName;
Map<String ,Integer> nameCount = new HashMap<String , Integer>();
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<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr;
Iterator<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<ConfigTerm> 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;
}
}
package entity;
public class ConfigurationItem {
}
package entity;
public class Goods {
}
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<String, String> statusMap = new HashMap<String, String>() {
{
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<String, String> 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<String> curPremise, List<String> hisPremise, Map<String, String> 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<String> 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<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr;
Iterator<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<JConfig> 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;
}
}
package entity;
public class Npc {
}
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;
}
}
package entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class World {
public List<String> queryAroundAllBySite(String site){ return new ArrayList<>();}; // 返回所有模块下的实例名称列表
public List<String> queryAroundNpcBySite(String site){ return new ArrayList<>();}; // 返回npcname 字符串列表
public List<String> queryAroundGoodsBySite(String site){ return new ArrayList<>();}; // 返回goodsname 字符串列表
public List<String> queryCanGoBySite(String site){ return new ArrayList<>();}; //地点名称的列表
public List<String> 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<String> 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
}
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<String ,String> curInfoPoint = null;
public Map<String ,String> historyInfoPoint = null;
public WorldController worldController = null;
public GameUtil(GameEnv gameEnv, WorldController worldController, Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint) {
this.gameEnv = gameEnv;
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.worldController = worldController;
}
public void gamePreprocessing(LogWriter logWriter){
}
public void gamePostprocessing(LogWriter logWriter){
}
}
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<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>();
Map<String, String> question2keyword = new HashMap<String, String>();
Map<String, ArrayList<String>> name2nickname = new HashMap<String, ArrayList<String>>();
JSONArray locations = null;
Map<String, String> script = null; //话术模板
public MapConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> 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<Integer> 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<String, String> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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<String, StringBuffer> 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
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<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
private HashMap<String, JSONObject> plotIndex = new HashMap<String, JSONObject>();
private HashMap<String, String> plotTextIndex = new HashMap<String, String>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
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<String, StringBuffer> keywordMap, HashSet<String> 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<String, StringBuffer> 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<String> 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<JSONObject> queue = new LinkedList<JSONObject>();
Map<String, String> autoJumpUpdateKnowledge = new HashMap<String, String >();
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<String, String> 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<Integer> 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<String, StringBuffer> 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<String> 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();
}
}
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<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
private HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public static String TASK_LINE = "任务线_%s进度";
public static String TASK_CONDITION = "任务线%s最后一个condition";
public static String TASK_REPLY = "任务线%s最后的回答";
public HashMap<String, JSONObject> getId2j() {
return id2j;
}
public PlotConstructor3(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> 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<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, branchSize;
List<String> 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<JSONObject> queue = new LinkedList<JSONObject>();
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<String, String> 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<Integer> 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);
}
}
}
package gameDesign;
public class Scene {
}
package gameDesign;
public class SceneConstructor {
}
Manifest-Version: 1.0
Main-Class: com.qiwu.chatbotbackend.ChatbotBackendApplication
...@@ -3,9 +3,11 @@ package com.qiwu.chatbotbackend; ...@@ -3,9 +3,11 @@ package com.qiwu.chatbotbackend;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ServletComponentScan @ServletComponentScan
@ComponentScan
public class ChatbotBackendApplication { public class ChatbotBackendApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -5,19 +5,38 @@ import org.springframework.stereotype.Component; ...@@ -5,19 +5,38 @@ import org.springframework.stereotype.Component;
@Component @Component
public class Config { public class Config {
public static String TEXT_PARSE_ERROR = null; //url
public static String CONDITION_URL = null; public static String CONDITION_URL = null;
public static String TEST_VAR = null;
public static String QA_URL = null; public static String QA_URL = null;
public static String CC_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 GAME_MODULE_ERROR = null;
public static String DELETE_OLD_CONFIG_TERM_ERROR = null; public static String DELETE_OLD_CONFIG_TERM_ERROR = null;
public static String DELETE_OLD_VARIABLE_ERROR = null; public static String DELETE_OLD_VARIABLE_ERROR = null;
public static String DELETE_OLD_CATEGORY_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 UNKNOWN_TEXT_DESCRIPTION = null;
public static String GAME_STEP_DESCRIPTION = null; public static String GAME_STEP_DESCRIPTION = null;
public static String START_PLOT_NOT_EXIST = null; public static String START_PLOT_NOT_EXIST = null;
...@@ -50,8 +69,11 @@ public class Config { ...@@ -50,8 +69,11 @@ public class Config {
public static int SIZE = 12; 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 TOKEN_TIME_OUT = null;
public static String ENCODE_ERROR = null; public static String ENCODE_ERROR = null;
...@@ -84,14 +106,15 @@ public class Config { ...@@ -84,14 +106,15 @@ public class Config {
//生成action //生成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 GAME_CONDITION_CATEGORY = null;
public static String AUTOMATCH_THRESHOLD = null; public static String AUTOMATCH_THRESHOLD = null;
public static String IDLE_LIMIT = null; public static String IDLE_LIMIT = null;
public static String CONDITION_BACKEND_URL = null; public static String CONDITION_BACKEND_URL = null;
public static String CONDITION_GENERATE_URL= null;
public static String OPTIONS = null; public static String OPTIONS = null;
public static String STYLE = null; public static String DEFAULT_STYLE = null;
public static String AUTOMATCH_URL = null;
public static String SERVICE_URL = null; public static String SERVICE_URL = null;
public static String FELLOW = null; public static String FELLOW = null;
...@@ -108,4 +131,42 @@ public class Config { ...@@ -108,4 +131,42 @@ public class Config {
public static String DELETE_USER_DATA_ERROR = null; 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;
} }
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 + "]";
}
}
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<Attr> attrs;
private List<GoodsInstance> goodsInstances;
private List<NpcInstance> npcInstances;
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> goodsInstances) {
this.goodsInstances = goodsInstances;
}
public List<NpcInstance> getNpcInstances() {
return npcInstances;
}
public void setNpcInstances(List<NpcInstance> 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<Attr> getAttrs() {
return attrs;
}
public void setAttrs(List<Attr> 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 + "]";
}
}
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<Integer, String> queryConditionPatternText(int botId, List<String> 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<Integer, String> patternTextMap = new HashMap<Integer, String>();
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<Integer, EngineUnit> queryUnitsByIdList(List<Integer> 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<Integer, EngineUnit> id2unit= new HashMap<Integer, EngineUnit>();
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;
}
}
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<Integer> queryConditionIdByTypetreeId(List typetreeIdList){
String sql = "select conditionId from typetreeNcondition where typetreeId in (?)";
String keywordText = "";
List<Integer> idList = new ArrayList<Integer>();
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;
}
}
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;
}
}
package com.qiwu.chatbotbackend.actiongenerate.entity;
import java.util.List;
public class Backup {
int botId;
String botName;
String botCategoryName;
List<Condition> conditionList =null;
List<ConfigTerm> configTermList = null;
List<Category> categoryList = null;
List<Variable> variableList = null;
BotInfo botInfo = null;
public Backup(int botId, String botName, String botCategoryName,
List<Condition> conditionList, List<ConfigTerm> configTermList, List<Category> categoryList, List<Variable> 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<Condition> getConditionList() {
return conditionList;
}
public void setConditionList(List<Condition> conditionList) {
this.conditionList = conditionList;
}
public List<ConfigTerm> getConfigTermList() {
return configTermList;
}
public void setConfigTermList(List<ConfigTerm> configTermList) {
this.configTermList = configTermList;
}
public List<Category> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<Category> categoryList) {
this.categoryList = categoryList;
}
public List<Variable> getVariablesList() {
return variableList;
}
public void setVariablesList(List<Variable> variableList) {
this.variableList = variableList;
}
public BotInfo getBotInfo() {
return botInfo;
}
public void setBotInfo(BotInfo botInfo) {
this.botInfo = botInfo;
}
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
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;
}
}
package com.qiwu.chatbotbackend.actiongenerate.entity;
import com.alibaba.fastjson.JSONObject;
public class Solution {
int status = 0;
JSONObject payload = null;
}
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;
}
}
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 {
}
}
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<Condition> conditionList = new ArrayList<Condition>();
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
List<Integer> childCategoryIds = new ArrayList<Integer>();
List<Category> childCategories = new ArrayList<Category>();
List<Variable> variablesList = new ArrayList<Variable>();
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();
}
}
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 {
}
}
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
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 = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
writer.write(data);
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.actiongenerate.servlet;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
...@@ -6,14 +6,22 @@ import javax.servlet.http.HttpServlet; ...@@ -6,14 +6,22 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ReloadChatCacheServlet", urlPatterns = {"/reloadChatCache"}) @WebServlet(name = "GetNextstepExceptionServlet", urlPatterns = {"/getNextStepException"})
public class ReloadChatCacheServlet extends HttpServlet { public class GetNextstepExceptionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
} }
protected void doGet(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();
} }
} }
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 {
}
}
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<Integer, Integer> idReplaceMap = new HashMap<Integer, Integer>();
ConfigTermText configTermText = null;
Set<String> variableNameSet1, variableNameSet2, conditionNameSet1, conditionNameSet2;
List<String> actionTextList = new ArrayList<String>();
//List<Condition> originConditionList = null;
//List<>
List<Category> categoryList = data.getJSONArray("categoryList").toJavaList(Category.class);
List<Condition> originConditionList = null, conditionList = data.getJSONArray("conditionList").toJavaList(Condition.class);
List<ConfigTerm> configTermList = data.getJSONArray("configTermList").toJavaList(ConfigTerm.class);
List<Variable> 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);
}
}
}
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 {
}
}
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);
}
}
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<Condition> conditionList = new ArrayList<Condition>();
Boolean insertFlag = false;
JSONArray conditions = parameters.getJSONArray("conditionData");
Integer botId = parameters.getInteger("botId");
List<String> actionTextList = helper.queryActionTextList(botId);
Set<String> conditionNameSet = new HashSet<String>();
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<String> actionTextList){
Integer botId = parameters.getInteger("botId");
BotInfo botInfo = helper.queryBotInfo(botId);
Boolean bothValue = true;
String styleText = "", serviceURL = "", elements[], conditionName;
Set<String> conditionNameSet = new HashSet<String>();
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<Condition> 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<String> 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<Condition> conditionList = helper.queryConditionAll(botId);
List<String> conditionTextList = new ArrayList<String>();
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<Condition> conditionList = new ArrayList<Condition>();
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<Condition> conditionList = helper.queryConditionAll(botId);
List<String> conditionRelationList = new ArrayList<String>();
List<JSONObject> conditionJsonList = new ArrayList<JSONObject>();
intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{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<Integer, String> 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<String, String> extraKeyword, Map<String, StringBuffer> 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<String[]> returnList = new ArrayList<String[]>();
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<String, HashSet<String>> conditionExtraKeywords){
Boolean flag = true;
String elem[], postfix, conditionName, keywordPosition, actionText, relationName, finalText, activeFlag;
PlatformUtils platformUtils = null;
JSONObject patternConditionJson = null, conditionJson = null;
List<Integer> idList = new ArrayList<Integer>();
List<String> actionTextList = new ArrayList<String>();
List<Condition> conditionList = new ArrayList<Condition>();
JSONArray conditionData = new JSONArray(), conditionPostPair = new JSONArray();
Map<Integer, EngineUnit> id2unit = null;
Map<String, StringBuffer> macroMap = null, macroAppendMap = new HashMap<String, StringBuffer>();
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<String, String>() {{
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<String, HashSet<String>> conditionExtraKeywords, Map<String, StringBuffer> 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<String> getConditionNameSet(List<Condition> conditionList){
String elements[];
String conditionName;
Set<String> conditionNameSet = new HashSet<String>();
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<Condition> conditionList = helper.queryConditionAll(botId);
Set<String> 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<String, String>(){{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<String, String>(){{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);
}
}
}
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<Integer> 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<Integer> findChildCategoryIds(int botId, int rootId){
List<Category> categories = helper.queryCategoryAll(botId);
List<Integer> idList = new ArrayList<Integer>(){
{
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<Integer> findChildCategoryIds(int botId, int rootId, List<Category> childCategories){
List<Category> categories = helper.queryCategoryAll(botId);
List<Integer> idList = new ArrayList<Integer>(){
{
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<Integer> defaultCategoryPath = new ArrayList<Integer>();
List<Category> categories = helper.queryCategoryAll(botId);
Map<Integer, Category> categoryMap = new HashMap<Integer, Category>();
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");
List<Integer>idList = 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);
}
}
}
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<JSONObject> configList = new ArrayList<JSONObject>();
List<Integer> idList = new ArrayList<Integer>();
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<Premise> curPremiseList = new ArrayList<Premise>();
List<Premise> hisPremiseList = new ArrayList<Premise>();
Map<String, String> updateKnowledge = new HashMap<String, String>();
Map<String, String> punctReplaceMap = new HashMap<String, String>(){
{
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<ConfigTerm> 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<ConfigTerm> 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<String, String> replaceMap){
for(String key:replaceMap.keySet()){
text = text.replace(key, replaceMap.get(key));
}
return text;
}
public void generateSingleConfigText(JSONObject configJson){
}
}
package com.qiwu.chatbotbackend.actiongenerate.utils;
public class MacroUtils {
}
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<Variable> 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<String> getVariableNameSet(List<Variable> variableList){
Set<String> variableNameSet = new HashSet<String>();
for(Variable variable:variableList){
variableNameSet.add(variable.getName());
}
return variableNameSet;
}
}
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<byte[]> 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<byte[]> 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);
}
}
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: ";
}
}
...@@ -15,7 +15,8 @@ public class C3p0Utils { ...@@ -15,7 +15,8 @@ public class C3p0Utils {
//通过标识名来创建相应连接池 //通过标识名来创建相应连接池
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); 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 { public static Connection getConnection() throws SQLException {
...@@ -39,6 +40,17 @@ public class C3p0Utils { ...@@ -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 { public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
if (rs != null) { if (rs != null) {
......
package com.qiwu.chatbotbackend.db; package com.qiwu.chatbotbackend.db;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.actiongenerate.entity.BotInfo; import com.google.common.base.Joiner;
import com.qiwu.actiongenerate.entity.Condition; import com.qiwu.chatbotbackend.actiongenerate.entity.*;
import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor;
...@@ -37,6 +37,524 @@ public class SqlHelper { ...@@ -37,6 +37,524 @@ public class SqlHelper {
} }
} }
//---------------------------------------变量的操作---------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
public List<Variable> queryVariableAll(int botId){
String sql = "select * from chatbot_variable where botId= ?";
List<Variable> variables = new ArrayList<Variable>();
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<Integer> 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<Category> queryCategoryAll(int botId){
String sql = "select * from config_categories where botId= ?";
List<Category> categories = new ArrayList<Category>();
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<Integer> 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<ConfigTerm> queryConfigByCategoryId(int botId, int configId){
String sql = "select * from chatbot_config where botId= ? and categoryId = ?";
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
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<ConfigTerm> querySleepingConfig(int botId){
String sql = "select * from chatbot_config where configName != '' and botId = ?";
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
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<ConfigTerm> queryConfigByCategoryIdList(int botId, List<Integer> categoryIdList){
String sql = "select * from chatbot_config where botId= ? and categoryId in (" + Joiner.on(",").join(categoryIdList) + ")";
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
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<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
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操作--------------------------------------------------------------- //----------------------------------------condition操作---------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------
...@@ -53,15 +571,23 @@ public class SqlHelper { ...@@ -53,15 +571,23 @@ public class SqlHelper {
PreparedStatement ps1 = conn.prepareStatement(sql1); PreparedStatement ps1 = conn.prepareStatement(sql1);
ps1.setInt(1, botId); ps1.setInt(1, botId);
b1 = ps1.execute(); b1 = ps1.execute();
ps1.close();
PreparedStatement ps2 = conn.prepareStatement(sql2); PreparedStatement ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, botId); ps2.setInt(1, botId);
b2 = ps1.execute(); b2 = ps2.execute();
ps2.close();
PreparedStatement ps3 = conn.prepareStatement(sql3); PreparedStatement ps3 = conn.prepareStatement(sql3);
ps3.setInt(1, botId); ps3.setInt(1, botId);
b3 = ps1.execute(); b3 = ps3.execute();
ps3.close();
PreparedStatement ps4 = conn.prepareStatement(sql4); PreparedStatement ps4 = conn.prepareStatement(sql4);
ps4.setInt(1, botId); ps4.setInt(1, botId);
b4 = ps1.execute(); b4 = ps4.execute();
ps4.close();
} catch (SQLException e) { } catch (SQLException e) {
System.out.println(DELETE_USER_DATA_ERROR); System.out.println(DELETE_USER_DATA_ERROR);
e.printStackTrace(); e.printStackTrace();
...@@ -71,7 +597,7 @@ public class SqlHelper { ...@@ -71,7 +597,7 @@ public class SqlHelper {
} }
public Boolean batchInsertCondition(List<String[]> insertList){ public Boolean batchInsertCondition(List<Condition> conditionList){
int count[]; int count[];
boolean insertFlag = true; boolean insertFlag = true;
String sql = "", varName, varValue, description; String sql = "", varName, varValue, description;
...@@ -84,12 +610,12 @@ public class SqlHelper { ...@@ -84,12 +610,12 @@ public class SqlHelper {
sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)"; sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for(String[] elements:insertList){ for(Condition condition:conditionList){
ps.setString(1, elements[0]); ps.setInt(1, condition.getBotId());
ps.setString(2, elements[1]); ps.setString(2, condition.getConditionJsonText());
ps.setString(3, elements[2]); ps.setString(3, condition.getCategory());
ps.setString(4, elements[3]); ps.setString(4, condition.getActionText());
ps.setString(5, elements[4]); ps.setString(5, condition.getActive());
ps.addBatch(); ps.addBatch();
} }
...@@ -131,6 +657,9 @@ public class SqlHelper { ...@@ -131,6 +657,9 @@ public class SqlHelper {
actionTextList.add(rs.getString("actionText")); actionTextList.add(rs.getString("actionText"));
} }
ps.close();
rs.close();
}catch(Exception e){ }catch(Exception e){
...@@ -142,18 +671,22 @@ public class SqlHelper { ...@@ -142,18 +671,22 @@ public class SqlHelper {
public Condition queryActiveCondition(int botId){ public Condition queryActiveCondition(int botId){
Condition condition = null; 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 = ""; String pre_name = "";
List<String> actionTextList = new ArrayList<String>(); List<String> actionTextList = new ArrayList<String>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()){ if(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"), 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){ }catch(Exception e){
...@@ -162,10 +695,29 @@ public class SqlHelper { ...@@ -162,10 +695,29 @@ public class SqlHelper {
return condition; 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<String> queryConditionCategoriesById(int botId){ public List<String> queryConditionCategoriesById(int botId){
String sql = "select categoryStr from chatbot_condition where botId= ?"; String sql = "select categoryInfo from chatbot_condition where botId= ?";
String pre_name = ""; String pre_name = "";
List<String> categoryList = new ArrayList<String>(); List<String> categoryList = new ArrayList<String>();
try{ try{
...@@ -173,9 +725,12 @@ public class SqlHelper { ...@@ -173,9 +725,12 @@ public class SqlHelper {
ps.setInt(1,botId); ps.setInt(1,botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
while(rs.next()){ while(rs.next()){
categoryList.add(rs.getString("categoryStr")); categoryList.add(rs.getString("categoryInfo"));
} }
ps.close();
rs.close();
}catch(Exception e){ }catch(Exception e){
...@@ -195,10 +750,13 @@ public class SqlHelper { ...@@ -195,10 +750,13 @@ public class SqlHelper {
ps.setInt(1,botId); ps.setInt(1,botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()){ 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")); rs.getString("bothValue"), rs.getString("queryTextTransfer"));
} }
ps.close();
rs.close();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
...@@ -206,6 +764,36 @@ public class SqlHelper { ...@@ -206,6 +764,36 @@ public class SqlHelper {
return botInfo; 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){ public Boolean updateConditionById(Condition condition){
boolean b; boolean b;
...@@ -219,7 +807,7 @@ public class SqlHelper { ...@@ -219,7 +807,7 @@ public class SqlHelper {
ps1.setInt(5, condition.getBotId()); ps1.setInt(5, condition.getBotId());
ps1.setInt(6, condition.getConditionId()); ps1.setInt(6, condition.getConditionId());
b = ps1.execute(); b = ps1.executeUpdate() == 1;
ps1.close(); ps1.close();
return b; return b;
...@@ -283,35 +871,6 @@ public class SqlHelper { ...@@ -283,35 +871,6 @@ public class SqlHelper {
} }
public List<Condition> queryConditionByCategory(String category){
boolean b;
List<Condition> conditionList = new ArrayList<Condition>();
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<Condition> queryConditionByCategory(int botId, String category){ public List<Condition> queryConditionByCategory(int botId, String category){
...@@ -320,7 +879,7 @@ public class SqlHelper { ...@@ -320,7 +879,7 @@ public class SqlHelper {
Condition condition = null; Condition condition = null;
try { 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); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId); ps.setInt(1, botId);
ps.setString(2, category); ps.setString(2, category);
...@@ -328,7 +887,7 @@ public class SqlHelper { ...@@ -328,7 +887,7 @@ public class SqlHelper {
while(rs.next()){ while(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"), rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active")); rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder"));
conditionList.add(condition); conditionList.add(condition);
} }
ps.close(); ps.close();
...@@ -350,7 +909,7 @@ public class SqlHelper { ...@@ -350,7 +909,7 @@ public class SqlHelper {
Condition condition = null; Condition condition = null;
try { 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); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId); ps.setInt(1, botId);
ps.setInt(2, conditionId); ps.setInt(2, conditionId);
...@@ -358,7 +917,7 @@ public class SqlHelper { ...@@ -358,7 +917,7 @@ public class SqlHelper {
if(rs.next()){ if(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"), rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active")); rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder"));
} }
ps.close(); ps.close();
rs.close(); rs.close();
...@@ -367,7 +926,7 @@ public class SqlHelper { ...@@ -367,7 +926,7 @@ public class SqlHelper {
return condition; return condition;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); System.out.println(CONFIG_DELETE_ERROR);
e.printStackTrace(); e.printStackTrace();
return condition; return condition;
} }
...@@ -380,14 +939,14 @@ public class SqlHelper { ...@@ -380,14 +939,14 @@ public class SqlHelper {
Condition condition = null; Condition condition = null;
try { 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); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId); ps.setInt(1, botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
while(rs.next()){ while(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"), rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active")); rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder"));
conditionList.add(condition); conditionList.add(condition);
} }
ps.close(); ps.close();
...@@ -397,7 +956,7 @@ public class SqlHelper { ...@@ -397,7 +956,7 @@ public class SqlHelper {
return conditionList; return conditionList;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); System.out.println(CONFIG_DELETE_ERROR);
e.printStackTrace(); e.printStackTrace();
return conditionList; return conditionList;
} }
...@@ -405,7 +964,8 @@ public class SqlHelper { ...@@ -405,7 +964,8 @@ public class SqlHelper {
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------
...@@ -472,7 +1032,7 @@ public class SqlHelper { ...@@ -472,7 +1032,7 @@ public class SqlHelper {
try { try {
PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?");
ps1.setString(1, String.valueOf(botId)); ps1.setString(1, String.valueOf(botId));
b = ps1.execute(); b = ps1.executeUpdate() == 1;
ps1.close(); ps1.close();
return b; return b;
...@@ -491,7 +1051,7 @@ public class SqlHelper { ...@@ -491,7 +1051,7 @@ public class SqlHelper {
try { try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
b = ps.execute(); b = ps.executeUpdate() == 1;
ps.close(); ps.close();
...@@ -512,7 +1072,7 @@ public class SqlHelper { ...@@ -512,7 +1072,7 @@ public class SqlHelper {
try { try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
b = ps.execute(); b = ps.executeUpdate() == 1;
ps.close(); ps.close();
...@@ -582,6 +1142,47 @@ public class SqlHelper { ...@@ -582,6 +1142,47 @@ public class SqlHelper {
} }
public boolean batchInsertVariable(int botId, List<Variable> 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<JSONObject> jsonList, List<Integer> idList, int categoryId) { public boolean batchInsertConfigByBotId(int botId, List<JSONObject> jsonList, List<Integer> idList, int categoryId) {
int count[]; int count[];
boolean insertFlag = true; boolean insertFlag = true;
...@@ -635,6 +1236,52 @@ public class SqlHelper { ...@@ -635,6 +1236,52 @@ public class SqlHelper {
return insertFlag; return insertFlag;
} }
public boolean batchInsertConfig(int botId, List<ConfigTerm> 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<String, Integer> categoryMap) { public boolean batchInsertCategoryByBotId(int botId, Map<String, Integer> categoryMap) {
...@@ -756,7 +1403,7 @@ public class SqlHelper { ...@@ -756,7 +1403,7 @@ public class SqlHelper {
ps.setString(2, variableName); ps.setString(2, variableName);
ps.setString(3, description); ps.setString(3, description);
ps.setString(4, defaultValue); ps.setString(4, defaultValue);
b = ps.execute(); b = ps.executeUpdate() == 1;
ps.close(); ps.close();
conn.commit(); conn.commit();
...@@ -924,4 +1571,5 @@ public class SqlHelper { ...@@ -924,4 +1571,5 @@ public class SqlHelper {
} }
...@@ -16,18 +16,7 @@ public class ConfigTermText implements Cloneable{ ...@@ -16,18 +16,7 @@ public class ConfigTermText implements Cloneable{
} }
}; };
private int id = 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 curPremise = "";
private String hisPremise = ""; private String hisPremise = "";
...@@ -40,10 +29,14 @@ public class ConfigTermText implements Cloneable{ ...@@ -40,10 +29,14 @@ public class ConfigTermText implements Cloneable{
private String auxiliaryPriority = "1"; private String auxiliaryPriority = "1";
private String status = "waiting"; private String status = "waiting";
static HashMap<String, Integer> StatusMap = new HashMap<String, Integer>(){
{
put("waiting", 0);
put("sleeping", 1);
}
};
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
public String getFeature() { public String getFeature() {
return feature; return feature;
} }
...@@ -73,8 +66,6 @@ public class ConfigTermText implements Cloneable{ ...@@ -73,8 +66,6 @@ public class ConfigTermText implements Cloneable{
iterNum.set(iterNum.get() + 1); iterNum.set(iterNum.get() + 1);
System.out.println("iterNum:" + iterNum.get());
//iterNum++;
this.configName = configName + "_" + iterNum.get(); this.configName = configName + "_" + iterNum.get();
}else{ }else{
this.configName = configName; this.configName = configName;
...@@ -90,58 +81,6 @@ public class ConfigTermText implements Cloneable{ ...@@ -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) { public void setCurPremise(String curPremise) {
this.curPremise = curPremise; this.curPremise = curPremise;
} }
...@@ -414,7 +353,7 @@ public class ConfigTermText implements Cloneable{ ...@@ -414,7 +353,7 @@ public class ConfigTermText implements Cloneable{
data.put("configName", configName); data.put("configName", configName);
//添加config状态 //添加config状态
data.put("configStatus", jStatus); data.put("configStatus", statusMap.get(status));
boolean doPost = false; boolean doPost = false;
......
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;
}
}
...@@ -7,10 +7,26 @@ public class Premise { ...@@ -7,10 +7,26 @@ public class Premise {
private String keyword = ""; private String keyword = "";
public Premise(String conditionName, String cmpType, String operator, String keyword) { public Premise(String conditionName, String cmpType, String operator, String keyword) {
this.conditionName = conditionName; this.conditionName = conditionName;
this.cmpType = cmpType; this.cmpType = cmpType;
this.operator = operator; this.operator = operator;
this.keyword = keyword; 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() { public String getConditionName() {
......
...@@ -315,7 +315,6 @@ public class MapConstructor extends ElementConstructor { ...@@ -315,7 +315,6 @@ public class MapConstructor extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("plot_" + placeA + "_doudi", false); configTermText.setConfigName("plot_" + placeA + "_doudi", false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -327,7 +326,6 @@ public class MapConstructor extends ElementConstructor { ...@@ -327,7 +326,6 @@ public class MapConstructor extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("plot_" + placeA + "_doudi2", false); configTermText.setConfigName("plot_" + placeA + "_doudi2", false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
......
...@@ -284,14 +284,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -284,14 +284,6 @@ public class PlotConstructor2 extends ElementConstructor {
/**
* 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理,
* 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id
*/
if(reply.equals("")) if(reply.equals(""))
reply = curUnknownText; reply = curUnknownText;
...@@ -543,7 +535,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -543,7 +535,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("queryskip1",false); configTermText.setConfigName("queryskip1",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -554,7 +545,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -554,7 +545,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("queryskip2",false); configTermText.setConfigName("queryskip2",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -564,7 +554,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -564,7 +554,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("queryskip3",false); configTermText.setConfigName("queryskip3",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -591,7 +580,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -591,7 +580,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("unknown1",false); configTermText.setConfigName("unknown1",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -603,7 +591,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -603,7 +591,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("unknown2",false); configTermText.setConfigName("unknown2",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -615,7 +602,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -615,7 +602,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("unknown3",false); configTermText.setConfigName("unknown3",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -626,7 +612,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -626,7 +612,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("unknown4",false); configTermText.setConfigName("unknown4",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
...@@ -638,7 +623,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -638,7 +623,6 @@ public class PlotConstructor2 extends ElementConstructor {
); );
configTermText.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTermText.setConfigName("common_answer",false); configTermText.setConfigName("common_answer",false);
configTermText.setjStatus(1);
configTermText.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
//--------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------
......
...@@ -129,55 +129,6 @@ public class ActionMatcher { ...@@ -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 { ...@@ -336,19 +287,17 @@ public class ActionMatcher {
} }
/** /**
* 单个条件的匹配,判断是否满足条件 * 单个条件的匹配,判断是否满足条件
* 比较类型分为 match、number、time、variable, * 比较类型分为 match、number、time、variable,
* curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息
* *
* @param keyword * @param variableValue 变量的值或者condition识别到的关键字
* @param cmpType 比较类型 * @param cmpType 比较类型
* @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 * @param keywordSet 限定值域
* @return 返回匹配或者不匹配 * @return 返回匹配或者不匹配
*/ */
public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet) { public boolean premiseSatisfy(String variableValue, String cmpType, HashSet<String> keywordSet) {
boolean flag = true; boolean flag = true;
String operator = ""; String operator = "";
...@@ -361,60 +310,74 @@ public class ActionMatcher { ...@@ -361,60 +310,74 @@ public class ActionMatcher {
if (cmpType.equals("match")) { if (cmpType.equals("match")) {
if(operator.equals("Keyword") || operator.equals("Include")) { if(operator.equals("Keyword") || operator.equals("Include")) { //识别到的关键词 属于预先设定的值域
if (!keywordSet.contains(keyword)) { if (!keywordSet.contains(variableValue)) {
flag = false; flag = false;
} }
if (flag == false && keyword.contains(":")) { if (flag == false && variableValue.contains(":")) {
String ks[] = keyword.split(":"); String ks[] = variableValue.split(":");
for (String k : ks) { for (String k : ks) {
if (keywordSet.contains(k)) if (keywordSet.contains(k))
flag = true; flag = true;
} }
} }
} else if(operator.equals("Exclude")) { } else if(operator.equals("Exclude")) {
if(keyword.contains(":")){ if(variableValue.contains(":")){
String ks[] = keyword.split(":", 2); String ks[] = variableValue.split(":", 2);
if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1]))
flag = false; flag = false;
}else { }else {
if (keywordSet.contains(keyword)) { if (keywordSet.contains(variableValue)) {
flag = false; 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){ for(String key:keywordSet){
if(key.equals("")) if(key.equals(""))
continue; continue;
if(!keyword.contains(key)){ if(variableValue.contains(key)){
flag = false; flag = false;
break; break;
} }
} }
}else if(operator.equals("Any")){
if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足
flag = false;
}else{ }else{
flag = false; flag = false;
} }
} else if (cmpType.equals("number") && !keyword.equals("")) { } else if (cmpType.equals("number") && !variableValue.equals("")) {
int candidateA = 0; int candidateA = 0;
int candidateB = 0; int candidateB = 0;
if (keyword.contains(":")) { if (variableValue.contains(":")) {
String ks[] = keyword.split(":"); String ks[] = variableValue.split(":");
for (String k : ks) { for (String k : ks) {
if(StringUtils.isNumeric(k)) if(StringUtils.isNumeric(k))
keyword = k; variableValue = k;
} }
} }
if(!StringUtils.isNumeric(keyword)){ if(!StringUtils.isNumeric(variableValue)){
return false; return false;
} }
candidateA = Integer.parseInt(keyword); candidateA = Integer.parseInt(variableValue);
for (String k : keywordSet) { for (String k : keywordSet) {
if (!k.equals("")) { if (!k.equals("")) {
candidateB = Integer.parseInt(k); candidateB = Integer.parseInt(k);
...@@ -436,16 +399,16 @@ public class ActionMatcher { ...@@ -436,16 +399,16 @@ public class ActionMatcher {
long candidateA, candidateB = 0; long candidateA, candidateB = 0;
if (keyword.contains(":")) { if (variableValue.contains(":")) {
String ks[] = keyword.split(":"); String ks[] = variableValue.split(":");
for (String k : ks) { for (String k : ks) {
if(k.contains("年") && k.contains("月") && k.contains("日")) if(k.contains("年") && k.contains("月") && k.contains("日"))
keyword = k; variableValue = k;
} }
} }
candidateA = SimpleUtil.transferToMillisecond(keyword); candidateA = SimpleUtil.transferToMillisecond(variableValue);
for (String k : keywordSet) { for (String k : keywordSet) {
if (!k.equals("")) { if (!k.equals("")) {
...@@ -482,10 +445,10 @@ public class ActionMatcher { ...@@ -482,10 +445,10 @@ public class ActionMatcher {
*/ */
flag = false; flag = false;
if(operator.equals("Equal")){ if(operator.equals("Equal")){
flag = keyword.equals(conditionValue2); flag = variableValue.equals(conditionValue2);
}else if(keyword.contains(":") && conditionValue2.contains(":")){ }else if(variableValue.contains(":") && conditionValue2.contains(":")){
String relPair1[] = keyword.split(":", 2), keyword1 = ""; String relPair1[] = variableValue.split(":", 2), keyword1 = "";
String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; String relPair2[] = conditionValue2.split(":", 2), keyword2 = "";
boolean similar = false; boolean similar = false;
...@@ -539,9 +502,9 @@ public class ActionMatcher { ...@@ -539,9 +502,9 @@ public class ActionMatcher {
// 操作符为等于时可以比较两个字符串是否相同 // 操作符为等于时可以比较两个字符串是否相同
} }
} }
}else if(!keyword.contains(":") && !conditionValue2.contains(":")){ }else if(!variableValue.contains(":") && !conditionValue2.contains(":")){
if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ if(StringUtils.isNumeric(variableValue) && StringUtils.isNumeric(conditionValue2)){
int candidateA = Integer.parseInt(keyword); int candidateA = Integer.parseInt(variableValue);
int candidateB = Integer.parseInt(conditionValue2); int candidateB = Integer.parseInt(conditionValue2);
...@@ -558,9 +521,9 @@ public class ActionMatcher { ...@@ -558,9 +521,9 @@ public class ActionMatcher {
else if (operator.equals("NotEqual")) else if (operator.equals("NotEqual"))
flag = candidateA != candidateB; 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("日")){ && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){
long candidateA = SimpleUtil.transferToMillisecond(keyword); long candidateA = SimpleUtil.transferToMillisecond(variableValue);
long candidateB = SimpleUtil.transferToMillisecond(conditionValue2); long candidateB = SimpleUtil.transferToMillisecond(conditionValue2);
if (operator.equals("Bigger")) if (operator.equals("Bigger"))
...@@ -584,7 +547,7 @@ public class ActionMatcher { ...@@ -584,7 +547,7 @@ public class ActionMatcher {
} else if (cmpType.equals("any")) { } else if (cmpType.equals("any")) {
if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足
flag = false; flag = false;
} else { } else {
...@@ -592,22 +555,19 @@ public class ActionMatcher { ...@@ -592,22 +555,19 @@ public class ActionMatcher {
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
System.out.println("配置文件格式有误"); System.out.println("配置文件格式有误");
logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0);
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
flag = false; flag = false;
e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
System.out.println("时间解析错误"); System.out.println("时间解析错误");
historyInfoPoint.put("error_message", "解析出错:" + keyword); historyInfoPoint.put("error_message", "解析出错:variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
e.printStackTrace();
flag = false; flag = false;
} catch (Exception e) { } catch (Exception e) {
System.out.println("操作符有误"); System.out.println("操作符有误");
logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0);
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
e.printStackTrace();
flag = false; flag = false;
} }
...@@ -1100,9 +1060,7 @@ public class ActionMatcher { ...@@ -1100,9 +1060,7 @@ public class ActionMatcher {
try { try {
configId = originAction.getId(); configId = originAction.getId();
newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); newAction = new Action(originAction, basePriority, baseAuxiliaryPriority);
//action = ActionMatcher.buildCondition(action, configStr);
...@@ -1110,10 +1068,7 @@ public class ActionMatcher { ...@@ -1110,10 +1068,7 @@ public class ActionMatcher {
if (activatedMap.containsKey(configId)) { if (activatedMap.containsKey(configId)) {
if(higherPriority(newAction, activatedMap.get(configId))) if(higherPriority(newAction, activatedMap.get(configId)))
activatedMap.put(configId, newAction); 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)) { } else if (!activatedMap.containsKey(configId)) {
activatedMap.put(configId, newAction); activatedMap.put(configId, newAction);
activatedQueue.add(newAction); activatedQueue.add(newAction);
...@@ -1141,10 +1096,6 @@ public class ActionMatcher { ...@@ -1141,10 +1096,6 @@ public class ActionMatcher {
Queue<Action> activatedQueue = new LinkedList<Action>(); Queue<Action> activatedQueue = new LinkedList<Action>();
Solution bestMatch = oldBestMatch; Solution bestMatch = oldBestMatch;
Action newAction1 = ansAction, newAction2; 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);
......
...@@ -54,33 +54,23 @@ public class ChatCacheController { ...@@ -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); chatCache = new ChatCache(userinfo, userKey, randKey, botType);
chatCacheMap.put(userKey, chatCache); 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<String, String>) 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()); System.out.println(chatCache.getGameEnv());
...@@ -138,7 +128,6 @@ public class ChatCacheController { ...@@ -138,7 +128,6 @@ public class ChatCacheController {
} catch (Exception e) { } catch (Exception e) {
System.out.println("游戏存档时发生异常"); System.out.println("游戏存档时发生异常");
e.printStackTrace();
opFlag = false; opFlag = false;
} }
...@@ -158,33 +147,27 @@ public class ChatCacheController { ...@@ -158,33 +147,27 @@ public class ChatCacheController {
String fileDir = System.getProperty("user.dir") + "/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[]; String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
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; return chatCache;
} }
...@@ -194,7 +177,7 @@ public class ChatCacheController { ...@@ -194,7 +177,7 @@ public class ChatCacheController {
/** /**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 * 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; String sessionKey;
ChatCache chatCache = null; ChatCache chatCache = null;
SqlHelper helper = null; SqlHelper helper = null;
...@@ -289,7 +272,7 @@ public class ChatCacheController { ...@@ -289,7 +272,7 @@ public class ChatCacheController {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return false; findFlag = false;
} }
return findFlag; return findFlag;
......
...@@ -6,6 +6,8 @@ import com.qiwu.chatbotbackend.entity.Solution; ...@@ -6,6 +6,8 @@ import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity; 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.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
...@@ -23,7 +25,7 @@ import java.util.Date; ...@@ -23,7 +25,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
public class MyFunc { public class SimpleUtil {
/** /**
* 将后台返回的数据转成json格式 * 将后台返回的数据转成json格式
...@@ -64,6 +66,57 @@ public class MyFunc { ...@@ -64,6 +66,57 @@ public class MyFunc {
return json.toString(); 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方法传递参数时需要对参数的编码进行转换 * 通过get方法传递参数时需要对参数的编码进行转换
*/ */
...@@ -134,18 +187,22 @@ public class MyFunc { ...@@ -134,18 +187,22 @@ public class MyFunc {
try { try {
HttpResponse resp = client.execute(httpPost); HttpResponse resp = client.execute(httpPost);
jobj.put("status_code", resp.getStatusLine().getStatusCode());
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent); jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1); jobj.put("post_status", 1);
jobj.put("status_code", 200);
} else { } else {
jobj.put("post_status", 0); jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常"); jobj.put("status_code", resp.getStatusLine().getStatusCode());
jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase());
} }
} catch (Exception e) { } catch (Exception e) {
jobj.put("status_code", 0);
jobj.put("post_status", 0);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -181,12 +238,11 @@ public class MyFunc { ...@@ -181,12 +238,11 @@ public class MyFunc {
} else { } else {
jobj.put("post_status", 0); jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常"); jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode());
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); jobj.put("error_message", "提交表单时出错:" + e.getMessage());
jobj.put("post_status", 0); jobj.put("post_status", 0);
} }
return jobj; return jobj;
......
...@@ -5,15 +5,13 @@ import com.qiwu.chatbotbackend.entity.UserInfo; ...@@ -5,15 +5,13 @@ import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.CONFIG_DIR;
import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR;
public class UserInfoController { public class UserInfoController {
static String CONFIG_DIR = System.getProperty("user.dir") + "/config";
static String FILE_ERROR = ".txt文件有误";
...@@ -24,9 +22,8 @@ public class UserInfoController { ...@@ -24,9 +22,8 @@ public class UserInfoController {
String line; 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()) if (!dir.exists())
dir.mkdir(); dir.mkdir();
for (File configFile : dir.listFiles()) { for (File configFile : dir.listFiles()) {
...@@ -36,13 +33,8 @@ public class UserInfoController { ...@@ -36,13 +33,8 @@ public class UserInfoController {
String fileName = configFile.getName(); String fileName = configFile.getName();
UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]);
try { userinfo = buildUserInfo(br, userinfo, true);
userinfo = buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.botAccount, userinfo);
context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) {
System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace();
}
reader.close(); reader.close();
br.close(); br.close();
...@@ -50,38 +42,37 @@ public class UserInfoController { ...@@ -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; 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()) { if (!userFile.exists()) {
BufferedReader br = new BufferedReader(new StringReader("")); BufferedReader br = new BufferedReader(new StringReader(""));
UserInfo userinfo = new UserInfo(botAccount); userInfo = new UserInfo(botAccount);
try {
userinfo = buildUserInfo(br, userinfo, true); userInfo = buildUserInfo(br, userInfo, true);
context.setAttribute(userinfo.botAccount, userinfo); context.setAttribute(userInfo.botAccount, userInfo);
} catch (Exception e) {
System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace();
}
} else { } else {
FileReader reader = new FileReader(userFile); FileReader reader = new FileReader(userFile);
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
UserInfo userinfo = new UserInfo(botAccount); UserInfo userinfo = new UserInfo(botAccount);
try { userInfo = buildUserInfo(br, userinfo, true);
userinfo = buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.botAccount, userinfo);
context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) {
System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace();
}
reader.close(); reader.close();
br.close(); br.close();
} }
return userInfo;
} }
...@@ -97,12 +88,6 @@ public class UserInfoController { ...@@ -97,12 +88,6 @@ public class UserInfoController {
try { try {
text = line.split("---");
line = text[0];
if(text.length > 1 && text[1].startsWith("<-"))
line += "---" + text[1];
element = line.replace("\n", "").split("\\|=\\>\\|"); element = line.replace("\n", "").split("\\|=\\>\\|");
premises = element[0].split("\\|"); premises = element[0].split("\\|");
feature = premises[2]; feature = premises[2];
...@@ -165,13 +150,8 @@ public class UserInfoController { ...@@ -165,13 +150,8 @@ public class UserInfoController {
insertPremise(action.getHistoryPremise(), history_premises); insertPremise(action.getHistoryPremise(), history_premises);
//满足条件越多,优先级越大 //满足条件越多,优先级越大
action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); 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]; firstCnditionName = cur_premises[0];
if (firstCnditionName.equals(" ")) if (firstCnditionName.equals(" "))
action.setIndexName("emptySet"); action.setIndexName("emptySet");
...@@ -193,8 +173,8 @@ public class UserInfoController { ...@@ -193,8 +173,8 @@ public class UserInfoController {
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide){
String line, infoName, extraElements[]; String line = "", infoName, extraElements[];
HashMap<String, List<Action>> conditionTable = null; HashMap<String, List<Action>> conditionTable = null;
//是否覆盖原有的数据 //是否覆盖原有的数据
...@@ -213,8 +193,8 @@ public class UserInfoController { ...@@ -213,8 +193,8 @@ public class UserInfoController {
List<Action> actionList = null; List<Action> actionList = null;
while ((line = br.readLine()) != null) { try{
try { while ((line = br.readLine()) != null) {
if (line.trim().equals("")) if (line.trim().equals(""))
continue; continue;
line = line.replace("\n", ""); line = line.replace("\n", "");
...@@ -235,7 +215,7 @@ public class UserInfoController { ...@@ -235,7 +215,7 @@ public class UserInfoController {
actionList.add(action); actionList.add(action);
conditionTable.put(action.getIndexName(), actionList); conditionTable.put(action.getIndexName(), actionList);
if (action.getId() != 0) { if (action.getId() != 0) {
if(!action.getConfigName().equals("")){ if (!action.getConfigName().equals("")) {
userinfo.name2condition.put(action.getConfigName(), action); userinfo.name2condition.put(action.getConfigName(), action);
} }
userinfo.id2config.put(action.getId(), line); userinfo.id2config.put(action.getId(), line);
...@@ -243,16 +223,17 @@ public class UserInfoController { ...@@ -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; userinfo.conditionTable = conditionTable;
return userinfo; return userinfo;
...@@ -292,26 +273,15 @@ public class UserInfoController { ...@@ -292,26 +273,15 @@ public class UserInfoController {
* @param bot_name 用户名 * @param bot_name 用户名
* @return 用户信息 * @return 用户信息
*/ */
public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException {
/*根据数据库得到botAccount改为直接得到
SqlHelper helper = new SqlHelper();
String botAccount = helper.querybotAccountByKey(chat_key);
*/
String botAccount = bot_name; String botAccount = bot_name;
UserInfo userinfo = null; UserInfo userinfo = null;
if (context.getAttribute(botAccount) == null) { if (context.getAttribute(botAccount) == null) {
userConfigInit(botAccount, context); userinfo = userConfigInit(botAccount, context);
}
if (context.getAttribute(botAccount) == null) {
return null;
//userinfo = new UserInfo(botAccount);
//userinfo.conditionTable = new HashMap<String, List<Action>>();
} else { } else {
userinfo = (UserInfo) context.getAttribute(botAccount); userinfo = (UserInfo) context.getAttribute(botAccount);
} }
//helper.destroy();
return userinfo; return userinfo;
} }
...@@ -321,7 +291,6 @@ public class UserInfoController { ...@@ -321,7 +291,6 @@ public class UserInfoController {
int id = Integer.parseInt(configId); int id = Integer.parseInt(configId);
Action action = new Action(); Action action = new Action();
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(","); String conditionNameList[] = data.split(",");
String conditionName = ""; String conditionName = "";
...@@ -333,12 +302,8 @@ public class UserInfoController { ...@@ -333,12 +302,8 @@ public class UserInfoController {
if (userInfo.id2config.containsKey(id)) { if (userInfo.id2config.containsKey(id)) {
Action oldAction = userInfo.id2condition.get(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) { if (userInfo.conditionTable.get(conditionName) != null) {
...@@ -363,18 +328,14 @@ public class UserInfoController { ...@@ -363,18 +328,14 @@ public class UserInfoController {
} }
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException { public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Action action = new Action();
String conditionName = ""; String conditionName = "";
for (int configId : idGroup) { for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) { if (userInfo.id2config.containsKey(configId)) {
Action oldAction = userInfo.id2condition.get(configId); Action oldAction = userInfo.id2condition.get(configId);
try {
conditionName = oldAction.getIndexName(); conditionName = oldAction.getIndexName();
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) { if (userInfo.conditionTable.get(conditionName) != null) {
...@@ -403,13 +364,13 @@ public class UserInfoController { ...@@ -403,13 +364,13 @@ public class UserInfoController {
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Action action = new Action(); Action action = new Action();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---"); String dataPair[] = data.split("---");
String configLine = dataPair[0]; String configLine = dataPair[0];
String conditionNameList[];
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
int id = Integer.parseInt(configId); int id = Integer.parseInt(configId);
action = userInfoController.buildCondition(action, configLine); action = userInfoController.buildCondition(action, configLine);
if (context.getAttribute(userName) == null) { if (context.getAttribute(userName) == null) {
...@@ -487,29 +448,28 @@ public class UserInfoController { ...@@ -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; try {
String path = CONFIG_DIR + "/" + userName + ".txt"; 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); if (!dir.exists())
System.out.println("config_dir" + dir.getAbsolutePath()); dir.mkdir();
String returnMessage = "success"; if (!file.exists()) {
file.createNewFile();
}
if (!dir.exists()) fw = new FileWriter(file);
dir.mkdir(); bw = new BufferedWriter(fw);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator(); Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) { while (keyIter.hasNext()) {
String info = keyIter.next(); String info = keyIter.next();
...@@ -533,8 +493,13 @@ public class UserInfoController { ...@@ -533,8 +493,13 @@ public class UserInfoController {
e.printStackTrace(); e.printStackTrace();
returnMessage = "config file write error"; returnMessage = "config file write error";
} finally { } finally {
bw.close(); try {
fw.close(); bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return returnMessage; return returnMessage;
......
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; 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.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
...@@ -21,7 +25,8 @@ import java.time.LocalDateTime; ...@@ -21,7 +25,8 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; 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"}) @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
...@@ -74,157 +79,152 @@ public class GameDesignServlet extends HttpServlet { ...@@ -74,157 +79,152 @@ public class GameDesignServlet extends HttpServlet {
try { try {
helper = new SqlHelper(); 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")); JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
//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");
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); flag = botInit(botId, botAccount, userinfo, helper);
} catch (SQLException e) {
System.out.println("清空旧数据失败");
e.printStackTrace();
}
StringBuffer mergedConfigText = new StringBuffer(); StringBuffer mergedConfigText = new StringBuffer();
int skipCount = 0; 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------------------------------------------------------"); idList.clear();
readKeywords(keywordMap, KEYWORD_DIR); helper.batchInsertVariableByBotId(botId, constructor);
List<JSONObject> jsonList = new ArrayList<JSONObject>();
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) { helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2));
case "map": constructor.postProcessing(idList, categoryMap.get(moduleName2));
moduleName2 = "地图"; constructor.generateConfigText(idList);
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")); mergedConfigText.append(constructor.getConfigText());
break; }else {
case "goods": returnStatus = 0;
moduleName2 = "物品"; returnMessage = constructor.getMessage();
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; 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<JSONObject> jsonList = new ArrayList<JSONObject>();
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(); if(returnStatus == 1) {
now = ldt.format(dtf); // ldt = LocalDateTime.now();
timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); // now = ldt.format(dtf);
// timeUsedDetect.append("\n发送post请求预处理:").append(now);
} StringReader sr = new StringReader(mergedConfigText.toString());
BufferedReader br = new BufferedReader(sr);
if(returnStatus == 1) { //System.out.println(mergedConfigText.toString());
ldt = LocalDateTime.now(); UserInfoController.buildUserInfo(br, userinfo, true);
now = ldt.format(dtf); context.setAttribute(botAccount, userinfo);
timeUsedDetect.append("\n发送post请求预处理:").append(now); UserInfoController.writeConfigText(botAccount, userinfo);
StringReader sr = new StringReader(mergedConfigText.toString()); // ldt = LocalDateTime.now();
BufferedReader br = new BufferedReader(sr); // now = ldt.format(dtf);
//System.out.println(mergedConfigText.toString()); // timeUsedDetect.append("\n发送post请求前:").append(now);
UserInfoController.buildUserInfo(br, userinfo, true); IntervalStatus generateResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS, helper);
context.setAttribute(botAccount, userinfo);
UserInfoController.writeConfigText(botAccount, userinfo); // ldt = LocalDateTime.now();
ldt = LocalDateTime.now(); // now = ldt.format(dtf);
now = ldt.format(dtf); // timeUsedDetect.append("\n发送post请求后:").append(now);
timeUsedDetect.append("\n发送post请求前:").append(now);
String postResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS); if(generateResult.getStatus() != 1){
returnStatus = 0;
ldt = LocalDateTime.now(); returnMessage = generateResult.getMessage();
now = ldt.format(dtf); }
timeUsedDetect.append("\n发送post请求后:").append(now);
if(!postResult.equals("success")){
returnStatus = 0;
returnMessage = postResult;
} }
}
helper.destroy(); helper.destroy();
}else { }else {
returnStatus = 0; returnStatus = 0;
returnMessage = "请求解析失败"; returnMessage = "请求解析失败";
}
} catch (SQLException e) {
e.printStackTrace();
} }
...@@ -269,47 +269,65 @@ public class GameDesignServlet extends HttpServlet { ...@@ -269,47 +269,65 @@ public class GameDesignServlet extends HttpServlet {
return deleteConfigFlag && deleteVariableFlag; return deleteConfigFlag && deleteVariableFlag;
} }
public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap<String, HashSet<String>> additionalKeywords, HashSet<String> 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<String, HashSet<String>> additionalKeywords, HashSet<String> exceptRelation, StringBuffer POS, SqlHelper helper){
String startCondition, POS2 = "", botName = gameElements.getString("botName");
System.out.println(botName);
JSONObject returnMessage = null; JSONObject returnMessage = null;
EngineUtils engine = null;
IntervalStatus intervalStatus = new IntervalStatus(1, "");
JSONObject actionPostData = new JSONObject(); JSONObject actionPostData = new JSONObject();
//System.out.println("root"+ root.toJSONString());
startCondition = (String)root.get("conditionName"); startCondition = (String)root.get("conditionName");
actionPostData.put("startCondition", "start_options"); actionPostData.put("startCondition", "start_options");
actionPostData.put("botName_yhm", (String)gameElements.get("botName")); actionPostData.put("welcome", String.format(GAME_WELCOME_TEXT, gameElements.getString("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("relationKeywords", additionalKeywords); 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")) if (gameElements.containsKey("POS"))
POS2 = (String)gameElements.get("POS"); POS2 = (String)gameElements.get("POS");
actionPostData.put("POS", POS.toString() + POS2); actionPostData.put("POS", POS.toString() + POS2);
System.out.println(actionPostData.toJSONString()); System.out.println(actionPostData.toJSONString());
userInfo.extraInfo.put("activeAction", startCondition);
try { try {
returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth")); engine = new EngineUtils();
} catch (UnsupportedEncodingException e) { 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(); 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 { ...@@ -356,7 +374,4 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Action;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
...@@ -16,13 +17,12 @@ import javax.servlet.http.HttpServletRequest; ...@@ -16,13 +17,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; 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.processing.ChatCacheController.COMBINE_PUNC2;
import static com.qiwu.chatbotbackend.Config.Config.TEST_VAR;
@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"})
...@@ -31,15 +31,14 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -31,15 +31,14 @@ public class GetAnswerServlet extends HttpServlet {
* GetAnswerServlet就是处理post请求并返回答案的入口 * GetAnswerServlet就是处理post请求并返回答案的入口
*/ */
String NAME_MISSING_ERROR = "没找到bot名?";
String LOG_PATH = "/var/www/html/logs/";
//String LOG_PATH = "/home/hxw/source/logs/"; //String LOG_PATH = "/home/hxw/source/logs/";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap()); Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap());
Map<String ,String> curInfoPoint = new HashMap<String, String>(); Map<String ,String> curInfoPoint = new HashMap<String, String>();
//Map<String, String> historyInfoPoint = null;
Solution bestMatch = null; Solution bestMatch = null;
BasicBotUtil botUtil = null; BasicBotUtil botUtil = null;
Action ansAction = null; Action ansAction = null;
...@@ -60,148 +59,144 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -60,148 +59,144 @@ public class GetAnswerServlet extends HttpServlet {
userKey = chatKeys[0]; userKey = chatKeys[0];
randKey = chatKeys[1]; randKey = chatKeys[1];
} }
receiveParamters.put("userKey", new String[]{userKey}); receiveParamters.put("userKey", new String[]{userKey});
receiveParamters.put("randKey", new String[]{randKey}); receiveParamters.put("randKey", new String[]{randKey});
LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
UserInfo userinfo = null;
UserInfoController uiController = new UserInfoController();
try { try {
//userinfo = process.userInfoQuery(chatKey,context); LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
//从servlet根据用户名查询用户信息
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context);
} 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) { if (userinfo != null) {
//获得用户历史信息 //获得用户历史信息
ChatCache chatCache = null; ChatCache chatCache = null;
Boolean loadCacheStatus = Boolean.valueOf(false); Boolean loadCacheStatus = Boolean.valueOf(false);
if(userinfo.varInitialMap.get("botType") != null) if (userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType"); botType = userinfo.varInitialMap.get("botType");
try {
chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType);
if(chatCache == null){ if (chatCache == null) {
throw(new Exception("chatCache初始化失败")); 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": debugFlag = botUtil.preprocessing(receiveParamters, context);
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);
//信息点预处理
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 (!botUtil.getChatCache().getReload()) {
//读档成功不应该再激活 //读档成功不应该再激活
//if(matcher.) //if(matcher.)
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
}
} else {
//跳过
botUtil.getChatCache().setReload(false); //清楚标识
} }
}else{
//跳过
botUtil.getChatCache().setReload(false); //清楚标识
}
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); 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类型做后处理 //针对不同bot类型做后处理
botUtil.postprocessing(chatKey, context, bestMatch); botUtil.postprocessing(chatKey, context, bestMatch);
botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer());
if (debugFlag) { if (debugFlag) {
matcher.appendDebugInfo(bestMatch, context); matcher.appendDebugInfo(bestMatch, context);
} }
//if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after"))
matcher.infoTransfer(bestMatch, context, debugFlag); matcher.infoTransfer(bestMatch, context, debugFlag);
ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo);
//清理超时的用户数据 //清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null) if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) {
ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); 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); System.out.println(ansJ);
out.write(ansJ.getBytes());
out.flush(); out.flush();
} }
......
...@@ -75,6 +75,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -75,6 +75,7 @@ public class GameBotUtil extends BasicBotUtil{
} }
@Override
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
...@@ -144,6 +145,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -144,6 +145,7 @@ public class GameBotUtil extends BasicBotUtil{
return true; return true;
} }
@Override
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){ public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = ""; String keyword = "";
String nameSeries[] = actionName.split("_"); String nameSeries[] = actionName.split("_");
...@@ -328,7 +330,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -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; String keyword = "", site;
ChatCache loadCache = null; ChatCache loadCache = null;
...@@ -342,13 +344,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -342,13 +344,7 @@ public class GameBotUtil extends BasicBotUtil{
chatCache.getInfoPoint().put("common_answer", ""); chatCache.getInfoPoint().put("common_answer", "");
try { loadCache = ChatCacheController.loadChatCache(archiveInfo);
loadCache = ChatCacheController.loadChatCache(archiveInfo);
} catch (Exception e) {
System.out.println("从本地加载存档失败");
solution.setAnswer("从本地加载存档失败");
e.printStackTrace();
}
//this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint());
......
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
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
spring.profiles.active=@profiles.active@
test.var=111122223333
TEST_VAR=11111
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池mysql-->
<named-config name="engine">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://192.168.1.82:3306/chatCN?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--从platform获取某个类别下condition列表-->
<named-config name="platform">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://192.168.1.82:3306/platform?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">2</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">8</property>
<property name="minPoolSize">2</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置操作chatCN-->
<named-config name="engine">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/chatCN?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--从platform获取某个类别下condition列表-->
<named-config name="platform">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/platform?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">3</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">10</property>
<property name="minPoolSize">3</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
\ No newline at end of file
### 设置###
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
/*! 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&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&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<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+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="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",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="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";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<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=fe(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=pe(t);function ye(){}ye.prototype=r.filters=r.pseudos,r.setFilters=new ye,a=oe.tokenize=function(e,t){var n,i,o,a,s,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=r.preFilter;while(s){n&&!(i=F.exec(s))||(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),n=!1,(i=_.exec(s))&&(n=i.shift(),o.push({value:n,type:i[0].replace(B," ")}),s=s.slice(n.length));for(a in r.filter)!(i=V[a].exec(s))||l[a]&&!(i=l[a](i))||(n=i.shift(),o.push({value:n,type:a,matches:i}),s=s.slice(n.length));if(!n)break}return t?s.length:s?oe.error(e):k(e,u).slice(0)};function ve(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function me(e,t,n){var r=t.dir,i=t.next,o=i||r,a=n&&"parentNode"===o,s=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||a)return e(t,n,i);return!1}:function(t,n,u){var l,c,f,p=[T,s];if(u){while(t=t[r])if((1===t.nodeType||a)&&e(t,n,u))return!0}else while(t=t[r])if(1===t.nodeType||a)if(f=t[b]||(t[b]={}),c=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((l=c[o])&&l[0]===T&&l[1]===s)return p[2]=l[2];if(c[o]=p,p[2]=e(t,n,u))return!0}return!1}}function xe(e){return e.length>1?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<i;r++)oe(e,t[r],n);return n}function we(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Te(e,t,n,r,i,o){return r&&!r[b]&&(r=Te(r)),i&&!i[b]&&(i=Te(i,o)),se(function(o,a,s,u){var l,c,f,p=[],d=[],h=a.length,g=o||be(t||"*",s.nodeType?[s]:s,[]),y=!e||!o&&t?g:we(g,p,e,s,u),v=n?i||(o?e:h||r)?[]:a:y;if(n&&n(y,v,s,u),r){l=we(v,d),r(l,[],s,u),c=l.length;while(c--)(f=l[c])&&(v[d[c]]=!(y[d[c]]=f))}if(o){if(i||e){if(i){l=[],c=v.length;while(c--)(f=v[c])&&l.push(y[c]=f);i(null,v=[],l,u)}c=v.length;while(c--)(f=v[c])&&(l=i?O(o,f):p[c])>-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}];u<o;u++)if(n=r.relative[e[u].type])p=[me(xe(p),n)];else{if((n=r.filter[e[u].type].apply(null,e[u].matches))[b]){for(i=++u;i<o;i++)if(r.relative[e[i].type])break;return Te(u>1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u<i&&Ce(e.slice(u,i)),i<o&&Ce(e=e.slice(i)),i<o&&ve(e))}p.push(n)}return xe(p)}function Ee(e,t){var n=t.length>0,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="<a href='#'></a>","#"===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="<input/>",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;t<r;t++)if(w.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)w.find(e,i[t],n);return r>1?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<n;e++)if(w.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&w(e);if(!D.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-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<o.length)!1===o[s].apply(n[0],n[1])&&e.stopOnFalse&&(s=o.length,n=!1)}e.memory||(n=!1),t=!1,i&&(o=n?[]:"")},l={add:function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){w.each(n,function(n,r){g(r)?e.unique&&l.has(r)||o.push(r):r&&r.length&&"string"!==x(r)&&t(r)})}(arguments),n&&!t&&u()),this},remove:function(){return w.each(arguments,function(e,t){var n;while((n=w.inArray(t,o,n))>-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)){if((e=r.apply(s,u))===n.promise())throw new TypeError("Thenable self-resolution");l=e&&("object"==typeof e||"function"==typeof e)&&e.then,g(l)?i?l.call(e,a(o,n,I,i),a(o,n,W,i)):(o++,l.call(e,a(o,n,I,i),a(o,n,W,i),a(o,n,I,n.notifyWith))):(r!==I&&(s=void 0,u=[e]),(i||n.resolveWith)(s,u))}},c=i?l:function(){try{l()}catch(e){w.Deferred.exceptionHook&&w.Deferred.exceptionHook(e,c.stackTrace),t+1>=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(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},X=/^-ms-/,U=/-([a-z])/g;function V(e,t){return t.toUpperCase()}function G(e){return e.replace(X,"ms-").replace(U,V)}var Y=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Q(){this.expando=w.expando+Q.uid++}Q.uid=1,Q.prototype={cache:function(e){var t=e[this.expando];return t||(t={},Y(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[G(t)]=n;else for(r in t)i[G(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][G(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(G):(t=G(t))in r?[t]:t.match(M)||[]).length;while(n--)delete r[t[n]]}(void 0===t||w.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!w.isEmptyObject(t)}};var J=new Q,K=new Q,Z=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ee=/[A-Z]/g;function te(e){return"true"===e||"false"!==e&&("null"===e?null:e===+e+""?+e:Z.test(e)?JSON.parse(e):e)}function ne(e,t,n){var r;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(ee,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n=te(n)}catch(e){}K.set(e,t,n)}else n=void 0;return n}w.extend({hasData:function(e){return K.hasData(e)||J.hasData(e)},data:function(e,t,n){return K.access(e,t,n)},removeData:function(e,t){K.remove(e,t)},_data:function(e,t,n){return J.access(e,t,n)},_removeData:function(e,t){J.remove(e,t)}}),w.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=K.get(o),1===o.nodeType&&!J.get(o,"hasDataAttrs"))){n=a.length;while(n--)a[n]&&0===(r=a[n].name).indexOf("data-")&&(r=G(r.slice(5)),ne(o,r,i[r]));J.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof e?this.each(function(){K.set(this,e)}):z(this,function(t){var n;if(o&&void 0===t){if(void 0!==(n=K.get(o,e)))return n;if(void 0!==(n=ne(o,e)))return n}else this.each(function(){K.set(this,e,t)})},null,t,arguments.length>1,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<n?w.queue(this[0],e):void 0===t?this:this.each(function(){var n=w.queue(this,e,t);w._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&w.dequeue(this,e)})},dequeue:function(e){return this.each(function(){w.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=w.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=J.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var re=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ie=new RegExp("^(?:([+-])=|)("+re+")([a-z%]*)$","i"),oe=["Top","Right","Bottom","Left"],ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&w.contains(e.ownerDocument,e)&&"none"===w.css(e,"display")},se=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};function ue(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return w.css(e,t,"")},u=s(),l=n&&n[3]||(w.cssNumber[t]?"":"px"),c=(w.cssNumber[t]||"px"!==l&&+u)&&ie.exec(w.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)w.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,w.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var le={};function ce(e){var t,n=e.ownerDocument,r=e.nodeName,i=le[r];return i||(t=n.body.appendChild(n.createElement(r)),i=w.css(t,"display"),t.parentNode.removeChild(t),"none"===i&&(i="block"),le[r]=i,i)}function fe(e,t){for(var n,r,i=[],o=0,a=e.length;o<a;o++)(r=e[o]).style&&(n=r.style.display,t?("none"===n&&(i[o]=J.get(r,"display")||null,i[o]||(r.style.display="")),""===r.style.display&&ae(r)&&(i[o]=ce(r))):"none"!==n&&(i[o]="none",J.set(r,"display",n)));for(o=0;o<a;o++)null!=i[o]&&(e[o].style.display=i[o]);return e}w.fn.extend({show:function(){return fe(this,!0)},hide:function(){return fe(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?w(this).show():w(this).hide()})}});var pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_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<r;n++)J.set(e[n],"globalEval",!t||J.get(t[n],"globalEval"))}var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===x(o))w.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+w.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;w.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&w.inArray(o,r)>-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="<textarea>x</textarea>",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<arguments.length;n++)u[n]=arguments[n];if(t.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,t)){s=w.event.handlers.call(this,t,l),n=0;while((o=s[n++])&&!t.isPropagationStopped()){t.currentTarget=o.elem,r=0;while((a=o.handlers[r++])&&!t.isImmediatePropagationStopped())t.rnamespace&&!t.rnamespace.test(a.namespace)||(t.handleObj=a,t.data=a.data,void 0!==(i=((w.event.special[a.origType]||{}).handle||a.handler).apply(o.elem,u))&&!1===(t.result=i)&&(t.preventDefault(),t.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,t),t.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&e.button>=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?w(i,this).index(l)>-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<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(e,t){Object.defineProperty(w.Event.prototype,e,{enumerable:!0,configurable:!0,get:g(t)?function(){if(this.originalEvent)return t(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[e]},set:function(t){Object.defineProperty(this,e,{enumerable:!0,configurable:!0,writable:!0,value:t})}})},fix:function(e){return e[w.expando]?e:new w.Event(e)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==Se()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===Se()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&N(this,"input"))return this.click(),!1},_default:function(e){return N(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},w.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},w.Event=function(e,t){if(!(this instanceof w.Event))return new w.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Ee:ke,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&w.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[w.expando]=!0},w.Event.prototype={constructor:w.Event,isDefaultPrevented:ke,isPropagationStopped:ke,isImmediatePropagationStopped:ke,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Ee,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Ee,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Ee,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},w.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&we.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&Te.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},w.event.addProp),w.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){w.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return i&&(i===r||w.contains(r,i))||(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),w.fn.extend({on:function(e,t,n,r){return De(this,e,t,n,r)},one:function(e,t,n,r){return De(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,w(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=ke),this.each(function(){w.event.remove(this,e,n,t)})}});var Ne=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/<script|<style|<link/i,je=/checked\s*(?:[^=]|=\s*.checked.)/i,qe=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\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;n<r;n++)w.event.add(t,i,l[i][n])}K.hasData(e)&&(s=K.access(e),u=w.extend({},s),K.set(t,u))}}function Me(e,t){var n=t.nodeName.toLowerCase();"input"===n&&pe.test(e.type)?t.checked=e.checked:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}function Re(e,t,n,r){t=a.apply([],t);var i,o,s,u,l,c,f=0,p=e.length,d=p-1,y=t[0],v=g(y);if(v||p>1&&"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<p;f++)l=i,f!==d&&(l=w.clone(l,!0,!0),u&&w.merge(s,ye(l,"script"))),n.call(e[f],l,f);if(u)for(c=s[s.length-1].ownerDocument,w.map(s,Oe),f=0;f<u;f++)l=s[f],he.test(l.type||"")&&!J.access(l,"globalEval")&&w.contains(c,l)&&(l.src&&"module"!==(l.type||"").toLowerCase()?w._evalUrl&&w._evalUrl(l.src):m(l.textContent.replace(qe,""),c,l))}return e}function Ie(e,t,n){for(var r,i=t?w.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||w.cleanData(ye(r)),r.parentNode&&(n&&w.contains(r.ownerDocument,r)&&ve(ye(r,"script")),r.parentNode.removeChild(r));return e}w.extend({htmlPrefilter:function(e){return e.replace(Ne,"<$1></$2>")},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;r<i;r++)Me(o[r],a[r]);if(t)if(n)for(o=o||ye(e),a=a||ye(s),r=0,i=o.length;r<i;r++)Pe(o[r],a[r]);else Pe(e,s);return(a=ye(s,"script")).length>0&&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<r;n++)1===(t=this[n]||{}).nodeType&&(w.cleanData(ye(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return Re(this,arguments,function(t){var n=this.parentNode;w.inArray(this,e)<0&&(w.cleanData(ye(this)),n&&n.replaceChild(t,this))},e)}}),w.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){w.fn[e]=function(e){for(var n,r=[],i=w(e),o=i.length-1,a=0;a<=o;a++)n=a===o?this:this.clone(!0),w(i[a])[t](n),s.apply(r,n.get());return this.pushStack(r)}});var We=new RegExp("^("+re+")(?!px)[a-z%]+$","i"),$e=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},Be=new RegExp(oe.join("|"),"i");!function(){function t(){if(c){l.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",c.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",be.appendChild(l).appendChild(c);var t=e.getComputedStyle(c);i="1%"!==t.top,u=12===n(t.marginLeft),c.style.right="60%",s=36===n(t.right),o=36===n(t.width),c.style.position="absolute",a=36===c.offsetWidth||"absolute",be.removeChild(l),c=null}}function n(e){return Math.round(parseFloat(e))}var i,o,a,s,u,l=r.createElement("div"),c=r.createElement("div");c.style&&(c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",h.clearCloneStyle="content-box"===c.style.backgroundClip,w.extend(h,{boxSizingReliable:function(){return t(),o},pixelBoxStyles:function(){return t(),s},pixelPosition:function(){return t(),i},reliableMarginLeft:function(){return t(),u},scrollboxSize:function(){return t(),a}}))}();function Fe(e,t,n){var r,i,o,a,s=e.style;return(n=n||$e(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||w.contains(e.ownerDocument,e)||(a=w.style(e,t)),!h.pixelBoxStyles()&&We.test(a)&&Be.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function _e(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}var ze=/^(none|table(?!-c[ea]).+)/,Xe=/^--/,Ue={position:"absolute",visibility:"hidden",display:"block"},Ve={letterSpacing:"0",fontWeight:"400"},Ge=["Webkit","Moz","ms"],Ye=r.createElement("div").style;function Qe(e){if(e in Ye)return e;var t=e[0].toUpperCase()+e.slice(1),n=Ge.length;while(n--)if((e=Ge[n]+t)in Ye)return e}function Je(e){var t=w.cssProps[e];return t||(t=w.cssProps[e]=Qe(e)||e),t}function Ke(e,t,n){var r=ie.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Ze(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=w.css(e,n+oe[a],!0,i)),r?("content"===n&&(u-=w.css(e,"padding"+oe[a],!0,i)),"margin"!==n&&(u-=w.css(e,"border"+oe[a]+"Width",!0,i))):(u+=w.css(e,"padding"+oe[a],!0,i),"padding"!==n?u+=w.css(e,"border"+oe[a]+"Width",!0,i):s+=w.css(e,"border"+oe[a]+"Width",!0,i));return!r&&o>=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;a<i;a++)o[t[a]]=w.css(e,t[a],!1,r);return o}return void 0!==n?w.style(e,t,n):w.css(e,t)},e,t,arguments.length>1)}});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;o<a;o++)if(r=i[o].call(n,t,e))return r}function ct(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),y=J.get(e,"fxshow");n.queue||(null==(a=w._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,w.queue(e,"fx").length||a.empty.fire()})}));for(r in t)if(i=t[r],it.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!y||void 0===y[r])continue;g=!0}d[r]=y&&y[r]||w.style(e,r)}if((u=!w.isEmptyObject(t))||!w.isEmptyObject(d)){f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=y&&y.display)&&(l=J.get(e,"display")),"none"===(c=w.css(e,"display"))&&(l?c=l:(fe([e],!0),l=e.style.display||l,c=w.css(e,"display"),fe([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===w.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1;for(r in d)u||(y?"hidden"in y&&(g=y.hidden):y=J.access(e,"fxshow",{display:l}),o&&(y.hidden=!g),g&&fe([e],!0),p.done(function(){g||fe([e]),J.remove(e,"fxshow");for(r in d)w.style(e,r,d[r])})),u=lt(g?y[r]:0,r,p),r in y||(y[r]=u.start,g&&(u.end=u.start,u.start=0))}}function ft(e,t){var n,r,i,o,a;for(n in e)if(r=G(n),i=t[r],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=w.cssHooks[r])&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function pt(e,t,n){var r,i,o=0,a=pt.prefilters.length,s=w.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=nt||st(),n=Math.max(0,l.startTime+l.duration-t),r=1-(n/l.duration||0),o=0,a=l.tweens.length;o<a;o++)l.tweens[o].run(r);return s.notifyWith(e,[l,r,n]),r<1&&a?n:(a||s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:w.extend({},t),opts:w.extend(!0,{specialEasing:{},easing:w.easing._default},n),originalProperties:t,originalOptions:n,startTime:nt||st(),duration:n.duration,tweens:[],createTween:function(t,n){var r=w.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;n<r;n++)l.tweens[n].run(1);return t?(s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l,t])):s.rejectWith(e,[l,t]),this}}),c=l.props;for(ft(c,l.opts.specialEasing);o<a;o++)if(r=pt.prefilters[o].call(l,e,c,l.opts))return g(r.stop)&&(w._queueHooks(l.elem,l.opts.queue).stop=r.stop.bind(r)),r;return w.map(c,lt,l),g(l.opts.start)&&l.opts.start.call(e,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),w.fx.timer(w.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l}w.Animation=w.extend(pt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return ue(n.elem,e,ie.exec(t),n),n}]},tweener:function(e,t){g(e)?(t=e,e=["*"]):e=e.match(M);for(var n,r=0,i=e.length;r<i;r++)n=e[r],pt.tweeners[n]=pt.tweeners[n]||[],pt.tweeners[n].unshift(t)},prefilters:[ct],prefilter:function(e,t){t?pt.prefilters.unshift(e):pt.prefilters.push(e)}}),w.speed=function(e,t,n){var r=e&&"object"==typeof e?w.extend({},e):{complete:n||!n&&t||g(e)&&e,duration:e,easing:n&&t||t&&!g(t)&&t};return w.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in w.fx.speeds?r.duration=w.fx.speeds[r.duration]:r.duration=w.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){g(r.old)&&r.old.call(this),r.queue&&w.dequeue(this,r.queue)},r},w.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=w.isEmptyObject(e),o=w.speed(t,n,r),a=function(){var t=pt(this,w.extend({},e),o);(i||J.get(this,"finish"))&&t.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&!1!==e&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=w.timers,a=J.get(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&ot.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));!t&&n||w.dequeue(this,e)})},finish:function(e){return!1!==e&&(e=e||"fx"),this.each(function(){var t,n=J.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=w.timers,a=r?r.length:0;for(n.finish=!0,w.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;t<a;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),w.each(["toggle","show","hide"],function(e,t){var n=w.fn[t];w.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ut(t,!0),e,r,i)}}),w.each({slideDown:ut("show"),slideUp:ut("hide"),slideToggle:ut("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){w.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),w.timers=[],w.fx.tick=function(){var e,t=0,n=w.timers;for(nt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||w.fx.stop(),nt=void 0},w.fx.timer=function(e){w.timers.push(e),w.fx.start()},w.fx.interval=13,w.fx.start=function(){rt||(rt=!0,at())},w.fx.stop=function(){rt=null},w.fx.speeds={slow:600,fast:200,_default:400},w.fn.delay=function(t,n){return t=w.fx?w.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e=r.createElement("input"),t=r.createElement("select").appendChild(r.createElement("option"));e.type="checkbox",h.checkOn=""!==e.value,h.optSelected=t.selected,(e=r.createElement("input")).value="t",e.type="radio",h.radioValue="t"===e.value}();var dt,ht=w.expr.attrHandle;w.fn.extend({attr:function(e,t){return z(this,w.attr,e,t,arguments.length>1)},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<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!N(n.parentNode,"optgroup"))){if(t=w(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=w.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=w.inArray(w.valHooks.option.get(r),o)>-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("<script>").prop({charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&o("error"===e.type?404:200,e.type)}),r.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Yt=[],Qt=/(=)\?(?=&|$)|\?\?/;w.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Yt.pop()||w.expando+"_"+Et++;return this[e]=!0,e}}),w.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=!1!==t.jsonp&&(Qt.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qt.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0])return i=t.jsonpCallback=g(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(Qt,"$1"+i):!1!==t.jsonp&&(t.url+=(kt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||w.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){void 0===o?w(e).removeProp(i):e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,Yt.push(i)),a&&g(o)&&o(a[0]),a=o=void 0}),"script"}),h.createHTMLDocument=function(){var e=r.implementation.createHTMLDocument("").body;return e.innerHTML="<form></form><form></form>",2===e.childNodes.length}(),w.parseHTML=function(e,t,n){if("string"!=typeof e)return[];"boolean"==typeof t&&(n=t,t=!1);var i,o,a;return t||(h.createHTMLDocument?((i=(t=r.implementation.createHTMLDocument("")).createElement("base")).href=r.location.href,t.head.appendChild(i)):t=r),o=A.exec(e),a=!n&&[],o?[t.createElement(o[1])]:(o=xe([e],t,a),a&&a.length&&w(a).remove(),w.merge([],o.childNodes))},w.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return s>-1&&(r=vt(e.slice(s)),e=e.slice(0,s)),g(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&w.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?w("<div>").append(w.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},w.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){w.fn[t]=function(e){return this.on(t,e)}}),w.expr.pseudos.animated=function(e){return w.grep(w.timers,function(t){return e===t.elem}).length},w.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=w.css(e,"position"),f=w(e),p={};"static"===c&&(e.style.position="relative"),s=f.offset(),o=w.css(e,"top"),u=w.css(e,"left"),(l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1)?(a=(r=f.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),g(t)&&(t=t.call(e,n,w.extend({},s))),null!=t.top&&(p.top=t.top-s.top+a),null!=t.left&&(p.left=t.left-s.left+i),"using"in t?t.using.call(e,p):f.css(p)}},w.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){w.offset.setOffset(this,e,t)});var t,n,r=this[0];if(r)return r.getClientRects().length?(t=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:t.top+n.pageYOffset,left:t.left+n.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===w.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===w.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),i.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-w.css(r,"marginTop",!0),left:t.left-i.left-w.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===w.css(e,"position"))e=e.offsetParent;return e||be})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;w.fn[e]=function(r){return z(this,function(e,r,i){var o;if(y(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===i)return o?o[t]:e[r];o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):e[r]=i},e,r,arguments.length)}}),w.each(["top","left"],function(e,t){w.cssHooks[t]=_e(h.pixelPosition,function(e,n){if(n)return n=Fe(e,t),We.test(n)?w(e).position()[t]+"px":n})}),w.each({Height:"height",Width:"width"},function(e,t){w.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){w.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),s=n||(!0===i||!0===o?"margin":"border");return z(this,function(t,n,i){var o;return y(t)?0===r.indexOf("outer")?t["inner"+e]:t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?w.css(t,n,s):w.style(t,n,i,s)},t,a?i:void 0,a)}})}),w.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,t){w.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),w.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),w.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),w.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),g(e))return r=o.call(arguments,2),i=function(){return e.apply(t||this,r.concat(o.call(arguments)))},i.guid=e.guid=e.guid||w.guid++,i},w.holdReady=function(e){e?w.readyWait++:w.ready(!0)},w.isArray=Array.isArray,w.parseJSON=JSON.parse,w.nodeName=N,w.isFunction=g,w.isWindow=y,w.camelCase=G,w.type=x,w.now=Date.now,w.isNumeric=function(e){var t=w.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return w});var Jt=e.jQuery,Kt=e.$;return w.noConflict=function(t){return e.$===w&&(e.$=Kt),t&&e.jQuery===w&&(e.jQuery=Jt),w},t||(e.jQuery=e.$=w),w});
<!DOCTYPE HTML>
<html>
<head>
<title>配置文件 v2.2.4</title>
<script src="./js/jquery-3.3.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p><input type="button" value="查询" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
<p><input type="button" value="批量更新" onclick="batch_update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "getConfig",//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
function batch_update() {
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<%--
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" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>配置文件 v2.2.4</title>
<script src="../static/js/jquery-3.3.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p><input type="button" value="查询" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
<p><input type="button" value="批量更新" onclick="batch_update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "getConfig",//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
function batch_update() {
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title> 配置文件 </title>
<script src="./js/jquery-3.1.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:autopx;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<br/><textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p>关键词替换:<br/><textarea style="width:700px;height:100px;word-break:break-all" name="macro" type="password"
id="macro" tabindex="2" value=""></textarea></p>
<p><input type="button" value="登录" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
var macroStr = document.getElementById("macro").value;
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
if (macroStr != "") {
var macro = macroStr.split("\n");
for (var i = 0; i < macro.length; i++) {
if (macro[i] != "") {
pair = macro[i].split("|");
if (pair.length == 1) {
alert("格式有误");
}
text = text.replace(pair[0], pair[1]);
}
}
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
...@@ -13,10 +13,10 @@ ...@@ -13,10 +13,10 @@
<named-config name="mysql"> <named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property> <property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl"> <property name="jdbcUrl">
jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8 jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8
</property> </property>
<property name="user">root</property> <property name="user">root</property>
<property name="password">admin</property> <property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property> <property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property> <property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property> <property name="maxPoolSize">50</property>
......
### 设置###
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
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<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>();
//chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) 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<String, String>) 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<String ,String> 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<String, String> infoPoints = new HashMap<String, String>();
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<String, String> history = new HashMap<String, String>();
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
try {
Iterator<String> 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<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) 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<String ,String> infoPoint = null;
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
SqlHelper helper;
Map<String, String> infoPoints = new HashMap<String, String>();
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<String, ChatCache> chatCacheHashMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache");
chatCacheHashMap.remove(chatKey);
} catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
}
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<Integer, Condition> activatedMap = new HashMap<Integer, Condition>();
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<String,String[]> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, StringBuffer curInfoRecord){
String return_str = "", k ;
boolean debugFlag = false;
//输出所有actionName的值
Iterator<String> 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<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,HashMap<String,List<Condition>> conditionTable, ServletContext context) throws IOException {
Integer configId = 0;
List<Condition> conditionList = null;
Condition bestMatch = new Condition(-1),iterCon;
Iterator<String> it = curInfoPoint.keySet().iterator();
Queue<Condition> activatedQueue = new LinkedList<Condition>();
Queue<Condition> activatedCondition = new LinkedList<Condition>();
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<Condition> activatedQueue, Map<String,String[]> curInfoPoint,Map<String,String> 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<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,Condition condition){
boolean flag = true;
String actionName,keywords[],keyword,comparePair[],cmpType,premiseStr;
HashSet<String> keywordSet = null;
if(condition.featureMap.containsKey("match")){
Iterator<String> 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<String> 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<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Iterator<String> 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<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag){
//将当前信息点更新至历史信息点
Iterator<String> 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<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context) {
Iterator<String> it = null;
String key, values[], value;
HashSet<String> skipSet = new HashSet<String>(){
{
add("activeList");
add("currentAction");
add("lastUpdateTime");
add("bot_name");
add("action_name");
add("chat_key");
add("lastReply");
}
};
it = curInfoPoint.keySet().iterator();
String debugInfo = "";
debugInfo += "<font color=\"green\">(识别:";
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 + ")</font>" + ans.getAnswer());
}
/**
* 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换)
* @param ans 返回给用户的数据
* @param ansCondition 满足条件最多的condition(配置文件的某一行)
*/
public Solution postToServer(Solution ans, Condition ansCondition, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint) throws IOException {
String url = null,elem[], subElem[], key, postType = "all";
Map<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> 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<String> 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<String,String[]> curInfoPoint, Map<String,String> 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<String,String> historyInfoPoint) throws ParseException {
String keyword, variableName, updateValue;
Iterator<String> 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<Condition> 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<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Queue<Condition> activatedQueue = new LinkedList<Condition>();
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;
}
}
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<Integer, Condition> activatedMap = new HashMap<Integer, Condition>();
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<String ,String> curInfoPoint = null;
public Map<String ,String> historyInfoPoint = null;
public WorldController worldController = null;
BasicBotUtil botUtil = null;
public QuestionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> 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<String, List<Condition>> conditionTable, ServletContext context, UserInfo userInfo) throws IOException {
Integer configId = 0;
List<Condition> conditionList = null;
Condition bestMatch = new Condition(-1), iterCon;
Iterator<String> it = curInfoPoint.keySet().iterator();
Queue<Condition> activatedQueue = new LinkedList<Condition>();
Queue<Condition> activatedCondition = new LinkedList<Condition>();
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<Condition> 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<String> keywordSet = null;
logWriter.record("-----------------------------------检索到配置条目", 0);
logWriter.record(userinfo.id2config.get(condition.id), 1);
if (condition.featureMap.containsKey("match")) {
Iterator<String> 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<String> 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<String> 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<String> 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("处理完成后的信息点:<br>" + historyInfoPoint.toString(), 1);
HashSet<String> skipSet = new HashSet<String>() {
{
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<String> it = null;
String key, values, value;
HashSet<String> skipSet = new HashSet<String>() {
{
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 += "<font color=\"green\">(识别:";
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 + ")</font>" + 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<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> k_iter = null;
FormsPoster poster = new FormsPoster(logWriter);
HashSet<String> skipSet = new HashSet<String>() {
{
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<String> 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<Condition> 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<Condition> originConditionList = new ArrayList<Condition>();
for (String configIdStr : activateList.split(",")) {
logWriter.record("------激活-------" + configIdStr + "-------<br>", 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<Condition> activatedQueue = new LinkedList<Condition>();
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;
}
}
//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<String ,String> curInfoPoint, Map<String ,String> 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<String> unknownList = new ArrayList<String>();
//
// 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<String> finalUnknownList = new ArrayList<String>();
//
//
// 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<String ,String> curInfoPoint, Map<String ,String> 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<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){
//
// List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
// String npc = "";
// List<String> filtedNpcList = new ArrayList<String>();
//
// 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<String, String> historyInfoPoint){
// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
// }
// static Boolean isOnlineText(String text, Map<String, String> 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;
// }
// }
//
//}
//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<String ,String> curInfoPoint, Map<String ,String> 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<String> unknownList = new ArrayList<String>();
//
// 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<String> finalUnknownList = new ArrayList<String>();
//
//
// 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<String ,String> curInfoPoint, Map<String ,String> 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<String ,String> 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<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){
//
// List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
// String npc = "";
// List<String> filtedNpcList = new ArrayList<String>();
//
// 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<String, String> historyInfoPoint){
// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
// }
//
// public static String findPlotLastTalker(String text, String site, Map<String, String> 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;
// }
//
//}
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<BasicNameValuePair> 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<String> strList){
String reply;
int randNum = (int) (Math.random() * strList.size());
reply = strList.get(randNum);
return reply;
}
}
\ No newline at end of file
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<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj;
Iterator<String> 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();
}
}
}
}
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<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj;
Iterator<String> 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();
}
}
}
}
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","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
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 {
}
}
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","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
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 {
}
}
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<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext();
String botAccount = request.getParameter("botAccount");
UserInfo userinfo = new UserInfo(botAccount);
userinfo.conditionTable = new HashMap<String, List<Action>>();
List<Action> actionList = null;
HashSet<String> 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<Action>();
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","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
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 {
}
}
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");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment