Commit dff6f518 by hxw

添加配置文件

parent 89d80ae8
test_var=1111
qa_url=http://192.168.1.78:59000/game
cc_url=http://localhost:8070/api/update/data
//condition_backend=http://192.168.1.82
unknown_text=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧
location_hint=请到%s
game_start_hint=请说开始剧情或者继续剧情
game_module_error=游戏模块出错
# -------------------------------游戏生成---------------------------
delete_old_config_term_error=删除旧数据config失败
delete_old_variable_error=删除旧变量失败
delete_old_category_error=删除旧类别失败
# ----------------------------------------------------------------
unknown_text_description=对于无法识别的问题做出的回答
game_step_description=QA问答游戏进度
star_plot_not_exist=开始剧情不存在,请到剧情列表设置
助手对应的变量
assistant=globalVariable_智能助手
# ------------------------助手情绪--------------
assistant_emotion=正常
talker_pattern=【%s@%s】
# ----------------------------------------------
game_step_format=%s_plot_%s
# ----------------------剧情进度标识-----------------
task_line=任务线_%s进度
task_condition=任务线%s最后一个condition
task_reply=任务线%s最后的回答
plot_status=剧情%s状态
# ---------------------------------------------------
plot_generation_error=剧情接口处理出现异常
默认condition
default_condition=yaobuyao
script_not_exist=话术不存在
goto_condition=yaobuyao
#-------------------话术------------------------
nothing_found=什么都没有
dont_found=没有找到
nowhere_can_go=没有地方可以去了
attribute_hidden=不能看到哦
attr_value_slot=[属性值]
attr_name_slot=[属性名]
npc_name_slot=[人名]
npc_list_slot=[人物列表]
site_slot=[地点名]
site_slot2=[地点]
site_list_slot=[地点列表]
item_list_slot=[物品列表]
item_name_slot=[物品名]
npc_item_list_slot=[人物物品列表]
can_go_site_slot=[可去列表]
path_slot=[途径]
start_slot=
destination_slot=[目的地]
task_description_slot=[任务描述]"
find_item_owner=[物品名]在[人名]身上
#----------------------------------------------
# ---------------------文本解析---------------------
text_parse_error=文本解析出错
automatch_threshold=0.5
game_condition_category=97
service_url=http://192.168.1.178:8081/bot/dialog
options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat
automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train
idlelimit=180000
condition_generate_url=http://192.168.1.178:1111/conditionProcess
condition_backend_url=http://192.168.1.82:6636/api
style=interrupt,multimatchvalues,bothvalue
fellow=pivot_httppost
post_style1=style=httppost,bothvalue,multimatchvalues
post_style2=style=httppost,multimatchvalues
post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s
# ----------------------condition增删改查异常----------------------------
update_keyword_error=更新关键词单元失败
delete_user_data_error=删除用户数据失败
game_condition_category_id=123
platform_sql_init_error=新平台获取sql连接失败
\ No newline at end of file
#!/bin/bash
mvn clean package -Ppro -Dmaven.test.skip=true
cd target
scp my-app.jar hz1:visualkm/chatbot-backend
cd ..
{"gameStart":[{"conditionName":"start_options","plotText":"请说开始剧情或者继续剧情","id":"start1","place":"加载","branch":[{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"重新开始"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"newGame","nextPlotId":"startId",},{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"+开始+开始游戏+继续游戏+继续"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"loadLastArchive","nextPlotId":"startId",},{"curPremise":[{"conditionName":"load_game_by_site","cmpType":"match","operator":"Include","keyword":"site_list"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"loadArchiveBySite","nextPlotId":"startId"},{"curPremise":[],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{},"nextPlotId":"start1",},{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"+存档列表"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"extraFeature":"sendArchiveList","moveWithPlot":false,"updateKnowledge":{},"nextPlotId":"start1",}]}]}
\ No newline at end of file
# ------------------------------------------------------------------------------
# 格式
# 意图|语义关系名字|关键词
# name表示可以替换的名字,如物品名、角色名
# attrName是属性名
# qiwu就是玩家“我”
# ------------------------------------------------------------------------------
# 我在哪里
WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方
WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu+哪:landey+地方:landey+位置:landey+地点:landey+哪里:landey+哪儿:landey
# 我能去哪里
WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu+哪:到+哪儿:到+哪里:到
# 周围有什么人
AROUND_NPC|know_exist_what|+周围:人+旁边:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人+附近:谁+有:附近+旁边:谁
AROUND_NPC|zhiwen|+这里:谁+这里:谁+谁:在
# 周围有什么npc类别
AROUND_NPC_CLASS|know_exist_what|+周围:name+附近:name
# 周围有什么
AROUND_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面+有什么:旁边+qiwu:旁边+有什么:这里+有:哪些
# 周围有什么物品
AROUND_ITEM|know_exist_what|+周围:物品+旁边:物品+旁边:东西+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西+有:东西+里面:物品
AROUND_ITEM|nums|+有:哪些
# AROUND_ITEM|zhiwen|+附近:who+周围:who+旁边:who
# 周围有什么地方
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:地方
WHAT_ITEM_I_HAVE|know_exist_what|有什么:东西
WHAT_ITEM_I_HAVE|zhiwen|+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:任务
TASK_IS_WHAT|zhiwen|+qiwu:要去
# npc在哪里
NPC_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name
# 物品在哪里
ITEM_LOCATION|wenzainali|+哪里:name+哪: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|+去:name
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>chatbot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>chatbot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<finalName>my-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Xmx64m</jvmArguments>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!--资源根目录排除各环境的配置,防止在生成目录中多余其它目录-->
<excludes>
<exclude>test/*</exclude>
<exclude>pro/*</exclude>
<exclude>dev/*</exclude>
</excludes>
<includes>
<include>*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
</resource>
</resources>
</build>
<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>pro</id>
<properties>
<profiles.active>pro</profiles.active>
<activatedProperties>pro</activatedProperties>
</properties>
</profile>
</profiles>
</project>
package com.qiwu.chatbotbackend.Config;
import org.springframework.stereotype.Component;
@Component
public class Config {
public static String TEXT_PARSE_ERROR = null;
public static String CONDITION_URL = null;
public static String TEST_VAR = null;
public static String QA_URL = null;
public static String CC_URL = null;
public static String UNKNOWN_TEXT = null;
public static String LOCATION_HINT = null;
public static String GAME_START_HINT = null;
public static String GAME_MODULE_ERROR = null;
public static String DELETE_OLD_CONFIG_TERM_ERROR = null;
public static String DELETE_OLD_VARIABLE_ERROR = null;
public static String DELETE_OLD_CATEGORY_ERROR = null;
public static String UNKNOWN_TEXT_DESCRIPTION = null;
public static String GAME_STEP_DESCRIPTION = null;
public static String START_PLOT_NOT_EXIST = null;
public static String ASSISTANT = null;
public static String ASSISTANT_EMOTION = null;
public static String TASK_DESCRIPTION = null;
public static String TALKER_PATTERN = null;
public static String GAME_STEP_FORMAT = null;
public static String PLOT_STATUS = null;
public static String TASK_LINE = null;
public static String TASK_CONDITION = null;
public static String TASK_REPLY = null;
public static String PLOT_GENERATION_ERROR = null;
//默认condition
public static String DEFAULT_CONDITION = null;
//去xx地方condition
public static String GOTO_CONDITION = null;
public static class Script {
public static String CODE = "subcode";
public static int SIZE = 12;
};
public static String POST_ACTION_ERROR = null;
public static String TOKEN_TIME_OUT = null;
public static String ENCODE_ERROR = null;
//话术
public static String NOTHING_FOUND = null;
public static String DONT_FOUND = null;
public static String NOWHERE_CAN_GO = null;
public static String ATTRIBUTE_HIDDEN = null;
public static String ATTR_VALUE_SLOT = null;
public static String ATTR_NAME_SLOT = null;
public static String NPC_NAME_SLOT = null;
public static String NPC_LIST_SLOT = null;
public static String SITE_SLOT = null;
public static String SITE_SLOT2 = null;
public static String ITEM_LIST_SLOT = null;
public static String ITEM_NAME_SLOT = null;
public static String NPC_ITEM_LIST_SLOT = null;
public static String CAN_GO_SITE_SLOT = null;
public static String PATH_SLOT = null;
public static String START_SLOT = null;
public static String DESTINATION_SLOT = null;
public static String SITE_LIST_SLOT = null;
public static String TASK_DESCRIPTION_SLOT = null;
public static String FIND_ITEM_OWNER = null;
//生成action
public static String GAME_CONDITION_CATEGORY = null;
public static String AUTOMATCH_THRESHOLD = null;
public static String IDLE_LIMIT = null;
public static String CONDITION_BACKEND_URL = null;
public static String CONDITION_GENERATE_URL= null;
public static String OPTIONS = null;
public static String STYLE = null;
public static String AUTOMATCH_URL = null;
public static String SERVICE_URL = null;
public static String FELLOW = null;
public static String POST_STYLE1 = null;
public static String POST_STYLE2 = null;
public static String POST_ACTION_HEAD=null;
//condition增删改查异常
public static String UPDATE_KEYWORD_ERROR = null;
public static String DELETE_USER_DATA_ERROR = null;
}
package com.qiwu.chatbotbackend.Config;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Properties;
import java.util.Set;
public class ConfigInitializer {
private static final String CONFIGFILE = "config.properties";
private static final String CLASSPREFIX = "com.qiwu.chatbotbackend.config.config";
/**
* 读取配置文件
*/
public static void init() {
InputStream configInputStream;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(CONFIGFILE));
Properties properties = new Properties();
properties.load(bufferedReader);
initNextLevel(properties, Config.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static void initNextLevel(Properties properties, Class nowClass) throws IllegalAccessException {
String baseClassName = nowClass.getName().toLowerCase().replaceAll("\\$", "\\.");
String shortName = baseClassName.replaceAll(CLASSPREFIX, "").replaceFirst("\\.", "");
//key集合
Set<Object> keys = properties.keySet();
for (Field field : nowClass.getFields()) {
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String classParam = field.getName().toLowerCase();
if (shortName.equals("")) {
if (keys.contains(classParam)) {
pushNewValue(classParam, properties, field);
}
} else {
if (keys.contains(shortName + "." + classParam)) {
pushNewValue(shortName + "." + classParam, properties, field);
}
}
}
}
for (Class<?> aClass : nowClass.getClasses()) {
initNextLevel(properties, aClass);
}
}
public static void pushNewValue(String classParam, Properties properties, Field field) throws IllegalAccessException {
String value = properties.getProperty(classParam);
if (value != null) {
Class<?> type = field.getType();
if (type.equals(int.class))
field.set(null, Integer.valueOf(value));
else if (type.equals(String.class))
field.set(null, value);
else if (type.equals(long.class))
field.set(null, Long.valueOf(value));
else if (type.equals(boolean.class))
field.set(null, Boolean.valueOf(value));
else if (type.isEnum())
field.set(null, Enum.valueOf((Class<Enum>) type, value.toUpperCase()));
}
}
}
......@@ -14,6 +14,8 @@ public class C3p0Utils {
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("mysql2");
//从连接池中取用一个连接
public static Connection getConnection() throws SQLException {
......@@ -26,6 +28,17 @@ public class C3p0Utils {
}
}
//从连接池中取用一个连接
public static Connection getEngineConnection() throws SQLException {
try {
return dataSource2.getConnection();
} catch (Exception e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
//释放连接回连接池
public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
if (rs != null) {
......
......@@ -31,6 +31,7 @@ public class Action {
//this.activePriority = priority;
}
/**
*
* @param originAction 这个action的初始状态
......@@ -50,15 +51,17 @@ public class Action {
this.id = originAction.id;
this.configName = originAction.configName;
this.status = originAction.status;
//this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级
this.priority = originAction.priority + basePriority + 1;
this.priority = originAction.priority + basePriority + 1; //如果激活的配置没有条件
//如果激活originAction的action,它的辅助优先级高于originAction,那么。。
if(baseAuxiliaryPriority > originAction.auxiliaryPriority)
this.auxiliaryPriority = baseAuxiliaryPriority;
else
this.auxiliaryPriority = originAction.auxiliaryPriority;
this.auxiliaryPriority = originAction.auxiliaryPriority + baseAuxiliaryPriority; //优先级为两者之和
// //如果激活originAction的action,它的辅助优先级高于originAction,那么。。
// if(baseAuxiliaryPriority > originAction.auxiliaryPriority)
// this.auxiliaryPriority = baseAuxiliaryPriority;
// else
// this.auxiliaryPriority = originAction.auxiliaryPriority;
//
// this.auxiliaryPriority = this.getAuxiliaryPriority() + 1;
}
public Action() {
......
......@@ -92,25 +92,29 @@ public class ChatCache implements DisposableBean {
public void destroy() throws IOException {
}
public ChatCache(UserInfo userInfo, String userKey, String randKey) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount);
} catch (Exception e) {
System.out.println(ENV_ERROR);
infoPoint.put("error_message", ENV_ERROR);
e.printStackTrace();
public ChatCache(UserInfo userInfo, String userKey, String randKey, String botType) throws Exception {
if(botType.equals("game")) {
try {
this.gameEnv = new GameEnv(userInfo.botAccount);
System.out.println("初始化时:" + this.gameEnv);
} catch (Exception e) {
System.out.println(ENV_ERROR);
this.infoPoint.put("error_message", ENV_ERROR);
e.printStackTrace();
}
}
String k;
this.botAccount = userInfo.botAccount;
infoPoint = new HashMap<String, String>();
this.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));
this.infoPoint.put(k, userInfo.varInitialMap.get(k));
}
infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
this.infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
this.randKey = randKey;
this.userKey = userKey;
......
......@@ -3,7 +3,7 @@ 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.ConfigTerm;
import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*;
......@@ -19,8 +19,7 @@ public class ElementConstructor {
Map<String, StringBuffer> keywordMap = null;
SqlHelper helper = null;
HashSet<String> exceptRelation = null;
ConfigTerm configTerm = null;
String CHITCHAT_URL = "http:192.168.1.178:1111/test";
ConfigTermText configTermText = null;
String botAccount;
......@@ -29,7 +28,7 @@ public class ElementConstructor {
List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>();
List<ConfigTermText> configTermTextList = new ArrayList<ConfigTermText>();
StringBuffer configText = new StringBuffer();
Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>();
......@@ -46,8 +45,8 @@ public class ElementConstructor {
public void construct(JSONObject gameElements, UserInfo userinfo) { }
public List<ConfigTerm> getConfigTermList() {
return configTermList;
public List<ConfigTermText> getConfigTermTextList() {
return configTermTextList;
}
public Map<String, String> getConditionDescription() {
......@@ -66,16 +65,19 @@ public class ElementConstructor {
return configText.toString();
}
//生成完整的后台配置文件
public void generateConfigText(List<Integer> idList) {
int id, length = idList.size();
String varValue;
ConfigTerm configTerm = null;
ConfigTermText configTermText = null;
for (int i = 0; i < length; i++) {
configTerm = configTermList.get(i);
configTermText = configTermTextList.get(i);
id = idList.get(i);
configText.append(configTerm.toString() + id + "\n");
configText.append(configTermText.toString() + id + "\n");
}
//变量
for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n");
......@@ -83,6 +85,14 @@ public class ElementConstructor {
}
/**
* 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition
* @param config
* @param relationKeywords
* @param exceptRelation
* @param botName
*/
public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation, String botName){
String conditionName, pair[];
for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){
......@@ -92,11 +102,13 @@ public class ElementConstructor {
if(!exceptRelation.contains(conditionName)) {
//初始化
if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>());
}
//visitorname和bot的替换
premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname"));
for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
......@@ -106,6 +118,7 @@ public class ElementConstructor {
} else if(keyword.contains(":")){
//有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域
pair = keyword.split(":",2);
if(pair[1].equals(""))
......@@ -133,6 +146,7 @@ public class ElementConstructor {
if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>());
......@@ -189,4 +203,57 @@ public class ElementConstructor {
}
}
public void queryTypeConfigTermGenerate(Map<String, StringBuffer> keywordMap, String intent, String module, String queryMethod){
String conditionKeywords = "";
String conditionNameList[] = keywordMap.get(intent).toString().split(",");
for (String conditionName : conditionNameList) {
conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString();
configTermText = new ConfigTermText(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0",
"",
" ",
module + "_query:" + queryMethod + ":" + conditionName
);
//ConfigTermText.activateCopy(configTermText, configTermTextList, module);
//查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTermText.setConfigName(module, true);
configTermTextList.add(configTermText);
}
}
/**
* 将condition的关键词复制一份,然后清空原来关键词
* @param intent
*/
public void copyPattern(String intent){
for(String conditionName:keywordMap.get(intent).toString().split(",")){
keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName)));
keywordMap.get(intent + "_" + conditionName).setLength(0);
}
}
public void appendReplacedKeyword(String intent, List<String[]> replaceList){
String pattern, replaceText;
for(String conditionName:keywordMap.get(intent).toString().split(",")){
pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString();
for(String[] replacePair: replaceList){
pattern = pattern.replace(replacePair[0], replacePair[1]);
}
keywordMap.get(intent + "_" + conditionName).append(pattern);
}
}
}
......@@ -8,6 +8,8 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import static com.qiwu.chatbotbackend.Config.Config.CC_URL;
public class GlobalVariableConstructor extends ElementConstructor {
public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
......@@ -40,7 +42,7 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put("botType", "game");
varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList"));
varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText"));
varInitialMap.put("CC_URL", keywordMap.get("CC_URL").toString());
varInitialMap.put("CC_URL", CC_URL);
JSONObject script = gameElements.getJSONObject("speechcraft");
......
......@@ -3,13 +3,13 @@ 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.ConfigTerm;
import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*;
import static com.qiwu.chatbotbackend.Config.Config.*;
public class ListeningConstructor extends ElementConstructor{
......@@ -30,7 +30,7 @@ public class ListeningConstructor extends ElementConstructor{
}
public static void cc(String botAccount, JSONObject gameELments, HashMap<String, JSONObject> plotIndex, List<ConfigTerm> configTermList){
public static void cc(String botAccount, JSONObject gameELments, HashMap<String, JSONObject> plotIndex, List<ConfigTermText> configTermTextList){
int size = 0;
String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority;
String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep;
......@@ -70,7 +70,7 @@ public class ListeningConstructor extends ElementConstructor{
if(nextCondition == null || nextCondition.equals("")){
nextCondition = "yaobuyao";
nextCondition = DEFAULT_CONDITION;
}
if(autoJump){
......@@ -108,7 +108,7 @@ public class ListeningConstructor extends ElementConstructor{
feature = "match,return-0";
}
ConfigTerm configTerm = new ConfigTerm(
ConfigTermText configTermText = new ConfigTermText(
curPremiseList,
hisPremiseList,
updateKnowledge,
......@@ -116,7 +116,7 @@ public class ListeningConstructor extends ElementConstructor{
);
System.out.println("生成:" + curPremiseList.get(0));
configTermList.add(configTerm);
configTermTextList.add(configTermText);
}
}
......
......@@ -24,8 +24,6 @@ public class ActionMatcher {
static String API_ERROR = "api处理过程中出错了";
public LogWriter logWriter = null;
public UserInfo userinfo = null;
public ServletContext context = null;
......@@ -35,15 +33,18 @@ public class ActionMatcher {
public WorldController worldController = null;
BasicBotUtil botUtil = null;
public ActionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) {
public ActionMatcher(Map<String ,String> curInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, BasicBotUtil botUtil) {
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.historyInfoPoint = botUtil.getChatCache().getInfoPoint();
this.logWriter = logWriter;
this.userinfo = userinfo;
this.context = context;
this.gameEnv = gameEnv;
this.worldController = new WorldController(logWriter, userinfo);
this.botUtil = botUtil;
if(botUtil.botType.equals("game")) {
this.gameEnv = botUtil.getChatCache().getGameEnv();
}
}
......@@ -53,7 +54,6 @@ public class ActionMatcher {
/**
* 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch
*
......@@ -235,7 +235,7 @@ public class ActionMatcher {
//没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过
if(!activateFlag && !replaceFlag && !parentFlag) {
logWriter.record("-----------------------------------优先级不足,跳过", 0);
logWriter.record(userinfo.id2config.get(action.getId()), 1);
//logWriter.record(userinfo.id2config.get(action.getId()), 1);
continue;
}
......@@ -253,33 +253,6 @@ public class ActionMatcher {
// //当前condition的辅助优先级高于bestMatch、或者优先级已知添加数量更多、或者
// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)
// || action.featureMap.get("activate") != null
// || bestMatch.nextStep.contains(String.valueOf(action.id)) || (!action.configName.equals("") && bestMatch.nextStep.contains(action.configName.substring(0,3)))){
// //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。
// if(conditionSatisfy(action)){
//
// //有激活配置文件,但是没有post提交表单,则激活,如果有post就放到提交表单之后激活(postActivate)
// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) {
// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context);
// }
//
// bestMatch = action;
// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2);
// logWriter.writeln();
//
// }
//
// } else {
// logWriter.record("-----------------------------------优先级不足,跳过", 0);
// logWriter.record(userinfo.id2config.get(action.id), 1);
// }
}
return bestMatch;
......@@ -887,7 +860,8 @@ public class ActionMatcher {
}else if(postType.equals("term")){
poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url);
}else if(postType.equals("gameQA")){
poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo);
System.out.println("提交表单" + gameEnv);
poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo);
}
return ans;
......
......@@ -30,7 +30,7 @@ public class ChatCacheController {
private static String ENV_POSTFIX = "-env.data";
private static String INFO_POSTFIX = "-info.data";
public static String COMBINE_PUNC1 = "@@@";
public static String COMBINE_PUNC1 = "@@@"; //chatKey的连接符 chatKey格式为 用户名@@@bot账号@@@@随机码
public static String COMBINE_PUNC2 = "@@@@";
......@@ -41,7 +41,7 @@ public class ChatCacheController {
*
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
......@@ -60,7 +60,7 @@ public class ChatCacheController {
//如果用户之前没有玩过或者有一段时间没有玩
if(chatCache == null){
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCache = new ChatCache(userinfo, userKey, randKey, botType);
chatCacheMap.put(userKey, chatCache);
//用户几分钟前还在玩
} else {
......@@ -69,7 +69,7 @@ public class ChatCacheController {
if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) {
ChatCacheController.saveChatCache(chatCache, null);
}
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCache = new ChatCache(userinfo, userKey, randKey, botType);
chatCacheMap.put(userKey, chatCache);
}
}
......@@ -79,9 +79,10 @@ public class ChatCacheController {
e.printStackTrace();
//chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
//chatCacheMap.put(userKey, chatCache);
}
System.out.println(chatCache.getGameEnv());
return chatCache;
}
......@@ -235,12 +236,13 @@ public class ChatCacheController {
/**
* 根据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()));
public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) {
chatCache.getInfoPoint().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);
keyCacheMap.put(chatCache.getUserKey(), chatCache);
//ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey"));
//chatCache.setInfoPoint(historyInfoPoint);
//chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap);
}
......
package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId);
Condition condition = new Condition();
UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
String conditionName = "";
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userInfo = (UserInfo) context.getAttribute(userName);
if (userInfo.id2config.containsKey(id)) {
Condition oldCondition = userInfo.id2condition.get(id);
//-------------------
try {
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == id) {
condIter.remove();
}
}
}
userInfo.name2condition.remove(oldCondition.configName);
userInfo.id2config.remove(id);
userInfo.id2condition.remove(id);
} else {
System.out.println("未找到要删除的configId");
}
return true;
}
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition();
String conditionName = "";
for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) {
Condition oldCondition = userInfo.id2condition.get(configId);
try {
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == configId) {
condIter.remove();
}
}
}
userInfo.name2condition.remove(oldCondition.configName);
userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId);
} else {
System.out.println("未找到要删除的configId:" + configId);
}
}
return true;
}
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[];
UserInfoController userInfoController = new UserInfoController();
int id = Integer.parseInt(configId);
condition = userInfoController.buildCondition(condition, configLine);
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.conditionTable.get(condition.indexName) == null) {
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(condition.indexName, conditionList);
}
if(!condition.configName.equals("")){
userinfo.name2condition.put(condition.configName, condition);
}
userinfo.conditionTable.get(condition.indexName).add(condition);
userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, condition);
return true;
}
public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---", -1);
String name = dataPair[0], value = dataPair[1];
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.put(name, value);
return true;
}
public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException {
//data=configLine+"---"+conditionNameList
String name = data;
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.remove(name);
return true;
}
public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
return true;
}
public static String writeConfigText(String userName, UserInfo userinfo) throws IOException {
String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText;
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir") + "/config");
System.out.println(userName);
System.out.println("config_dir" + dir.getAbsolutePath());
String returnMessage = "success";
if (!dir.exists())
dir.mkdir();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if (!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
keyIter = userinfo.varInitialMap.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n");
}
Iterator<Integer> idIter = userinfo.id2config.keySet().iterator();
while (idIter.hasNext()) {
int id = idIter.next();
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
} catch (Exception e) {
e.printStackTrace();
returnMessage = "config file write error";
} finally {
bw.close();
fw.close();
}
return returnMessage;
}
}
......@@ -253,6 +253,9 @@ public class FormsPoster {
if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){
postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo);
}
// historyInfoPoint.put("common_answer", "【旁白@%正常】QA暂时关闭");
// historyInfoPoint.put("qa_score", "99");
// historyInfoPoint.put("qa_status", "OK");
}
......
......@@ -134,12 +134,12 @@ public class SimpleUtil {
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());
......
......@@ -8,12 +8,15 @@ import java.io.*;
import java.sql.SQLException;
import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR;
public class UserInfoController {
static String CONFIG_DIR = System.getProperty("user.dir") + "/config";
static String FILE_ERROR = ".txt文件有误";
/**
* 根据本地配置文件生成用户信息
*/
......@@ -82,6 +85,12 @@ public class UserInfoController {
}
/**
* 解析一行配置文件
* @param action
* @param line
* @return
*/
public static Action buildCondition(Action action, String line) {
String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[];
......@@ -90,8 +99,6 @@ public class UserInfoController {
text = line.split("---");
if (line.startsWith("yaobuyao::match-Keyword=+海边|game_step::match-Include=9826795627_plot_1-2,1-2::number-BiggerOrEqual=1|match,updateKnowledge-<-unknownText:-<-site:武器库-<--<-game_step:9826795627_plot_1-5-<-unknownText:还没到下一个地点-<-site:武器库-<-npc_update:updateFollowerLocation:武"))
System.out.println("xxx");
line = text[0];
if(text.length > 1 && text[1].startsWith("<-"))
line += "---" + text[1];
......@@ -102,10 +109,14 @@ public class UserInfoController {
cur_premises = premises[0].split(",");
history_premises = premises[1].split(",");
if (premises.length < 4)
action.setAuxiliaryPriority(0);
else
action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
//action.setConfigName(premises[4].split("=", 2)[1]);
next = element[1].split("\\|");
if (next.length < 4)
return action;
if(premises.length < 5)
action.setConfigName("");
......@@ -113,11 +124,9 @@ public class UserInfoController {
action.setConfigName(premises[4].split("=", 2)[1]);
next = element[1].split("\\|");
if (next.length < 4)
return action;
//回答可以有多个,然后可随机选择一个
action.setAnswer(next[0].split("~"));
//action.nextStep = next[1];
//第二处
action.setNextStep(next[1].split("=", 2)[1]);
action.setId(Integer.parseInt(next[3].split("=")[1]));
......@@ -171,7 +180,7 @@ public class UserInfoController {
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println(line);
System.out.println("文本格式有误");
System.out.println(TEXT_PARSE_ERROR);
}
return action;
}
......@@ -235,7 +244,7 @@ public class UserInfoController {
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数据格式有误");
System.out.println(TEXT_PARSE_ERROR);
e.printStackTrace();
} catch (Exception e) {
......
......@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.*;
import com.qiwu.chatbotbackend.processing.ChatCacheController;
......@@ -21,6 +21,8 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL;
@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet {
......@@ -166,8 +168,8 @@ public class GameDesignServlet extends HttpServlet {
helper.batchInsertVariableByBotId(botId, constructor);
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for(ConfigTerm configTerm : constructor.getConfigTermList()){
json = configTerm.toJson(constructor.getConditionDescription());
for(ConfigTermText configTermText : constructor.getConfigTermTextList()){
json = configTermText.toJson(constructor.getConditionDescription());
constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName);
jsonList.add(json);
}
......@@ -296,7 +298,7 @@ public class GameDesignServlet extends HttpServlet {
userInfo.extraInfo.put("activeAction", startCondition);
try {
returnMessage = SimpleUtil.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth"));
returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
......@@ -316,7 +318,7 @@ public class GameDesignServlet extends HttpServlet {
public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){
File file = new File(path);
String line, pair[];
String line, elem[];
if(file.exists()){
FileReader reader = null;
......@@ -326,10 +328,23 @@ public class GameDesignServlet extends HttpServlet {
while ((line = br.readLine()) != null) {
if(!line.equals("") && !line.startsWith("#")){
pair = line.split("\\|", 2);
keywordsMap.put(pair[0], new StringBuffer(pair[1]));
if(!line.equals("") && !line.startsWith("#")) {
elem = line.split("\\|", 3);
//查看意图是否已经存在相关的condition,如果已经存在就append,如果不存在就初始化
if (!elem[1].equals("pattern")) {
if (keywordsMap.get(elem[0]) == null) {
keywordsMap.put(elem[0], new StringBuffer(elem[1]));
} else {
keywordsMap.get(elem[0]).append(",").append(elem[1]);
}
}
//根据意图和condition名字添加关键字
keywordsMap.put(elem[0] + "_" + elem[1], new StringBuffer(elem[2]));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
......
......@@ -21,6 +21,9 @@ import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
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"})
public class GetAnswerServlet extends HttpServlet {
......@@ -36,7 +39,7 @@ public class GetAnswerServlet extends HttpServlet {
request.setCharacterEncoding("UTF-8");
Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap());
Map<String ,String> curInfoPoint = new HashMap<String, String>();
Map<String, String> historyInfoPoint = null;
//Map<String, String> historyInfoPoint = null;
Solution bestMatch = null;
BasicBotUtil botUtil = null;
Action ansAction = null;
......@@ -49,7 +52,7 @@ public class GetAnswerServlet extends HttpServlet {
//如果有client_id,会用@分隔
chatKey = receiveParamters.get("chat_key")[0];
String chatKeys[] = receiveParamters.get("chat_key")[0].split("@@@@");
String chatKeys[] = receiveParamters.get("chat_key")[0].split(COMBINE_PUNC2);
if(chatKeys.length == 1){
userKey = chatKeys[0];
randKey = chatKeys[0];
......@@ -83,12 +86,20 @@ public class GetAnswerServlet extends HttpServlet {
//获得用户历史信息
ChatCache chatCache = null;
Boolean loadCacheStatus = Boolean.valueOf(false);
if(userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType");
try {
chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType);
if(chatCache == null){
throw(new Exception("chatCache初始化失败"));
}
} catch (Exception e) {
System.out.println(e.getMessage());
//e.printStackTrace();
}
/**
......@@ -96,19 +107,18 @@ public class GetAnswerServlet extends HttpServlet {
* 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据
*/
historyInfoPoint = chatCache.getInfoPoint();
//historyInfoPoint = chatCache.getInfoPoint();
if(userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType");
switch(botType){
case "game":
WorldController worldController = new WorldController(logWriter,userinfo);
botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv(), chatCache);
botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController);
break;
default:
botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter);
botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter);
break;
}
......@@ -117,10 +127,10 @@ public class GetAnswerServlet extends HttpServlet {
//信息点预处理
ActionMatcher matcher = new ActionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil);
ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
/*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/
ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansAction.getPriority()== -1)
state = "我不理解,";
......@@ -129,24 +139,31 @@ public class GetAnswerServlet extends HttpServlet {
bestMatch = matcher.getSolution(ansAction, context, userinfo);
//读档成功不应该再激活
//if(matcher.)
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
if(!botUtil.getChatCache().getReload()) {
//读档成功不应该再激活
//if(matcher.)
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
}
}else{
//跳过
botUtil.getChatCache().setReload(false); //清楚标识
}
} catch (ParseException e) {
e.printStackTrace();
}
} else {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction"));
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction"));
}
//针对不同游戏类型做后处理
//针对不同bot类型做后处理
botUtil.postprocessing(chatKey, context, bestMatch);
historyInfoPoint.put("lastReply", bestMatch.getAnswer());
botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer());
if (debugFlag) {
matcher.appendDebugInfo(bestMatch, context);
}
......@@ -156,7 +173,7 @@ public class GetAnswerServlet extends HttpServlet {
matcher.infoTransfer(bestMatch, context, debugFlag);
ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo);
ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo);
//清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
......@@ -172,6 +189,8 @@ public class GetAnswerServlet extends HttpServlet {
ansJ = "找不到配置文件";
}
System.out.println(TEST_VAR);
logWriter.writeln();
......
package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.entity.Action;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.LogWriter;
......@@ -15,19 +16,23 @@ import java.util.regex.Pattern;
public class BasicBotUtil {
Map<String, String> curInfoPoint = null;
Map<String, String> historyInfoPoint = null;
UserInfo userinfo = null;
LogWriter logWriter = null;
ChatCache chatCache = null;
public String botType = "basic";
public ChatCache getChatCache() {
return chatCache;
}
public BasicBotUtil(){};
public BasicBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter){
public BasicBotUtil(Map<String, String> curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter){
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.userinfo = userinfo;
this.logWriter = logWriter;
this.chatCache = chatCache;
}
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
......@@ -36,7 +41,6 @@ public class BasicBotUtil {
}
//在接收到请求后对数据做处理,转化为系统可以处理的数据
/**
......@@ -104,18 +108,18 @@ public class BasicBotUtil {
}
String currentAction = "";
if (historyInfoPoint.containsKey("currentAction"))
currentAction = historyInfoPoint.get("currentAction");
if (chatCache.getInfoPoint().containsKey("currentAction"))
currentAction = chatCache.getInfoPoint().get("currentAction");
else if (userinfo.extraInfo.containsKey("activeAction")) {
currentAction = userinfo.extraInfo.get("activeAction");
historyInfoPoint.put("currentAction", currentAction);
chatCache.getInfoPoint().put("currentAction", currentAction);
} else
currentAction = " ";
curInfoPoint.put("emptySet", " ");
if (historyInfoPoint.get("activeList") == null) {
historyInfoPoint.put("activeList", currentAction);
if (chatCache.getInfoPoint().get("activeList") == null) {
chatCache.getInfoPoint().put("activeList", currentAction);
}
if (unknown_flag && !currentAction.equals("")) {
......@@ -123,7 +127,7 @@ public class BasicBotUtil {
curInfoPoint.put(currentAction, i);
}
logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1);
logWriter.record("historyInfoPoint:" + chatCache.getInfoPoint().toString(), 1);
......@@ -131,8 +135,8 @@ public class BasicBotUtil {
}
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
if(historyInfoPoint.get("error_message") != null && historyInfoPoint.get("error_message") != ""){
bestMatch.setAnswer(bestMatch.getAnswer() + historyInfoPoint.get("error_message"));
if(chatCache.getInfoPoint().get("error_message") != null && chatCache.getInfoPoint().get("error_message") != ""){
bestMatch.setAnswer(bestMatch.getAnswer() + chatCache.getInfoPoint().get("error_message"));
}
......@@ -172,7 +176,7 @@ public class BasicBotUtil {
* @param updateValue
*/
public void putKeyword(String variableName, String updateValue){
historyInfoPoint.put(variableName, updateValue);
chatCache.getInfoPoint().put(variableName, updateValue);
}
public String knowledgeProcess(String variableName, String updateValue){
......@@ -209,11 +213,11 @@ public class BasicBotUtil {
reply = reply.replace("{" + variable + "-1}", keyword);
}
} else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null)
if(historyInfoPoint.get(variable).equals("do_reset")){
if (chatCache.getInfoPoint().get(variable) != null)
if(chatCache.getInfoPoint().get(variable).equals("do_reset")){
reply = reply.replace("{" + variable + "-2}", "");
}else
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
reply = reply.replace("{" + variable + "-2}", chatCache.getInfoPoint().get(variable));
}
}
......
package com.qiwu.chatbotbackend.task.utils;
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.task.utils;
import com.qiwu.chatbotbackend.Config.ConfigInitializer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ContextInitialListener implements ServletContextListener {
String CONFIG_DIR = "config.txt";
/**
* 在程序初始化时,从配置文件中加载数据
* @param sce
*/
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Initial context....");
//Config config = new Config();
ConfigInitializer.init();
}
}
......@@ -5,18 +5,17 @@ import com.qiwu.chatbotbackend.processing.SimpleUtil;
import java.io.UnsupportedEncodingException;
import static com.qiwu.chatbotbackend.Config.Config.CC_URL;
public class DataDeliver extends Thread {
JSONObject data = null;
String url = "";
String url = CC_URL;
public void setData(JSONObject data) {
this.data = data;
}
public void setUrl(String url) {
this.url = url;
}
......@@ -25,7 +24,7 @@ public class DataDeliver extends Thread {
System.out.println("线程开始");
System.out.println(url);
try {
SimpleUtil.postJSON(url, data, null);
SimpleUtil.postJSON(CC_URL, data, null);
System.out.println("线程完成");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
......
......@@ -7,6 +7,8 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC1;
/**
* 实现一个支持通配符的基于广度优先算法的文件查找器
*/
......@@ -88,7 +90,7 @@ public class FileFinder {
public static boolean deleteGameArchive(String baseDirName, String botAccount){
String tempName;
String regEx = ".*@@@" + botAccount + "@@@@.*";
String regEx = ".*" + COMBINE_PUNC1 + botAccount + "-.*";
List fileList = new ArrayList();
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = null;
......
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