From 3c0c6f8a10d0fbbdb24046e511691e8407d43147 Mon Sep 17 00:00:00 2001 From: hxw Date: Sat, 23 Feb 2019 13:27:36 +0800 Subject: [PATCH] 游戏重新生成时删除所有存档、填表项目接到中控bot、在文本中删除拼音标注 --- src/db/SqlHelper.java | 50 ++++++++++++++++++++------------------------------ src/gameDesign/ListeningConstructor.java | 11 +++++++---- src/gameDesign/PlotConstructor2.java | 25 +++++++------------------ src/processing/ActionMatcher.java | 2 +- src/processing/ChatCacheController.java | 57 ++++++++++++++++++++++++++------------------------------- src/processing/FormsPoster.java | 15 ++++++++++++--- src/servlet/ContextDestroyListener.java | 2 -- src/servlet/FindCacheServlet.java | 3 ++- src/servlet/GameDesignServlet.java | 28 +++++++++++++++++++--------- src/servlet/GetAnswerServlet.java | 7 ------- src/task/utils/FileFinder.java | 40 +++++++++++++++++++++++++++++++++++----- src/task/utils/GameBotUtil.java | 2 ++ 12 files changed, 131 insertions(+), 111 deletions(-) diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 070cbb6..8308a8b 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -548,36 +548,26 @@ public class SqlHelper { return archiveInfo; } -// public boolean insertCategoryByBotId(int botId, String categoryName) { -// String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; -// int id = 0; -// boolean b = true; -// int bNum = 0; -// try { -// PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); -// ps.setString(1, String.valueOf(botId)); -// ps.setString(2, "0"); -// ps.setString(4, jConfig.getConfigName()); -// -// System.out.println(ps.toString()); -// -// bNum = ps.executeUpdate(); -// ResultSet rs = ps.getGeneratedKeys(); -// if(rs.next()){ -// id = rs.getInt(1); -// idList.add(id); -// } -// ps.close(); -// rs.close(); -// conn.commit(); -// -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// return b; -// -// } + + public boolean deleteArchiveByBotAccount(String botAccount) { + String sql = "delete from game_archive where user_key like ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, "%" + botAccount); + b = ps.execute(); + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除游戏存档失败"); + e.printStackTrace(); + return false; + } + } diff --git a/src/gameDesign/ListeningConstructor.java b/src/gameDesign/ListeningConstructor.java index 3db91e5..8d1f8fd 100644 --- a/src/gameDesign/ListeningConstructor.java +++ b/src/gameDesign/ListeningConstructor.java @@ -44,7 +44,7 @@ public class ListeningConstructor extends ElementConstructor{ for(int i = 0; i < size;i++){ plotNode = null; autoJump = false; - priority = "1"; + priority = "2"; feature = "match"; config = listeningActions.getJSONObject(i); curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), String.class); @@ -78,10 +78,11 @@ public class ListeningConstructor extends ElementConstructor{ } - if(plotNode.getString("priority") != null) - priority = plotNode.getString("priority"); + if(config.getString("priority") != null) + priority = config.getString("priority"); - updateKnowledge.put(nextPlotId + "_from", ""); + updateKnowledge.put(nextLocation + "_activate_by", ""); + updateKnowledge.put(nextLocation + "_activate_ready", "0"); updateKnowledge.put("site", nextLocation); @@ -92,10 +93,12 @@ public class ListeningConstructor extends ElementConstructor{ nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextPlotId); + updateKnowledge.put(lastTaskCondition, nextCondition); updateKnowledge.put(lastTaskReply, reply); updateKnowledge.put(nextPlotId, "1"); //下一步设为1 updateKnowledge.put(nTaskLineName, nextGameStep); + updateKnowledge.put("game_step", nextGameStep); }else{ feature = "match,return-0"; } diff --git a/src/gameDesign/PlotConstructor2.java b/src/gameDesign/PlotConstructor2.java index b84c6d9..3634d19 100644 --- a/src/gameDesign/PlotConstructor2.java +++ b/src/gameDesign/PlotConstructor2.java @@ -78,6 +78,7 @@ public class PlotConstructor2 extends ElementConstructor { BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); varInitialMap.put(start, "1"); + ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermList); } else { @@ -87,7 +88,7 @@ public class PlotConstructor2 extends ElementConstructor { return; } - ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermList); + @@ -434,7 +435,8 @@ public class PlotConstructor2 extends ElementConstructor { //下一部剧情在不同地点时,为了防止到达下个地点的剧情重复执行,需要加一个标志表示下一步剧情是否已经发生过 - appendKnowledge(extraUK, nextId + "_from", id); + appendKnowledge(extraUK, nextLocation + "_activate_by", id); + appendKnowledge(extraUK, nextLocation + "_activate_ready", "1"); @@ -863,27 +865,13 @@ public class PlotConstructor2 extends ElementConstructor { StringBuffer curPremise = new StringBuffer(); appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); - appendPremise(hisPremise, nextId + "_from", "match", "Include", plotId); + 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(hisPremise, plotId, "match", "Include", "2"); //剧情已完成且未前往 -// appendPremise(hisPremise, "from_" + plotId, "match", "Include", "0"); -// appendPremise(hisPremise, "to_" + nextId, "match", "Include", "0"); - - -// if(autoJump) { -// feature = "match,activate:after" -// appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); -// -// arriveActivatePlot2(jsonObject, id, nextId, gameStep, "plot_" + nextId + "_*", nextUnknownText, arriveUK.toString(), "match,activate:after"); -// }else { -// feature = "match"; -// arriveActivatePlot2(jsonObject, id, nextId, reply, gameStep, nextGameStep, nextLocation, nextCondition, nextUnknownText, arriveUK.toString(), "match"); -// } JSONObject updateKnowledge = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); curPremiseList.add(curPremise.toString()); @@ -897,6 +885,7 @@ public class PlotConstructor2 extends ElementConstructor { listeningConfig.put("hisPremise", hisPremiseList); listeningConfig.put("updateKnowledge", updateKnowledge); listeningConfig.put("nextPlotId", nextId); + listeningConfig.put("priority", "1"); if(gameElements.getJSONArray("listeningActions") == null) gameElements.put("listeningActions", new JSONArray()); diff --git a/src/processing/ActionMatcher.java b/src/processing/ActionMatcher.java index a137f38..8dcef16 100644 --- a/src/processing/ActionMatcher.java +++ b/src/processing/ActionMatcher.java @@ -791,7 +791,7 @@ public class ActionMatcher { /** - * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 + * 如果接收到的表单中包含debug_mode这个参数, 后台会将存储的变量值返回给前段,用于调试 * * @param ans 最终返回的数据 * @param context diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index 0837e28..deacdb7 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -21,7 +21,7 @@ public class ChatCacheController { public static long TIME_OUT = 300000; - private static String CHAT_CACHE_DIR = "ChatCache/"; + public 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"; @@ -89,7 +89,7 @@ public class ChatCacheController { 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); + String nowTime = now .format(format), userId, botAccount, keyElem[]; Boolean opFlag, destroy = false; System.out.println("游戏存档中"); @@ -196,6 +196,7 @@ public class ChatCacheController { Map chatCacheMap = (Map) context.getAttribute("chatCache"); try { + helper = new SqlHelper(); Iterator it = chatCacheMap.keySet().iterator(); while (it.hasNext()) { @@ -211,7 +212,7 @@ public class ChatCacheController { chatCache = chatCacheMap.get(sessionKey); if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { - saveChatCache(chatCache, null); + saveChatCache(chatCache, helper); } System.out.println("移除" + sessionKey); it.remove(); @@ -219,6 +220,8 @@ public class ChatCacheController { } }catch (Exception e){ e.printStackTrace(); + }finally { + helper.destroy(); } context.setAttribute("chatCache", chatCacheMap); } @@ -236,53 +239,45 @@ public class ChatCacheController { } - public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; + public static synchronized boolean findChatCache(String userKey, ServletContext context) throws Exception { ArchiveInfo archiveInfo = null; - Map infoPoint = null; + Map chatCacheMap = null; + ChatCache chatCache = null; String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; + Boolean findFlag = false; SqlHelper helper; Map infoPoints = new HashMap(); try { - helper = new SqlHelper(); - archiveInfo = helper.queryUserLastGameArchive(userKey); - helper.destroy(); + if (context.getAttribute("chatCache") == null) { + chatCacheMap = new HashMap(); + if (chatCacheMap.containsKey(userKey)) { + chatCache = chatCacheMap.get(userKey); + findFlag = !(chatCache.getUserKey().endsWith(chatCache.getRandKey())); //userKey和randKey不同表示存在用户id,如果相同则没有登录只是试玩 + } + } - } catch(Exception e){ - e.printStackTrace(); - return false; - } + System.out.println("findFlag" + findFlag); + if (!findFlag) { - return archiveInfo != null; - } + helper = new SqlHelper(); + archiveInfo = helper.queryUserLastGameArchive(userKey); + helper.destroy(); + findFlag = (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){ + } catch (Exception e) { e.printStackTrace(); return false; } - return true; + return findFlag; } - - - - - - - } diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 1bb00fc..915bd36 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -189,7 +189,7 @@ public class FormsPoster { * @param URL * @throws UnsupportedEncodingException */ - public void postGameQA(Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { + public void postGameQA1(String gameStep, Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { String key, keyName; Iterator k_iter = null; List pairList = new ArrayList(); @@ -198,7 +198,7 @@ public class FormsPoster { if (historyInfoPoint.get("qa_threshold") != null) threshold = historyInfoPoint.get("qa_threshold"); - pairList.add(new BasicNameValuePair("game_step", historyInfoPoint.get("game_step"))); + pairList.add(new BasicNameValuePair("game_step", gameStep)); pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); pairList.add(new BasicNameValuePair("qa_threshold", threshold)); @@ -251,4 +251,13 @@ public class FormsPoster { } } -} + 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")){ + postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo); + } + + } + + } diff --git a/src/servlet/ContextDestroyListener.java b/src/servlet/ContextDestroyListener.java index 6a21b42..92eedbf 100644 --- a/src/servlet/ContextDestroyListener.java +++ b/src/servlet/ContextDestroyListener.java @@ -38,8 +38,6 @@ public class ContextDestroyListener implements ServletContextListener { chatKey = cacheIter.next(); cache = chatCacheMap.get(chatKey); - - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { System.out.println(String.format("saving %s", chatKey)); diff --git a/src/servlet/FindCacheServlet.java b/src/servlet/FindCacheServlet.java index c0c13d7..e261b5a 100644 --- a/src/servlet/FindCacheServlet.java +++ b/src/servlet/FindCacheServlet.java @@ -24,7 +24,8 @@ public class FindCacheServlet extends HttpServlet { Boolean exist = false; try { - exist = ChatCacheController.findChatCache(userKey, context, botAccount); + + exist = ChatCacheController.findChatCache(userKey, context); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 7d1414d..72d9f7c 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.UserInfoController; +import com.qiwu.chatbotbackend.task.utils.FileFinder; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -20,6 +21,8 @@ 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 { @@ -103,7 +106,7 @@ public class GameDesignServlet extends HttpServlet { //清空之前生成的配置条目 try { - flag = botInit(botId, userinfo, helper); + flag = botInit(botId, botAccount, userinfo, helper); } catch (SQLException e) { System.out.println("清空旧数据失败"); e.printStackTrace(); @@ -122,7 +125,7 @@ public class GameDesignServlet extends HttpServlet { ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n,预处理之后:").append(now); - String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots", "listeningActions"}; + String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; for(String moduleName: moduleList){ switch (moduleName) { @@ -153,10 +156,6 @@ public class GameDesignServlet extends HttpServlet { constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; - case "listeningActions": - moduleName2 = "生成处于监听的action"; - constructor = new ListeningConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); default: continue; @@ -218,6 +217,10 @@ public class GameDesignServlet extends HttpServlet { } } + if(returnStatus == 1){ + deleteOldArchive(helper, botAccount); + } + helper.destroy(); @@ -259,11 +262,12 @@ public class GameDesignServlet extends HttpServlet { out.flush(); } - public boolean botInit(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { + public boolean botInit(int botId, String botAccount, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { boolean deleteConfigFlag = helper.deleteConfigByBotId(botId); boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); + boolean deleteArchiveFlag = deleteOldArchive(helper, botAccount); return deleteConfigFlag && deleteVariableFlag; @@ -293,8 +297,6 @@ public class GameDesignServlet extends HttpServlet { 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")); @@ -340,6 +342,14 @@ 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 ba9bcb1..b6ea93b 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -60,12 +60,6 @@ public class GetAnswerServlet extends HttpServlet { 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); @@ -90,7 +84,6 @@ public class GetAnswerServlet extends HttpServlet { ChatCache chatCache = null; Boolean loadCacheStatus = Boolean.valueOf(false); try { - //chatCache = ChatCacheController.getChatCache2(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); } catch (SQLException e) { e.printStackTrace(); diff --git a/src/task/utils/FileFinder.java b/src/task/utils/FileFinder.java index 4fc2de4..1097ca3 100644 --- a/src/task/utils/FileFinder.java +++ b/src/task/utils/FileFinder.java @@ -1,13 +1,11 @@ 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; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * 实现一个支持通配符的基于广度优先算法的文件查找器 @@ -18,7 +16,6 @@ public class FileFinder { * 查找文件。 * @param baseDirName 待查找的目录 * @param targetFileName 目标文件名,支持通配符形式 - * @param count 期望结果数目,如果畏0,则表示查找全部。 * @return 满足查询条件的文件名列表 */ public static List findFiles(String baseDirName, String targetFileName) { @@ -88,4 +85,37 @@ public class FileFinder { return (strIndex == strLength); } + public static boolean deleteGameArchive(String baseDirName, String botAccount){ + + String tempName; + String regEx = ".*@@@" + botAccount + "@@@@.*"; + List fileList = new ArrayList(); + Pattern pattern = Pattern.compile(regEx); + Matcher matcher = null; + //判断目录是否存在 + File baseDir = new File(baseDirName); + if (!baseDir.exists() || !baseDir.isDirectory()){ + System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); + return false; + } + + File[] files = baseDir.listFiles(); + for (int i = 0; i < files.length; i++) { + //如果是目录则放进队列 + if (files[i].isDirectory()) { + continue; + } else { + //如果是文件则根据文件名与目标文件名进行匹配 + tempName = files[i].getName(); + matcher = pattern.matcher(tempName); + if (matcher.find()) { + //匹配成功,将文件名添加到结果集 + files[i].delete(); + } + } + } + + return true; + } + } diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java index 0537f4c..9977c5a 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/task/utils/GameBotUtil.java @@ -293,6 +293,8 @@ public class GameBotUtil extends BasicBotUtil{ }else{ System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); } + } else if(ansAction.featureMap.containsKey("sendArchiveList")){ + } } catch (SQLException e) { -- libgit2 0.27.1