Commit b76cae13 by hxw

条件中的两条condition相同时要生成两个condition

parent 3c0c6f8a
...@@ -271,6 +271,7 @@ public class SqlHelper { ...@@ -271,6 +271,7 @@ public class SqlHelper {
ps.setString(2, String.valueOf(categoryId)); ps.setString(2, String.valueOf(categoryId));
ps.setString(3, json.toJSONString()); ps.setString(3, json.toJSONString());
ps.setString(4, (String)json.get("configName")); ps.setString(4, (String)json.get("configName"));
ps.addBatch(); ps.addBatch();
} }
...@@ -569,6 +570,31 @@ public class SqlHelper { ...@@ -569,6 +570,31 @@ public class SqlHelper {
} }
} }
public List<ArchiveInfo> queryArchiveByUserKey(String userKey){
String sql = "select * from game_archive where user_key = ? order by update_time desc";
List<ArchiveInfo> archiveList = new ArrayList<ArchiveInfo>();
ArchiveInfo archiveInfo = null;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userKey);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"),
rs.getString("site"), rs.getString("update_time"), rs.getString("plot"));
archiveList.add(archiveInfo);
}
ps.close();
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return archiveList;
}
......
...@@ -10,25 +10,25 @@ import java.util.LinkedHashMap; ...@@ -10,25 +10,25 @@ import java.util.LinkedHashMap;
* 独立于引擎的另一种condition * 独立于引擎的另一种condition
*/ */
public class Action { public class Action {
public int priority = -1; private int priority = -1;
public int activePriority = 0; //如果本condition被其他condition激活 //public int activePriority = 0; //如果本condition被其他condition激活
public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 private int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级
public HashSet<String> keywordSet = new HashSet<String>(); private HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>(); private HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>(); private HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, String> updateKnowledge = new LinkedHashMap<String, String>(); private HashMap<String, String> updateKnowledge = new LinkedHashMap<String, String>();
public String[] answer = {"",}; private String[] answer = {"",};
public String nextStep = ""; private String nextStep = "";
public HashMap<String, String> featureMap = new HashMap<String, String>(); private HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = ""; private String indexName = "";
public int id = 0; private int id = 0;
public String configName = ""; private String configName = "";
public String status = "waiting"; private String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>(); //public ArrayList<String> indexName = new ArrayList<String>();
public Action(int priority) { public Action(int priority) {
this.priority = priority; this.priority = priority;
this.activePriority = priority; //this.activePriority = priority;
} }
/** /**
...@@ -50,7 +50,8 @@ public class Action { ...@@ -50,7 +50,8 @@ public class Action {
this.id = originAction.id; this.id = originAction.id;
this.configName = originAction.configName; this.configName = originAction.configName;
this.status = originAction.status; this.status = originAction.status;
this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级 //this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级
this.priority = originAction.priority + basePriority + 1;
//如果激活originAction的action,它的辅助优先级高于originAction,那么。。 //如果激活originAction的action,它的辅助优先级高于originAction,那么。。
...@@ -63,4 +64,107 @@ public class Action { ...@@ -63,4 +64,107 @@ public class Action {
public Action() { public Action() {
} }
public int getPriority() {
return priority;
}
public int getAuxiliaryPriority() {
return auxiliaryPriority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setAuxiliaryPriority(int auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority;
}
public HashSet<String> getKeywordSet() {
return keywordSet;
}
public HashMap<String, HashSet<String>> getHistoryPremise() {
return historyPremise;
}
public HashMap<String, HashSet<String>> getCurrentPremise() {
return currentPremise;
}
public HashMap<String, String> getUpdateKnowledge() {
return updateKnowledge;
}
public String[] getAnswer() {
return answer;
}
public String getNextStep() {
return nextStep;
}
public HashMap<String, String> getFeatureMap() {
return featureMap;
}
public String getIndexName() {
return indexName;
}
public int getId() {
return id;
}
public String getConfigName() {
return configName;
}
public String getStatus() {
return status;
}
public void setKeywordSet(HashSet<String> keywordSet) {
this.keywordSet = keywordSet;
}
public void setHistoryPremise(HashMap<String, HashSet<String>> historyPremise) {
this.historyPremise = historyPremise;
}
public void setCurrentPremise(HashMap<String, HashSet<String>> currentPremise) {
this.currentPremise = currentPremise;
}
public void setUpdateKnowledge(HashMap<String, String> updateKnowledge) {
this.updateKnowledge = updateKnowledge;
}
public void setAnswer(String[] answer) {
this.answer = answer;
}
public void setNextStep(String nextStep) {
this.nextStep = nextStep;
}
public void setFeatureMap(HashMap<String, String> featureMap) {
this.featureMap = featureMap;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setId(int id) {
this.id = id;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public void setStatus(String status) {
this.status = status;
}
} }
...@@ -11,6 +11,7 @@ import java.util.Map; ...@@ -11,6 +11,7 @@ import java.util.Map;
public class ChatCache implements DisposableBean { public class ChatCache implements DisposableBean {
public String ENV_ERROR = "游戏平台初始化失败";
// private String chatKey = "不知道"; // private String chatKey = "不知道";
private String userKey = ""; private String userKey = "";
private String randKey = ""; private String randKey = "";
...@@ -18,7 +19,8 @@ public class ChatCache implements DisposableBean { ...@@ -18,7 +19,8 @@ public class ChatCache implements DisposableBean {
private Map<String, String> infoPoint = null; private Map<String, String> infoPoint = null;
private GameEnv gameEnv = null; private GameEnv gameEnv = null;
private boolean gameStart = false; private Boolean gameStart = false;
private Boolean reload = false;
public String getBotAccount() { public String getBotAccount() {
...@@ -62,6 +64,14 @@ public class ChatCache implements DisposableBean { ...@@ -62,6 +64,14 @@ public class ChatCache implements DisposableBean {
this.gameStart = gameStart; this.gameStart = gameStart;
} }
public Boolean getReload() {
return reload;
}
public void setReload(Boolean reload) {
this.reload = reload;
}
public GameEnv getGameEnv() { public GameEnv getGameEnv() {
return gameEnv; return gameEnv;
} }
...@@ -86,7 +96,9 @@ public class ChatCache implements DisposableBean { ...@@ -86,7 +96,9 @@ public class ChatCache implements DisposableBean {
try { try {
gameEnv = new GameEnv(userInfo.botAccount); gameEnv = new GameEnv(userInfo.botAccount);
} catch (Exception e) { } catch (Exception e) {
System.out.println("游戏平台初始化失败"); System.out.println(ENV_ERROR);
infoPoint.put("error_message", ENV_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -104,5 +116,8 @@ public class ChatCache implements DisposableBean { ...@@ -104,5 +116,8 @@ public class ChatCache implements DisposableBean {
} }
public ChatCache(String userKey, String randKey) {
this.userKey = userKey;
this.randKey = randKey;
}
} }
...@@ -10,7 +10,17 @@ import java.util.Map; ...@@ -10,7 +10,17 @@ import java.util.Map;
public class ConfigTerm implements Cloneable{ public class ConfigTerm implements Cloneable{
static int iterNum = 0; ThreadLocal<Integer> iterNum=new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
ThreadLocal<Map<String, Integer>> conditionCount = new ThreadLocal<Map<String, Integer>>(){
protected Map<String, Integer> initialValue(){
return new HashMap<String, Integer>();
};
};
private int id = 0; private int id = 0;
private String jCurPremise = ""; private String jCurPremise = "";
...@@ -65,8 +75,11 @@ public class ConfigTerm implements Cloneable{ ...@@ -65,8 +75,11 @@ public class ConfigTerm implements Cloneable{
public void setConfigName(String configName, Boolean append) { public void setConfigName(String configName, Boolean append) {
if(append) { if(append) {
iterNum++;
this.configName = configName + "_" + iterNum; iterNum.set(iterNum.get() + 1);
//iterNum++;
this.configName = configName + "_" + iterNum.get();
}else{ }else{
this.configName = configName; this.configName = configName;
} }
...@@ -218,7 +231,7 @@ public class ConfigTerm implements Cloneable{ ...@@ -218,7 +231,7 @@ public class ConfigTerm implements Cloneable{
} }
public ConfigTerm(List<String> curPremise, List<String> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { public ConfigTerm(List<Premise> curPremise, List<Premise> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP); this.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
...@@ -228,21 +241,46 @@ public class ConfigTerm implements Cloneable{ ...@@ -228,21 +241,46 @@ public class ConfigTerm implements Cloneable{
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public String appendPremiseStr(List<String> premises, String extraPM) { public String appendPremiseStr(List<Premise> premises, String extraPremise) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String premiseStr = ""; String premiseStr = "", conditionName;
Map<String ,Integer> nameCount = new HashMap<String , Integer>();
for (Premise premise : premises){
//设置初始值
//System.out.println("nameCount" + nameCount);
conditionName = premise.getConditionName();
nameCount.putIfAbsent(conditionName, 0);
for (String premise : premises) //nameCount加一
sb.append("," + premise); nameCount.put(conditionName, nameCount.get(conditionName) + 1);
//在conditionName后添加count
if(nameCount.get(conditionName) > 1) {
premise.setConditionName(conditionName + nameCount.get(conditionName));
}
sb.append(",");
sb.append(premise.getConditionName());
sb.append("::");
sb.append(premise.getCmpType());
sb.append("-");
sb.append(premise.getOperator());
sb.append("=");
sb.append(premise.getKeyword());
}
if (sb.length() > 0) if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号 sb.deleteCharAt(0); //删除第一个逗号
if (!extraPM.equals("")) { if (!extraPremise.equals("")) {
if (sb.length() == 0) if (sb.length() == 0)
sb.append(extraPM); sb.append(extraPremise);
else else
sb.append("," + extraPM); sb.append("," + extraPremise);
} else if (sb.length() == 0) { } else if (sb.length() == 0) {
sb.append(" "); sb.append(" ");
} }
...@@ -255,7 +293,7 @@ public class ConfigTerm implements Cloneable{ ...@@ -255,7 +293,7 @@ public class ConfigTerm implements Cloneable{
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr; String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator(); Iterator<String> iit = knowledge.keySet().iterator();
Boolean delayUpdateFollowerLocation = false; Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后
String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = "";
while (iit.hasNext()) { while (iit.hasNext()) {
...@@ -436,18 +474,23 @@ public class ConfigTerm implements Cloneable{ ...@@ -436,18 +474,23 @@ public class ConfigTerm implements Cloneable{
} }
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer();
String text = curPremise + "|" + sb.append(curPremise).append("|");
hisPremise + "|" + sb.append(hisPremise);
feature + "," + updateKnowledge + "," + nextStepStatus + "|" + sb.append("|").append(feature).append(",");
"auxiliaryPriority=" + auxiliaryPriority + "|" + sb.append(updateKnowledge).append(",");
"configName=" + configName + "|=>|" + sb.append(nextStepStatus).append( "|");
reply + "|" + sb.append("auxiliaryPriority=");
"nextStep=" + nextStep + "|" + sb.append(auxiliaryPriority).append("|").append("configName=");
"status=" + status + "|" + sb.append(configName);
"configId="; sb.append("|=>|").append(reply);
sb.append("|").append("nextStep=");
sb.append(nextStep).append("|");
sb.append("status=").append(status);
sb.append("|").append("configId=");
return text; return sb.toString();
} }
public Object clone() { public Object clone() {
...@@ -467,11 +510,6 @@ public class ConfigTerm implements Cloneable{ ...@@ -467,11 +510,6 @@ public class ConfigTerm implements Cloneable{
ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone();
// if(configTerm.getHisPremise().equals(" "))
// configTerm.setHisPremise("临时变量condition::match-Include=+null");
// else
// configTerm.setHisPremise(configTerm.getjHisPremise() + ",临时变量condition::match-Include=+null");
// configTerm.setConfigName(name, true);
if(configTerm2.getUpdateKnowledge().equals("")) if(configTerm2.getUpdateKnowledge().equals(""))
configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}");
...@@ -479,14 +517,12 @@ public class ConfigTerm implements Cloneable{ ...@@ -479,14 +517,12 @@ public class ConfigTerm implements Cloneable{
configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTerm2.setConfigName(name, true); configTerm2.setConfigName(name, true);
//configTermList.add(configTerm);
configTermList.add(configTerm2); configTermList.add(configTerm2);
} }
public static ConfigTerm simpleCopy(ConfigTerm configTerm){ public ConfigTerm simpleCopy(ConfigTerm configTerm){
ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone();
......
package com.qiwu.chatbotbackend.entity;
public class Premise {
private String conditionName = "";
private String cmpType = "";
private String operator = "";
private String keyword = "";
public Premise(String conditionName, String cmpType, String operator, String keyword) {
this.conditionName = conditionName;
this.cmpType = cmpType;
this.operator = operator;
this.keyword = keyword;
}
public String getConditionName() {
return conditionName;
}
public void setConditionName(String conditionName) {
this.conditionName = conditionName;
}
public String getCmpType() {
return cmpType;
}
public void setCmpType(String cmpType) {
this.cmpType = cmpType;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
package com.qiwu.chatbotbackend.gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -42,6 +40,7 @@ public class GlobalVariableConstructor extends ElementConstructor { ...@@ -42,6 +40,7 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put("botType", "game"); varInitialMap.put("botType", "game");
varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList"));
varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText"));
varInitialMap.put("CC_URL", keywordMap.get("CC_URL").toString());
JSONObject script = gameElements.getJSONObject("speechcraft"); JSONObject script = gameElements.getJSONObject("speechcraft");
......
...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; ...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -34,10 +35,14 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -34,10 +35,14 @@ public class ListeningConstructor extends ElementConstructor{
String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority;
String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep;
Boolean autoJump = false; Boolean autoJump = false;
List<String> curPremiseList = new ArrayList<String>(); List<Premise> curPremiseList = new ArrayList<Premise>();
List<String> hisPremiseList = new ArrayList<String>(); List<Premise> hisPremiseList = new ArrayList<Premise>();
JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); JSONArray listeningActions = gameELments.getJSONArray("listeningActions");
JSONObject plotNode = null; JSONObject plotNode = null;
if(listeningActions == null)
return;
size = listeningActions.size(); size = listeningActions.size();
JSONObject config = null; JSONObject config = null;
...@@ -47,8 +52,8 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -47,8 +52,8 @@ public class ListeningConstructor extends ElementConstructor{
priority = "2"; priority = "2";
feature = "match"; feature = "match";
config = listeningActions.getJSONObject(i); config = listeningActions.getJSONObject(i);
curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), String.class); curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), Premise.class);
hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), String.class); hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), Premise.class);
Map<String, String> updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); Map<String, String> updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class);
nextPlotId = config.getString("nextPlotId"); nextPlotId = config.getString("nextPlotId");
...@@ -71,7 +76,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -71,7 +76,7 @@ public class ListeningConstructor extends ElementConstructor{
if(autoJump){ if(autoJump){
feature = "match,activate:after"; feature = "match,activate:after";
updateKnowledge.put("plot_jump_text", "str+" + reply); updateKnowledge.put("plot_jump_text", "str+" + reply);
nextCondition = "plot_" + nextPlotId + "_*"; nextCondition = "plot_" + nextPlotId;
reply = ""; reply = "";
}else{ }else{
feature = "match"; feature = "match";
......
...@@ -384,6 +384,16 @@ public class MapConstructor extends ElementConstructor { ...@@ -384,6 +384,16 @@ public class MapConstructor extends ElementConstructor {
configTerm.setjStatus(1); configTerm.setjStatus(1);
configTermList.add(configTerm); configTermList.add(configTerm);
//上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step
configTerm = new ConfigTerm(
lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA
+ "-<-npc_update:updateFollowerLocation:" + placeA
);
configTerm.setStatus("sleeping");
configTerm.setConfigName("plot_" + placeA + "_doudi2", false);
configTerm.setjStatus(1);
configTermList.add(configTerm);
} }
...@@ -418,6 +428,21 @@ public class MapConstructor extends ElementConstructor { ...@@ -418,6 +428,21 @@ public class MapConstructor extends ElementConstructor {
configTerm.setConfigName("map", true); configTerm.setConfigName("map", true);
configTermList.add(configTerm); configTermList.add(configTerm);
/**
* 要去的地方不可到达
*/
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + toAllSiteskeywords
+ ",isNeighbour:" + conditionName + "::match-Include=5",
" ",
"match,return-0",
"",
" ",
"map_query:queryPathNotExist:"
);
configTerm.setConfigName("map", true);
configTermList.add(configTerm);
} }
......
...@@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.task.utils.FileFinder;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
...@@ -76,7 +77,8 @@ public class ChatCacheController { ...@@ -76,7 +77,8 @@ public class ChatCacheController {
} catch (Exception e) { } catch (Exception e) {
//可整合 //可整合
e.printStackTrace(); e.printStackTrace();
chatCache = new ChatCache(userinfo, userKey, randKey);
//chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache); chatCacheMap.put(userKey, chatCache);
} }
...@@ -92,6 +94,10 @@ public class ChatCacheController { ...@@ -92,6 +94,10 @@ public class ChatCacheController {
String nowTime = now .format(format), userId, botAccount, keyElem[]; String nowTime = now .format(format), userId, botAccount, keyElem[];
Boolean opFlag, destroy = false; Boolean opFlag, destroy = false;
if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey()))
return true;
System.out.println("游戏存档中"); System.out.println("游戏存档中");
String userKey = chatCache.getUserKey(); String userKey = chatCache.getUserKey();
...@@ -249,21 +255,29 @@ public class ChatCacheController { ...@@ -249,21 +255,29 @@ public class ChatCacheController {
SqlHelper helper; SqlHelper helper;
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
helper = new SqlHelper();
if (context.getAttribute("chatCache") != null) {
if (context.getAttribute("chatCache") == null) { chatCacheMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache");
chatCacheMap = new HashMap<String, ChatCache>();
if (chatCacheMap.containsKey(userKey)) { if (chatCacheMap.containsKey(userKey)) {
chatCache = chatCacheMap.get(userKey); chatCache = chatCacheMap.get(userKey);
findFlag = !(chatCache.getUserKey().endsWith(chatCache.getRandKey())); //userKey和randKey不同表示存在用户id,如果相同则没有登录只是试玩
// //保存到本地,并从chatCacheMap中删除
if(!chatCache.getUserKey().endsWith(chatCache.getRandKey()) && chatCache.isGameStart()){
findFlag = true;
saveChatCache(chatCache, helper);
chatCacheMap.remove(userKey);
}
} }
} }
System.out.println("findFlag" + findFlag);
if (!findFlag) { if (!findFlag) {
helper = new SqlHelper();
archiveInfo = helper.queryUserLastGameArchive(userKey); archiveInfo = helper.queryUserLastGameArchive(userKey);
helper.destroy(); helper.destroy();
...@@ -280,4 +294,13 @@ public class ChatCacheController { ...@@ -280,4 +294,13 @@ public class ChatCacheController {
} }
public static Boolean deleteChatCache(SqlHelper helper, String botAccount){
Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount);
Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount);
return sqlDeleteFlag && fileDeleteFlag;
}
} }
...@@ -86,7 +86,7 @@ public class FormsPoster { ...@@ -86,7 +86,7 @@ public class FormsPoster {
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator(); Iterator<String> kit = jobj.keySet().iterator();
...@@ -133,14 +133,14 @@ public class FormsPoster { ...@@ -133,14 +133,14 @@ public class FormsPoster {
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
k_iter = ansAction.currentPremise.keySet().iterator(); k_iter = ansAction.getCurrentPremise().keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) if (curInfoPoint.get(key) != null && !curInfoPoint.equals(""))
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
} }
k_iter = ansAction.historyPremise.keySet().iterator(); k_iter = ansAction.getHistoryPremise().keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
if(!historyInfoPoint.get(key).equals("")) { if(!historyInfoPoint.get(key).equals("")) {
...@@ -154,7 +154,7 @@ public class FormsPoster { ...@@ -154,7 +154,7 @@ public class FormsPoster {
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator(); Iterator<String> kit = jobj.keySet().iterator();
...@@ -202,9 +202,15 @@ public class FormsPoster { ...@@ -202,9 +202,15 @@ public class FormsPoster {
pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text")));
pairList.add(new BasicNameValuePair("qa_threshold", threshold)); pairList.add(new BasicNameValuePair("qa_threshold", threshold));
//设置初始值
historyInfoPoint.put("common_answer", "");
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", "OK");
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
...@@ -212,10 +218,7 @@ public class FormsPoster { ...@@ -212,10 +218,7 @@ public class FormsPoster {
System.out.println(jobj.toJSONString()); System.out.println(jobj.toJSONString());
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){ if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){
//设置初始值
historyInfoPoint.put("common_answer", "");
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", "OK");
List<JSONArray> candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); List<JSONArray> candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class);
for(JSONArray pair:candidates){ for(JSONArray pair:candidates){
...@@ -230,31 +233,24 @@ public class FormsPoster { ...@@ -230,31 +233,24 @@ public class FormsPoster {
if (m.find()) { if (m.find()) {
npc = m.group(1); npc = m.group(1);
if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController, historyInfoPoint.get("site"), logWriter) == 1)) { if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, historyInfoPoint.get("site"), logWriter) == 1)) {
historyInfoPoint.put("common_answer", (String)textscore.get(0)); historyInfoPoint.put("common_answer", (String)textscore.get(0));
historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1)));
break; break;
} }
} }
} }
} }
}else{
historyInfoPoint.put("common_answer", (String)jobj.get("common_answer"));
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", (String)jobj.get("qa_status"));
} }
}else { }else {
ans.setAnswer("提交表单出现异常"); historyInfoPoint.put("error_message", jobj.getString("error_message"));
} }
} }
public void postGameQA(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { public void postGameQA(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException {
postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo); postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo);
if(historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer")){ 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); postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo);
} }
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
// String site = historyInfoPoint.get("site"); // String site = historyInfoPoint.get("site");
// //
// //
// reply = MyFunc.randStr(reply.split("~")); // reply = SimpleUtil.randStr(reply.split("~"));
// //
// if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 // if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪
// return reply; // return reply;
...@@ -75,7 +75,7 @@ ...@@ -75,7 +75,7 @@
// } // }
// } // }
// if (unknownList.size() > 0) { // if (unknownList.size() > 0) {
// return MyFunc.randStr(unknownList); // return SimpleUtil.randStr(unknownList);
// } // }
// //
// } // }
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
// } // }
// } // }
// if(finalUnknownList.size() > 0){ // if(finalUnknownList.size() > 0){
// return MyFunc.randStr(finalUnknownList); // return SimpleUtil.randStr(finalUnknownList);
// //
// } // }
// } // }
...@@ -181,7 +181,7 @@ ...@@ -181,7 +181,7 @@
// } // }
// } // }
// if(filtedNpcList.size() != 0) // if(filtedNpcList.size() != 0)
// npc = MyFunc.randStr(filtedNpcList); // npc = SimpleUtil.randStr(filtedNpcList);
// else // else
// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); // npc = historyInfoPoint.get(PlotConstructor.ASSISTANT);
// //
......
package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class SimpleUtil {
/**
* 将后台返回的数据转成json格式
*/
public static String toJson(Solution ans) {
JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus());
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject();
jobj.put("returnString", returnStr);
return jobj.toString();
}
/**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据
*
* @param request
* @return json字符串
*/
public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
json.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 通过get方法传递参数时需要对参数的编码进行转换
*/
public static String convert2Utf8(String s) {
if (s == null) return null;
try {
s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
public static long transferToMillisecond(String keyword) throws ParseException {
long time;
System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"};
for (String f : timeSeries) {
if (!keyword.contains(f))
keyword += "0" + f;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
time = format.parse(keyword).getTime();
return time;
}
public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
Date date = new Date(time);
return format.format(date);
}
public static boolean isInteger(String str){
return true;
}
public static JSONObject postJSON(String url, JSON data, String auth) throws UnsupportedEncodingException {
JSONObject jobj = new JSONObject();
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
StringEntity entity = new StringEntity(data.toJSONString(), "utf-8");
entity.setContentType("application/json; charset=utf-8");
httpPost.setEntity(entity);
if(auth != null){
httpPost.setHeader("Authorization", auth);
}
try {
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else {
jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
return jobj;
}
public static JSONObject postFORM(String url, List<BasicNameValuePair> pairList) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
JSONObject jobj = new JSONObject();
try {
System.out.println("url为:" + url);
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else {
jobj.put("post_status", 0);
jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode());
}
} catch (Exception e) {
jobj.put("error_message", "提交表单时出错:" + e.getMessage());
jobj.put("post_status", 0);
}
return jobj;
}
public static String randStr(String strList[]){
String reply;
int randNum = (int) (Math.random() * strList.length);
reply = strList[randNum];
return reply;
}
public static String randStr(List<String> strList){
String reply;
int randNum = (int) (Math.random() * strList.size());
reply = strList.get(randNum);
return reply;
}
}
\ No newline at end of file
...@@ -103,25 +103,25 @@ public class UserInfoController { ...@@ -103,25 +103,25 @@ public class UserInfoController {
history_premises = premises[1].split(","); history_premises = premises[1].split(",");
if (premises.length < 4) if (premises.length < 4)
action.auxiliaryPriority = 0; action.setAuxiliaryPriority(0);
else else
action.auxiliaryPriority = Integer.parseInt(premises[3].split("=", 2)[1]); action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
if(premises.length < 5) if(premises.length < 5)
action.configName = ""; action.setConfigName("");
else else
action.configName = premises[4].split("=", 2)[1]; action.setConfigName(premises[4].split("=", 2)[1]);
next = element[1].split("\\|"); next = element[1].split("\\|");
if (next.length < 4) if (next.length < 4)
return action; return action;
action.answer = next[0].split("~"); action.setAnswer(next[0].split("~"));
//action.nextStep = next[1]; //action.nextStep = next[1];
//第二处 //第二处
action.nextStep = next[1].split("=", 2)[1]; action.setNextStep(next[1].split("=", 2)[1]);
action.id = Integer.parseInt(next[3].split("=")[1]); action.setId(Integer.parseInt(next[3].split("=")[1]));
action.status = next[2].split("=")[1]; action.setStatus(next[2].split("=")[1]);
//featureMap的构建 //featureMap的构建
...@@ -132,31 +132,31 @@ public class UserInfoController { ...@@ -132,31 +132,31 @@ public class UserInfoController {
} else if (feat.startsWith("updateKnowledge")) { } else if (feat.startsWith("updateKnowledge")) {
String[] knowledge = feat.split("-<-"); String[] knowledge = feat.split("-<-");
int length = knowledge.length; int length = knowledge.length;
action.featureMap.put("updateKnowledge", ""); action.getFeatureMap().put("updateKnowledge", "");
for (int i = 1; i < length; i++) { for (int i = 1; i < length; i++) {
if (knowledge[i].equals("") || knowledge[i].equals(" ")) if (knowledge[i].equals("") || knowledge[i].equals(" "))
continue; continue;
pair = knowledge[i].split(":", 2); pair = knowledge[i].split(":", 2);
action.updateKnowledge.put(pair[0], pair[1]); action.getUpdateKnowledge().put(pair[0], pair[1]);
} }
} else if (feat.startsWith("post")) { } else if (feat.startsWith("post")) {
pair = feat.split("\\(", 2); pair = feat.split("\\(", 2);
url = pair[1]; url = pair[1];
url = url.substring(0, url.length() - 1); url = url.substring(0, url.length() - 1);
pair = pair[0].split("::"); pair = pair[0].split("::");
action.featureMap.put("post", url + "|" + pair[1]); action.getFeatureMap().put("post", url + "|" + pair[1]);
} else { } else {
action.featureMap.put(feat, ""); action.getFeatureMap().put(feat, "");
} }
} }
insertPremise(action.currentPremise, cur_premises); insertPremise(action.getCurrentPremise(), cur_premises);
insertPremise(action.historyPremise, history_premises); insertPremise(action.getHistoryPremise(), history_premises);
//满足条件越多,优先级越大 //满足条件越多,优先级越大
action.priority = action.historyPremise.size() + action.currentPremise.size(); action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size());
action.activePriority = action.priority; //action.activePriority = action.priority;
/* /*
for(String premise:cur_premises){ for(String premise:cur_premises){
pair = premise.split("="); pair = premise.split("=");
...@@ -165,9 +165,9 @@ public class UserInfoController { ...@@ -165,9 +165,9 @@ public class UserInfoController {
*/ */
firstCnditionName = cur_premises[0]; firstCnditionName = cur_premises[0];
if (firstCnditionName.equals(" ")) if (firstCnditionName.equals(" "))
action.indexName = "emptySet"; action.setIndexName("emptySet");
else else
action.indexName = firstCnditionName.split("=")[0].split("::")[0]; action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(line); System.out.println(line);
...@@ -220,17 +220,17 @@ public class UserInfoController { ...@@ -220,17 +220,17 @@ public class UserInfoController {
} else { } else {
Action action = new Action(); Action action = new Action();
action = buildCondition(action, line); action = buildCondition(action, line);
actionList = conditionTable.get(action.indexName); actionList = conditionTable.get(action.getIndexName());
if (actionList == null) if (actionList == null)
actionList = new ArrayList<Action>(); actionList = new ArrayList<Action>();
actionList.add(action); actionList.add(action);
conditionTable.put(action.indexName, actionList); conditionTable.put(action.getIndexName(), actionList);
if (action.id != 0) { if (action.getId() != 0) {
if(!action.configName.equals("")){ if(!action.getConfigName().equals("")){
userinfo.name2condition.put(action.configName, action); userinfo.name2condition.put(action.getConfigName(), action);
} }
userinfo.id2config.put(action.id, line); userinfo.id2config.put(action.getId(), line);
userinfo.id2condition.put(action.id, action); userinfo.id2condition.put(action.getId(), action);
} }
} }
...@@ -326,7 +326,7 @@ public class UserInfoController { ...@@ -326,7 +326,7 @@ public class UserInfoController {
//------------------- //-------------------
try { try {
conditionName = oldAction.indexName; conditionName = oldAction.getIndexName();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -337,13 +337,13 @@ public class UserInfoController { ...@@ -337,13 +337,13 @@ public class UserInfoController {
Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator(); Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) { while (condIter.hasNext()) {
Action c = condIter.next(); Action c = condIter.next();
if (c.id == id) { if (c.getId() == id) {
condIter.remove(); condIter.remove();
} }
} }
} }
userInfo.name2condition.remove(oldAction.configName); userInfo.name2condition.remove(oldAction.getConfigName());
userInfo.id2config.remove(id); userInfo.id2config.remove(id);
userInfo.id2condition.remove(id); userInfo.id2condition.remove(id);
} else { } else {
...@@ -362,7 +362,7 @@ public class UserInfoController { ...@@ -362,7 +362,7 @@ public class UserInfoController {
Action oldAction = userInfo.id2condition.get(configId); Action oldAction = userInfo.id2condition.get(configId);
try { try {
conditionName = oldAction.indexName; conditionName = oldAction.getIndexName();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -373,13 +373,13 @@ public class UserInfoController { ...@@ -373,13 +373,13 @@ public class UserInfoController {
Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator(); Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) { while (condIter.hasNext()) {
Action c = condIter.next(); Action c = condIter.next();
if (c.id == configId) { if (c.getId() == configId) {
condIter.remove(); condIter.remove();
} }
} }
} }
userInfo.name2condition.remove(oldAction.configName); userInfo.name2condition.remove(oldAction.getConfigName());
userInfo.id2config.remove(configId); userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId); userInfo.id2condition.remove(configId);
} else { } else {
...@@ -408,15 +408,15 @@ public class UserInfoController { ...@@ -408,15 +408,15 @@ public class UserInfoController {
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.conditionTable.get(action.indexName) == null) { if (userinfo.conditionTable.get(action.getIndexName()) == null) {
List<Action> actionList = new ArrayList<Action>(); List<Action> actionList = new ArrayList<Action>();
userinfo.conditionTable.put(action.indexName, actionList); userinfo.conditionTable.put(action.getIndexName(), actionList);
} }
if(!action.configName.equals("")){ if(!action.getConfigName().equals("")){
userinfo.name2condition.put(action.configName, action); userinfo.name2condition.put(action.getConfigName(), action);
} }
userinfo.conditionTable.get(action.indexName).add(action); userinfo.conditionTable.get(action.getIndexName()).add(action);
userinfo.id2config.put(id, configLine); userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, action); userinfo.id2condition.put(id, action);
......
...@@ -11,8 +11,6 @@ import java.util.List; ...@@ -11,8 +11,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.ASSISTANT_EMOTION;
public class WorldController { public class WorldController {
public LogWriter logWriter = null; public LogWriter logWriter = null;
public UserInfo userInfo = null; public UserInfo userInfo = null;
...@@ -223,7 +221,7 @@ public class WorldController { ...@@ -223,7 +221,7 @@ public class WorldController {
lastTalker = m.group(1); lastTalker = m.group(1);
} }
returnStr = String.format(PlotConstructor2.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker);
break; break;
...@@ -387,6 +385,10 @@ public class WorldController { ...@@ -387,6 +385,10 @@ public class WorldController {
} }
} }
break; break;
case "queryPathNotExist":
returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination;
break;
case "queryAroundPlace": case "queryAroundPlace":
if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) { if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) {
format = userInfo.varInitialMap.get("AROUND_PLACE"); format = userInfo.varInitialMap.get("AROUND_PLACE");
......
...@@ -5,9 +5,9 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -5,9 +5,9 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.gameDesign.*;
import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.UserInfoController; import com.qiwu.chatbotbackend.processing.UserInfoController;
import com.qiwu.chatbotbackend.task.utils.FileFinder;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -21,8 +21,6 @@ import java.time.LocalDateTime; ...@@ -21,8 +21,6 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.CHAT_CACHE_DIR;
@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
...@@ -79,7 +77,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -79,7 +77,7 @@ public class GameDesignServlet extends HttpServlet {
} }
//读取并解析json数据 //读取并解析json数据
String jsonStr = MyFunc.readJSONString(request); String jsonStr = SimpleUtil.readJSONString(request);
if (jsonStr != null && !jsonStr.equals("")) { if (jsonStr != null && !jsonStr.equals("")) {
...@@ -217,10 +215,6 @@ public class GameDesignServlet extends HttpServlet { ...@@ -217,10 +215,6 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
if(returnStatus == 1){
deleteOldArchive(helper, botAccount);
}
helper.destroy(); helper.destroy();
...@@ -267,7 +261,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -267,7 +261,7 @@ public class GameDesignServlet extends HttpServlet {
boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); boolean deleteVariableFlag = helper.deleteVariableByBotId(botId);
boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId);
boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap);
boolean deleteArchiveFlag = deleteOldArchive(helper, botAccount); boolean deleteArchiveFlag = ChatCacheController.deleteChatCache(helper, botAccount);
return deleteConfigFlag && deleteVariableFlag; return deleteConfigFlag && deleteVariableFlag;
...@@ -286,40 +280,44 @@ public class GameDesignServlet extends HttpServlet { ...@@ -286,40 +280,44 @@ public class GameDesignServlet extends HttpServlet {
actionPostData.put("botName", botName); actionPostData.put("botName", botName);
actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("botId", (Integer)gameElements.get("botId"));
actionPostData.put("type", "game_plot_init"); actionPostData.put("type", "game_plot_init");
actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始剧情或者重新开始"); actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始");
actionPostData.put("relationKeywords", additionalKeywords); actionPostData.put("relationKeywords", additionalKeywords);
actionPostData.put("auth", gameElements.get("auth")); actionPostData.put("auth", gameElements.get("auth"));
if (gameElements.containsKey("POS")) if (gameElements.containsKey("POS"))
POS2 = (String)gameElements.get("POS"); POS2 = (String)gameElements.get("POS");
actionPostData.put("POS", POS.toString() + POS2); actionPostData.put("POS", POS.toString() + POS2);
System.out.println(actionPostData.toJSONString());
userInfo.extraInfo.put("activeAction", startCondition); userInfo.extraInfo.put("activeAction", startCondition);
try { try {
returnMessage = MyFunc.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth")); returnMessage = SimpleUtil.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
if((Integer)returnMessage.get("post_status") == 1 && (Integer)returnMessage.get("status") == 1 ) { if(returnMessage.getInteger("post_status") == 1 && returnMessage.getInteger("status") != null && returnMessage.getInteger("status") == 1 ) {
return "success"; return "success";
}else { }else {
System.out.println(returnMessage.get("parameter")); System.out.println(returnMessage.get("parameter"));
System.out.println("语义关系修改失败"); System.out.println("语义关系生成失败");
return (String)returnMessage.get("parameter"); return (String)returnMessage.get("parameter");
} }
} }
//从配置文件中读取生成状态表所需要的关键词
public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){ public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){
File file = new File(path); File file = new File(path);
String line, pair[]; String line, pair[];
//System.out.println(file.getAbsolutePath());
if(file.exists()){ if(file.exists()){
FileReader reader = null; FileReader reader = null;
try { try {
...@@ -342,13 +340,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -342,13 +340,7 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
public Boolean deleteOldArchive(SqlHelper helper, String botAccount){
Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount);
Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount);
return sqlDeleteFlag && fileDeleteFlag;
}
......
...@@ -122,14 +122,16 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -122,14 +122,16 @@ public class GetAnswerServlet extends HttpServlet {
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansAction.priority == -1) if (state.equals("") && ansAction.getPriority()== -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { try {
System.out.println("test2");
bestMatch = matcher.getSolution(ansAction, context, userinfo); bestMatch = matcher.getSolution(ansAction, context, userinfo);
if ((ansAction.featureMap.containsKey("activate") && ansAction.featureMap.containsKey("post")) || ansAction.featureMap.containsKey("activate:after")) {
//读档成功不应该再激活
//if(matcher.)
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
} }
...@@ -165,7 +167,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -165,7 +167,7 @@ public class GetAnswerServlet extends HttpServlet {
ansJ = MyFunc.toJson(bestMatch); ansJ = SimpleUtil.toJson(bestMatch);
} else { } else {
ansJ = "找不到配置文件"; ansJ = "找不到配置文件";
} }
......
...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; ...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Action;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.UserInfoController; import com.qiwu.chatbotbackend.processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -54,16 +54,16 @@ public class UpdateServlet extends HttpServlet { ...@@ -54,16 +54,16 @@ public class UpdateServlet extends HttpServlet {
userinfo.configStr += line + "\n"; userinfo.configStr += line + "\n";
continue; continue;
} }
//line = MyFunc.convert2Utf8(line.trim()); //line = SimpleUtil.convert2Utf8(line.trim());
userinfo.configStr += line + "\n"; userinfo.configStr += line + "\n";
Action action = new Action(); Action action = new Action();
try { try {
action = UserInfoController.buildCondition(action, line); action = UserInfoController.buildCondition(action, line);
actionList = userinfo.conditionTable.get(action.indexName); actionList = userinfo.conditionTable.get(action.getIndexName());
if (actionList == null) if (actionList == null)
actionList = new ArrayList<Action>(); actionList = new ArrayList<Action>();
actionList.add(action); actionList.add(action);
userinfo.conditionTable.put(action.indexName, actionList); userinfo.conditionTable.put(action.getIndexName(), actionList);
/* /*
for(String name:action.indexName){ for(String name:action.indexName){
userinfo.conditionTable.put() userinfo.conditionTable.put()
...@@ -84,7 +84,7 @@ public class UpdateServlet extends HttpServlet { ...@@ -84,7 +84,7 @@ public class UpdateServlet extends HttpServlet {
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); String returnStr = SimpleUtil.toJson("更新失败,以下行有误:" + errorStr + "\\\n");
out.println("更新失败,以下行有误: "); out.println("更新失败,以下行有误: ");
for (String error : errorList) for (String error : errorList)
out.println("---" + error); out.println("---" + error);
......
...@@ -31,14 +31,23 @@ public class BasicBotUtil { ...@@ -31,14 +31,23 @@ public class BasicBotUtil {
} }
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
return infoPointPreprocessing(receiveParameters, context); return infoPointPreprocessing(receiveParameters, context, true);
} }
//在接收到请求后对数据做处理,转化为系统可以处理的数据 //在接收到请求后对数据做处理,转化为系统可以处理的数据
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
/**
*
* @param receiveParameters
* @param context
* @param setUnknown 如果什么都没识别到就将上一个激活的condition设为unknown
* @return
* @throws IOException
*/
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context, Boolean setUnknown) throws IOException {
String return_str = "", k, botType = ""; String return_str = "", k, botType = "";
String receiveParameterStr = ""; String receiveParameterStr = "";
...@@ -71,12 +80,8 @@ public class BasicBotUtil { ...@@ -71,12 +80,8 @@ public class BasicBotUtil {
String values[] = receiveParameters.get(k); String values[] = receiveParameters.get(k);
// for (String v : values) {
// receiveParameterStr += v + " ";
// }
receiveParameterStr += values[0] + " " + "<br>"; receiveParameterStr += values[0] + " " + "<br>";
if (values[0].equals(":")) { if (values[0].equals(":")) {
curInfoPoint.put(k, ""); curInfoPoint.put(k, "");
} }
...@@ -86,7 +91,7 @@ public class BasicBotUtil { ...@@ -86,7 +91,7 @@ public class BasicBotUtil {
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator(); iit = curInfoPoint.keySet().iterator();
boolean unknown_flag = true; boolean unknown_flag = setUnknown;
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
String values = curInfoPoint.get(k); String values = curInfoPoint.get(k);
...@@ -126,6 +131,10 @@ public class BasicBotUtil { ...@@ -126,6 +131,10 @@ public class BasicBotUtil {
} }
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ 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"));
}
return true; return true;
} }
......
package com.qiwu.chatbotbackend.task.utils;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.processing.SimpleUtil;
import java.io.UnsupportedEncodingException;
public class DataDeliver extends Thread {
JSONObject data = null;
String url = "";
public void setData(JSONObject data) {
this.data = data;
}
public void setUrl(String url) {
this.url = url;
}
public void run()
{
System.out.println("线程开始");
System.out.println(url);
try {
SimpleUtil.postJSON(url, data, null);
System.out.println("线程完成");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
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