diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 8308a8b..4ddefaf 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -271,6 +271,7 @@ public class SqlHelper { ps.setString(2, String.valueOf(categoryId)); ps.setString(3, json.toJSONString()); ps.setString(4, (String)json.get("configName")); + ps.addBatch(); } @@ -569,6 +570,31 @@ public class SqlHelper { } } + public List queryArchiveByUserKey(String userKey){ + String sql = "select * from game_archive where user_key = ? order by update_time desc"; + List archiveList = new ArrayList(); + 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; + } + diff --git a/src/entity/Action.java b/src/entity/Action.java index 54304cd..4f4bf7f 100644 --- a/src/entity/Action.java +++ b/src/entity/Action.java @@ -10,25 +10,25 @@ import java.util.LinkedHashMap; * 独立于引擎的另一种condition */ public class Action { - public int priority = -1; - public int activePriority = 0; //如果本condition被其他condition激活 - public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 - public HashSet keywordSet = new HashSet(); - public HashMap> historyPremise = new HashMap>(); - public HashMap> currentPremise = new HashMap>(); - public HashMap updateKnowledge = new LinkedHashMap(); - public String[] answer = {"",}; - public String nextStep = ""; - public HashMap featureMap = new HashMap(); - public String indexName = ""; - public int id = 0; - public String configName = ""; - public String status = "waiting"; + private int priority = -1; + //public int activePriority = 0; //如果本condition被其他condition激活 + private int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 + private HashSet keywordSet = new HashSet(); + private HashMap> historyPremise = new HashMap>(); + private HashMap> currentPremise = new HashMap>(); + private HashMap updateKnowledge = new LinkedHashMap(); + private String[] answer = {"",}; + private String nextStep = ""; + private HashMap featureMap = new HashMap(); + private String indexName = ""; + private int id = 0; + private String configName = ""; + private String status = "waiting"; //public ArrayList indexName = new ArrayList(); public Action(int priority) { this.priority = priority; - this.activePriority = priority; + //this.activePriority = priority; } /** @@ -50,7 +50,8 @@ public class Action { this.id = originAction.id; this.configName = originAction.configName; 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,那么。。 @@ -63,4 +64,107 @@ public class 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 getKeywordSet() { + return keywordSet; + } + + public HashMap> getHistoryPremise() { + return historyPremise; + } + + public HashMap> getCurrentPremise() { + return currentPremise; + } + + public HashMap getUpdateKnowledge() { + return updateKnowledge; + } + + public String[] getAnswer() { + return answer; + } + + public String getNextStep() { + return nextStep; + } + + public HashMap 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 keywordSet) { + this.keywordSet = keywordSet; + } + + public void setHistoryPremise(HashMap> historyPremise) { + this.historyPremise = historyPremise; + } + + public void setCurrentPremise(HashMap> currentPremise) { + this.currentPremise = currentPremise; + } + + public void setUpdateKnowledge(HashMap updateKnowledge) { + this.updateKnowledge = updateKnowledge; + } + + public void setAnswer(String[] answer) { + this.answer = answer; + } + + public void setNextStep(String nextStep) { + this.nextStep = nextStep; + } + + public void setFeatureMap(HashMap 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; + } } diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index 6171e98..4da13e5 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -11,6 +11,7 @@ import java.util.Map; public class ChatCache implements DisposableBean { + public String ENV_ERROR = "游戏平台初始化失败"; // private String chatKey = "不知道"; private String userKey = ""; private String randKey = ""; @@ -18,7 +19,8 @@ public class ChatCache implements DisposableBean { private Map infoPoint = null; private GameEnv gameEnv = null; - private boolean gameStart = false; + private Boolean gameStart = false; + private Boolean reload = false; public String getBotAccount() { @@ -62,6 +64,14 @@ public class ChatCache implements DisposableBean { this.gameStart = gameStart; } + public Boolean getReload() { + return reload; + } + + public void setReload(Boolean reload) { + this.reload = reload; + } + public GameEnv getGameEnv() { return gameEnv; } @@ -86,7 +96,9 @@ public class ChatCache implements DisposableBean { try { gameEnv = new GameEnv(userInfo.botAccount); } catch (Exception e) { - System.out.println("游戏平台初始化失败"); + System.out.println(ENV_ERROR); + + infoPoint.put("error_message", ENV_ERROR); e.printStackTrace(); } @@ -104,5 +116,8 @@ public class ChatCache implements DisposableBean { } - + public ChatCache(String userKey, String randKey) { + this.userKey = userKey; + this.randKey = randKey; + } } diff --git a/src/entity/ConfigTerm.java b/src/entity/ConfigTerm.java index 8dd3b5d..a1f3725 100644 --- a/src/entity/ConfigTerm.java +++ b/src/entity/ConfigTerm.java @@ -10,7 +10,17 @@ import java.util.Map; public class ConfigTerm implements Cloneable{ - static int iterNum = 0; + ThreadLocal iterNum=new ThreadLocal() { + protected Integer initialValue() { + return 0; + } + }; + ThreadLocal> conditionCount = new ThreadLocal>(){ + protected Map initialValue(){ + return new HashMap(); + }; + }; + private int id = 0; private String jCurPremise = ""; @@ -65,8 +75,11 @@ public class ConfigTerm implements Cloneable{ public void setConfigName(String configName, Boolean append) { if(append) { - iterNum++; - this.configName = configName + "_" + iterNum; + + iterNum.set(iterNum.get() + 1); + + //iterNum++; + this.configName = configName + "_" + iterNum.get(); }else{ this.configName = configName; } @@ -218,7 +231,7 @@ public class ConfigTerm implements Cloneable{ } - public ConfigTerm(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { + public ConfigTerm(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { this.curPremise = appendPremiseStr(curPremise, extraCP); this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); @@ -228,21 +241,46 @@ public class ConfigTerm implements Cloneable{ this.auxiliaryPriority = auxiliaryPriority; } - public String appendPremiseStr(List premises, String extraPM) { + public String appendPremiseStr(List premises, String extraPremise) { StringBuffer sb = new StringBuffer(); - String premiseStr = ""; + String premiseStr = "", conditionName; + Map nameCount = new HashMap(); + + for (Premise premise : premises){ + //设置初始值 + //System.out.println("nameCount" + nameCount); + conditionName = premise.getConditionName(); + + nameCount.putIfAbsent(conditionName, 0); - for (String premise : premises) - sb.append("," + premise); + //nameCount加一 + nameCount.put(conditionName, nameCount.get(conditionName) + 1); + + //在conditionName后添加count + if(nameCount.get(conditionName) > 1) { + premise.setConditionName(conditionName + nameCount.get(conditionName)); + } + + + + sb.append(","); + sb.append(premise.getConditionName()); + sb.append("::"); + sb.append(premise.getCmpType()); + sb.append("-"); + sb.append(premise.getOperator()); + sb.append("="); + sb.append(premise.getKeyword()); + } if (sb.length() > 0) sb.deleteCharAt(0); //删除第一个逗号 - if (!extraPM.equals("")) { + if (!extraPremise.equals("")) { if (sb.length() == 0) - sb.append(extraPM); + sb.append(extraPremise); else - sb.append("," + extraPM); + sb.append("," + extraPremise); } else if (sb.length() == 0) { sb.append(" "); } @@ -255,7 +293,7 @@ public class ConfigTerm implements Cloneable{ StringBuffer sb = new StringBuffer(); String varName = "", varValue = "", knowledgeStr; Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; + Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; while (iit.hasNext()) { @@ -436,18 +474,23 @@ public class ConfigTerm implements Cloneable{ } public String toString() { + StringBuffer sb = new StringBuffer(); - String text = curPremise + "|" + - hisPremise + "|" + - feature + "," + updateKnowledge + "," + nextStepStatus + "|" + - "auxiliaryPriority=" + auxiliaryPriority + "|" + - "configName=" + configName + "|=>|" + - reply + "|" + - "nextStep=" + nextStep + "|" + - "status=" + status + "|" + - "configId="; + sb.append(curPremise).append("|"); + sb.append(hisPremise); + sb.append("|").append(feature).append(","); + sb.append(updateKnowledge).append(","); + sb.append(nextStepStatus).append( "|"); + sb.append("auxiliaryPriority="); + sb.append(auxiliaryPriority).append("|").append("configName="); + sb.append(configName); + sb.append("|=>|").append(reply); + sb.append("|").append("nextStep="); + sb.append(nextStep).append("|"); + sb.append("status=").append(status); + sb.append("|").append("configId="); - return text; + return sb.toString(); } public Object clone() { @@ -467,11 +510,6 @@ public class ConfigTerm implements Cloneable{ 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("")) configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); @@ -479,14 +517,12 @@ public class ConfigTerm implements Cloneable{ configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); configTerm2.setConfigName(name, true); - - //configTermList.add(configTerm); configTermList.add(configTerm2); } - public static ConfigTerm simpleCopy(ConfigTerm configTerm){ + public ConfigTerm simpleCopy(ConfigTerm configTerm){ ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); diff --git a/src/entity/Premise.java b/src/entity/Premise.java new file mode 100644 index 0000000..f15c76e --- /dev/null +++ b/src/entity/Premise.java @@ -0,0 +1,47 @@ +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; + } +} diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java index 1f464a8..f1d39f0 100644 --- a/src/gameDesign/GlobalVariableConstructor.java +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -1,11 +1,9 @@ package com.qiwu.chatbotbackend.gameDesign; -import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.UserInfo; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; @@ -42,6 +40,7 @@ public class GlobalVariableConstructor extends ElementConstructor { varInitialMap.put("botType", "game"); varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); + varInitialMap.put("CC_URL", keywordMap.get("CC_URL").toString()); JSONObject script = gameElements.getJSONObject("speechcraft"); diff --git a/src/gameDesign/ListeningConstructor.java b/src/gameDesign/ListeningConstructor.java index 8d1f8fd..fd81405 100644 --- a/src/gameDesign/ListeningConstructor.java +++ b/src/gameDesign/ListeningConstructor.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -34,10 +35,14 @@ public class ListeningConstructor extends ElementConstructor{ String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; Boolean autoJump = false; - List curPremiseList = new ArrayList(); - List hisPremiseList = new ArrayList(); + List curPremiseList = new ArrayList(); + List hisPremiseList = new ArrayList(); JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); JSONObject plotNode = null; + + if(listeningActions == null) + return; + size = listeningActions.size(); JSONObject config = null; @@ -47,8 +52,8 @@ public class ListeningConstructor extends ElementConstructor{ priority = "2"; feature = "match"; config = listeningActions.getJSONObject(i); - curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), String.class); - hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), String.class); + curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), Premise.class); + hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), Premise.class); Map updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); nextPlotId = config.getString("nextPlotId"); @@ -71,7 +76,7 @@ public class ListeningConstructor extends ElementConstructor{ if(autoJump){ feature = "match,activate:after"; updateKnowledge.put("plot_jump_text", "str+" + reply); - nextCondition = "plot_" + nextPlotId + "_*"; + nextCondition = "plot_" + nextPlotId; reply = ""; }else{ feature = "match"; diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index 9a4cfb8..a81d7ab 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -384,6 +384,16 @@ public class MapConstructor extends ElementConstructor { configTerm.setjStatus(1); 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 { configTerm.setConfigName("map", true); 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); + } diff --git a/src/gameDesign/PlotConstructor2.java b/src/gameDesign/PlotConstructor2.java index 3634d19..cd5003c 100644 --- a/src/gameDesign/PlotConstructor2.java +++ b/src/gameDesign/PlotConstructor2.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.UserInfo; import java.io.*; @@ -57,7 +58,6 @@ public class PlotConstructor2 extends ElementConstructor { - this.plots = plots; constructAdjList(plots); @@ -87,11 +87,6 @@ public class PlotConstructor2 extends ElementConstructor { message = "开始剧情不存在,请到剧情列表设置"; return; } - - - - - } catch(Exception e){ operationStatus = 0; message = "剧情接口处理出现异常"; @@ -100,7 +95,11 @@ public class PlotConstructor2 extends ElementConstructor { } } - //根据id构造邻接表 + + /** + * 根据id构造邻接表 + * @param plots + */ public void constructAdjList(JSONArray plots) { int length = plots.size(), branchSize; String id = "", nextPlotId = "", nextPlotText; @@ -143,10 +142,19 @@ public class PlotConstructor2 extends ElementConstructor { } } + + /** + * 将条件文本中的一些特殊字符过滤调 + * @param premiseList 条件列表 + * @return + */ JSONArray premiseTextFilt(JSONArray premiseList){ + JSONObject premise = null; int size = premiseList.size(); for(int i = 0;i < size;i++){ - premiseList.set(i, premiseList.getString(i).replace("\r\n", "").replace("\n", "").replace("\r", "")); + premise = premiseList.getJSONObject(i); + premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", "")); + premiseList.set(i, premise); } return premiseList; @@ -158,8 +166,7 @@ public class PlotConstructor2 extends ElementConstructor { */ public static void varSlotFilt(JSONObject plot, Map keywordMap){ - - String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; + String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 System.out.println(plot.getString("id")); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); Matcher m = replacePattern.matcher(plot.getString("plotText")); @@ -197,7 +204,7 @@ public class PlotConstructor2 extends ElementConstructor { int branchSize; - List curPremiseList, historyPremiseList; + List curPremiseList, historyPremiseList; root.put("nextUnknownText", varInitialMap.get("unknownText")); root.put("parentId", "null"); @@ -232,6 +239,7 @@ public class PlotConstructor2 extends ElementConstructor { Queue queue = new LinkedList(); queue.add(root); + System.out.println(root.toJSONString()); while (!queue.isEmpty()) { node = queue.remove(); @@ -454,9 +462,10 @@ public class PlotConstructor2 extends ElementConstructor { } } + //System.out.println(branchNode); - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); + curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class); + historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class); @@ -472,7 +481,7 @@ public class PlotConstructor2 extends ElementConstructor { if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ appendFeature(extraFT, "activate:after"); - nextCondition = "plot_" + nextId + "_*"; + nextCondition = "plot_" + nextId; } configTerm = new ConfigTerm( @@ -482,7 +491,7 @@ public class PlotConstructor2 extends ElementConstructor { "", extraHP.toString(), extraUK.toString(), extraFT.toString(), reply, nextCondition, "1" ); - configTerm.setConfigName("plot_" + id, true); + configTerm.setConfigName("plot_" + id, false); //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 @@ -693,11 +702,11 @@ public class PlotConstructor2 extends ElementConstructor { jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); jsonStr = jsonStr.replace("startId", gameElements.getString("start")); jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); + + //System.out.println("JSONSTR ------------------------------\n" + jsonStr); JSONObject config = JSONObject.parseObject(jsonStr); - //System.out.println(config.toJSONString()); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); + gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); gameElements.put("start", "start1"); gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); @@ -816,67 +825,33 @@ public class PlotConstructor2 extends ElementConstructor { /** - * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况 - */ - void arriveActivatePlot(Map updateKnowledge, String plotId, String nextId, String reply, String gameStep, String nextGameStep, String nextLocation, String nextCondition, String nextUnknownText, String extraUK, String feature){ - - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - StringBuffer hisPremise = new StringBuffer(); - StringBuffer curPremise = new StringBuffer(); - - appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); - appendPremise(hisPremise, plotId, "match", "Include", "2"); //剧情已完成且未前往 - appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); -// appendPremise(hisPremise, "from_" + plotId, "match", "Include", "0"); -// appendPremise(hisPremise, "to_" + nextId, "match", "Include", "0"); - - - - configTerm = new ConfigTerm( - curPremise.toString(), - hisPremise.toString(), - feature, reply, nextCondition, - extraUK + "-<-game_step:" + nextGameStep - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation - ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("plot_" + nextLocation + "_" + plotId,false); - configTerm.setjStatus(1); - - configTermList.add(configTerm); - - - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - //updateKnowledge.remove("unknownText"); - updateKnowledge.remove("site"); - - - } - - /** * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况,将这块处理当做listening模块的一个剧情处理 */ void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ - String feature; + //String feature; //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - StringBuffer hisPremise = new StringBuffer(); - StringBuffer curPremise = new StringBuffer(); + //StringBuffer hisPremise = new StringBuffer(); + //StringBuffer curPremise = new StringBuffer(); - appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); - appendPremise(hisPremise, nextLocation + "_activate_by", "match", "Include", plotId); - appendPremise(hisPremise, nextLocation + "_activate_ready", "match", "Include", "1"); - appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); +// appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); +// appendPremise(hisPremise, nextLocation + "_activate_by", "match", "Include", plotId); +// appendPremise(hisPremise, nextLocation + "_activate_ready", "match", "Include", "1"); +// appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); JSONObject updateKnowledge = new JSONObject(); JSONArray curPremiseList = new JSONArray(); - curPremiseList.add(curPremise.toString()); + //curPremiseList.add(curPremise.toString()); JSONArray hisPremiseList = new JSONArray(); - hisPremiseList.add(hisPremise.toString()); + //hisPremiseList.add(hisPremise.toString()); + + curPremiseList.add(new Premise("yaobuyao", "match", "Include", nextLocation)); + hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); + hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); + hisPremiseList.add(new Premise("isNeighbour:yaobuyao", "match", "Include", "1+3+4")); diff --git a/src/processing/ActionMatcher.java b/src/processing/ActionMatcher.java index 8dcef16..f22c480 100644 --- a/src/processing/ActionMatcher.java +++ b/src/processing/ActionMatcher.java @@ -91,14 +91,17 @@ public class ActionMatcher { activateFlag = false; satisfyFlag = false; replaceFlag = false; - if (action.status.equals("waiting")){ + if (action.getStatus().equals("waiting")){ + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(action.getId()), 1); //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 - if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { + if (action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) { activateFlag = true; } - if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)){ + if(higherPriority(action, bestMatch)){ replaceFlag = true; } @@ -106,7 +109,7 @@ public class ActionMatcher { //没有激活,优先级不够高,直接跳过 if(!activateFlag && !replaceFlag){ - logWriter.record("-----------------------------------优先级不足其没有激活,跳过", 0); + logWriter.record("-----------------------------------优先级不足,跳过", 0); continue; } @@ -117,11 +120,11 @@ public class ActionMatcher { if(satisfyFlag){ if(activateFlag){ - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); } if(replaceFlag){ bestMatch = action; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); logWriter.writeln(); } } @@ -211,16 +214,20 @@ public class ActionMatcher { parentFlag = false; action = activatedQueue.remove(); - activatedMap.remove(action.id); + activatedMap.remove(action.getId()); + + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(action.getId()), 1); - if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)) + if(higherPriority(action, bestMatch)) replaceFlag = true; - if(action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) + if(action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) activateFlag = true; - if(bestMatch.nextStep.contains(String.valueOf(action.id))) + if(bestMatch.getNextStep().contains(String.valueOf(action.getId()))) //现在的condition是被bestMatch这个condition激活的 parentFlag = true; @@ -228,17 +235,17 @@ public class ActionMatcher { //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 if(!activateFlag && !replaceFlag && !parentFlag) { logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(action.id), 1); + logWriter.record(userinfo.id2config.get(action.getId()), 1); continue; } if(conditionSatisfy(action)){ if(activateFlag) { - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); } if(replaceFlag){ bestMatch = action; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); logWriter.writeln(); } } @@ -291,11 +298,10 @@ public class ActionMatcher { String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; HashSet keywordSet = null; - logWriter.record("-----------------------------------检索到配置条目", 0); - logWriter.record(userinfo.id2config.get(action.id), 1); - if (action.featureMap.containsKey("match")) { - Iterator it = action.currentPremise.keySet().iterator(); + + if (action.getFeatureMap().containsKey("match")) { + Iterator it = action.getCurrentPremise().keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); @@ -311,7 +317,7 @@ public class ActionMatcher { break; } - keywordSet = action.currentPremise.get(premiseStr); + keywordSet = action.getCurrentPremise().get(premiseStr); if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; @@ -320,18 +326,19 @@ public class ActionMatcher { } } - it = action.historyPremise.keySet().iterator(); + it = action.getHistoryPremise().keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); cmpType = comparePair[1]; actionName = comparePair[0]; //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.featureMap.containsKey("includeCurInfo"), actionName); + keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.getFeatureMap().containsKey("includeCurInfo"), actionName); if (keyword == null) { flag = false; if(flag == false){ + logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } break; @@ -339,11 +346,12 @@ public class ActionMatcher { - keywordSet = action.historyPremise.get(premiseStr); + keywordSet = action.getHistoryPremise().get(premiseStr); if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; if(flag == false){ + logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } } @@ -464,11 +472,11 @@ public class ActionMatcher { } } - candidateA = MyFunc.transferToMillisecond(keyword); + candidateA = SimpleUtil.transferToMillisecond(keyword); for (String k : keywordSet) { if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); + candidateB = SimpleUtil.transferToMillisecond(k); break; } } @@ -539,8 +547,8 @@ public class ActionMatcher { } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword1); - long candidateB = MyFunc.transferToMillisecond(keyword2); + long candidateA = SimpleUtil.transferToMillisecond(keyword1); + long candidateB = SimpleUtil.transferToMillisecond(keyword2); if (operator.equals("Bigger")) flag = candidateA > candidateB; @@ -579,8 +587,8 @@ public class ActionMatcher { } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword); - long candidateB = MyFunc.transferToMillisecond(conditionValue2); + long candidateA = SimpleUtil.transferToMillisecond(keyword); + long candidateB = SimpleUtil.transferToMillisecond(conditionValue2); if (operator.equals("Bigger")) flag = candidateA > candidateB; @@ -611,14 +619,21 @@ public class ActionMatcher { } } catch (IndexOutOfBoundsException e) { System.out.println("配置文件格式有误"); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + flag = false; e.printStackTrace(); } catch (ParseException e) { System.out.println("时间解析错误"); + historyInfoPoint.put("error_message", "解析出错:" + keyword); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); e.printStackTrace(); flag = false; } catch (Exception e) { System.out.println("操作符有误"); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); e.printStackTrace(); flag = false; } @@ -644,7 +659,7 @@ public class ActionMatcher { //System.out.println(ans.getAnswer()); //post关键字 - if (ansAction.featureMap.containsKey("post")) { + if (ansAction.getFeatureMap().containsKey("post")) { logWriter.record("---------------------进入表单结束",1); ans = postToServer(ans, ansAction); logWriter.record("---------------------提交表单结束",1); @@ -655,7 +670,7 @@ public class ActionMatcher { //----------------------------------------------------------------------------- //updateKnowledge关键字 - if (ansAction.featureMap.containsKey("updateKnowledge")) { + if (ansAction.getFeatureMap().containsKey("updateKnowledge")) { logWriter.record("---------------------进入更新答案【略】",1); updateKnowledge(ansAction); logWriter.record("---------------------更新答案结束",1); @@ -665,12 +680,12 @@ public class ActionMatcher { //----------------------------------------------------------------------------- - if (ansAction.featureMap.containsKey("newNext")) { + if (ansAction.getFeatureMap().containsKey("newNext")) { logWriter.record("---------------------进入判断下一步【略】",1); ans = findNewNext(ans, ansAction); logWriter.record("---------------------判断下一步结束",1); //上一步 - } else if (ansAction.featureMap.containsKey("return-1")) { + } else if (ansAction.getFeatureMap().containsKey("return-1")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) ans.setNext("nextStep=" + activeList[activeList.length - 1]); @@ -678,14 +693,14 @@ public class ActionMatcher { ans.setNext("nextStep=" + activeList[activeList.length - 2]); } //停留 - } else if (ansAction.featureMap.containsKey("return-0")) { + } else if (ansAction.getFeatureMap().containsKey("return-0")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if(activeList.length > 0) ans.setNext("nextStep=" + activeList[activeList.length - 1]); else ans.setNext("nextStep= "); //激活 - } else if (ansAction.featureMap.containsKey("activate") || ansAction.featureMap.containsKey("activate:after")) { + } else if (ansAction.getFeatureMap().containsKey("activate") || ansAction.getFeatureMap().containsKey("activate:after")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) ans.setNext("nextStep=" + activeList[activeList.length - 1]); @@ -700,9 +715,8 @@ public class ActionMatcher { try { - reply = MyFunc.randStr(ansAction.answer); + reply = SimpleUtil.randStr(ansAction.getAnswer()); reply = botUtil.varSlotReplace(reply); - //reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansAction, logWriter); ans.setAnswer(reply); @@ -714,7 +728,7 @@ public class ActionMatcher { if (ans.getNext().equals("")) { - ans.setNext("nextStep=" + ansAction.nextStep); + ans.setNext("nextStep=" + ansAction.getNextStep()); } } catch (Exception e) { @@ -752,11 +766,6 @@ public class ActionMatcher { } }; -// if (debugFlag) -// lastReply = ans.getAnswer().split(")")[2]; -// else -// lastReply = ans.getAnswer(); -// historyInfoPoint.put("lastReply", lastReply); try { String keyword1, keyword2; @@ -781,9 +790,6 @@ public class ActionMatcher { - //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); - - } catch (Exception e) { e.printStackTrace(); } @@ -871,7 +877,7 @@ public class ActionMatcher { } }; - elem = ansAction.featureMap.get("post").split("\\|"); + elem = ansAction.getFeatureMap().get("post").split("\\|"); url = elem[0]; postType = elem[1]; @@ -889,7 +895,7 @@ public class ActionMatcher { } public Solution findNewNext(Solution ans, Action ansAction) { - String nextOptions[] = ansAction.nextStep.split(","); + String nextOptions[] = ansAction.getNextStep().split(","); String conditionName, premises[], cpPair[]; boolean flag = true; @@ -940,13 +946,13 @@ public class ActionMatcher { - Iterator iit = action.updateKnowledge.keySet().iterator(); + Iterator iit = action.getUpdateKnowledge().keySet().iterator(); while (iit.hasNext()) { variableName = iit.next(); keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); - updateValue = botUtil.knowledgeProcess(variableName, action.updateKnowledge.get(variableName)); + updateValue = botUtil.knowledgeProcess(variableName, action.getUpdateKnowledge().get(variableName)); try { @@ -955,9 +961,9 @@ public class ActionMatcher { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); + long time = SimpleUtil.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); @@ -968,9 +974,9 @@ public class ActionMatcher { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); + long time = SimpleUtil.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); @@ -991,9 +997,9 @@ public class ActionMatcher { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); + long time = SimpleUtil.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(5)); @@ -1004,9 +1010,9 @@ public class ActionMatcher { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); + long time = SimpleUtil.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); @@ -1042,14 +1048,14 @@ public class ActionMatcher { //提取配置条目的下一步 } else if (updateValue.endsWith("nextStep-3}")) { - updateValue = action.nextStep; + updateValue = action.getNextStep(); //提取配置条目的回答 } else if (updateValue.endsWith("reply-3}")) { - updateValue = MyFunc.randStr(action.answer); + updateValue = SimpleUtil.randStr(action.getAnswer()); } //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue if (variableName.startsWith("process-nextStep")) { - action.nextStep = updateValue; + action.setNextStep(updateValue); updateValue = ""; } @@ -1057,7 +1063,9 @@ public class ActionMatcher { } catch (Exception e) { - e.printStackTrace(); + logWriter.record(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue, 0); + System.out.println(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue); + //e.printStackTrace(); continue; } @@ -1117,7 +1125,7 @@ public class ActionMatcher { originAction = action; try { - configId = originAction.id; + configId = originAction.getId(); newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); //action = ActionMatcher.buildCondition(action, configStr); @@ -1126,17 +1134,19 @@ public class ActionMatcher { //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 if (activatedMap.containsKey(configId)) { - if(newAction.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) - activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; - if(newAction.activePriority > activatedMap.get(configId).activePriority) - activatedMap.get(configId).activePriority = newAction.activePriority; + if(higherPriority(newAction, activatedMap.get(configId))) + activatedMap.put(configId, newAction); +// if(newAction.getAuxiliaryPriority() > activatedMap.get(configId).getAuxiliaryPriority()) +// activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; +// if(newAction.priority > activatedMap.get(configId).priority) +// activatedMap.get(configId).priority = newAction.priority; } else if (!activatedMap.containsKey(configId)) { activatedMap.put(configId, newAction); activatedQueue.add(newAction); } }catch (Exception e) { e.printStackTrace(); - logWriter.record("----------激活失败:" + action.configName, 5); + logWriter.record("----------激活失败:" + action.getConfigName(), 5); } } @@ -1164,9 +1174,9 @@ public class ActionMatcher { - while ((newAction1.featureMap.containsKey("activate") && newAction1.featureMap.containsKey("post")) || newAction1.featureMap.containsKey("activate:after")) { + while ((newAction1.getFeatureMap().containsKey("activate") && newAction1.getFeatureMap().containsKey("post")) || newAction1.getFeatureMap().containsKey("activate:after")) { //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - activateCondition(activatedQueue, userinfo.botAccount, newAction1.priority, newAction1.auxiliaryPriority, newAction1.nextStep, context); + activateCondition(activatedQueue, userinfo.botAccount, newAction1.getPriority(), newAction1.getAuxiliaryPriority(), newAction1.getNextStep(), context); newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); @@ -1185,5 +1195,9 @@ public class ActionMatcher { } + public Boolean higherPriority(Action action1, Action action2){ + return ((action1.getAuxiliaryPriority() > action2.getAuxiliaryPriority()) || (action1.getAuxiliaryPriority() == action2.getAuxiliaryPriority() && action1.getPriority() > action2.getPriority())); + } + } diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index deacdb7..6345d8c 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.FileFinder; import javax.servlet.ServletContext; import java.io.*; @@ -76,7 +77,8 @@ public class ChatCacheController { } catch (Exception e) { //可整合 e.printStackTrace(); - chatCache = new ChatCache(userinfo, userKey, randKey); + + //chatCache = new ChatCache(userinfo, userKey, randKey); chatCacheMap.put(userKey, chatCache); } @@ -92,6 +94,10 @@ public class ChatCacheController { String nowTime = now .format(format), userId, botAccount, keyElem[]; Boolean opFlag, destroy = false; + if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey())) + return true; + + System.out.println("游戏存档中"); String userKey = chatCache.getUserKey(); @@ -249,21 +255,29 @@ public class ChatCacheController { SqlHelper helper; Map infoPoints = new HashMap(); try { + helper = new SqlHelper(); - - if (context.getAttribute("chatCache") == null) { - chatCacheMap = new HashMap(); + if (context.getAttribute("chatCache") != null) { + chatCacheMap = (HashMap)context.getAttribute("chatCache"); if (chatCacheMap.containsKey(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) { - helper = new SqlHelper(); + archiveInfo = helper.queryUserLastGameArchive(userKey); helper.destroy(); @@ -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; + } + + } diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 915bd36..28daa2e 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -86,7 +86,7 @@ public class FormsPoster { logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - JSONObject jobj = MyFunc.postFORM(URL, pairList); + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); if((Integer)jobj.get("post_status") == 1){ Iterator kit = jobj.keySet().iterator(); @@ -133,14 +133,14 @@ public class FormsPoster { pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_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()) { key = k_iter.next().split("::")[0]; if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); } - k_iter = ansAction.historyPremise.keySet().iterator(); + k_iter = ansAction.getHistoryPremise().keySet().iterator(); while (k_iter.hasNext()) { key = k_iter.next().split("::")[0]; if(!historyInfoPoint.get(key).equals("")) { @@ -154,7 +154,7 @@ public class FormsPoster { logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - JSONObject jobj = MyFunc.postFORM(URL, pairList); + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); if((Integer)jobj.get("post_status") == 1){ Iterator kit = jobj.keySet().iterator(); @@ -202,9 +202,15 @@ public class FormsPoster { pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); pairList.add(new BasicNameValuePair("qa_threshold", threshold)); + + //设置初始值 + historyInfoPoint.put("common_answer", ""); + historyInfoPoint.put("qa_score", "0"); + historyInfoPoint.put("qa_status", "OK"); + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - JSONObject jobj = MyFunc.postFORM(URL, pairList); + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); @@ -212,10 +218,7 @@ public class FormsPoster { System.out.println(jobj.toJSONString()); if((Integer)jobj.get("post_status") == 1){ 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 candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); for(JSONArray pair:candidates){ @@ -230,31 +233,24 @@ public class FormsPoster { if (m.find()) { 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("qa_score", String.valueOf(textscore.get(1))); 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 { - ans.setAnswer("提交表单出现异常"); + historyInfoPoint.put("error_message", jobj.getString("error_message")); } } public void postGameQA(Map curInfoPoint, Map 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); - 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); } diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java index 8839631..c8d8226 100644 --- a/src/processing/ResponseFilter.java +++ b/src/processing/ResponseFilter.java @@ -27,7 +27,7 @@ // String site = historyInfoPoint.get("site"); // // -// reply = MyFunc.randStr(reply.split("~")); +// reply = SimpleUtil.randStr(reply.split("~")); // // if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 // return reply; @@ -75,7 +75,7 @@ // } // } // if (unknownList.size() > 0) { -// return MyFunc.randStr(unknownList); +// return SimpleUtil.randStr(unknownList); // } // // } @@ -97,7 +97,7 @@ // } // } // if(finalUnknownList.size() > 0){ -// return MyFunc.randStr(finalUnknownList); +// return SimpleUtil.randStr(finalUnknownList); // // } // } @@ -181,7 +181,7 @@ // } // } // if(filtedNpcList.size() != 0) -// npc = MyFunc.randStr(filtedNpcList); +// npc = SimpleUtil.randStr(filtedNpcList); // else // npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); // diff --git a/src/processing/SimpleUtil.java b/src/processing/SimpleUtil.java new file mode 100644 index 0000000..747dd12 --- /dev/null +++ b/src/processing/SimpleUtil.java @@ -0,0 +1,213 @@ +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 pairList) throws UnsupportedEncodingException { + + + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + String keyName = null; + + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); + entity.setContentType("application/x-www-form-urlencoded"); + httpPost.setEntity(entity); + JSONObject jobj = new JSONObject(); + + try { + System.out.println("url为:" + url); + HttpResponse resp = client.execute(httpPost); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + jobj.put("post_status", 1); + + } else { + jobj.put("post_status", 0); + jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); + } + } catch (Exception e) { + jobj.put("error_message", "提交表单时出错:" + e.getMessage()); + jobj.put("post_status", 0); + } + + return jobj; + + } + + public static String randStr(String strList[]){ + String reply; + int randNum = (int) (Math.random() * strList.length); + reply = strList[randNum]; + + return reply; + } + + public static String randStr(List strList){ + String reply; + + int randNum = (int) (Math.random() * strList.size()); + reply = strList.get(randNum); + + return reply; + } + + +} \ No newline at end of file diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index 82d9d57..0538156 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -103,25 +103,25 @@ public class UserInfoController { history_premises = premises[1].split(","); if (premises.length < 4) - action.auxiliaryPriority = 0; + action.setAuxiliaryPriority(0); else - action.auxiliaryPriority = Integer.parseInt(premises[3].split("=", 2)[1]); + action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); if(premises.length < 5) - action.configName = ""; + action.setConfigName(""); else - action.configName = premises[4].split("=", 2)[1]; + action.setConfigName(premises[4].split("=", 2)[1]); next = element[1].split("\\|"); if (next.length < 4) return action; - action.answer = next[0].split("~"); + action.setAnswer(next[0].split("~")); //action.nextStep = next[1]; //第二处 - action.nextStep = next[1].split("=", 2)[1]; - action.id = Integer.parseInt(next[3].split("=")[1]); - action.status = next[2].split("=")[1]; + action.setNextStep(next[1].split("=", 2)[1]); + action.setId(Integer.parseInt(next[3].split("=")[1])); + action.setStatus(next[2].split("=")[1]); //featureMap的构建 @@ -132,31 +132,31 @@ public class UserInfoController { } else if (feat.startsWith("updateKnowledge")) { String[] knowledge = feat.split("-<-"); int length = knowledge.length; - action.featureMap.put("updateKnowledge", ""); + action.getFeatureMap().put("updateKnowledge", ""); for (int i = 1; i < length; i++) { if (knowledge[i].equals("") || knowledge[i].equals(" ")) continue; pair = knowledge[i].split(":", 2); - action.updateKnowledge.put(pair[0], pair[1]); + action.getUpdateKnowledge().put(pair[0], pair[1]); } } else if (feat.startsWith("post")) { pair = feat.split("\\(", 2); url = pair[1]; url = url.substring(0, url.length() - 1); pair = pair[0].split("::"); - action.featureMap.put("post", url + "|" + pair[1]); + action.getFeatureMap().put("post", url + "|" + pair[1]); } else { - action.featureMap.put(feat, ""); + action.getFeatureMap().put(feat, ""); } } - insertPremise(action.currentPremise, cur_premises); - insertPremise(action.historyPremise, history_premises); + insertPremise(action.getCurrentPremise(), cur_premises); + insertPremise(action.getHistoryPremise(), history_premises); //满足条件越多,优先级越大 - action.priority = action.historyPremise.size() + action.currentPremise.size(); - action.activePriority = action.priority; + action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); + //action.activePriority = action.priority; /* for(String premise:cur_premises){ pair = premise.split("="); @@ -165,9 +165,9 @@ public class UserInfoController { */ firstCnditionName = cur_premises[0]; if (firstCnditionName.equals(" ")) - action.indexName = "emptySet"; + action.setIndexName("emptySet"); else - action.indexName = firstCnditionName.split("=")[0].split("::")[0]; + action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); System.out.println(line); @@ -220,17 +220,17 @@ public class UserInfoController { } else { Action action = new Action(); action = buildCondition(action, line); - actionList = conditionTable.get(action.indexName); + actionList = conditionTable.get(action.getIndexName()); if (actionList == null) actionList = new ArrayList(); actionList.add(action); - conditionTable.put(action.indexName, actionList); - if (action.id != 0) { - if(!action.configName.equals("")){ - userinfo.name2condition.put(action.configName, action); + conditionTable.put(action.getIndexName(), actionList); + if (action.getId() != 0) { + if(!action.getConfigName().equals("")){ + userinfo.name2condition.put(action.getConfigName(), action); } - userinfo.id2config.put(action.id, line); - userinfo.id2condition.put(action.id, action); + userinfo.id2config.put(action.getId(), line); + userinfo.id2condition.put(action.getId(), action); } } @@ -326,7 +326,7 @@ public class UserInfoController { //------------------- try { - conditionName = oldAction.indexName; + conditionName = oldAction.getIndexName(); } catch (Exception e) { e.printStackTrace(); } @@ -337,13 +337,13 @@ public class UserInfoController { Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); while (condIter.hasNext()) { Action c = condIter.next(); - if (c.id == id) { + if (c.getId() == id) { condIter.remove(); } } } - userInfo.name2condition.remove(oldAction.configName); + userInfo.name2condition.remove(oldAction.getConfigName()); userInfo.id2config.remove(id); userInfo.id2condition.remove(id); } else { @@ -362,7 +362,7 @@ public class UserInfoController { Action oldAction = userInfo.id2condition.get(configId); try { - conditionName = oldAction.indexName; + conditionName = oldAction.getIndexName(); } catch (Exception e) { e.printStackTrace(); } @@ -373,13 +373,13 @@ public class UserInfoController { Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); while (condIter.hasNext()) { Action c = condIter.next(); - if (c.id == configId) { + if (c.getId() == configId) { condIter.remove(); } } } - userInfo.name2condition.remove(oldAction.configName); + userInfo.name2condition.remove(oldAction.getConfigName()); userInfo.id2config.remove(configId); userInfo.id2condition.remove(configId); } else { @@ -408,15 +408,15 @@ public class UserInfoController { } UserInfo userinfo = (UserInfo) context.getAttribute(userName); - if (userinfo.conditionTable.get(action.indexName) == null) { + if (userinfo.conditionTable.get(action.getIndexName()) == null) { List actionList = new ArrayList(); - userinfo.conditionTable.put(action.indexName, actionList); + userinfo.conditionTable.put(action.getIndexName(), actionList); } - if(!action.configName.equals("")){ - userinfo.name2condition.put(action.configName, action); + if(!action.getConfigName().equals("")){ + 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.id2condition.put(id, action); diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 85016f8..4c1f6b5 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -11,8 +11,6 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.ASSISTANT_EMOTION; - public class WorldController { public LogWriter logWriter = null; public UserInfo userInfo = null; @@ -223,7 +221,7 @@ public class WorldController { 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; @@ -387,6 +385,10 @@ public class WorldController { } } break; + + case "queryPathNotExist": + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; + break; case "queryAroundPlace": if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) { format = userInfo.varInitialMap.get("AROUND_PLACE"); diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 72d9f7c..cfe4ae5 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -5,9 +5,9 @@ import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; 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.task.utils.FileFinder; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -21,8 +21,6 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; -import static com.qiwu.chatbotbackend.processing.ChatCacheController.CHAT_CACHE_DIR; - @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) public class GameDesignServlet extends HttpServlet { @@ -79,7 +77,7 @@ public class GameDesignServlet extends HttpServlet { } //读取并解析json数据 - String jsonStr = MyFunc.readJSONString(request); + String jsonStr = SimpleUtil.readJSONString(request); if (jsonStr != null && !jsonStr.equals("")) { @@ -217,10 +215,6 @@ public class GameDesignServlet extends HttpServlet { } } - if(returnStatus == 1){ - deleteOldArchive(helper, botAccount); - } - helper.destroy(); @@ -267,7 +261,7 @@ public class GameDesignServlet extends HttpServlet { boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); - boolean deleteArchiveFlag = deleteOldArchive(helper, botAccount); + boolean deleteArchiveFlag = ChatCacheController.deleteChatCache(helper, botAccount); return deleteConfigFlag && deleteVariableFlag; @@ -286,40 +280,44 @@ public class GameDesignServlet extends HttpServlet { actionPostData.put("botName", botName); actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("type", "game_plot_init"); - actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始剧情或者重新开始"); + actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始"); actionPostData.put("relationKeywords", additionalKeywords); actionPostData.put("auth", gameElements.get("auth")); + if (gameElements.containsKey("POS")) POS2 = (String)gameElements.get("POS"); actionPostData.put("POS", POS.toString() + POS2); + System.out.println(actionPostData.toJSONString()); + userInfo.extraInfo.put("activeAction", startCondition); try { - returnMessage = MyFunc.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth")); + returnMessage = SimpleUtil.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth")); } catch (UnsupportedEncodingException e) { 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"; }else { System.out.println(returnMessage.get("parameter")); - System.out.println("语义关系修改失败"); + System.out.println("语义关系生成失败"); return (String)returnMessage.get("parameter"); } } + + //从配置文件中读取生成状态表所需要的关键词 public void readKeywords(Map keywordsMap, String path){ File file = new File(path); String line, pair[]; - //System.out.println(file.getAbsolutePath()); if(file.exists()){ FileReader reader = null; try { @@ -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; - } diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index b6ea93b..9c0689c 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -122,14 +122,16 @@ public class GetAnswerServlet extends HttpServlet { /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); - if (state.equals("") && ansAction.priority == -1) + if (state.equals("") && ansAction.getPriority()== -1) state = "我不理解,"; if (state.equals("")) { try { - System.out.println("test2"); 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包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); } @@ -165,7 +167,7 @@ public class GetAnswerServlet extends HttpServlet { - ansJ = MyFunc.toJson(bestMatch); + ansJ = SimpleUtil.toJson(bestMatch); } else { ansJ = "找不到配置文件"; } diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index dfa1a0f..da89789 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; import com.qiwu.chatbotbackend.entity.Action; 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 javax.servlet.ServletContext; @@ -54,16 +54,16 @@ public class UpdateServlet extends HttpServlet { userinfo.configStr += line + "\n"; continue; } - //line = MyFunc.convert2Utf8(line.trim()); + //line = SimpleUtil.convert2Utf8(line.trim()); userinfo.configStr += line + "\n"; Action action = new Action(); try { action = UserInfoController.buildCondition(action, line); - actionList = userinfo.conditionTable.get(action.indexName); + actionList = userinfo.conditionTable.get(action.getIndexName()); if (actionList == null) actionList = new ArrayList(); actionList.add(action); - userinfo.conditionTable.put(action.indexName, actionList); + userinfo.conditionTable.put(action.getIndexName(), actionList); /* for(String name:action.indexName){ userinfo.conditionTable.put() @@ -84,7 +84,7 @@ public class UpdateServlet extends HttpServlet { response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); - String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); + String returnStr = SimpleUtil.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); out.println("更新失败,以下行有误: "); for (String error : errorList) out.println("---" + error); diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java index edbbce8..cadc92c 100644 --- a/src/task/utils/BasicBotUtil.java +++ b/src/task/utils/BasicBotUtil.java @@ -31,14 +31,23 @@ public class BasicBotUtil { } public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { - return infoPointPreprocessing(receiveParameters, context); + return infoPointPreprocessing(receiveParameters, context, true); } //在接收到请求后对数据做处理,转化为系统可以处理的数据 - public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context) throws IOException { + + /** + * + * @param receiveParameters + * @param context + * @param setUnknown 如果什么都没识别到就将上一个激活的condition设为unknown + * @return + * @throws IOException + */ + public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context, Boolean setUnknown) throws IOException { String return_str = "", k, botType = ""; String receiveParameterStr = ""; @@ -71,12 +80,8 @@ public class BasicBotUtil { String values[] = receiveParameters.get(k); -// for (String v : values) { -// receiveParameterStr += v + " "; -// } receiveParameterStr += values[0] + " " + "
"; - if (values[0].equals(":")) { curInfoPoint.put(k, ""); } @@ -86,7 +91,7 @@ public class BasicBotUtil { //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown iit = curInfoPoint.keySet().iterator(); - boolean unknown_flag = true; + boolean unknown_flag = setUnknown; while (iit.hasNext()) { k = iit.next(); String values = curInfoPoint.get(k); @@ -126,6 +131,10 @@ public class BasicBotUtil { } public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + if(historyInfoPoint.get("error_message") != null && historyInfoPoint.get("error_message") != ""){ + bestMatch.setAnswer(bestMatch.getAnswer() + historyInfoPoint.get("error_message")); + } + return true; } diff --git a/src/task/utils/DataDeliver.java b/src/task/utils/DataDeliver.java new file mode 100644 index 0000000..6d3cbea --- /dev/null +++ b/src/task/utils/DataDeliver.java @@ -0,0 +1,35 @@ +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(); + } + } + +} diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java index 9977c5a..ba76fa0 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/task/utils/GameBotUtil.java @@ -1,12 +1,13 @@ package com.qiwu.chatbotbackend.task.utils; +import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.LogWriter; -import com.qiwu.chatbotbackend.processing.MyFunc; +import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.WorldController; import javax.servlet.ServletContext; @@ -33,15 +34,15 @@ public class GameBotUtil extends BasicBotUtil{ this.historyInfoPoint = historyInfoPoint; this.userinfo = userinfo; this.logWriter = logWriter; - this.worldController = worldController; this.gameEnv = gameEnv; this.chatCache = chatCache; + this.worldController = worldController; } @Override public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { - Boolean debugFlag = infoPointPreprocessing(receiveParameters, context); + Boolean debugFlag = infoPointPreprocessing(receiveParameters, context, false); //将要去的地点的别名替换为真名 // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; @@ -83,8 +84,14 @@ public class GameBotUtil extends BasicBotUtil{ StringBuffer finalText = new StringBuffer(); String plotText = bestMatch.getAnswer(); //将自动跳转文本、qa文本、查询文本拼接 - String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text"}; + String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"}; String queryResult; + Set keepNoSpeaker = new HashSet(){ + { + add("sendData:archiveList"); + add("请说开始剧情或者继续剧情"); + } + }; historyInfoPoint.put("plot_text", plotText); @@ -92,7 +99,7 @@ public class GameBotUtil extends BasicBotUtil{ for(String queryName:queryList){ queryResult = historyInfoPoint.get(queryName); if(queryResult != null){ - if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-1])){ + if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 //剧情可以为空,其他不行 continue; } @@ -108,17 +115,17 @@ public class GameBotUtil extends BasicBotUtil{ case "map_query": case "goods_query": case "npc_query": - queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv, worldController); + case "error_message": + queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv); finalText.append(queryResult); break; case "plot_text": - if(plotText.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 + if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪 finalText.setLength(0); finalText.append(plotText); } //文本为空跳过 else if(plotText.equals("") && finalText.length() != 0){ - System.out.println("sdfs"); continue; }else { @@ -130,9 +137,8 @@ public class GameBotUtil extends BasicBotUtil{ } - - historyInfoPoint.put(queryName, ""); + } } bestMatch.setAnswer(finalText.toString()); @@ -163,13 +169,11 @@ public class GameBotUtil extends BasicBotUtil{ } }else if (actionName.startsWith("goods_")) { - if (nameSeries.length == 4) { - keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]); - System.out.println("return" + keyword); - }else if (nameSeries.length == 3){ - keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); + nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); + keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); + //System.out.println("return" + keyword); + - } }else if(actionName.startsWith("isNeighbour")){ String opPair[] = actionName.split(":"); if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ @@ -205,12 +209,14 @@ public class GameBotUtil extends BasicBotUtil{ String namePair[] = variableName.split("_"); - //如果变量名开头为NPC或者item,就专门交给world处理 + + //如果变量名开头为NPC或者item,就专门交给游戏环境处理 if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { try { if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { updateValue = "update:" + updateValue; } + variableName = variableName.replace("所属玩家", "owner"); String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); updateValue = returnStr; } catch (Exception e) { @@ -257,32 +263,35 @@ public class GameBotUtil extends BasicBotUtil{ if(userKey.equals(randKey)) return; - if(ansAction.featureMap.containsKey("newGame")) { + if(ansAction.getFeatureMap().containsKey("newGame")) { System.out.println("newGame"); this.chatCache.setGameStart(true); - }else if (ansAction.featureMap.containsKey("gameBackup")) { + }else if (ansAction.getFeatureMap().containsKey("gameBackup")) { + System.out.println("gameBackup"); - if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档 - chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); - flag = ChatCacheController.saveChatCache(chatCache, null); - if(flag) - solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); - else - solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); - }else{ - solution.setAnswer("体验作品时无法存档哦,请下载我们的app体验更多功能"); - solution.setNext(""); //可能存在问题,估计要一个空格 - } + chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); + flag = ChatCacheController.saveChatCache(chatCache, null); + if(flag) + solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); + else + solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); + + } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { - } else if (ansAction.featureMap.containsKey("loadLastArchive")) { System.out.println("loadLastArchive"); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); + if(archiveInfo != null){ + System.out.println("存档Id" + archiveInfo.getArchiveId()); + }else{ + System.out.println("没有找到存档"); + } loading(archiveInfo, solution); this.chatCache.setGameStart(true); - } else if (ansAction.featureMap.containsKey("loadArchiveBySite")) { + } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) { + System.out.println("loadArchiveBySite"); if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; @@ -293,9 +302,22 @@ public class GameBotUtil extends BasicBotUtil{ }else{ System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); } - } else if(ansAction.featureMap.containsKey("sendArchiveList")){ - + } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){ + + System.out.println("sendArchiveList"); + DataDeliver dataDeliver = new DataDeliver(); + dataDeliver.setUrl(userinfo.varInitialMap.get("CC_URL")); + JSONObject data = new JSONObject(); + List archiveList = helper.queryArchiveByUserKey(userKey); + data.put("data", JSONObject.toJSON(archiveList)); + data.put("dataType", "archiveList"); + data.put("userKey", userKey); + dataDeliver.setData(data); + dataDeliver.start(); + + solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个 } + } catch (SQLException e) { e.printStackTrace(); @@ -324,6 +346,7 @@ public class GameBotUtil extends BasicBotUtil{ solution.setAnswer("从本地加载存档失败"); e.printStackTrace(); } + //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setGameEnv(loadCache.getGameEnv()); @@ -335,6 +358,7 @@ public class GameBotUtil extends BasicBotUtil{ String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site)); solution.setAnswer(reply); solution.setNext("nextStep=" + nextStep); + this.chatCache.setReload(true); }else{ System.out.println("没有找到该存档"); @@ -416,19 +440,18 @@ public class GameBotUtil extends BasicBotUtil{ * @param curInfoPoint * @param historyInfoPoint * @param gameEnv - * @param worldController * @param site * @param logWriter * @return */ - public static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ + public static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){ String npc, location; Matcher m = findTalker(reply); int flag = 1; if(m.find()) { npc = m.group(1); - location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); + location = gameEnv.queryNpcAttrByNpcName(npc, "location"); if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ flag = 1; @@ -466,6 +489,9 @@ public class GameBotUtil extends BasicBotUtil{ Boolean flag = false; location = gameEnv.queryNpcAttrByNpcName(npc, "location"); + if( location == null){ + return false; + } if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ @@ -491,7 +517,7 @@ public class GameBotUtil extends BasicBotUtil{ } - public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ + public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv){ return String.format(TALKER_PATTERN, npc, PlotConstructor2.ASSISTANT_EMOTION) + text; @@ -511,7 +537,7 @@ public class GameBotUtil extends BasicBotUtil{ returnText = reply; break; case "less_talker": - return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv, worldController); + return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv); case "to_unknown": Set candidates = new HashSet(); Map> npcTextMap = null; @@ -535,14 +561,14 @@ public class GameBotUtil extends BasicBotUtil{ //先找剧情相关的npc foundNPC = foundCandidateText(candidates, npcTextMap); if(!foundNPC.equals("")){ - returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); + returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); break; }else{ //再找地点相关的npc candidates.addAll(findRelateTalkers(true)); foundNPC = foundCandidateText(candidates, npcTextMap); if(!foundNPC.equals("")){ - returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); + returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); break; } } @@ -615,8 +641,12 @@ public class GameBotUtil extends BasicBotUtil{ private List findRelateTalkers(Boolean includeSiteNPC){ String site = historyInfoPoint.get("site"); String lastReply = historyInfoPoint.get("lastReply"); + List talkers = new ArrayList(); + + if(lastReply == null) lastReply = ""; + String plotLastTalker = findTextLastTalker(lastReply, site); if(!plotLastTalker.equals("")){ talkers.add(plotLastTalker);