From 3d56c4c50e1ada21e5eeb0b8dd078eb0646fdb8f Mon Sep 17 00:00:00 2001 From: hxw Date: Sat, 26 Jan 2019 13:54:21 +0800 Subject: [PATCH] 添加根据地点存档、离线语音过滤 --- src/db/SqlHelper.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- src/entity/ArchiveInfo.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/entity/ChatCache.java | 53 +++++++++++++++++++++++++++-------------------------- src/entity/ChatCache3.java | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/entity/JConfig.java | 46 +++++++++++++++++++--------------------------- src/gameDesign/CharacterConstructor.java | 14 +++++++++++++- src/gameDesign/MapConstructor2.java | 5 ++--- src/gameDesign/PlotConstructor.java | 219 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------ src/processing/ChatCacheController.java | 131 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------- src/processing/ChatCacheController2.java | 278 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/processing/FormsPoster.java | 16 +++++++++++++--- src/processing/LogWriter.java | 21 +++++++++++++++++++++ src/processing/MyFunc.java | 7 +++---- src/processing/QuestionMatcher.java | 70 ++++++++++++++++++++++++++++------------------------------------------ src/processing/ResponseFilter.java | 16 +++++++++++++--- src/processing/WorldController.java | 4 +++- src/servlet/FindCacheServlet.java | 7 ++++--- src/servlet/GameDesignServlet.java | 2 -- src/servlet/GetAnswerServlet.java | 148 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------ src/servlet/MyListener.java | 7 +++++-- src/servlet/SaveChatCacheServlet.java | 11 ++++------- src/task/utils/BasicBotUtil.java | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- src/task/utils/FileFinder.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/task/utils/GameBotUtil.java | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 24 files changed, 1301 insertions(+), 302 deletions(-) create mode 100644 src/entity/ArchiveInfo.java create mode 100644 src/entity/ChatCache3.java create mode 100644 src/processing/ChatCacheController2.java create mode 100644 src/task/utils/FileFinder.java diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 796817d..070cbb6 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -1,13 +1,14 @@ package com.qiwu.chatbotbackend.db; import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.QuestionKeyWord; +import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; -import com.qiwu.chatbotbackend.processing.MyFunc; import java.sql.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; public class SqlHelper { private Connection conn = null; @@ -473,6 +474,80 @@ public class SqlHelper { } + + public Boolean insertArchiveInfo(String archiveName, String userKey, String site){ + String sql = "insert into game_archive (archive_id, user_key, site, plot) VALUES (?, ?, ?, '')"; + int id = 0; + boolean b = true; + int bNum = 0; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(archiveName)); + ps.setString(2, String.valueOf(userKey)); + ps.setString(3, String.valueOf(site)); + + + System.out.println(ps.toString()); + + bNum = ps.executeUpdate(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return bNum == 1; + } + + public ArchiveInfo queryUserLastGameArchive(String userKey){ + String sql = "select * from game_archive where user_key = ? order by update_time desc"; + String result = "{}"; + ArchiveInfo archiveInfo = null; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(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")); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return archiveInfo; + } + + + public ArchiveInfo queryUserLastGameArchiveBySite(String userKey, String site){ + String sql = "select * from game_archive where user_key = ? and site = ? order by update_time desc"; + String result = "{}"; + ArchiveInfo archiveInfo = null; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, userKey); + ps.setString(2, site); + 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")); + } + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return archiveInfo; + } + // public boolean insertCategoryByBotId(int botId, String categoryName) { // String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; // int id = 0; diff --git a/src/entity/ArchiveInfo.java b/src/entity/ArchiveInfo.java new file mode 100644 index 0000000..068a3e9 --- /dev/null +++ b/src/entity/ArchiveInfo.java @@ -0,0 +1,57 @@ +package com.qiwu.chatbotbackend.entity; + +public class ArchiveInfo { + String archiveId; + String userKey; + String site; + String updateTime; + String plot; + + public String getArchiveId() { + return archiveId; + } + + public void setArchiveId(String archiveId) { + this.archiveId = archiveId; + } + + public String getUserKey() { + return userKey; + } + + public void setUserKey(String userKey) { + this.userKey = userKey; + } + + public String getSite() { + return site; + } + + public void setSite(String site) { + this.site = site; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getPlot() { + return plot; + } + + public void setPlot(String plot) { + this.plot = plot; + } + + public ArchiveInfo(String archiveId, String userKey, String site, String updateTime, String plot) { + this.archiveId = archiveId; + this.userKey = userKey; + this.site = site; + this.updateTime = updateTime; + this.plot = plot; + } +} diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index 8f3882f..371f739 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -1,22 +1,19 @@ package com.qiwu.chatbotbackend.entity; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import org.springframework.beans.factory.DisposableBean; + import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.concurrent.ExecutionException; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.processing.ChatCacheController; -import org.springframework.beans.factory.DisposableBean; +public class ChatCache implements DisposableBean { -import javax.annotation.PreDestroy; - -public class ChatCache implements DisposableBean { - - - private String chatKey = "不知道"; +// private String chatKey = "不知道"; + private String userKey = ""; + private String randKey = ""; private String botAccount = ""; private Map infoPoint = null; @@ -36,16 +33,24 @@ public class ChatCache implements DisposableBean { return reloading; } - public void setReloading(boolean reloading) { - this.reloading = reloading; + public String getUserKey() { + return userKey; + } + + public void setUserKey(String userKey) { + this.userKey = userKey; } - public String getChatKey() { - return chatKey; + public String getRandKey() { + return randKey; } - public void setChatKey(String chatKey) { - this.chatKey = chatKey; + public void setRandKey(String randKey) { + this.randKey = randKey; + } + + public void setReloading(boolean reloading) { + this.reloading = reloading; } public Map getInfoPoint() { @@ -64,8 +69,9 @@ public class ChatCache implements DisposableBean { this.gameEnv = gameEnv; } - public ChatCache(String chatKey, GameEnv gameEnv, Map infoPoint) { - this.chatKey = chatKey; + public ChatCache(String userKey, String randKey, GameEnv gameEnv, Map infoPoint) { + this.userKey = userKey; + this.randKey = randKey; this.gameEnv = gameEnv; this.infoPoint = infoPoint; } @@ -73,11 +79,9 @@ public class ChatCache implements DisposableBean { @Override public void destroy() throws IOException { - //System.out.println("销毁:" + chatKey); - //ChatCacheController.saveChatCache(chatKey, this); } - public ChatCache(UserInfo userInfo) throws Exception { + public ChatCache(UserInfo userInfo, String userKey, String randKey) throws Exception { try { gameEnv = new GameEnv(userInfo.botAccount); } catch (Exception e) { @@ -94,13 +98,10 @@ public class ChatCache implements DisposableBean { infoPoint.put(k, userInfo.varInitialMap.get(k)); } infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + this.randKey = randKey; + this.userKey = userKey; } - @PreDestroy - public void dostory() { - System.out.println("I'm destory method using @PreDestroy....."); - - } } diff --git a/src/entity/ChatCache3.java b/src/entity/ChatCache3.java new file mode 100644 index 0000000..a0ce10a --- /dev/null +++ b/src/entity/ChatCache3.java @@ -0,0 +1,93 @@ +package com.qiwu.chatbotbackend.entity; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.processing.ChatCacheController; +import org.springframework.beans.factory.DisposableBean; + + +import javax.annotation.PreDestroy; + +public class ChatCache3 implements DisposableBean { + + +// private String chatKey = "不知道"; + private String chatKey = ""; + private String botAccount = ""; + + private Map infoPoint = null; + private GameEnv gameEnv = null; + private boolean reloading = false; + + + public String getBotAccount() { + return botAccount; + } + + public void setBotAccount(String botAccount) { + this.botAccount = botAccount; + } + + public boolean isReloading() { + return reloading; + } + + + public void setReloading(boolean reloading) { + this.reloading = reloading; + } + + public Map getInfoPoint() { + return infoPoint; + } + + public void setInfoPoint(Map infoPoint) { + this.infoPoint = infoPoint; + } + + public GameEnv getGameEnv() { + return gameEnv; + } + + public void setGameEnv(GameEnv gameEnv) { + this.gameEnv = gameEnv; + } + + public ChatCache3(String chatKey, GameEnv gameEnv, Map infoPoint) { + this.chatKey = chatKey; + this.gameEnv = gameEnv; + this.infoPoint = infoPoint; + } + + + @Override + public void destroy() throws IOException { + } + + public ChatCache3(UserInfo userInfo) throws Exception { + try { + gameEnv = new GameEnv(userInfo.botAccount); + } catch (Exception e) { + System.out.println("游戏平台初始化失败"); + e.printStackTrace(); + } + + String k; + this.botAccount = userInfo.botAccount; + infoPoint = new HashMap(); + Iterator iit = userInfo.varInitialMap.keySet().iterator(); + while (iit.hasNext()) { + k = iit.next(); + infoPoint.put(k, userInfo.varInitialMap.get(k)); + } + infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + + } + + +} diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index d420e65..be49382 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -21,17 +21,24 @@ public class JConfig implements Cloneable{ private String jNextStep = ""; private String jReply = ""; private String jAuxiliaryPriority = "0"; - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - private int jStatus = 0; + private String curPremise = ""; private String hisPremise = ""; + private String feature = ""; + private String reply = ""; + private String nextStep = ""; + private String updateKnowledge = ""; + private String nextStepStatus = "return"; + private String configName = ""; + private String auxiliaryPriority = "1"; + private String status = "waiting"; + public void setjStatus(int jStatus) { + this.jStatus = jStatus; + } public String getFeature() { return feature; } @@ -40,8 +47,9 @@ public class JConfig implements Cloneable{ this.feature = feature; } - private String feature = ""; - private String reply = ""; + public String getCurPremise() { + return curPremise; + } public String getNextStep() { return nextStep; @@ -50,8 +58,9 @@ public class JConfig implements Cloneable{ public void setNextStep(String nextStep) { this.nextStep = nextStep; } - - private String nextStep = ""; + public String getConfigName() { + return configName; + } public void setConfigName(String configName, Boolean append) { @@ -62,21 +71,6 @@ public class JConfig implements Cloneable{ this.configName = configName; } } - - public String getConfigName() { - return configName; - } - - private String configName = ""; - - public String getCurPremise() { - return curPremise; - } - - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - public int getId() { return id; } @@ -85,6 +79,7 @@ public class JConfig implements Cloneable{ this.id = id; } + public String getjCurPremise() { return jCurPremise; } @@ -177,8 +172,6 @@ public class JConfig implements Cloneable{ this.updateKnowledge = updateKnowledge; } - private String updateKnowledge = ""; - private String nextStepStatus = "return"; static Map statusMap = new HashMap() { { @@ -189,7 +182,6 @@ public class JConfig implements Cloneable{ put("activate:after", "activate:after"); } }; - static int querySkipCount = 10; public void setStatus(String status) { this.status = status; diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index d67e3f4..38e70a8 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -26,6 +26,8 @@ public class CharacterConstructor extends ElementConstructor { try { String pattern1 = keywordMap.get("npc_location_pattern").toString(); + StringBuffer onlineModeTalkers = new StringBuffer(","); + JSONArray allNPC = gameElements.getJSONArray("npc"); @@ -56,12 +58,19 @@ public class CharacterConstructor extends ElementConstructor { + String classPattern = keywordMap.get("npc_class_pattern").toString(); for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { - name = (String) character.get("name"); + name = character.getString("name"); + + + //找到所有处于离线模式的npc + if(character.getBoolean("offline")!= null && !character.getBoolean("offline")){ + onlineModeTalkers.append(name).append(","); + } List nameList = new ArrayList(); nameList.add(name); @@ -86,6 +95,7 @@ public class CharacterConstructor extends ElementConstructor { } + //添加类名称 if (!classSet.contains(className)) { classSet.add(className); @@ -111,6 +121,8 @@ public class CharacterConstructor extends ElementConstructor { } } + varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); + conditionDescription.put("onlineModeTalkers", "所有在线npc"); //根据根据NPC的名字查询地点 for (String conditionName : locationRelateConditions) { diff --git a/src/gameDesign/MapConstructor2.java b/src/gameDesign/MapConstructor2.java index dada4d3..8e57a13 100644 --- a/src/gameDesign/MapConstructor2.java +++ b/src/gameDesign/MapConstructor2.java @@ -41,17 +41,18 @@ public class MapConstructor2 extends ElementConstructor { locationNum = locations.size(); StringBuffer nameSet = null; + keywordMap.putIfAbsent("site_list", new StringBuffer()); for (int i = 0; i < locationNum; i++) { jobj = locations.getJSONObject(i); jobj.put("index", i); locationName = (String) jobj.get("name"); + keywordMap.get("site_list").append("+").append(locationName); taskLineName = String.format(PlotConstructor.TASK_LINE, locationName); - if (!varInitialMap.containsKey(taskLineName)) { conditionDescription.put(taskLineName, taskLineName); varInitialMap.put(taskLineName, ""); @@ -219,8 +220,6 @@ public class MapConstructor2 extends ElementConstructor { - - /** * 生成‘怎么去哪里’所需要的配置文件 */ diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index 1de6fe1..c16beae 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -6,18 +6,20 @@ import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.UserInfo; +import java.io.*; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL; public class PlotConstructor extends ElementConstructor { public static String ASSISTANT = "globalVariable_智能助手"; - public static String ASSISTANT_EMOTION = "0"; + public static String ASSISTANT_EMOTION = "正常"; public static String TASK_DESCRIPTION = "globalVariable_任务"; - public static String TALKER_PATTERN = "【%s】"; + public static String TALKER_PATTERN = "【%s@%s】"; String GAME_STEP_FORMAT = "%s_plot_%s"; JSONArray plots = null; @@ -27,7 +29,6 @@ public class PlotConstructor extends ElementConstructor { HashMap visited = new HashMap(); - public static String TASK_LINE = "任务线_%s进度"; public static String TASK_CONDITION = "任务线%s最后一个condition"; public static String TASK_REPLY = "任务线%s最后的回答"; @@ -49,7 +50,7 @@ public class PlotConstructor extends ElementConstructor { public void construct(JSONObject jsonObject, UserInfo userinfo) { try { - addGameStartPlot(jsonObject); + addGameStartPlot(jsonObject, keywordMap); JSONArray plots = jsonObject.getJSONArray("plots"); String start = (String) jsonObject.get("start"), startCondition; @@ -121,6 +122,7 @@ public class PlotConstructor extends ElementConstructor { if (revAdjList.get(nextPlotId) == null) { revAdjList.put(nextPlotId, new ArrayList<>()); } + varSlotFilt(branch.getJSONObject(j), varInitialMap); adjList.get(id).add(nextPlotId); revAdjList.get(nextPlotId).add(id); @@ -129,6 +131,28 @@ public class PlotConstructor extends ElementConstructor { } } + /** + * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 + * @param branchNode + */ + public static void varSlotFilt(JSONObject branchNode, Map varInitialMap){ + + + String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; + Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); + Matcher m = replacePattern.matcher(branchNode.getString("reply")); + while (m.find()) { + npcName = m.group(1); + //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 + if(!varInitialMap.get("onlineModeTalkers").contains("," + npcName)) { + varSlot = m.group(3); + middleText = m.group(2); + branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); + } + + } + } + /** @@ -193,13 +217,13 @@ public class PlotConstructor extends ElementConstructor { taskLineName = String.format(PlotConstructor.TASK_LINE, location); conditionDescription.put(id, "剧情" + id + "状态"); varInitialMap.put(id ,""); - skipText.setLength(0); + //本任务线的最后一个condition和本任务线的最后一个回答 - visited.put(id, true); + branch = node.getJSONArray("branch"); @@ -207,13 +231,18 @@ public class PlotConstructor extends ElementConstructor { - - for (int i = 0; i < branchSize; i++) { + System.out.println("branch:" + i); + skipText.setLength(0); + branchNode = branch.getJSONObject(i); Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + + System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString()); + nextUnknownText = updateKnowledge.get("unknownText"); + System.out.println(id + "分支内" +nextUnknownText); nextId = (String)branchNode.get("nextPlotId"); //skipText.append(); @@ -241,7 +270,9 @@ public class PlotConstructor extends ElementConstructor { branchNode.put("reply", jumpBranchNode.get("reply")); Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); autoJumpUpdateKnowledge.putAll(newUpdateKnowledge); + nextUnknownText = (String)newUpdateKnowledge.get("unknownText"); + System.out.println("循环内" +nextUnknownText); //updateKnowledge.putAll(newUpdateKnowledge); @@ -298,7 +329,9 @@ public class PlotConstructor extends ElementConstructor { * 2. 设一个专门的剧情表示剧情的结尾 */ - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + //现在暂时放开下一步剧情未发生过的限制条件 + //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText; @@ -359,11 +392,13 @@ public class PlotConstructor extends ElementConstructor { */ //如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 if(!location.equals(beforeJumpLocatin)){ - if(curUnknownText.equals("")) + //System.out.println(id + "报异常" + curUnknownText); + if(curUnknownText.equals("")) { reply = "请到" + beforeJumpLocatin; - //如果当前地点和下一步剧情地点不同,要提示 - else + //如果当前地点和下一步剧情地点不同,要提示 + }else { reply = curUnknownText; + } //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 @@ -403,11 +438,14 @@ public class PlotConstructor extends ElementConstructor { + extraFT = ""; //是否将当前识别到的数据加入到已知数据列表 if((Boolean)branchNode.get("includeCurInfo")){ - extraFT = ",includeCurInfo"; - }else{ - extraFT = ""; + extraFT += ",includeCurInfo"; + } + + if(branchNode.get("extraFeature") != null){ + extraFT += "," + branchNode.getString("extraFeature"); } jConfig = new JConfig( @@ -432,9 +470,11 @@ public class PlotConstructor extends ElementConstructor { //将子结点加入队列 adjId = (String) branchNode.get("nextPlotId"); if (visited.get(adjId) == null && id2j.get(adjId) != null) { + visited.put(adjId, true); adjNode = id2j.get(adjId); adjNode.put("parentId", id); + //System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText); adjNode.put("nextUnknownText", nextUnknownText); queue.add(adjNode); } else { @@ -498,11 +538,13 @@ public class PlotConstructor extends ElementConstructor { */ //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + QA_URL+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); + jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); jConfig.setNextStepStatus("active"); jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); + System.out.println("qa_URL" + keywordMap.get("QA_URL")); + jConfig = new JConfig( " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" @@ -563,10 +605,13 @@ public class PlotConstructor extends ElementConstructor { /** * ---------------------------------------------------------------------------------------------------- - * 用于处理开始游戏或者继续游戏 - * - * + * 用于存档 */ + jConfig = new JConfig( + "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" + ); + jConfig.setAuxiliaryPriority("4"); + jConfigList.add(jConfig); } @@ -627,46 +672,100 @@ public class PlotConstructor extends ElementConstructor { id2j.put(nextId, endNode); visited.put(nextId, true); - } - void addGameStartPlot(JSONObject gameElements){ - JSONObject startPlot = new JSONObject(); - startPlot.put("id", "start"); - startPlot.put("conditionName", "start_options"); - startPlot.put("place", "哪呢? 还没开始呢"); - startPlot.put("branch", new JSONArray()); - - JSONObject branch1 = new JSONObject(); - branch1.put("curPremise", new JSONArray(){ - { - add("start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始"); - } - }); - - branch1.get("curPremise"); - branch1.put("higherPriority", true); - branch1.put("hisPremise", new JSONArray()); - branch1.put("reply", gameElements.get("plotStartText")); - branch1.put("updateKnowledge", new JSONObject(){ - { - put("unknownText", gameElements.get("firstUnknownText")); - } - }); - branch1.put("nextPlotId", gameElements.get("start")); - branch1.put("includeCurInfo", false); - if(gameElements.get("startAutoJump") != null) - branch1.put("autoJump", gameElements.get("startAutoJump")); - else - branch1.put("autoJump", false); - - startPlot.getJSONArray("branch").add(branch1); - gameElements.getJSONArray("plots").add(startPlot); - gameElements.put("start", "start"); - gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); - - - + void addGameStartPlot(JSONObject gameElements, Map keywordMap){ +// JSONObject startPlot = new JSONObject(); +// startPlot.put("id", "start"); +// startPlot.put("conditionName", "start_options"); +// startPlot.put("place", "哪呢? 还没开始呢"); +// startPlot.put("branch", new JSONArray()); +// +// JSONObject branch1 = new JSONObject(); +// branch1.put("curPremise", new JSONArray(){ +// { +// add("start_options::match-Include=+重新开始"); +// } +// }); +// +// branch1.put("higherPriority", true); +// branch1.put("hisPremise", new JSONArray()); +// branch1.put("extraFeature", "newGame"); +// branch1.put("reply", gameElements.get("plotStartText")); +// branch1.put("updateKnowledge", new JSONObject(){ +// { +// put("unknownText", gameElements.get("firstUnknownText")); +// } +// }); +// branch1.put("nextPlotId", gameElements.get("start")); +// branch1.put("includeCurInfo", false); +// +// +// +// startPlot.getJSONArray("branch").add(branch1); +// +// +// JSONObject branch2 = new JSONObject(); +// branch2.put("curPremise", new JSONArray(){ +// { +// add("start_options::match-Include=+开始+开始游戏+继续游戏+继续"); +// } +// }); +// +// branch2.put("higherPriority", true); +// branch2.put("hisPremise", new JSONArray()); +// branch2.put("reply", gameElements.get("plotStartText")); +// branch2.put("updateKnowledge", new JSONObject(){ +// { +// put("unknownText", gameElements.get("firstUnknownText")); +// } +// }); +// branch2.put("extraFeature", "loadLastArchive"); +// branch2.put("nextPlotId", gameElements.get("start")); +// branch2.put("includeCurInfo", false); +// if(gameElements.get("startAutoJump") != null) +// branch2.put("autoJump", gameElements.get("startAutoJump")); +// else +// branch2.put("autoJump", false); +// startPlot.getJSONArray("branch").add(branch2); +// +// +// gameElements.getJSONArray("plots").add(startPlot); +// gameElements.put("start", "start"); +// gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); + + File file = null; + FileReader fr = null; + BufferedReader br = null; + try { + file = new File("gameconfig.txt"); + fr = new FileReader(file); + + br = new BufferedReader(fr); + String jsonStr = br.readLine(); + + jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); + jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); + jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); + jsonStr = jsonStr.replace("startId", gameElements.getString("start")); + jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); + JSONObject config = JSONObject.parseObject(jsonStr); + + System.out.println(config.toJSONString()); +// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); +// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); + gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); + gameElements.put("start", "start1"); + gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); + + + br.close(); + fr.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } } @@ -674,7 +773,7 @@ public class PlotConstructor extends ElementConstructor { //如果是无条件剧情,那么需要跟着一个激活操作 public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); + jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); jConfig.setNextStep("queryskip*,map*,item*,npc*"); jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); jConfig.setNextStepStatus("active"); @@ -702,7 +801,7 @@ public class PlotConstructor extends ElementConstructor { public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ knowledgeStr.append("-<-"); - knowledgeStr.append("key"); + knowledgeStr.append(key); knowledgeStr.append(":"); knowledgeStr.append(value); diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index 4363424..01772d7 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -1,23 +1,17 @@ package com.qiwu.chatbotbackend.processing; -import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.alibaba.fastjson.JSON; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; -import com.qiwu.chatbotbackend.GameEnvironment.Util; -import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.ChatCache3; import com.qiwu.chatbotbackend.entity.UserInfo; -import org.apache.catalina.User; +import com.qiwu.chatbotbackend.task.utils.FileFinder; import javax.servlet.ServletContext; import java.io.*; -import java.sql.SQLException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; +import java.util.*; public class ChatCacheController { @@ -25,11 +19,12 @@ public class ChatCacheController { private static String CHAT_CACHE_DIR = "ChatCache"; - private static String ENV_PATH = CHAT_CACHE_DIR + "/%s-env.data"; - private static String INFO_PATH = CHAT_CACHE_DIR + "/%s-info.data"; + //private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; + //private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; + private static String ENV_PATH = CHAT_CACHE_DIR + "%s-env.data"; + private static String INFO_PATH = CHAT_CACHE_DIR + "%s-info.data"; - - public static synchronized boolean saveChatCache(String chatKey, ChatCache chatCache) throws IOException { + public static synchronized boolean saveChatCache(String chatKey, ChatCache3 chatCache) throws IOException { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String nowStr = now .format(format); @@ -62,8 +57,8 @@ public class ChatCacheController { return saveFlag; } - public static synchronized ChatCache loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception { - ChatCache chatCache = null; + public static synchronized ChatCache3 loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception { + ChatCache3 chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; @@ -85,7 +80,7 @@ public class ChatCacheController { String jsonStr = br.readLine(); infoPoint = (Map)JSON.parseObject(jsonStr); - chatCache = new ChatCache(chatKey, gameEnv, infoPoint); + chatCache = new ChatCache3(chatKey, gameEnv, infoPoint); chatCache.setReloading(true); br.close(); @@ -97,7 +92,7 @@ public class ChatCacheController { } catch (IOException e) { System.out.println(e.toString()); - chatCache = new ChatCache(userInfo); + chatCache = new ChatCache3(userInfo); loadCacheStatus = false; } @@ -105,6 +100,47 @@ public class ChatCacheController { } + public static synchronized ChatCache3 loadChatCache2(String userKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception { + ChatCache3 chatCache = null; + GameEnv gameEnv = null; + Map infoPoint = null; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + Map infoPoints = new HashMap(); + try { + File file = new File(String.format(ENV_PATH, userKey)); + if (file.exists()){ + gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, userKey)); + }else{ + throw new IOException("环境存档不存在"); + } + + + file = new File(String.format(INFO_PATH, userKey)); + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String jsonStr = br.readLine(); + infoPoint = (Map)JSON.parseObject(jsonStr); + + chatCache.setReloading(true); + + br.close(); + fr.close(); + + loadCacheStatus = true; + + + + } catch (IOException e) { + System.out.println(e.toString()); + chatCache = new ChatCache3(userInfo); + loadCacheStatus = false; + } + + return chatCache; + } + @@ -114,16 +150,16 @@ public class ChatCacheController { * * @return 历史信息点,对话过程中引擎提取的用户信息 */ - public static synchronized ChatCache getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { - Map chatCacheMap = null; - ChatCache chatCache = null; + public static synchronized ChatCache3 getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { + Map chatCacheMap = null; + ChatCache3 chatCache = null; if (context.getAttribute("chatCache") == null) { - chatCacheMap = new HashMap(); + chatCacheMap = new HashMap(); //chatCacheMap.put(chatKey, new ChatCache(userinfo)); context.setAttribute("chatCache", chatCacheMap); } else { - chatCacheMap = (Map) context.getAttribute("chatCache"); + chatCacheMap = (Map) context.getAttribute("chatCache"); } String chatkey; @@ -159,10 +195,10 @@ public class ChatCacheController { chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus); //没有继续游戏相关的关键词 }else { - chatCache = new ChatCache(userinfo); + chatCache = new ChatCache3(userinfo); } }else { - chatCache = new ChatCache(userinfo); + chatCache = new ChatCache3(userinfo); } chatCacheMap.put(chatKey, chatCache); //用户几分钟前还在玩 @@ -175,14 +211,14 @@ public class ChatCacheController { if(startKeySet.contains(startKeyword)) { chatCache.setReloading(true); }else if(restartKeySet.contains(startKeyword)){ - chatCache = new ChatCache(userinfo); + chatCache = new ChatCache3(userinfo); } } } //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); } catch (Exception e) { //可整合 - chatCache = new ChatCache(userinfo); + chatCache = new ChatCache3(userinfo); } @@ -195,10 +231,10 @@ public class ChatCacheController { */ public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context, UserInfo userInfo) throws IOException { String chatKey; - ChatCache chatCache = null; + ChatCache3 chatCache = null; long lastChatTime, now; Map history = new HashMap(); - Map chatCacheMap = (Map) context.getAttribute("chatCache"); + Map chatCacheMap = (Map) context.getAttribute("chatCache"); Iterator it = chatCacheMap.keySet().iterator(); @@ -226,8 +262,8 @@ public class ChatCacheController { */ public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - Map keyCacheMap = (Map) context.getAttribute("chatCache"); - ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); + Map keyCacheMap = (Map) context.getAttribute("chatCache"); + ChatCache3 chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); chatCache.setInfoPoint(historyInfoPoint); chatCache.setGameEnv(gameEnv); context.setAttribute("chatCache", keyCacheMap); @@ -235,7 +271,7 @@ public class ChatCacheController { public static synchronized boolean findChatCache(String chatKey, ServletContext context, String botAccount) throws Exception { - ChatCache chatCache = null; + ChatCache3 chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; @@ -244,7 +280,7 @@ public class ChatCacheController { Map infoPoints = new HashMap(); try { if (context.getAttribute("chatCache") != null) { - if (((HashMap)context.getAttribute("chatCache")).get(chatKey) != null){ + if (((HashMap)context.getAttribute("chatCache")).get(chatKey) != null){ return true; } } @@ -266,7 +302,7 @@ public class ChatCacheController { public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { try { System.out.println("移除----------------------------"); - HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); + HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); chatCacheHashMap.remove(chatKey); } catch(Exception e){ @@ -277,6 +313,35 @@ public class ChatCacheController { return true; } + public static synchronized List queryChatCacheBySite(String key, String site) { + String findPattern = String.format(ENV_PATH, key, site, ".*?"); + List fileList = FileFinder.findFiles(CHAT_CACHE_DIR, findPattern); + + Comparator FILES_BY_MODEFIED_DATE = new Comparator() { + @Override + public int compare(File object1, File object2) { + + long d1 = object1.lastModified(); + long d2 = object2.lastModified(); + + if (d1 == d2) { + return 0; + } else { + return d1 < d2 ? 1 : -1; + } + } + }; + fileList.sort(FILES_BY_MODEFIED_DATE); + + return fileList; + } + + + + + + + diff --git a/src/processing/ChatCacheController2.java b/src/processing/ChatCacheController2.java new file mode 100644 index 0000000..860cfed --- /dev/null +++ b/src/processing/ChatCacheController2.java @@ -0,0 +1,278 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSON; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ArchiveInfo; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class ChatCacheController2 { + + public static long TIME_OUT = 300000; + + + private static String CHAT_CACHE_DIR = "ChatCache/"; + + private static String ARCHIVE_NAME = "%s-%s-%s"; + private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; + private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; + private static String ENV_POSTFIX = "-env.data"; + private static String INFO_POSTFIX = "-info.data"; + + public static String COMBINE_PUNC1 = "@@@"; + public static String COMBINE_PUNC2 = "@@@@"; + + + + /** + * 通过chat_key获得后台保存的历史信息点 + * chatCache:存储了chatKye相对应的对话记录(历史信息点) + * + * @return 历史信息点,对话过程中引擎提取的用户信息 + */ + public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { + Map chatCacheMap = null; + ChatCache chatCache = null; + + if (context.getAttribute("chatCache") == null) { + chatCacheMap = new HashMap(); + //chatCacheMap.put(chatKey, new ChatCache(userinfo)); + context.setAttribute("chatCache", chatCacheMap); + } else { + chatCacheMap = (Map) context.getAttribute("chatCache"); + } + + + + try { + chatCache = chatCacheMap.get(userKey); + + + //如果用户之前没有玩过或者有一段时间没有玩 + if(chatCache == null){ + chatCache = new ChatCache(userinfo, userKey, randKey); + chatCacheMap.put(userKey, chatCache); + //用户几分钟前还在玩 + } else { + if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 + saveChatCache(chatCache, null); + chatCache = new ChatCache(userinfo, userKey, randKey); + chatCacheMap.put(userKey, chatCache); + } + } + //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); + } catch (Exception e) { + //可整合 + e.printStackTrace(); + chatCache = new ChatCache(userinfo, userKey, randKey); + chatCacheMap.put(userKey, chatCache); + + } + + return chatCache; + } + + + + public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); + String nowTime = now .format(format); + Boolean opFlag; + + + String userKey = chatCache.getUserKey(); + String site = chatCache.getInfoPoint().get("site"); + String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); + + try { + + if(helper == null){ + helper = new SqlHelper(); + } + + File dir = new File(CHAT_CACHE_DIR); + if (!dir.exists()) + dir.mkdir(); + + + + + + ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); + + + File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); + FileWriter fw = new FileWriter(file); + + String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); + fw.write(jsonString); + fw.close(); + + + opFlag = helper.insertArchiveInfo(archiveName, userKey, site); + + } catch (Exception e) { + System.out.println("游戏存档时发生异常"); + e.printStackTrace(); + opFlag = false; + } + + return opFlag; + } + + + + public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { + ChatCache chatCache = null; + GameEnv gameEnv = null; + Map infoPoint = null; + String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); + keys[1] = keys[1].split("-")[0]; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + Map infoPoints = new HashMap(); + try { + File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + if (file.exists()){ + gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + }else{ + throw new IOException("环境存档不存在"); + } + + + file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String jsonStr = br.readLine(); + infoPoint = (Map)JSON.parseObject(jsonStr); + + chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); + chatCache.setReloading(true); + + br.close(); + fr.close(); + + + + + } catch (IOException e) { + System.out.println(e.toString()); + } + + return chatCache; + } + + + + /** + * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 + */ + public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { + String sessionKey; + ChatCache chatCache = null; + SqlHelper helper = null; + long lastChatTime, now; + Map history = new HashMap(); + Map chatCacheMap = (Map) context.getAttribute("chatCache"); + + try { + + Iterator it = chatCacheMap.keySet().iterator(); + while (it.hasNext()) { + sessionKey = it.next(); + if (sessionKey.equals(userKey)) { + saveChatCache(chatCacheMap.get(sessionKey),null); + continue; + } + history = chatCacheMap.get(sessionKey).getInfoPoint(); + lastChatTime = Long.valueOf(history.get("lastUpdateTime")); + now = System.currentTimeMillis(); + if (now - lastChatTime > ChatCacheController2.TIME_OUT) { + chatCache = chatCacheMap.get(sessionKey); + + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { + saveChatCache(chatCache, null); + } + System.out.println("移除" + sessionKey); + it.remove(); + } + } + }catch (Exception e){ + e.printStackTrace(); + } + context.setAttribute("chatCache", chatCacheMap); + } + + /** + * 根据chatKey更新chatCache的数据,并修改最后更新时间 + */ + public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { + historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + Map keyCacheMap = (Map) context.getAttribute("chatCache"); + ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); + chatCache.setInfoPoint(historyInfoPoint); + chatCache.setGameEnv(gameEnv); + context.setAttribute("chatCache", keyCacheMap); + } + + + public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception { + ChatCache chatCache = null; + GameEnv gameEnv = null; + ArchiveInfo archiveInfo = null; + Map infoPoint = null; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + SqlHelper helper; + Map infoPoints = new HashMap(); + try { + + helper = new SqlHelper(); + archiveInfo = helper.queryUserLastGameArchive(userKey); + + + } catch(Exception e){ + e.printStackTrace(); + return false; + } + + return archiveInfo != null; + } + + + public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { + try { + System.out.println("移除----------------------------"); + HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); + chatCacheHashMap.remove(chatKey); + + } catch(Exception e){ + e.printStackTrace(); + return false; + } + + return true; + } + + + + + + + + + +} diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index f3c927e..7987113 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -8,6 +8,7 @@ import com.qiwu.chatbotbackend.entity.Condition; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import org.apache.http.message.BasicNameValuePair; +import org.springframework.beans.factory.annotation.Value; import java.io.UnsupportedEncodingException; import java.util.*; @@ -17,8 +18,17 @@ import java.util.regex.Pattern; public class FormsPoster { - LogWriter logWriter = null; - public static String QA_URL = "http://qcloud-gz1.chewrobot.com:58000/game"; + LogWriter logWriter; + + static String TALKER = "【(.*?)@.*?】"; + + @Value("${qa.url}") + public String QA_URL; + + + public void setQaUrl(String qaUrl) { + QA_URL = qaUrl; + } public FormsPoster(LogWriter logWriter) { this.logWriter = logWriter; @@ -33,7 +43,7 @@ public class FormsPoster { } }; - static String TALKER = "【(.*?)@.*?】"; + /** * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 diff --git a/src/processing/LogWriter.java b/src/processing/LogWriter.java index d75c98f..c6a7b85 100644 --- a/src/processing/LogWriter.java +++ b/src/processing/LogWriter.java @@ -6,11 +6,32 @@ import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; + public class LogWriter { private PrintWriter recorder = null; DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"); LocalDateTime ldt = null; + + String filePath; + String fileName; + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + String PRINT_PATTERN = "[%s] %s" + "----------------------------------------------------------------------------
"; Map colorMap = new HashMap(){ diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java index 8bf1e3d..bb0e51d 100644 --- a/src/processing/MyFunc.java +++ b/src/processing/MyFunc.java @@ -19,10 +19,8 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; - -import static com.qiwu.chatbotbackend.processing.QuestionMatcher.API_ERROR; -import static com.qiwu.chatbotbackend.processing.QuestionMatcher.POST_ERROR; +import java.util.Date; +import java.util.List; public class MyFunc { @@ -173,6 +171,7 @@ public class MyFunc { JSONObject jobj = new JSONObject(); try { + System.out.println("url为:" + url); HttpResponse resp = client.execute(httpPost); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java index a99c7e4..4acb93f 100644 --- a/src/processing/QuestionMatcher.java +++ b/src/processing/QuestionMatcher.java @@ -1,19 +1,17 @@ package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; import org.apache.commons.lang.StringUtils; import org.apache.http.message.BasicNameValuePair; import javax.servlet.ServletContext; -import java.io.*; +import java.io.IOException; import java.text.ParseException; import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; public class QuestionMatcher { @@ -24,8 +22,8 @@ public class QuestionMatcher { static String POST_DATA_ERROR = "post数据有误"; static String POST_ERROR = "数据post时出错了"; static String API_ERROR = "api处理过程中出错了"; - static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; - Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + public LogWriter logWriter = null; @@ -147,11 +145,9 @@ public class QuestionMatcher { activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); } - if((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) { - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - } + bestMatch = condition; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); + logWriter.writeln(); } @@ -287,7 +283,7 @@ public class QuestionMatcher { String ks[] = keyword.split(":", 2); if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) flag = false; - }else { + }else { if (keywordSet.contains(keyword)) { flag = false; } @@ -585,46 +581,27 @@ public class QuestionMatcher { } } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - if (ans.getNext().equals("")) { - ans.setNext("nextStep=" + ansCondition.nextStep); - } try { reply = MyFunc.randStr(ansCondition.answer); - //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 - String keyword; - Matcher m = replacePattern.matcher(reply); - while (m.find()) { - variable = m.group(1).substring(1, m.group(1).length() - 3); - if (m.group(1).endsWith("-1}")) { - if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) { - keyword = curInfoPoint.get(variable); - if(keyword.contains(":")) - keyword = keyword.split(":")[1]; - - reply = reply.replace("{" + variable + "-1}", keyword); - } - } else if (m.group(1).endsWith("-2}")) { - if (historyInfoPoint.get(variable) != null) - if(historyInfoPoint.get(variable).equals("do_reset")){ - reply = reply.replace("{" + variable + "-2}", ""); - }else - reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); - } - } - + reply = botUtil.varSlotReplace(reply); reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter); + ans.setAnswer(reply); + botUtil.extraOperation(ansCondition, ans); + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- - ans.setAnswer(reply); + + if (ans.getNext().equals("")) { + ans.setNext("nextStep=" + ansCondition.nextStep); + } } catch (Exception e) { e.printStackTrace(); @@ -681,7 +658,7 @@ public class QuestionMatcher { historyInfoPoint.put(actionName, keyword1); }else if (historyInfoPoint.get(actionName).equals("do_reset")){ historyInfoPoint.put(actionName, ""); - }else if (keyword2 != null && !keyword1.equals("")) + }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); } historyInfoPoint.put("临时变量reply", ""); @@ -720,6 +697,8 @@ public class QuestionMatcher { add("unknownTextList"); add("finalUnknownText"); add("unknownText"); + add("randKey"); + add("userKey"); } }; @@ -930,6 +909,8 @@ public class QuestionMatcher { keyword = ""; updateValue = keyword.replace(updateValue.substring(5), ""); + + //变量提取 } else if (updateValue.startsWith("var=")) { String conditionName = updateValue.substring(5, updateValue.length() - 3); @@ -945,11 +926,15 @@ public class QuestionMatcher { } else { updateValue = ""; } + + //提取配置条目的下一步 } else if (updateValue.endsWith("nextStep-3}")) { updateValue = condition.nextStep; + //提取配置条目的回答 } else if (updateValue.endsWith("reply-3}")) { updateValue = MyFunc.randStr(condition.answer); } + //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue if (variableName.startsWith("process-nextStep")) { condition.nextStep = updateValue; updateValue = ""; @@ -957,6 +942,7 @@ public class QuestionMatcher { } + } catch (Exception e) { e.printStackTrace(); continue; @@ -965,7 +951,7 @@ public class QuestionMatcher { if(updateValue.equals("")) { - curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点转移时这个变量的已知信息依然不是空的。 + curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 curInfoPoint.put(variableName, ""); } diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java index 837ff8c..3332bb8 100644 --- a/src/processing/ResponseFilter.java +++ b/src/processing/ResponseFilter.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; public class ResponseFilter { @@ -38,7 +39,7 @@ public class ResponseFilter { return reply; } - if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT) + "@" + PlotConstructor.ASSISTANT_EMOTION + "】") ){ + if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ return reply; }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ return reply; @@ -61,11 +62,17 @@ public class ResponseFilter { List unknownList = new ArrayList(); String lastTalker = ""; - //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是剧情中的人 + //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); while(m.find()) { - lastTalker = m.group(1); + //回答unknown文本的npc必须处于在线模式 + npc = m.group(1); + if(historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",")) { + lastTalker = npc; + }else{ + System.out.println(npc + "是离线模式"); + } } for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { @@ -151,6 +158,9 @@ public class ResponseFilter { * @param logWriter * @return */ + + + static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ String npc, location; diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 379b5db..85005a7 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -10,6 +10,8 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION; + public class WorldController { public LogWriter logWriter = null; public UserInfo userInfo = null; @@ -200,7 +202,7 @@ public class WorldController { lastTalker = m.group(1); } - returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); + returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); break; diff --git a/src/servlet/FindCacheServlet.java b/src/servlet/FindCacheServlet.java index 9fb15eb..37afa82 100644 --- a/src/servlet/FindCacheServlet.java +++ b/src/servlet/FindCacheServlet.java @@ -1,7 +1,7 @@ package com.qiwu.chatbotbackend.servlet; import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.ChatCacheController2; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -19,12 +19,12 @@ public class FindCacheServlet extends HttpServlet { request.setCharacterEncoding("UTF-8"); - String chatKey = request.getParameter("client_id"); + String userKey = request.getParameter("client_id"); String botAccount = request.getParameter("aipioneer_username"); Boolean exist = false; try { - exist = ChatCacheController.findChatCache(chatKey+ "-" + botAccount, context, botAccount); + exist = ChatCacheController2.findChatCache(userKey, context, botAccount); } catch (Exception e) { e.printStackTrace(); } @@ -32,6 +32,7 @@ public class FindCacheServlet extends HttpServlet { JSONObject responseJSONObject = new JSONObject(); responseJSONObject.put("exist", exist); responseJSONObject.put("aipioneer_username", botAccount); + responseJSONObject.put("client_id", userKey); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 67c3bdb..e2ddc0c 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -267,8 +267,6 @@ public class GameDesignServlet extends HttpServlet { boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); - - return deleteConfigFlag && deleteVariableFlag; } diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 6693993..b34845c 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -1,7 +1,9 @@ package com.qiwu.chatbotbackend.servlet; -import com.qiwu.chatbotbackend.entity.*; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.*; import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; import com.qiwu.chatbotbackend.task.utils.GameBotUtil; @@ -12,10 +14,12 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.*; +import java.io.IOException; +import java.io.OutputStream; import java.sql.SQLException; import java.text.ParseException; -import java.util.*; +import java.util.HashMap; +import java.util.Map; @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) @@ -37,18 +41,30 @@ public class GetAnswerServlet extends HttpServlet { BasicBotUtil botUtil = null; Condition ansCondition = null; boolean debugFlag = false; - String ansJ = "", return_str = "", state = "", chatKey = "", botType = ""; + String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; String botName = receiveParamters.get("bot_name")[0]; OutputStream out = response.getOutputStream(); ServletContext context = this.getServletContext(); //如果有client_id,会用@分隔 - if(!receiveParamters.get("chat_key")[0].startsWith("@")) - chatKey = receiveParamters.get("chat_key")[0].split("@")[0]; - else - chatKey = receiveParamters.get("chat_key")[0]; - receiveParamters.get("chat_key")[0] = chatKey; + chatKey = receiveParamters.get("chat_key")[0]; + String chatKeys[] = receiveParamters.get("chat_key")[0].split("@@@@"); + if(chatKeys.length == 1){ + userKey = chatKeys[0]; + randKey = chatKeys[0]; + }else{ + userKey = chatKeys[0]; + randKey = chatKeys[1]; + } + receiveParamters.put("userKey", new String[]{userKey}); + receiveParamters.put("randKey", new String[]{randKey}); + +// if(!receiveParamters.get("chat_key")[0].startsWith("@")) +// chatKey = receiveParamters.get("chat_key")[0].split("@")[0]; +// else +// chatKey = receiveParamters.get("chat_key")[0]; +// receiveParamters.get("chat_key")[0] = chatKey; LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); @@ -74,7 +90,8 @@ public class GetAnswerServlet extends HttpServlet { ChatCache chatCache = null; Boolean loadCacheStatus = Boolean.valueOf(false); try { - chatCache = ChatCacheController.getChatCache(chatKey, context, userinfo, receiveParamters, loadCacheStatus); + //chatCache = ChatCacheController.getChatCache2(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); + chatCache = ChatCacheController2.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { @@ -86,86 +103,73 @@ public class GetAnswerServlet extends HttpServlet { * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 */ - if(!chatCache.isReloading()) { - historyInfoPoint = chatCache.getInfoPoint(); + historyInfoPoint = chatCache.getInfoPoint(); - if(userinfo.varInitialMap.get("botType") != null) - botType = userinfo.varInitialMap.get("botType"); + if(userinfo.varInitialMap.get("botType") != null) + botType = userinfo.varInitialMap.get("botType"); - switch(botType){ - case "game": - WorldController worldController = new WorldController(logWriter,userinfo); - botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv()); - break; - default: - botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); - break; - } + switch(botType){ + case "game": + WorldController worldController = new WorldController(logWriter,userinfo); + botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv(), chatCache); + break; + default: + botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); + break; + } - //针对不同游戏类型对信息点做预处理 - debugFlag = botUtil.preprocessing(receiveParamters, context); + //针对不同游戏类型对信息点做预处理 + debugFlag = botUtil.preprocessing(receiveParamters, context); - //信息点预处理 - QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); + //信息点预处理 + QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); - /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ - //process.removeTimeoutChatkey(context); - //System.out.println(userinfo.conditionTable); //测试 - ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); - if (state.equals("") && ansCondition.priority == -1) - state = "我不理解,"; - if (state.equals("")) { - try { - bestMatch = matcher.getSolution(ansCondition, context, userinfo); + /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ + //process.removeTimeoutChatkey(context); + //System.out.println(userinfo.conditionTable); //测试 + ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); + if (state.equals("") && ansCondition.priority == -1) + state = "我不理解,"; + if (state.equals("")) { + try { + bestMatch = matcher.getSolution(ansCondition, context, userinfo); - if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) { - //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansCondition, context, userinfo); - } - } catch (ParseException e) { - e.printStackTrace(); + if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + bestMatch = matcher.postActivate(ansCondition, context, userinfo); } - } else { - bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); + } catch (ParseException e) { + e.printStackTrace(); } + } else { + bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); + } - if (debugFlag) { - matcher.appendDebugInfo(bestMatch, context); - } - - - //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) - matcher.infoTransfer(bestMatch, context, debugFlag); - - - ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, chatCache.getGameEnv(), context, userinfo); - //清理超时的用户数据 - if (context.getAttribute("cacheUpdateTime") == null) - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { - ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - } - - //针对不同游戏类型做后处理 - botUtil.postprocessing(chatKey, context, bestMatch); + if (debugFlag) { + matcher.appendDebugInfo(bestMatch, context); + } + //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) + matcher.infoTransfer(bestMatch, context, debugFlag); - } else { + ChatCacheController2.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo); + //清理超时的用户数据 + if (context.getAttribute("cacheUpdateTime") == null) + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController2.TIME_OUT) { + ChatCacheController2.updateChatCache4Delete(chatKey, context, userinfo); + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + } - System.out.println("----------读档中------------"); - String site = chatCache.getInfoPoint().get("site"); + //针对不同游戏类型做后处理 + botUtil.postprocessing(chatKey, context, bestMatch); - String nextStep = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site)); - String reply = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site)); - bestMatch = new Solution(1, "--读取存档--" + reply, "nextStep=" + nextStep); - } ansJ = MyFunc.toJson(bestMatch); } else { ansJ = "找不到配置文件"; diff --git a/src/servlet/MyListener.java b/src/servlet/MyListener.java index 062367d..8d04fc6 100644 --- a/src/servlet/MyListener.java +++ b/src/servlet/MyListener.java @@ -1,7 +1,8 @@ package com.qiwu.chatbotbackend.servlet; +import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.ChatCacheController2; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; @@ -23,6 +24,7 @@ public class MyListener implements ServletContextListener { ServletContext servletContext = sce.getServletContext(); Object obj = servletContext.getAttribute("chatCache"); ChatCache cache = null; + SqlHelper helper = null; if(obj != null){ Map chatCacheMap = (Map)obj; @@ -34,8 +36,9 @@ public class MyListener implements ServletContextListener { chatKey = cacheIter.next(); cache = chatCacheMap.get(chatKey); try { + helper = new SqlHelper(); System.out.println(String.format("saving %s", chatKey)); - ChatCacheController.saveChatCache(chatKey, cache); + ChatCacheController2.saveChatCache(cache, helper); }catch (Exception e){ System.out.println(String.format("保存%s时出现异常", chatKey)); } diff --git a/src/servlet/SaveChatCacheServlet.java b/src/servlet/SaveChatCacheServlet.java index fe4877a..4aeb743 100644 --- a/src/servlet/SaveChatCacheServlet.java +++ b/src/servlet/SaveChatCacheServlet.java @@ -1,9 +1,8 @@ package com.qiwu.chatbotbackend.servlet; -import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.ChatCacheController2; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -12,7 +11,6 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.io.OutputStream; import java.io.PrintWriter; import java.util.Map; @@ -22,20 +20,19 @@ public class SaveChatCacheServlet extends HttpServlet { request.setCharacterEncoding("UTF-8"); String chatKey = request.getParameter("chatKey"), message = ""; ServletContext context = this.getServletContext(); - chatKey = chatKey.split("@")[0]; + chatKey = chatKey.split("@@@@")[0]; Boolean flag = false; Map chatCacheMap = (Map)context.getAttribute("chatCache"); ChatCache chatCache = chatCacheMap.get(chatKey); - if(chatCache != null) { - flag = ChatCacheController.saveChatCache(chatKey, chatCache); + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { + flag = ChatCacheController2.saveChatCache(chatCache, null); chatCacheMap.remove(chatKey); } System.out.println("调用接口删除" + chatKey); - //out.write(message.getBytes()); diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java index 632f369..1ee7142 100644 --- a/src/task/utils/BasicBotUtil.java +++ b/src/task/utils/BasicBotUtil.java @@ -1,5 +1,6 @@ package com.qiwu.chatbotbackend.task.utils; +import com.qiwu.chatbotbackend.entity.Condition; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.LogWriter; @@ -9,6 +10,8 @@ import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class BasicBotUtil { Map curInfoPoint = null; @@ -17,6 +20,8 @@ public class BasicBotUtil { LogWriter logWriter = null; + + public BasicBotUtil(){}; public BasicBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter){ this.curInfoPoint = curInfoPoint; @@ -29,10 +34,10 @@ public class BasicBotUtil { return infoPointPreprocessing(receiveParameters, context); - } + //在接收到请求后对数据做处理,转化为系统可以处理的数据 public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context) throws IOException { String return_str = "", k, botType = ""; @@ -42,6 +47,8 @@ public class BasicBotUtil { HashSet skipSet = new HashSet() { { add("chat_key"); + add("randKey"); + add("userKey"); add("action_name"); add("bot_name"); add("emptySet"); @@ -123,6 +130,14 @@ public class BasicBotUtil { } + /** + * 从当前信息点或者已知信息点中提取关键词 + * @param infoPoint + * @param infoPoint2 + * @param chooseLater + * @param actionName + * @return + */ public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ String keyword = ""; String nameSeries[] = actionName.split("_"); @@ -141,6 +156,11 @@ public class BasicBotUtil { return keyword; }; + /** + * 更新历史信息点中的某一个键值对 + * @param variableName + * @param updateValue + */ public void putKeyword(String variableName, String updateValue){ historyInfoPoint.put(variableName, updateValue); } @@ -149,4 +169,44 @@ public class BasicBotUtil { return updateValue; } + + /** + * 额外的更新操作 + */ + public void extraOperation(Condition ansCondition, Solution solution) throws IOException { + + } + + //将文本中存在的变量槽位{npc_xxx}替换成变量值 + public String varSlotReplace(String text){ + + String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 + String keyword, variable,reply = text; + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1).substring(1, m.group(1).length() - 3); + if (m.group(1).endsWith("-1}")) { + if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) { + keyword = curInfoPoint.get(variable); + + + if(keyword.contains(":")) + keyword = keyword.split(":")[1]; + + reply = reply.replace("{" + variable + "-1}", keyword); + } + } else if (m.group(1).endsWith("-2}")) { + if (historyInfoPoint.get(variable) != null) + if(historyInfoPoint.get(variable).equals("do_reset")){ + reply = reply.replace("{" + variable + "-2}", ""); + }else + reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); + } + } + + return reply; + } } diff --git a/src/task/utils/FileFinder.java b/src/task/utils/FileFinder.java new file mode 100644 index 0000000..4fc2de4 --- /dev/null +++ b/src/task/utils/FileFinder.java @@ -0,0 +1,91 @@ +package com.qiwu.chatbotbackend.task.utils; + + +import com.alibaba.fastjson.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * 实现一个支持通配符的基于广度优先算法的文件查找器 + */ +public class FileFinder { + + /** + * 查找文件。 + * @param baseDirName 待查找的目录 + * @param targetFileName 目标文件名,支持通配符形式 + * @param count 期望结果数目,如果畏0,则表示查找全部。 + * @return 满足查询条件的文件名列表 + */ + public static List findFiles(String baseDirName, String targetFileName) { + + String tempName; + List fileList = new ArrayList(); + //判断目录是否存在 + File baseDir = new File(baseDirName); + if (!baseDir.exists() || !baseDir.isDirectory()){ + System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); + return fileList; + } + + File[] files = baseDir.listFiles(); + for (int i = 0; i < files.length; i++) { + //如果是目录则放进队列 + if (files[i].isDirectory()) { + continue; + } else { + //如果是文件则根据文件名与目标文件名进行匹配 + tempName = files[i].getName(); + if (FileFinder.wildcardMatch(targetFileName, tempName)) { + //匹配成功,将文件名添加到结果集 + fileList.add(files[i]); + } + } + } + + return fileList; + } + /** + * 通配符匹配 + * @param pattern 通配符模式 + * @param str 待匹配的字符串 + * @return 匹配成功则返回true,否则返回false + */ + private static boolean wildcardMatch(String pattern, String str) { + int patternLength = pattern.length(); + int strLength = str.length(); + int strIndex = 0; + char ch; + for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) { + ch = pattern.charAt(patternIndex); + if (ch == '*') { + //通配符星号*表示可以匹配任意多个字符 + while (strIndex < strLength) { + if (wildcardMatch(pattern.substring(patternIndex + 1), + str.substring(strIndex))) { + return true; + } + strIndex++; + } + } else if (ch == '?') { + //通配符问号?表示匹配任意一个字符 + strIndex++; + if (strIndex > strLength) { + //表示str中已经没有字符匹配?了。 + return false; + } + } else { + if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) { + return false; + } + strIndex++; + } + } + return (strIndex == strLength); + } + +} diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java index 8831571..85e77f8 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/task/utils/GameBotUtil.java @@ -1,31 +1,43 @@ package com.qiwu.chatbotbackend.task.utils; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.ChatCacheController2; import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.WorldController; import javax.servlet.ServletContext; import java.io.IOException; +import java.sql.SQLException; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; public class GameBotUtil extends BasicBotUtil{ WorldController worldController = null; GameEnv gameEnv = null; + ChatCache chatCache = null; + public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; + public static String LOAD_BY_LAST = "load_last"; - public GameBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv){ + public GameBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv, ChatCache chatCache){ this.curInfoPoint = curInfoPoint; this.historyInfoPoint = historyInfoPoint; this.userinfo = userinfo; this.logWriter = logWriter; this.worldController = worldController; this.gameEnv = gameEnv; + this.chatCache = chatCache; } @@ -39,10 +51,14 @@ public class GameBotUtil extends BasicBotUtil{ for(String conditionName: conditionList) { if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { - String info = curInfoPoint.get(conditionName); + String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName); String destination = info.split(":")[1]; String site = historyInfoPoint.get("site"); - String newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); + try { + newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); + }catch(Exception e){ + e.printStackTrace(); + } logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); curInfoPoint.put(conditionName, newInfo); @@ -88,9 +104,6 @@ public class GameBotUtil extends BasicBotUtil{ } - - - return true; } @@ -185,4 +198,137 @@ public class GameBotUtil extends BasicBotUtil{ return returnValue; } + + + @Override + public void extraOperation(Condition ansCondition, Solution solution) throws IOException { + Boolean flag = true; + String userKey = curInfoPoint.get("userKey"); + String randKey = curInfoPoint.get("randKey"); + String keyword = "", site; + SqlHelper helper = null; + ChatCache chatCache = null; + + + try { + helper = new SqlHelper(); + + if(ansCondition.featureMap.containsKey("newGame")) { + System.out.println("newGame"); + this.chatCache.setReloading(true); + + }else if (ansCondition.featureMap.containsKey("gameBackup")) { + System.out.println("gameBackup"); + if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档 + chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); + flag = ChatCacheController2.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(""); //可能存在问题,估计要一个空格 + } + + } else if (ansCondition.featureMap.containsKey("loadLastArchive")) { + System.out.println("loadLastArchive"); + ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); + loading(archiveInfo, solution); + + } else if (ansCondition.featureMap.containsKey("loadArchiveBySite")) { + System.out.println("loadArchiveBySite"); + if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { + site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; + System.out.println("要读取的存档的地点是:" + site); + ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site); + loading(archiveInfo, solution); + }else{ + System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } finally{ + helper.destroy(); + } + + } + + private void loading(ArchiveInfo archiveInfo, Solution solution){ + String keyword = "", site; + ChatCache loadCache = null; + + if (archiveInfo != null) { + try { + loadCache = ChatCacheController2.loadChatCache(archiveInfo); + } catch (Exception e) { + System.out.println("从本地加载存档失败"); + solution.setAnswer("从本地加载存档失败"); + e.printStackTrace(); + } + this.chatCache.setInfoPoint(loadCache.getInfoPoint()); + this.chatCache.setGameEnv(loadCache.getGameEnv()); +// this.historyInfoPoint = chatCache.getInfoPoint(); +// this.gameEnv = chatCache.getGameEnv(); + + + System.out.println("----------读档中------------"); + site = loadCache.getInfoPoint().get("site"); + + String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site)); + String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site)); + solution.setAnswer(reply); + solution.setNext("nextStep=" + nextStep); + + }else{ + System.out.println("没有找到该存档"); + } + } + + + //将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版 + //@Override + public String varSlotReplace2(String text){ + String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + String varElements[] = {}, result = ""; + String keyword, variable, variableSlot, reply = text; + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1); + varElements = variable.split("_"); + variableSlot = "${" + variable + "}"; + + switch (varElements[0]){ + //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 + case "globalVariable": + reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); + + case "npc": + result = gameEnv.queryNpcAttrByNpcName(varElements[1], varElements[2]); + reply = reply.replace(variableSlot, result); + + case "goods": + result = gameEnv.queryGoodsAttrByGoodsName(varElements[1], varElements[2]); + reply = reply.replace(variableSlot, result); + + case "map": + System.out.println("地图替换还没写"); + + default: + if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ + reply = reply.replace(variableSlot, curInfoPoint.get(variable)); + }else if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")){ + reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); + } + + } + } + + return reply; + } } -- libgit2 0.27.1