package com.qiwu.chatbotbackend.servlet; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.ChatCache; 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; 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.IOException; import java.io.OutputStream; import java.sql.SQLException; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2; @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) public class GetAnswerServlet extends HttpServlet { /** * GetAnswerServlet就是处理post请求并返回答案的入口 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Map requestParamters = new HashMap<>(request.getParameterMap()); Map receiveParamters = new HashMap<>(); Set> entrySet = requestParamters.entrySet(); String tmpStr; for(Map.Entry entry : entrySet) { if(entry.getValue().length > 0) { tmpStr = entry.getValue()[0]; if(tmpStr == null || tmpStr.equals("")) continue; tmpStr = tmpStr.replace("qiwu", "我"); receiveParamters.put(entry.getKey(), tmpStr); } } String botName = receiveParamters.get("bot_name"); /* EngineUtils engineDBConn = null; try { engineDBConn = new EngineUtils(); String nickname = engineDBConn.queryBotNickNameByName(botName); } catch (SQLException e1) { e1.printStackTrace(); } finally { engineDBConn.destroy(); } Set> entrySet2 = receiveParamters.entrySet(); for(Entry entry : entrySet2) { String value = entry.getValue(); if(value.indexOf("")) { } } */ Map curInfoPoint = new HashMap(); Solution bestMatch = null; BasicBotUtil botUtil = null; Action ansAction = null; boolean debugFlag = false; String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; OutputStream out = response.getOutputStream(); ServletContext context = this.getServletContext(); //如果有client_id,会用@分隔 chatKey = receiveParamters.get("chat_key"); String chatKeys[] = receiveParamters.get("chat_key").split(COMBINE_PUNC2); if(chatKeys.length == 1){ userKey = chatKeys[0]; randKey = chatKeys[0]; }else{ userKey = chatKeys[0]; randKey = chatKeys[1]; } receiveParamters.put("userKey", userKey); receiveParamters.put("randKey", randKey); try { LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); UserInfo userinfo = null; UserInfoController uiController = new UserInfoController(); logWriter.record("query bot config", 0); userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); if (userinfo != null) { //获得用户历史信息 ChatCache chatCache = null; Boolean loadCacheStatus = Boolean.valueOf(false); if (userinfo.varInitialMap.get("botType") != null) botType = userinfo.varInitialMap.get("botType"); logWriter.record("get chat cache start", 0); chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); logWriter.record("get chat cache complete", 0); if (chatCache == null) { throw (new Exception("chatCache初始化失败")); } /** * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 */ switch (botType) { case "game": WorldController worldController = new WorldController(logWriter, userinfo); botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController); break; default: botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); break; } logWriter.record("form preprocessing", 0); //针对不同游戏类型对信息点做预处理 debugFlag = botUtil.preprocessing(receiveParamters, context); logWriter.record("action match start", 0); //信息点预处理 ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil); logWriter.record("action match complete", 0); /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/ ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); if (state.equals("") && ansAction.getPriority() == -1) state = INTENT_NOT_UNDERSTAND; if (state.equals("")) { try { bestMatch = matcher.getSolution(ansAction, context, userinfo); if (!botUtil.getChatCache().getReload()) { //读档成功不应该再激活 //if(matcher.) if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); } } else { //跳过 botUtil.getChatCache().setReload(false); //清楚标识 } } catch (ParseException e) { e.printStackTrace(); } } else { bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction")); } //针对不同bot类型做后处理 botUtil.postprocessing(chatKey, context, bestMatch); botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); if (debugFlag) { matcher.appendDebugInfo(bestMatch, context); } matcher.infoTransfer(bestMatch, context, debugFlag); logWriter.record("update chat cache start", 0); ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); //清理超时的用户数据 if (context.getAttribute("cacheUpdateTime") == null) context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > CHATCACHE_TIME_OUT) { ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); } logWriter.record("update chat cache complete", 0); ansJ = SimpleUtil.toJson(bestMatch); } else { ansJ = CONFIG_FILE_NOT_FOUND; } out.write(ansJ.getBytes()); logWriter.writeln(); logWriter.writeln(); logWriter.record("-----------------------------------------对话处理结束", 0); logWriter.writeln(); logWriter.writeln(); logWriter.close(); }catch (Exception e){ JSONObject errorData = new JSONObject(){ { put("solution", PROGRAM_ERROR); put("status", 1); } }; e.printStackTrace(); out.write(errorData.toJSONString().getBytes()); } System.out.println(ansJ); out.flush(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("do get method"); } }