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.UserInfo; 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; public class ChatCacheController { public static long TIME_OUT = 300000; 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"; /** * 通过chat_key获得后台保存的历史信息点 * chatCache:存储了chatKye相对应的对话记录(历史信息点) * * @return 历史信息点,对话过程中引擎提取的用户信息 */ // public static synchronized Map getChatCache(String chatKey, ServletContext context) { // // GameEnv gameEnv = new GameEnv(chatKey); // Map historyInfoPoint = null; // Map> chatCache = null; // if (context.getAttribute("chatCache") == null) { // chatCache = new HashMap>(); // context.setAttribute("chatCache", chatCache); // } else { // chatCache = (Map>) context.getAttribute("chatCache"); // } // String chatkey; // // // try { // historyInfoPoint = chatCache.get(chatKey); // //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); // } catch (Exception e) { // // //可整合 // historyInfoPoint = null; // // } // // return historyInfoPoint; // } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ // public static synchronized void updateChatCache4Delete(ServletContext context) { // String chatKey; // long lastChatTime, now; // Map history = new HashMap(); // Map> chatCache = (Map>) context.getAttribute("chatCache"); // // // Iterator it = chatCache.keySet().iterator(); // while (it.hasNext()) { // chatKey = it.next(); // history = chatCache.get(chatKey); // lastChatTime = Long.valueOf(history.get("lastUpdateTime")); // now = System.currentTimeMillis(); // if (now - lastChatTime > 300000) { // it.remove(); // } // } // context.setAttribute("chatCache", chatCache); // } /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ // public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, ServletContext context) { // historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); // Map> keyCache = (Map>) context.getAttribute("chatCache"); // keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint); // context.setAttribute("chatCache", keyCache); // } public static boolean saveChatCache(String chatKey, ChatCache chatCache) throws IOException { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String nowStr = now .format(format); boolean saveFlag = true; try { File dir = new File(CHAT_CACHE_DIR); if (!dir.exists()) dir.mkdir(); ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, chatKey.split("-")[0])); File file = new File(String.format(INFO_PATH, chatKey.split("-")[0])); FileWriter fw = new FileWriter(file); String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); fw.write(jsonString); fw.close(); } catch (Exception e) { System.out.println("游戏存档时发生异常"); saveFlag = false; } return saveFlag; } public static ChatCache loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception { ChatCache 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, chatKey)); if (file.exists()){ gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, chatKey)); }else{ throw new IOException("环境存档不存在"); } file = new File(String.format(INFO_PATH, chatKey)); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String jsonStr = br.readLine(); infoPoint = (Map)JSON.parseObject(jsonStr); chatCache = new ChatCache(chatKey, gameEnv, infoPoint); chatCache.setReloading(true); br.close(); fr.close(); loadCacheStatus = true; } catch (IOException e) { System.out.println(e.toString()); chatCache = new ChatCache(userInfo); loadCacheStatus = false; } return chatCache; } public static synchronized ChatCache getChatCache(String chatKey, 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"); } String chatkey; try { chatCache = chatCacheMap.get(chatKey); HashSet startKeySet = new HashSet(){ { add("开始"); add("开始剧情"); add("继续"); add("继续剧情"); } }; HashSet restartKeySet = new HashSet(){ { add("重新开始"); } }; if(chatCache == null){ if(receiveParamters.containsKey("start_options")){ String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1]; if(startKeySet.contains(startKeyword)) { chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus); }else { chatCache = new ChatCache(userinfo); } }else { chatCache = new ChatCache(userinfo); } chatCacheMap.put(chatKey, chatCache); } else { chatCache.setReloading(false); if(receiveParamters.containsKey("start_options")){ String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1]; if(startKeySet.contains(startKeyword)) { chatCache.setReloading(true); }else if(restartKeySet.contains(startKeyword)){ chatCache = new ChatCache(userinfo); } } } //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); } catch (Exception e) { //可整合 chatCache = new ChatCache(userinfo); } return chatCache; } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context) throws IOException { String chatKey; ChatCache chatCache = null; long lastChatTime, now; Map history = new HashMap(); Map chatCacheMap = (Map) context.getAttribute("chatCache"); Iterator it = chatCacheMap.keySet().iterator(); while (it.hasNext()) { chatKey = it.next(); if(curChatKey.equals(chatKey)) { saveChatCache(chatKey, chatCacheMap.get(chatKey)); continue; } history = chatCacheMap.get(chatKey).getInfoPoint(); lastChatTime = Long.valueOf(history.get("lastUpdateTime")); now = System.currentTimeMillis(); if (now - lastChatTime > ChatCacheController.TIME_OUT) { chatCache = chatCacheMap.get(chatKey); saveChatCache(chatKey, chatCache); System.out.println("移除" + chatKey); it.remove(); } } context.setAttribute("chatCache", chatCacheMap); } /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context) { historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); Map keyCacheMap = (Map) context.getAttribute("chatCache"); ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); chatCache.setInfoPoint(historyInfoPoint); chatCache.setGameEnv(gameEnv); context.setAttribute("chatCache", keyCacheMap); } public static synchronized boolean findChatCache(String chatKey, ServletContext context) throws Exception { ChatCache chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; Map infoPoints = new HashMap(); try { if (context.getAttribute("chatCache") != null) { if (((HashMap)context.getAttribute("chatCache")).get(chatKey) != null){ return true; } } File file = new File(String.format(ENV_PATH, chatKey)); if (file.exists()){ return true; } } catch(Exception e){ e.printStackTrace(); return false; } return false; } 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; } }