Commit db12838b by hxw

添加更新变量等功能

parent f38204e0
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<default-config> <default-config>
<property name="initialPoolSize">10</property> <property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property> <property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property> <property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property> <property name="minPoolSize">10</property>
<property name="maxStatements">200</property> <property name="maxStatements">200</property>
</default-config> </default-config>
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
<property name="password">admin</property> <property name="password">admin</property>
<property name="initialPoolSize">10</property> <property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property> <property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property> <property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property> <property name="minPoolSize">10</property>
<property name="maxStatements">200</property> <property name="maxStatements">200</property>
</named-config> </named-config>
......
...@@ -290,7 +290,7 @@ public class SqlHelper { ...@@ -290,7 +290,7 @@ public class SqlHelper {
public JSONObject queryGameElementsByBotId(int id) { public JSONObject queryGameElementsByBotId(int id) {
String sql = "select * from generate_json_tb where id = ?"; String sql = "select * from generate_json_tb where project_id = ?";
String userName = ""; String userName = "";
String result = "empty"; String result = "empty";
try { try {
...@@ -334,5 +334,35 @@ public class SqlHelper { ...@@ -334,5 +334,35 @@ public class SqlHelper {
} }
public boolean insertConfigByBotId(int botId, ElementConstructor constructor, JConfig jConfig, List<Integer> idList) {
String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
String userName = "";
String result = "empty";
ResultSet rs = null;
int id = 0;
boolean b = true;
try {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0));
ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString());
ps.setString(4, "");
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if(rs.next()){
id = rs.getInt(1);
idList.add(id);
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
} }
package entity;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ChatCache {
private Map<String, String> infoPoint = null;
private World world = null;
public Map<String, String> getInfoPoint() {
return infoPoint;
}
public void setInfoPoint(Map<String, String> infoPoint) {
this.infoPoint = infoPoint;
}
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
}
public ChatCache(Map<String, String[]> curInfoPoint, UserInfo userInfo) {
world = new World();
String k;
infoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, "");
}
//变量初始化
iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k));
}
}
}
...@@ -30,9 +30,8 @@ public class Condition { ...@@ -30,9 +30,8 @@ public class Condition {
this.activePriority = priority; this.activePriority = priority;
} }
public Condition(Condition originCondition, int basePriority) { public Condition(Condition originCondition, int basePriority, int baseAuxiliaryPriority) {
this.priority = originCondition.priority; this.priority = originCondition.priority;
this.auxiliaryPriority = originCondition.auxiliaryPriority;
this.keywordSet = originCondition.keywordSet; this.keywordSet = originCondition.keywordSet;
this.historyPremise = originCondition.historyPremise; this.historyPremise = originCondition.historyPremise;
this.currentPremise = originCondition.currentPremise; this.currentPremise = originCondition.currentPremise;
...@@ -44,6 +43,7 @@ public class Condition { ...@@ -44,6 +43,7 @@ public class Condition {
this.id = originCondition.id; this.id = originCondition.id;
this.status = originCondition.status; this.status = originCondition.status;
this.activePriority = originCondition.activePriority + basePriority; this.activePriority = originCondition.activePriority + basePriority;
this.auxiliaryPriority = originCondition.auxiliaryPriority + baseAuxiliaryPriority;
} }
public Condition() { public Condition() {
......
package entity;
public class Goods {
}
...@@ -19,7 +19,12 @@ public class JConfig { ...@@ -19,7 +19,12 @@ public class JConfig {
private String jNextStep = ""; private String jNextStep = "";
private String jReply = ""; private String jReply = "";
private String jAuxiliaryPriority = "0"; private String jAuxiliaryPriority = "0";
private String jStatus = "0";
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
private int jStatus = 0;
private String curPremise = ""; private String curPremise = "";
private String hisPremise = ""; private String hisPremise = "";
...@@ -29,6 +34,12 @@ public class JConfig { ...@@ -29,6 +34,12 @@ public class JConfig {
private String reply = ""; private String reply = "";
private String nextStep = ""; private String nextStep = "";
public void setConfigName(String configName) {
this.configName = configName;
}
private String configName = "";
public String getCurPremise() { public String getCurPremise() {
return curPremise; return curPremise;
} }
...@@ -49,7 +60,9 @@ public class JConfig { ...@@ -49,7 +60,9 @@ public class JConfig {
} }
}; };
public void setStatus(String status) {
this.status = status;
}
public void setAuxiliaryPriority(String auxiliaryPriority) { public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
...@@ -63,7 +76,7 @@ public class JConfig { ...@@ -63,7 +76,7 @@ public class JConfig {
this.hisPremise = hisPremise; this.hisPremise = hisPremise;
this.feature = feature; this.feature = feature;
if (!updateKnowledge.equals("")) if (!updateKnowledge.equals(""))
this.updateKnowledge += "-<-" + updateKnowledge; this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply; this.reply = reply;
this.nextStep = nextStep; this.nextStep = nextStep;
...@@ -111,7 +124,29 @@ public class JConfig { ...@@ -111,7 +124,29 @@ public class JConfig {
while (iit.hasNext()) { while (iit.hasNext()) {
varName = iit.next(); varName = iit.next();
varValue = knowledge.get(varName); varValue = knowledge.get(varName);
sb.append("-<-" + varName + ":" + varValue); if(varName.startsWith("NPC")) {
//当名字前为NPC或者items时,需要更新World的状态,所以要在更新信息前加上操作符
if(varValue.startsWith("update:")){
sb.append("-<-" + varName + ":" + "updateAttrByNPCName:" + varValue.substring(5));
} else if(varValue.startsWith("insert:")){
sb.append("-<-" + varName + ":" + "addNpc:" + varValue.substring(5));
} else if(varValue.startsWith("delete")){
sb.append("-<-" + varName + ":" + "deleteNpc:" + varValue.substring(5));
}
}else if(varName.startsWith("item_")){
sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue);
if(varValue.startsWith("update:")){
sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue.substring(5));
} else if(varValue.startsWith("insert:")){
sb.append("-<-" + varName + ":" + "addGoodsBase:" + varValue.substring(5));
} else if(varValue.startsWith("delete")){
sb.append("-<-" + varName + ":" + "deleteGoods:" + varValue.substring(5));
}
}else {
sb.append("-<-" + varName + ":" + varValue);
}
} }
if (!extraKL.equals("")) { if (!extraKL.equals("")) {
sb.append("-<-" + extraKL); sb.append("-<-" + extraKL);
...@@ -156,7 +191,7 @@ public class JConfig { ...@@ -156,7 +191,7 @@ public class JConfig {
} }
public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) { public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) {
String pair[] = knowledge.split(":"); String pair[] = knowledge.split(":", 2);
if (knowledge.equals("") || pair.length < 2) if (knowledge.equals("") || pair.length < 2)
return; return;
...@@ -213,10 +248,10 @@ public class JConfig { ...@@ -213,10 +248,10 @@ public class JConfig {
data.put("nextStepStatus", statusMap.get(nextStepStatus)); data.put("nextStepStatus", statusMap.get(nextStepStatus));
//添加configName //添加configName
data.put("configName", ""); data.put("configName", configName);
//添加config状态 //添加config状态
data.put("configStatus", 0); data.put("configStatus", jStatus);
boolean doPost = false; boolean doPost = false;
......
package entity;
public class Npc {
}
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
}
...@@ -3,6 +3,7 @@ package gameDesign; ...@@ -3,6 +3,7 @@ package gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.util.Iterator; import java.util.Iterator;
...@@ -21,6 +22,8 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -21,6 +22,8 @@ public class CharacterConstructor extends ElementConstructor {
JSONArray allNPC = jsonObject.getJSONArray("npc"); JSONArray allNPC = jsonObject.getJSONArray("npc");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
String conditionName1 = "wenzainali";
String conditionValue = "哪里:人称", repValue;
for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) { for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) {
category = (String) npc.get("category"); category = (String) npc.get("category");
...@@ -34,6 +37,13 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -34,6 +37,13 @@ public class CharacterConstructor extends ElementConstructor {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); varInitialMap.put(category + "_" + name + "_" + attrName, attrValue);
repValue = conditionValue.replace("人称", name);
jConfig = new JConfig(
conditionName1 + "::match-Keyword=" + repValue, " ",
"match,return-0", "{NPC_reply-2}", "yaobuyao", "NPC_reply:queryAttrByNPCName:" + conditionName1
);
jConfigList.add(jConfig);
} }
} }
} }
......
...@@ -70,6 +70,12 @@ public class ElementConstructor { ...@@ -70,6 +70,12 @@ public class ElementConstructor {
} }
/** /**
* 根据插入的数据做后处理
* @param idList
*/
public void postProcessing(List<Integer> idList){}
/**
* 构造参数配置文件的json版 * 构造参数配置文件的json版
*/ */
public void buildJconfig() { public void buildJconfig() {
......
...@@ -3,6 +3,7 @@ package gameDesign; ...@@ -3,6 +3,7 @@ package gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.util.Iterator; import java.util.Iterator;
...@@ -23,6 +24,8 @@ public class ItemConstructor extends ElementConstructor { ...@@ -23,6 +24,8 @@ public class ItemConstructor extends ElementConstructor {
JSONArray goods = jsonObject.getJSONArray("goods"); JSONArray goods = jsonObject.getJSONArray("goods");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
String conditionName1 = "nums";
String keywords1 = "";
for (JSONObject good : goods.toJavaList(JSONObject.class)) { for (JSONObject good : goods.toJavaList(JSONObject.class)) {
...@@ -37,8 +40,18 @@ public class ItemConstructor extends ElementConstructor { ...@@ -37,8 +40,18 @@ public class ItemConstructor extends ElementConstructor {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); varInitialMap.put(category + "_" + name + "_" + attrName, attrValue);
keywords1 += "+" + name + ":" + attrName ;
} }
} }
jConfig = new JConfig(
conditionName1 + "::match-Keyword=" + keywords1, " ",
"match,return-0",
"{items_reply-2}",
" ",
"items_reply:queryAttrByGoodsName:" + conditionName1
);
jConfigList.add(jConfig);
} }
} }
} }
...@@ -58,16 +58,15 @@ public class MapConstructor extends ElementConstructor { ...@@ -58,16 +58,15 @@ public class MapConstructor extends ElementConstructor {
matrix[index][i] = 1; matrix[index][i] = 1;
} }
} }
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
conditionDescription.put("site", "当前地点"); conditionDescription.put("site", "当前地点");
varInitialMap.put("site", ""); varInitialMap.put("site", "海边");
JSONObject map = jsonObject.getJSONObject("map"); JSONObject map = jsonObject.getJSONObject("map");
Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class);
JSONArray locations = map.getJSONArray("locations"); JSONArray locations = map.getJSONArray("locations");
String botName = (String)jsonObject.get("botName");
this.locations = locations; this.locations = locations;
this.question2keyword = question2keyword; this.question2keyword = question2keyword;
//通过邻接表构造邻接矩阵 //通过邻接表构造邻接矩阵
...@@ -79,7 +78,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -79,7 +78,7 @@ public class MapConstructor extends ElementConstructor {
floyd.printPath(matrix, locationNum); floyd.printPath(matrix, locationNum);
generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject); generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereIam(jsonObject); generateWhereIam(jsonObject, botName);
generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
} }
...@@ -87,10 +86,12 @@ public class MapConstructor extends ElementConstructor { ...@@ -87,10 +86,12 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 生成‘我在哪里’所需要的配置文件 * 生成‘我在哪里’所需要的配置文件
*/ */
public void generateWhereIam(JSONObject jsonObject) { public void generateWhereIam(JSONObject jsonObject, String botName) {
String zainaKeywords = question2keyword.get("zaina"); String conditionName = "rencheng";
String conditionKeywords = "botName:哪里+botName:哪";
String zainaliKeywords = conditionKeywords.replace("botName", botName);
jConfig = new JConfig( jConfig = new JConfig(
"zaina::match-Keyword=" + zainaKeywords, " ", conditionName + "::match-Keyword=" + zainaliKeywords, " ",
"match", "你在{site-2}", "yaobuyao", "" "match", "你在{site-2}", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -98,13 +99,18 @@ public class MapConstructor extends ElementConstructor { ...@@ -98,13 +99,18 @@ public class MapConstructor extends ElementConstructor {
} }
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String conditionName = "want_know_zenmezuo";
String conditionKeywords = "去:地点";
String placeA, placeB, descriptionB, placeKeywords, text, pathNode; String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String zenmequKeywords = question2keyword.get("zenmequ"); String want_know_zenmezuoKeywords = question2keyword.get("want_know_zenmezuo");
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
...@@ -113,11 +119,11 @@ public class MapConstructor extends ElementConstructor { ...@@ -113,11 +119,11 @@ public class MapConstructor extends ElementConstructor {
placeA = (String) locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
placeB = (String) locations.getJSONObject(j).get("name"); placeB = (String) locations.getJSONObject(j).get("name");
placeKeywords = zenmequKeywords.replace("地点", placeB); placeKeywords = conditionKeywords.replace("地点", placeB);
if (i == j) { if (i == j) {
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", "" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -126,7 +132,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -126,7 +132,7 @@ public class MapConstructor extends ElementConstructor {
; ;
if (pathMatirx[i][j] == 1) { if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", placeB + "就在附近哦", "yaobuyao", "" "match", placeB + "就在附近哦", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -140,7 +146,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -140,7 +146,7 @@ public class MapConstructor extends ElementConstructor {
} }
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", "" "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -154,7 +160,8 @@ public class MapConstructor extends ElementConstructor { ...@@ -154,7 +160,8 @@ public class MapConstructor extends ElementConstructor {
* 生成‘我能去哪里’所需要的配置文件 * 生成‘我能去哪里’所需要的配置文件
*/ */
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String nengqunaKeywords = question2keyword.get("nengquna"); String conditionKeywords = "能去:哪+能去:哪里+能去:哪儿";
String conditionName = "choose_gowhere";
String placeA, placeB, pathNode; String placeA, placeB, pathNode;
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
...@@ -169,7 +176,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -169,7 +176,7 @@ public class MapConstructor extends ElementConstructor {
} }
jConfig = new JConfig( jConfig = new JConfig(
"nengquna::match-Keyword=" + nengqunaKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + conditionKeywords, "site::match-Keyword=" + placeA,
"match", "你可以去" + pathNode, "yaobuyao", "" "match", "你可以去" + pathNode, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -185,8 +192,9 @@ public class MapConstructor extends ElementConstructor { ...@@ -185,8 +192,9 @@ public class MapConstructor extends ElementConstructor {
* 生成‘我要去那里’所需要的配置文件 * 生成‘我要去那里’所需要的配置文件
*/ */
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String placeA, placeB, descriptionB, placeKeywords, text, pathNode; String placeA, placeB, descriptionB, placeKeywords, text, pathNode, lastTaskCondition, lastTaskReply;
String qunaKeywords = question2keyword.get("quna"); String conditionName = "quna";
String conditionKeywords = "地点";
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
...@@ -194,12 +202,14 @@ public class MapConstructor extends ElementConstructor { ...@@ -194,12 +202,14 @@ public class MapConstructor extends ElementConstructor {
placeA = (String) locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
placeB = (String) locations.getJSONObject(j).get("name"); placeB = (String) locations.getJSONObject(j).get("name");
descriptionB = (String) locations.getJSONObject(j).get("description"); descriptionB = (String) locations.getJSONObject(j).get("description");
placeKeywords = qunaKeywords.replace("地点", placeB); placeKeywords = conditionKeywords.replace("地点", placeB);
lastTaskCondition = "任务线" + placeB + "最后一个condition";
lastTaskReply = "任务线" + placeB + "最后的回答";
if (i == j) { if (i == j) {
jConfig = new JConfig( jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", "" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -210,8 +220,14 @@ public class MapConstructor extends ElementConstructor { ...@@ -210,8 +220,14 @@ public class MapConstructor extends ElementConstructor {
//如果两点相邻 //如果两点相邻
if (pathMatirx[i][j] == 1) { if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Keyword=" + placeKeywords,
"match", "" + descriptionB, "yaobuyao", "site:" + placeB "site::match-Keyword=" + placeA + "," + lastTaskCondition + "::match-Keyword=null" + "," + lastTaskReply + "::match-Keyword=null",
"match, reutrn-0", "地点尚未激活", "yaobuyao", ""
);
jConfigList.add(jConfig);
jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeB + "-<-process-nextStep:var={" + lastTaskCondition +"-2}"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -225,7 +241,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -225,7 +241,7 @@ public class MapConstructor extends ElementConstructor {
k = preTable[k][j]; k = preTable[k][j];
} }
jConfig = new JConfig( jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, conditionName + "::match-Keyword=" + placeKeywords,
"site::match-Keyword=" + placeA, "site::match-Keyword=" + placeA,
"match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", "" "match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", ""
); );
...@@ -235,5 +251,27 @@ public class MapConstructor extends ElementConstructor { ...@@ -235,5 +251,27 @@ public class MapConstructor extends ElementConstructor {
} }
} }
public void generateSurroundingPeople(){
String conditionName = "know_exist_what";
String conditionKeywords = "周围:人";
jConfig = new JConfig(
conditionName + "::match-Keyword=" + conditionKeywords, " ",
"match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundNpcBySite:"
);
jConfigList.add(jConfig);
}
public void generateSurroundingItem(){
String conditionName = "know_exist_what";
String conditionKeywords = "周围:物品,周围:东西";
jConfig = new JConfig(
conditionName + "::match-Keyword=" + conditionKeywords, " ",
"match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundGoodsBySite:"
);
jConfigList.add(jConfig);
}
} }
...@@ -31,18 +31,22 @@ public class PlotConstructor extends ElementConstructor { ...@@ -31,18 +31,22 @@ public class PlotConstructor extends ElementConstructor {
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; if(id2j.containsKey(start)) {
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, start);
varInitialMap.put("unknownText", "你说啥?");
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度";
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, start);
varInitialMap.put("unknownText", "你说啥?");
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
BFSGenerate3(id2j.get(start), userinfo);
varInitialMap.put(start, "0"); BFSGenerate4(id2j.get(start), userinfo);
varInitialMap.put(start, "1");
} else {
System.out.println("start剧情不存在");
}
} }
//根据id构造邻接表 //根据id构造邻接表
...@@ -77,6 +81,12 @@ public class PlotConstructor extends ElementConstructor { ...@@ -77,6 +81,12 @@ public class PlotConstructor extends ElementConstructor {
} }
} }
/**
* 根据每个剧情点的进度设置计数器
* @param root
* @param userinfo
*/
public void BFSGenerate(JSONObject root, UserInfo userinfo) { public void BFSGenerate(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
nextUnknownText, curUnknownText, nextCondition; nextUnknownText, curUnknownText, nextCondition;
...@@ -385,9 +395,14 @@ public class PlotConstructor extends ElementConstructor { ...@@ -385,9 +395,14 @@ public class PlotConstructor extends ElementConstructor {
} }
/**
* 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。
* @param root
* @param userinfo
*/
public void BFSGenerate3(JSONObject root, UserInfo userinfo) { public void BFSGenerate3(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null; JSONArray branch = null;
...@@ -411,6 +426,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -411,6 +426,8 @@ public class PlotConstructor extends ElementConstructor {
conditionName = (String) node.get("conditionName"); conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText"); curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度"; taskLineName = "任务线_" + location + "进度";
//本任务线的最后一个condition和本任务线的最后一个回答
if (!varInitialMap.containsKey(taskLineName)) { if (!varInitialMap.containsKey(taskLineName)) {
...@@ -441,18 +458,25 @@ public class PlotConstructor extends ElementConstructor { ...@@ -441,18 +458,25 @@ public class PlotConstructor extends ElementConstructor {
nextUnknownText = updateKnowledge.get("unknownText"); nextUnknownText = updateKnowledge.get("unknownText");
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
if (id2j.get(nextId) != null) { if (id2j.get(nextId) != null) {
nextCondition = (String) id2j.get(nextId).get("conditionName"); nextCondition = (String) id2j.get(nextId).get("conditionName");
nextLocation = (String) id2j.get(nextId).get("place"); nextLocation = (String) id2j.get(nextId).get("place");
nTaskLineName = "任务线_" + nextLocation + "进度"; nTaskLineName = "任务线_" + nextLocation + "进度";
} else { } else {
//如果不存在下一剧情,就将condition设为空,任务线进度不变
nextCondition = " "; nextCondition = " ";
nTaskLineName = taskLineName; nTaskLineName = taskLineName;
nextLocation = location;
} }
lastTaskCondition = "任务线" + nextLocation + "最后一个condition";
lastTaskReply = "任务线" + nextLocation + "最后的回答";
extraHP = taskLineName + "::match-Keyword=" + id;
extraUK = nTaskLineName + ":" + nextId; //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location;
extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}";
jConfig = new JConfig( jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
...@@ -462,20 +486,175 @@ public class PlotConstructor extends ElementConstructor { ...@@ -462,20 +486,175 @@ public class PlotConstructor extends ElementConstructor {
"match", (String) branchNode.get("reply"), (String) nextCondition, "0" "match", (String) branchNode.get("reply"), (String) nextCondition, "0"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
// try {
// keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者";
// } catch (Exception e) {
// e.printStackTrace();
// }
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, "");
}
}
}
}
//对于unknown的特殊处理
if (curUnknownText.equals("")) {
jConfig = new JConfig( jConfig = new JConfig(
"yaobuyao::match-Keyword=" + location, conditionName + "::match-Keyword=unknown",
extraHP, extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId,
"match", (String) branchNode.get("reply"), (String) nextCondition, "0" "match,return-0,post::all(" + CHITCHAT_URL + ")",
" ",
" ",
""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
}
}
try { jConfig = new JConfig(
keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; " ", " ", "", " ", " ", ""
} catch (Exception e) { );
e.printStackTrace(); jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown");
jConfig.setjStatus(1);
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "", "", " " ," ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("common_answer");
jConfig.setjStatus(1);
jConfigList.add(jConfig);
}
/**
* 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。
* 加上剧情计数器, 每一步分为三个状态
* @param root
* @param userinfo
*/
public void BFSGenerate4(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition;
boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null;
List<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, branchSize;
root.put("nextUnknownText", varInitialMap.get("unknownText"));
root.put("parentId", "null");
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");
conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度";
conditionDescription.put(id, "剧情" + id + "状态");
varInitialMap.put(id ,"");
//本任务线的最后一个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 = "";
for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i);
nextId = (String) branchNode.get("nextPlotId");
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
nextUnknownText = updateKnowledge.get("unknownText");
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
if (id2j.get(nextId) != null) {
nextCondition = (String) id2j.get(nextId).get("conditionName");
nextLocation = (String) id2j.get(nextId).get("place");
nTaskLineName = "任务线_" + nextLocation + "进度";
} else {
//如果不存在下一剧情,就将condition设为空,任务线进度不变
nextCondition = " ";
nTaskLineName = taskLineName;
nextLocation = location;
} }
lastTaskCondition = "任务线" + nextLocation + "最后一个condition";
lastTaskReply = "任务线" + nextLocation + "最后的回答";
//额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Keyword=null";
extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}" +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1";;
jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
updateKnowledge,
"", extraHP, extraUK,
"match", (String) branchNode.get("reply"), (String) nextCondition, "0"
);
jConfigList.add(jConfig);
// try {
// keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者";
// } catch (Exception e) {
// e.printStackTrace();
// }
if (branchNode.get("nextPlotId") != null) { if (branchNode.get("nextPlotId") != null) {
adjId = (String) branchNode.get("nextPlotId"); adjId = (String) branchNode.get("nextPlotId");
...@@ -495,6 +674,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -495,6 +674,8 @@ public class PlotConstructor extends ElementConstructor {
} }
//对于unknown的特殊处理 //对于unknown的特殊处理
if (curUnknownText.equals("")) { if (curUnknownText.equals("")) {
jConfig = new JConfig( jConfig = new JConfig(
...@@ -507,40 +688,32 @@ public class PlotConstructor extends ElementConstructor { ...@@ -507,40 +688,32 @@ public class PlotConstructor extends ElementConstructor {
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
/*
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
jConfig = new JConfig(
conditionName + "::match-Keyword=unknown",
extraHP + ",unknown_counter::number-SmallOrEqual=0",
"match",
"{unknownReply-2}",
" ",
"unknown_counter:+1"
);
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
jConfig = new JConfig(
conditionName + "::match-Keyword=unknown",
extraHP + ",unknown_counter::number-BiggerOrEqual=1",
"match",
"你可以说" + keywordOptions,
" ",
"unknown_counter:+1"
);
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
*/
} }
//unknown时的处理
jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); jConfig = new JConfig(
jConfig.setNextStepStatus("return-0"); " ", " ", "", " ", " ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown");
jConfig.setjStatus(1);
jConfigList.add(jConfig); jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "", "", " " ," ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("common_answer");
jConfig.setjStatus(1);
jConfigList.add(jConfig);
}
@Override
public void postProcessing(List<Integer> idList){
jConfig = new JConfig(" ", "", "activate", "", idList.get(idList.size()-2) + "," + idList.get(idList.size()-1), "");
jConfigList.add(jConfig);
} }
......
package processing; package processing;
import entity.ChatCache;
import entity.UserInfo;
import entity.World;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.util.HashMap; import java.util.HashMap;
...@@ -15,6 +19,8 @@ public class ChatCacheController { ...@@ -15,6 +19,8 @@ public class ChatCacheController {
* @return 历史信息点,对话过程中引擎提取的用户信息 * @return 历史信息点,对话过程中引擎提取的用户信息
*/ */
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) { public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) {
World world = new World();
Map<String, String> historyInfoPoint = null; Map<String, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = null; Map<String, Map<String, String>> chatCache = null;
if (context.getAttribute("chatCache") == null) { if (context.getAttribute("chatCache") == null) {
...@@ -126,4 +132,79 @@ public class ChatCacheController { ...@@ -126,4 +132,79 @@ public class ChatCacheController {
return true; return true;
} }
public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, Map<String, String[]> curInfoPoint, UserInfo userinfo) {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>();
chatCacheMap.put(chatKey, new ChatCache(curInfoPoint, userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
}
String chatkey;
try {
chatCache = chatCacheMap.get(chatKey);
if(chatCache == null){
chatCache = new ChatCache(curInfoPoint, userinfo);
chatCacheMap.put(chatKey, chatCache);
}
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) {
//可整合
chatCache = new ChatCache(curInfoPoint, userinfo);
}
return chatCache;
}
/**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/
public static synchronized void updateChatCache4Delete2(String curChatKey, ServletContext context) {
String chatKey;
ChatCache chatCache = null;
long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>();
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
Iterator<String> it = chatCacheMap.keySet().iterator();
while (it.hasNext()) {
chatKey = it.next();
if(curChatKey.equals(chatKey))
continue;
history = chatCacheMap.get(chatKey).getInfoPoint();
lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis();
if (now - lastChatTime > 300000) {
it.remove();
}
}
context.setAttribute("chatCache", chatCacheMap);
}
/**
* 根据chatKey更新chatCache的数据,并修改最后更新时间
*/
public static synchronized void updateChatCache4Insert2(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, World world, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")[0]);
chatCache.setInfoPoint(historyInfoPoint);
chatCache.setWorld(world);
context.setAttribute("chatCache", keyCacheMap);
}
} }
...@@ -93,5 +93,9 @@ public class MyFunc { ...@@ -93,5 +93,9 @@ public class MyFunc {
} }
public static boolean isInteger(String str){
return true;
}
} }
...@@ -3,6 +3,7 @@ package processing; ...@@ -3,6 +3,7 @@ package processing;
import entity.Solution; import entity.Solution;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import entity.World;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
...@@ -33,8 +34,18 @@ public class QuestionMatcher { ...@@ -33,8 +34,18 @@ public class QuestionMatcher {
static String API_ERROR = "api处理过程中出错了"; static String API_ERROR = "api处理过程中出错了";
static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
public PrintWriter logWriter = null;
/* public UserInfo userinfo = null;
public ServletContext context = null;
public World world = null;
public QuestionMatcher(PrintWriter logWriter, UserInfo userinfo, ServletContext context, World world) {
this.logWriter = logWriter;
this.userinfo = userinfo;
this.context = context;
this.world = world;
}
/*
public void updateDB(QuestionKeyWord qkw) throws SQLException { public void updateDB(QuestionKeyWord qkw) throws SQLException {
SqlHelper helper = new SqlHelper(); SqlHelper helper = new SqlHelper();
String result = helper.queryActionByKey(qkw.getChatKey()); String result = helper.queryActionByKey(qkw.getChatKey());
...@@ -49,7 +60,7 @@ public class QuestionMatcher { ...@@ -49,7 +60,7 @@ public class QuestionMatcher {
*/ */
public boolean infoPointPreprocessing(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo) { public boolean infoPointPreprocessing(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException {
String return_str = "", k; String return_str = "", k;
boolean debugFlag = false; boolean debugFlag = false;
...@@ -67,10 +78,11 @@ public class QuestionMatcher { ...@@ -67,10 +78,11 @@ public class QuestionMatcher {
//输出所有actionName的值 //输出所有actionName的值
Iterator<String> iit = curInfoPoint.keySet().iterator(); Iterator<String> iit = curInfoPoint.keySet().iterator();
logWriter.println("-----------------------------------------识别数据列表-------------------------------------------<br>");
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
// //
System.out.print(k + ": "); logWriter.write(k + ": ");
if (k.equals("debug_mode")) if (k.equals("debug_mode"))
debugFlag = true; debugFlag = true;
...@@ -78,14 +90,16 @@ public class QuestionMatcher { ...@@ -78,14 +90,16 @@ public class QuestionMatcher {
String values[] = curInfoPoint.get(k); String values[] = curInfoPoint.get(k);
for (String v : values) { for (String v : values) {
System.out.print(v + " "); logWriter.write(v + " ");
} }
System.out.println(); logWriter.write("<br>");
if (values[0].equals(":")) { if (values[0].equals(":")) {
values[0] = ""; values[0] = "";
curInfoPoint.put(k, values); curInfoPoint.put(k, values);
} }
} }
logWriter.println("---------------------------------------------------------------------------------------");
logWriter.write("<br>");
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator(); iit = curInfoPoint.keySet().iterator();
...@@ -133,7 +147,7 @@ public class QuestionMatcher { ...@@ -133,7 +147,7 @@ public class QuestionMatcher {
* @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么
* @return bestMatch 状态表中满足条件最多的一条 * @return bestMatch 状态表中满足条件最多的一条
*/ */
public Condition getBestMatch(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, HashMap<String, List<Condition>> conditionTable, ServletContext context) throws IOException { public Condition getBestMatch(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, HashMap<String, List<Condition>> conditionTable, ServletContext context, UserInfo userInfo) throws IOException {
Integer configId = 0; Integer configId = 0;
List<Condition> conditionList = null; List<Condition> conditionList = null;
...@@ -143,6 +157,7 @@ public class QuestionMatcher { ...@@ -143,6 +157,7 @@ public class QuestionMatcher {
Queue<Condition> activatedCondition = new LinkedList<Condition>(); Queue<Condition> activatedCondition = new LinkedList<Condition>();
while (it.hasNext()) { while (it.hasNext()) {
String conditionName = it.next(); String conditionName = it.next();
String[] keywords = curInfoPoint.get(conditionName); String[] keywords = curInfoPoint.get(conditionName);
...@@ -151,10 +166,15 @@ public class QuestionMatcher { ...@@ -151,10 +166,15 @@ public class QuestionMatcher {
if (keywords != null && !keywords[0].equals("")) if (keywords != null && !keywords[0].equals(""))
keyword = keywords[0]; keyword = keywords[0];
if (keyword != null && conditionTable.get(conditionName) != null) { if (keyword != null && conditionTable.get(conditionName) != null) {
conditionList = conditionTable.get(conditionName); conditionList = conditionTable.get(conditionName);
for (Condition condition : conditionList) { for (Condition condition : conditionList) {
if (condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { if (condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) {
logWriter.println("-----更新匹配更新为------" + userInfo.id2config.get(condition.id) + "-----------<br>");
if (condition.featureMap.get("instantPost") != null) { if (condition.featureMap.get("instantPost") != null) {
...@@ -162,15 +182,18 @@ public class QuestionMatcher { ...@@ -162,15 +182,18 @@ public class QuestionMatcher {
} }
//Post后还是可以激活 //Post后还是可以激活
if (condition.featureMap.get("activate") != null) { if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) {
//有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。
bestMatch = condition; bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context);
} else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) //} else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority))
} else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority))
bestMatch = condition; bestMatch = condition;
} }
} }
} }
} }
bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context);
...@@ -179,7 +202,7 @@ public class QuestionMatcher { ...@@ -179,7 +202,7 @@ public class QuestionMatcher {
return bestMatch; return bestMatch;
} }
public Condition activatedQueueMatching(Condition bestMatch, Queue<Condition> activatedQueue, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) { public Condition activatedQueueMatching(Condition bestMatch, Queue<Condition> activatedQueue, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) throws IOException {
Condition condition; Condition condition;
//待激活配置条目被激活后的匹配 //待激活配置条目被激活后的匹配
while (!activatedQueue.isEmpty()) { while (!activatedQueue.isEmpty()) {
...@@ -188,10 +211,14 @@ public class QuestionMatcher { ...@@ -188,10 +211,14 @@ public class QuestionMatcher {
if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) {
if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) {
logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-----------");
bestMatch = condition; bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context);
} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) { //} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) {
} else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) {
bestMatch = condition; bestMatch = condition;
logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-------<br>");
} }
} }
...@@ -215,6 +242,8 @@ public class QuestionMatcher { ...@@ -215,6 +242,8 @@ public class QuestionMatcher {
String actionName, keywords[], keyword, comparePair[], cmpType, premiseStr; String actionName, keywords[], keyword, comparePair[], cmpType, premiseStr;
HashSet<String> keywordSet = null; HashSet<String> keywordSet = null;
logWriter.println("<br>" + "-----检索到配置条目------" + userinfo.id2config.get(condition.id) + "-----------");
if (condition.featureMap.containsKey("match")) { if (condition.featureMap.containsKey("match")) {
Iterator<String> it = condition.currentPremise.keySet().iterator(); Iterator<String> it = condition.currentPremise.keySet().iterator();
while (flag && it.hasNext()) { while (flag && it.hasNext()) {
...@@ -224,6 +253,9 @@ public class QuestionMatcher { ...@@ -224,6 +253,9 @@ public class QuestionMatcher {
keywords = curInfoPoint.get(actionName); keywords = curInfoPoint.get(actionName);
if (keywords == null) { if (keywords == null) {
flag = false; flag = false;
if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配");
}
break; break;
} }
keyword = keywords[0]; keyword = keywords[0];
...@@ -233,8 +265,12 @@ public class QuestionMatcher { ...@@ -233,8 +265,12 @@ public class QuestionMatcher {
cmpType = comparePair[1]; cmpType = comparePair[1];
keywordSet = condition.currentPremise.get(premiseStr); keywordSet = condition.currentPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet)) if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint))
flag = false; flag = false;
if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配");
}
} }
it = condition.historyPremise.keySet().iterator(); it = condition.historyPremise.keySet().iterator();
...@@ -246,6 +282,9 @@ public class QuestionMatcher { ...@@ -246,6 +282,9 @@ public class QuestionMatcher {
if (keyword == null) { if (keyword == null) {
flag = false; flag = false;
if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配");
}
break; break;
} }
...@@ -255,11 +294,17 @@ public class QuestionMatcher { ...@@ -255,11 +294,17 @@ public class QuestionMatcher {
cmpType = comparePair[1]; cmpType = comparePair[1];
keywordSet = condition.historyPremise.get(premiseStr); keywordSet = condition.historyPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet)) if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint))
flag = false; flag = false;
if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配");
}
} }
} }
return flag; return flag;
} }
...@@ -272,7 +317,7 @@ public class QuestionMatcher { ...@@ -272,7 +317,7 @@ public class QuestionMatcher {
* @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件
* @return 返回匹配或者不匹配 * @return 返回匹配或者不匹配
*/ */
public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet) { public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) {
boolean flag = true; boolean flag = true;
String operator = ""; String operator = "";
...@@ -337,7 +382,7 @@ public class QuestionMatcher { ...@@ -337,7 +382,7 @@ public class QuestionMatcher {
if (keyword.contains(":")) { if (keyword.contains(":")) {
String ks[] = keyword.split(":"); String ks[] = keyword.split(":");
for (String k : ks) { for (String k : ks) {
if(k.startsWith("20") && k.endsWith("日")) if(k.contains("年") && k.contains("月") && k.contains("日"))
keyword = k; keyword = k;
} }
...@@ -357,6 +402,125 @@ public class QuestionMatcher { ...@@ -357,6 +402,125 @@ public class QuestionMatcher {
flag = candidateA > candidateB; 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)[0].equals("")) {
conditionValue2 = curInfoPoint.get(conditionName2)[0];
}else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){
conditionValue2 = historyInfoPoint.get(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(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(!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(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;
// 操作符为等于时可以比较两个字符串是否相同
}
}
}
} }
//-------------------------------------------------------------------- //--------------------------------------------------------------------
//为兼容旧数据 //为兼容旧数据
...@@ -441,7 +605,12 @@ public class QuestionMatcher { ...@@ -441,7 +605,12 @@ public class QuestionMatcher {
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
System.out.println("配置文件格式有误"); System.out.println("配置文件格式有误");
flag = false;
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) {
System.out.println("时间解析错误");
e.printStackTrace();
flag = false;
} catch (Exception e) { } catch (Exception e) {
System.out.println("操作符有误"); System.out.println("操作符有误");
e.printStackTrace(); e.printStackTrace();
...@@ -476,7 +645,17 @@ public class QuestionMatcher { ...@@ -476,7 +645,17 @@ public class QuestionMatcher {
ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint); ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint);
//nextNext关键字 //nextNext关键字
} else if (ansCondition.featureMap.containsKey("newNext")) { }
//updateKnowledge关键字
if (ansCondition.featureMap.containsKey("updateKnowledge")) {
updateKnowledge(ansCondition, curInfoPoint, historyInfoPoint);
}
if (ansCondition.featureMap.containsKey("newNext")) {
ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint);
//上一步 //上一步
} else if (ansCondition.featureMap.containsKey("return-1")) { } else if (ansCondition.featureMap.containsKey("return-1")) {
...@@ -500,10 +679,7 @@ public class QuestionMatcher { ...@@ -500,10 +679,7 @@ public class QuestionMatcher {
} }
} }
//updateKnowledge关键字
if (ansCondition.featureMap.containsKey("updateKnowledge")) {
updateKnowledge(ansCondition, historyInfoPoint);
}
if (ans.getNext().equals("")) { if (ans.getNext().equals("")) {
ans.setNext("nextStep=" + ansCondition.nextStep); ans.setNext("nextStep=" + ansCondition.nextStep);
...@@ -538,7 +714,7 @@ public class QuestionMatcher { ...@@ -538,7 +714,7 @@ public class QuestionMatcher {
if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals("")) if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals(""))
reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]); reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]);
} else if (m.group(1).endsWith("-2}")) { } else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")) if (historyInfoPoint.get(variable) != null)
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
} }
} }
...@@ -561,6 +737,16 @@ public class QuestionMatcher { ...@@ -561,6 +737,16 @@ public class QuestionMatcher {
historyInfoPoint.put("currentAction", next); historyInfoPoint.put("currentAction", next);
historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next);
HashSet<String> skipSet = new HashSet<String>() {
{
add("chat_key");
add("action_name");
add("bot_name");
add("emptySet");
add("query_text");
}
};
if (debugFlag) if (debugFlag)
lastReply = ans.getAnswer().split(")")[2]; lastReply = ans.getAnswer().split(")")[2];
else else
...@@ -571,16 +757,22 @@ public class QuestionMatcher { ...@@ -571,16 +757,22 @@ public class QuestionMatcher {
String keyword1, keyword2; String keyword1, keyword2;
while (it.hasNext()) { while (it.hasNext()) {
actionName = it.next(); actionName = it.next();
if(skipSet.contains(actionName))
continue;
keyword1 = curInfoPoint.get(actionName)[0]; keyword1 = curInfoPoint.get(actionName)[0];
keyword2 = historyInfoPoint.get(actionName); keyword2 = historyInfoPoint.get(actionName);
if (keyword2 == null) if (keyword2 == null) {
historyInfoPoint.put(actionName, keyword1); historyInfoPoint.put(actionName, keyword1);
else if (keyword2 != null && !keyword1.equals("")) }else if (historyInfoPoint.get(actionName).equals("do_reset")){
historyInfoPoint.put(actionName, "");
}else if (keyword2 != null && !keyword1.equals(""))
historyInfoPoint.put(actionName, keyword1); historyInfoPoint.put(actionName, keyword1);
} }
ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); ChatCacheController.updateChatCache4Insert2(curInfoPoint, historyInfoPoint, world, context);
//context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint);
...@@ -609,7 +801,6 @@ public class QuestionMatcher { ...@@ -609,7 +801,6 @@ public class QuestionMatcher {
add("lastUpdateTime"); add("lastUpdateTime");
add("bot_name"); add("bot_name");
add("action_name"); add("action_name");
add("chat_key");
add("lastReply"); add("lastReply");
} }
}; };
...@@ -651,6 +842,15 @@ public class QuestionMatcher { ...@@ -651,6 +842,15 @@ public class QuestionMatcher {
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> k_iter = null; Iterator<String> k_iter = null;
HashSet<String> skipSet = new HashSet<String>() {
{
add("activeList");
add("currentAction");
add("lastUpdateTime");
add("lastReply");
}
};
elem = ansCondition.featureMap.get("post").split("\\|"); elem = ansCondition.featureMap.get("post").split("\\|");
url = elem[0]; url = elem[0];
postType = elem[1]; postType = elem[1];
...@@ -672,12 +872,16 @@ public class QuestionMatcher { ...@@ -672,12 +872,16 @@ public class QuestionMatcher {
//infoMap.put(key + "_his", historyInfoPoint.get(key)); //infoMap.put(key + "_his", historyInfoPoint.get(key));
if (key.equals("game_step")) if (key.equals("game_step"))
pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key)));
else if(skipSet.contains(key)){}
else else
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
} }
//提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值
} else if (postType.equals("term")) { } else if (postType.equals("term")) {
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")[0]));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")[0]));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")[0]));
k_iter = ansCondition.currentPremise.keySet().iterator(); k_iter = ansCondition.currentPremise.keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
...@@ -711,6 +915,7 @@ public class QuestionMatcher { ...@@ -711,6 +915,7 @@ public class QuestionMatcher {
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
JSONObject jobj = JSONObject.fromString(respContent); JSONObject jobj = JSONObject.fromString(respContent);
Iterator<String> kit = jobj.keys(); Iterator<String> kit = jobj.keys();
while (kit.hasNext()) { while (kit.hasNext()) {
keyName = kit.next(); keyName = kit.next();
if (keyName.equals("process")) { if (keyName.equals("process")) {
...@@ -718,8 +923,9 @@ public class QuestionMatcher { ...@@ -718,8 +923,9 @@ public class QuestionMatcher {
historyInfoPoint.put("process", (String) jobj.get(keyName)); historyInfoPoint.put("process", (String) jobj.get(keyName));
} else if (keyName.equals("solution")) { } else if (keyName.equals("solution")) {
ans.setAnswer((String) jobj.get(keyName)); ans.setAnswer((String) jobj.get(keyName));
} else { } else if (keyName.equals("status")){
ans.setNext("nextStep=" + ansCondition.nextStep); continue;
} else{
historyInfoPoint.put(keyName, jobj.getString(keyName)); historyInfoPoint.put(keyName, jobj.getString(keyName));
} }
} }
...@@ -783,8 +989,8 @@ public class QuestionMatcher { ...@@ -783,8 +989,8 @@ public class QuestionMatcher {
} }
public void updateKnowledge(Condition condition, Map<String, String> historyInfoPoint) throws ParseException { public void updateKnowledge(Condition condition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) throws ParseException {
String keyword, variableName, updateValue; String keyword, variableName, updateValue, returnStr = "1";
Iterator<String> iit = condition.updateKnowledge.keySet().iterator(); Iterator<String> iit = condition.updateKnowledge.keySet().iterator();
while (iit.hasNext()) { while (iit.hasNext()) {
...@@ -793,6 +999,13 @@ public class QuestionMatcher { ...@@ -793,6 +999,13 @@ public class QuestionMatcher {
updateValue = condition.updateKnowledge.get(variableName); updateValue = condition.updateKnowledge.get(variableName);
keyword = historyInfoPoint.get(variableName); keyword = historyInfoPoint.get(variableName);
//如果变量名开头为NPC或者item,就专门交给world处理
if(variableName.startsWith("NPC_") || variableName.startsWith("item_") || variableName.startsWith("map")){
returnStr = WorldController.worldOperation(world, variableName, updateValue, curInfoPoint, historyInfoPoint);
historyInfoPoint.put(variableName, returnStr);
break;
}
try { try {
//做数字加法 //做数字加法
if (updateValue.startsWith("+")) { if (updateValue.startsWith("+")) {
...@@ -830,19 +1043,87 @@ public class QuestionMatcher { ...@@ -830,19 +1043,87 @@ public class QuestionMatcher {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = ""; keyword = "";
updateValue = keyword.replace(updateValue.substring(4), ""); 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)[0];
}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 = condition.answer[0];
}
if(variableName.startsWith("process-nextStep")){
condition.nextStep = updateValue;
updateValue = "";
}
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
if(updateValue.equals(""))
updateValue = "do_reset";
historyInfoPoint.put(variableName, updateValue); historyInfoPoint.put(variableName, updateValue);
} }
} }
public void activateCondition(Queue<Condition> activatedQueue, String userName, int basePriority, String activateList, ServletContext context) { public void activateCondition(Queue<Condition> activatedQueue, String userName, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException {
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String configStr = ""; String configStr = "";
Integer configId; Integer configId;
...@@ -856,9 +1137,11 @@ public class QuestionMatcher { ...@@ -856,9 +1137,11 @@ public class QuestionMatcher {
configStr = userinfo.id2config.get(configId); configStr = userinfo.id2config.get(configId);
if (configStr != null) { if (configStr != null) {
originCondition = userinfo.id2condition.get(configId); originCondition = userinfo.id2condition.get(configId);
newCondition = new Condition(originCondition, basePriority); newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority);
//condition = QuestionMatcher.buildCondition(condition, configStr); //condition = QuestionMatcher.buildCondition(condition, configStr);
logWriter.write("------激活-------" + userinfo.id2config.get(configId) + "-------<br>");
if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) {
activatedMap.get(configId).activePriority = newCondition.activePriority; activatedMap.get(configId).activePriority = newCondition.activePriority;
} else if (!activatedMap.containsKey(configId)) { } else if (!activatedMap.containsKey(configId)) {
...@@ -874,7 +1157,7 @@ public class QuestionMatcher { ...@@ -874,7 +1157,7 @@ public class QuestionMatcher {
public Solution postActivate(Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { 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>(); Queue<Condition> activatedQueue = new LinkedList<Condition>();
Solution bestMatch = null; Solution bestMatch = null;
activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context); activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context);
ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context);
bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
......
package processing;
import entity.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WorldController {
public static String worldOperation(World world, String varName, String varValue, Map<String, String[]> currentInfoPoint, Map<String, String>historyInfoPoint){
String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr="";
String namePair[] = varName.split("_");
boolean operationFlag = true;
if (varName.startsWith("NPC_"))
moduleName = "NPC";
else if(varName.startsWith("items"))
moduleName = "items";
if(varName.startsWith("item_")) {
switch (valuePair[0]) {
case "addGoodsBase":
operationFlag = world.addGoodsBase(namePair[1], namePair[2], valuePair[1]);
break;
case "deleteGoods":
operationFlag = world.deleteGoods(namePair[1], namePair[2]);
break;
case "queryGoodsIntro":
returnStr = world.queryGoodsIntro(varName, historyInfoPoint.get("site"));
break;
case "queryAttrByGoodsName":
String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2);
returnStr = world.queryAttrByGoodsName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site"));
break;
case "queryAllAttrByGoodsName":
List<String> attrs = world.queryAllAttrByGoodsName(varName, historyInfoPoint.get("site"));
break;
case "updateAttrByGoodsName":
operationFlag = world.updateAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]);
break;
case "addAttrByGoodsName":
operationFlag = world.addAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]);
break;
case "deleteAttrByGoodsName":
operationFlag = world.deleteAttrByGoodsName(namePair[1], namePair[2], namePair[3]);
break;
default:
}
}else if(varName.startsWith("NPC")) {
switch(valuePair[0]){
case "addNpc":
operationFlag = world.addNpc(namePair[1], namePair[2], valuePair[1]);
break;
case "deleteNpc":
operationFlag = world.deleteNpc(namePair[1], namePair[2]);
break;
case "queryNpcIntro":
//operationFlag = world.queryNpcIntro(valuePair[1], namePair[2]);
break;
case "queryAttrByNPCName":
String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2);
subValuePair[1] = subValuePair[1].replace("哪里", "location");
returnStr = world.queryAttrByNPCName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site"));
break;
case "updateLocationByNPCName":
operationFlag = world.updateLocationByNPCName(namePair[1], namePair[2], namePair[3], "");
break;
case "addAttrByNPCName":
operationFlag = world.addAttrByNPCName(namePair[1], namePair[2], namePair[3], valuePair[1]);
break;
case "deleteAttrByNPCName":
operationFlag = world.deleteAttrByNPCName(namePair[1], namePair[2], namePair[3]);
break;
default:
}
}else if (varName.startsWith("map")){
List<String> sites = new ArrayList<>();
switch(valuePair[0]){
case "queryAroundAllBySite":
sites = world.queryAroundAllBySite(historyInfoPoint.get("site"));
break;
case "queryAroundNpcBySite":
sites = world.queryAroundNpcBySite(historyInfoPoint.get("site"));
break;
case "queryAroundGoodsBySite":
sites = world.queryAroundGoodsBySite(historyInfoPoint.get("site"));
break;
case "queryCanGoBySite":
sites = world.queryCanGoBySite(historyInfoPoint.get("site"));
break;
case "queryPathBySite":
sites = world.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]);
break;
}
for(String site: sites){
returnStr += site;
}
}
return returnStr;
}
}
...@@ -14,10 +14,7 @@ import javax.servlet.annotation.WebServlet; ...@@ -14,10 +14,7 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; 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.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
...@@ -49,7 +46,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -49,7 +46,7 @@ public class GameDesignServlet extends HttpServlet {
dataId = (Integer) jsonObject.get("id"); dataId = (Integer) jsonObject.get("id");
JSONObject gameElements = helper.queryGameElementsByBotId(dataId); JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
botId = (Integer) gameElements.get("botId"); botId = Integer.parseInt((String) gameElements.get("botId"));
userName = (String) gameElements.get("userName"); userName = (String) gameElements.get("userName");
//假设重新重新建用户信息 //假设重新重新建用户信息
...@@ -101,6 +98,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -101,6 +98,7 @@ public class GameDesignServlet extends HttpServlet {
idList.clear(); idList.clear();
helper.batchInsertVariableByBotId(botId, constructor); helper.batchInsertVariableByBotId(botId, constructor);
helper.batchInsertConfigByBotId(botId, constructor, idList); helper.batchInsertConfigByBotId(botId, constructor, idList);
constructor.postProcessing(idList);
constructor.generateConfigText(idList); constructor.generateConfigText(idList);
mergedConfigText.append(constructor.getConfigText()); mergedConfigText.append(constructor.getConfigText());
...@@ -124,7 +122,9 @@ public class GameDesignServlet extends HttpServlet { ...@@ -124,7 +122,9 @@ public class GameDesignServlet extends HttpServlet {
} }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OutputStream out = response.getOutputStream();
out.write("ssss".getBytes());
out.flush();
} }
public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException {
......
package servlet; package servlet;
import entity.Solution; import entity.*;
import entity.Condition;
import entity.UserInfo;
import processing.ChatCacheController; import processing.ChatCacheController;
import processing.MyFunc; import processing.MyFunc;
import processing.QuestionMatcher; import processing.QuestionMatcher;
...@@ -14,8 +12,7 @@ import javax.servlet.annotation.WebServlet; ...@@ -14,8 +12,7 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; 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.*;
import java.io.OutputStream;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.*;
...@@ -38,12 +35,34 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -38,12 +35,34 @@ public class GetAnswerServlet extends HttpServlet {
Condition ansCondition = null; Condition ansCondition = null;
String ansJ, return_str = "", state = ""; String ansJ, return_str = "", state = "";
String chatKey = curInfoPoint.get("chat_key")[0]; String chatKey = curInfoPoint.get("chat_key")[0];
QuestionMatcher matcher = new QuestionMatcher();
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
boolean debugFlag = false; boolean debugFlag = false;
//获得用户历史信息
historyInfoPoint = ChatCacheController.getChatCache(chatKey, context);
String fileName = "/var/www/html/logs/" + chatKey + ".html";
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
file.setReadable(true,false);
FileWriter fw = new FileWriter(file, true);
//BufferedWriter bw = new BufferedWriter(fos, "UTF-8");
//context.setAttribute("logWriter", bw);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>log</title>\n" +
"</head>");
UserInfo userinfo = null; UserInfo userinfo = null;
...@@ -57,31 +76,20 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -57,31 +76,20 @@ public class GetAnswerServlet extends HttpServlet {
e.printStackTrace(); e.printStackTrace();
} }
//如果historyInfoPoint不存在,就新建一个 //获得用户历史信息
if (historyInfoPoint == null) { ChatCache chatCache = ChatCacheController.getChatCache2(chatKey, context, curInfoPoint, userinfo);
String k; historyInfoPoint = chatCache.getInfoPoint();
historyInfoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
historyInfoPoint.put(k, "");
}
//变量初始化
iit = userinfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
historyInfoPoint.put(k, userinfo.varInitialMap.get(k));
}
}
//信息点预处理 //信息点预处理
debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo); QuestionMatcher matcher = new QuestionMatcher(pw,userinfo, context, chatCache.getWorld());
debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, context);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context); //process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试 //System.out.println(userinfo.conditionTable); //测试
ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context); ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansCondition.priority == -1) if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
...@@ -99,7 +107,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -99,7 +107,7 @@ public class GetAnswerServlet extends HttpServlet {
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") > 300000) { if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > 300000) {
ChatCacheController.updateChatCache4Delete(context); ChatCacheController.updateChatCache4Delete2(chatKey, context);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
} }
//bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); //bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
...@@ -115,6 +123,10 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -115,6 +123,10 @@ public class GetAnswerServlet extends HttpServlet {
matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag);
bw.write("<br><br>" +
"-----------------------------------------对话处理结束-----------------------------------<br><br><br>");
bw.close();
fw.close();
ansJ = MyFunc.toJson(bestMatch); ansJ = MyFunc.toJson(bestMatch);
System.out.println(ansJ); System.out.println(ansJ);
out.write(ansJ.getBytes()); out.write(ansJ.getBytes());
......
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