package com.qiwu.chatbotbackend.servlet; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; 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.sql.SQLException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL; @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) public class GameDesignServlet extends HttpServlet { String POST_URL = "http://localhost:1111/conditionProcess"; String KEYWORD_DIR = "keywords.txt"; //分组及其相应的id,id初始化为0, 新建分组成功后id会更新。 HashMap categoryMap = new HashMap(){ { put("地图", 0); put("剧情", 0); put("物品", 0); put("NPC", 0); put("全局变量", 0); } }; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS"); StringBuffer timeUsedDetect = new StringBuffer(); LocalDateTime ldt = LocalDateTime.now(); String now = ldt.format(dtf); timeUsedDetect.append("接收请求的时间:").append(now); //所有需要修改的词性 StringBuffer POS = new StringBuffer(); //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等,格式为: "conditionName_tail/head":"keywords" HashMap> additionalKeywords = new HashMap>(); //预先定义好的所有condition相关的关键词,格式为 "conditionName_标签":"keywords" Map keywordMap = new HashMap(); //特定的relation的三元组不会被添加到relationKeywords HashSet exceptRelation = new HashSet(); Integer botId, projectId, dataId, returnStatus = 1; String botAccount = null, userName, botName, moduleName2, returnMessage = "Success"; ServletContext context = this.getServletContext(); JSONObject json = null, root = null; Boolean flag; SqlHelper helper = null; List idList = new ArrayList<>(); ElementConstructor constructor = new ElementConstructor(); try { helper = new SqlHelper(); } catch (SQLException e) { e.printStackTrace(); } //读取并解析json数据 String jsonStr = SimpleUtil.readJSONString(request); if (jsonStr != null && !jsonStr.equals("")) { JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); dataId = (Integer) receiveParaneters.get("id"); JSONObject gameElements = helper.queryGameElementsByBotId(dataId); gameElements.put("auth", request.getHeader("authorization")); //System.out.println(gameElements.toJSONString()); botId = (Integer)gameElements.get("botId"); botAccount = (String) gameElements.get("botAccount"); userName = (String)gameElements.get("userName"); botName = (String)gameElements.get("botName"); //假设重建用户信息 if (context.getAttribute(botAccount) == null) { UserInfoController.userConfigInit(botAccount, context); } UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); //清空之前生成的配置条目 try { flag = botInit(botId, botAccount, userinfo, helper); } catch (SQLException e) { System.out.println("清空旧数据失败"); e.printStackTrace(); } StringBuffer mergedConfigText = new StringBuffer(); int skipCount = 0; //从文件中读取condition相关的关键词 System.out.println("----------------------read-------------------------/r------------------------------------------------------"); readKeywords(keywordMap, KEYWORD_DIR); ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n,预处理之后:").append(now); String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; for(String moduleName: moduleList){ switch (moduleName) { case "map": moduleName2 = "地图"; constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "plots": moduleName2 = "剧情"; constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); break; case "goods": moduleName2 = "物品"; constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "globalVariable": moduleName2 = "全局变量"; constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "npc": moduleName2 = "NPC"; constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; default: continue; } if (constructor.getOperationStatus() == 1) { System.out.println(moduleName); //先清空再插入 idList.clear(); helper.batchInsertVariableByBotId(botId, constructor); List jsonList = new ArrayList(); for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ json = configTermText.toJson(constructor.getConditionDescription()); constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); jsonList.add(json); } helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); constructor.postProcessing(idList, categoryMap.get(moduleName2)); constructor.generateConfigText(idList); mergedConfigText.append(constructor.getConfigText()); }else { returnStatus = 0; returnMessage = constructor.getMessage(); break; } ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); } if(returnStatus == 1) { ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n发送post请求预处理:").append(now); StringReader sr = new StringReader(mergedConfigText.toString()); BufferedReader br = new BufferedReader(sr); //System.out.println(mergedConfigText.toString()); UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(botAccount, userinfo); UserInfoController.writeConfigText(botAccount, userinfo); ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n发送post请求前:").append(now); String postResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS); ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n发送post请求后:").append(now); if(!postResult.equals("success")){ returnStatus = 0; returnMessage = postResult; } } helper.destroy(); }else { returnStatus = 0; returnMessage = "请求解析失败"; } System.out.println(timeUsedDetect.toString()); JSONObject responseJSONObject = new JSONObject(); responseJSONObject.put("status", returnStatus); responseJSONObject.put("message", returnMessage); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); System.out.println("xx:" + responseJSONObject.toJSONString()); PrintWriter out = response.getWriter(); out.append(responseJSONObject.toString()); out.flush(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); out.write("ssss".getBytes()); out.flush(); } 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 = ChatCacheController.deleteChatCache(helper, botAccount); return deleteConfigFlag && deleteVariableFlag; } public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS){ String startCondition, POS2 = ""; String botName = (String)gameElements.get("botName"); JSONObject returnMessage = null; JSONObject actionPostData = new JSONObject(); //System.out.println("root"+ root.toJSONString()); startCondition = (String)root.get("conditionName"); actionPostData.put("startCondition", "start_options"); actionPostData.put("botName_yhm", (String)gameElements.get("botName")); actionPostData.put("botName", botName); actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("type", "game_plot_init"); actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始"); actionPostData.put("relationKeywords", additionalKeywords); actionPostData.put("auth", gameElements.get("auth")); if (gameElements.containsKey("POS")) POS2 = (String)gameElements.get("POS"); actionPostData.put("POS", POS.toString() + POS2); System.out.println(actionPostData.toJSONString()); userInfo.extraInfo.put("activeAction", startCondition); try { returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if(returnMessage.getInteger("post_status") == 1 && returnMessage.getInteger("status") != null && returnMessage.getInteger("status") == 1 ) { return "success"; }else { System.out.println(returnMessage.get("parameter")); System.out.println("语义关系生成失败"); return (String)returnMessage.get("parameter"); } } //从配置文件中读取生成状态表所需要的关键词 public void readKeywords(Map keywordsMap, String path){ File file = new File(path); String line, elem[]; if(file.exists()){ FileReader reader = null; try { reader = new FileReader(file); BufferedReader br = new BufferedReader(reader); while ((line = br.readLine()) != null) { if(!line.equals("") && !line.startsWith("#")) { elem = line.split("\\|", 3); //查看意图是否已经存在相关的condition,如果已经存在就append,如果不存在就初始化 if (!elem[1].equals("pattern")) { if (keywordsMap.get(elem[0]) == null) { keywordsMap.put(elem[0], new StringBuffer(elem[1])); } else { keywordsMap.get(elem[0]).append(",").append(elem[1]); } } //根据意图和condition名字添加关键字 keywordsMap.put(elem[0] + "_" + elem[1], new StringBuffer(elem[2])); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }