package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.entity.Action; 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.IOException; import java.text.ParseException; import java.util.*; public class ActionMatcher { Map activatedMap = new HashMap(); static String POST_DATA_ERROR = "post数据有误"; static String POST_ERROR = "数据post时出错了"; static String API_ERROR = "api处理过程中出错了"; public LogWriter logWriter = null; public UserInfo userinfo = null; public ServletContext context = null; public GameEnv gameEnv = null; public Map curInfoPoint = null; public Map historyInfoPoint = null; public WorldController worldController = null; BasicBotUtil botUtil = null; public ActionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { this.curInfoPoint = curInfoPoint; this.historyInfoPoint = historyInfoPoint; this.logWriter = logWriter; this.userinfo = userinfo; this.context = context; this.gameEnv = gameEnv; this.worldController = new WorldController(logWriter, userinfo); this.botUtil = botUtil; } public ActionMatcher(){ } /** * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch * * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @return bestMatch 状态表中满足条件最多的一条 */ public Action getBestMatch(HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { Integer configId = 0; List actionList = null; Action bestMatch = new Action(-1), iterCon; Iterator it = curInfoPoint.keySet().iterator(); Queue activatedQueue = new LinkedList(); Queue activatedAction = new LinkedList(); while (it.hasNext()) { String conditionName = it.next(); String keywords = curInfoPoint.get(conditionName); String keyword = null; Boolean activateFlag = false; Boolean replaceFlag = false; Boolean satisfyFlag = false; if (keywords != null && !keywords.equals("")) keyword = keywords; if (keyword != null && conditionTable.get(conditionName) != null) { actionList = conditionTable.get(conditionName); for (Action action : actionList) { activateFlag = false; satisfyFlag = false; replaceFlag = false; if (action.status.equals("waiting")){ //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { activateFlag = true; } if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)){ replaceFlag = true; } //没有激活,优先级不够高,直接跳过 if(!activateFlag && !replaceFlag){ logWriter.record("-----------------------------------优先级不足其没有激活,跳过", 0); continue; } if(conditionSatisfy(action)){ satisfyFlag = true; } if(satisfyFlag){ if(activateFlag){ activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); } if(replaceFlag){ bestMatch = action; logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); logWriter.writeln(); } } // if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) // || action.featureMap.get("activate") != null){ // if(conditionSatisfy(action)){ // if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { // //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 // activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); // } // if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { // bestMatch = action; // logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); // logWriter.writeln(); // } // // // } // // }else { // logWriter.record("-----------------------------------优先级不足,跳过", 0); // logWriter.record(userinfo.id2config.get(action.id), 1); // } // } // // // // // // if (action.status.equals("waiting")){ // if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) // || action.featureMap.get("activate") != null){ // if(conditionSatisfy(action)){ // if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { // //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 // activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); // } // if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { // bestMatch = action; // logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); // logWriter.writeln(); // } // // // } // // }else { // logWriter.record("-----------------------------------优先级不足,跳过", 0); // logWriter.record(userinfo.id2config.get(action.id), 1); // } } } } } logWriter.record("----------------------匹配结束", 2); bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); return bestMatch; } /** * 在激活列表中选择满足匹配且优先级最高的一条配置条目 * @param bestMatch * @param activatedQueue * @param context * @return * @throws IOException */ public Action activatedQueueMatching(Action bestMatch, Queue activatedQueue, ServletContext context) throws IOException { Action action; Boolean activateFlag = false; Boolean replaceFlag = false; Boolean satisfyFlag = false; Boolean parentFlag = false; //待激活配置条目被激活后的匹配 while (!activatedQueue.isEmpty()) { activateFlag = false; replaceFlag = false; satisfyFlag = false; parentFlag = false; action = activatedQueue.remove(); activatedMap.remove(action.id); if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)) replaceFlag = true; if(action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) activateFlag = true; if(bestMatch.nextStep.contains(String.valueOf(action.id))) //现在的condition是被bestMatch这个condition激活的 parentFlag = true; //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 if(!activateFlag && !replaceFlag && !parentFlag) { logWriter.record("-----------------------------------优先级不足,跳过", 0); logWriter.record(userinfo.id2config.get(action.id), 1); continue; } if(conditionSatisfy(action)){ if(activateFlag) { activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); } if(replaceFlag){ bestMatch = action; logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); logWriter.writeln(); } } // //当前condition的辅助优先级高于bestMatch、或者优先级已知添加数量更多、或者 // if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority) // || action.featureMap.get("activate") != null // || bestMatch.nextStep.contains(String.valueOf(action.id)) || (!action.configName.equals("") && bestMatch.nextStep.contains(action.configName.substring(0,3)))){ // //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 // if(conditionSatisfy(action)){ // // //有激活配置文件,但是没有post提交表单,则激活,如果有post就放到提交表单之后激活(postActivate) // if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { // activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); // } // // bestMatch = action; // logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); // logWriter.writeln(); // // } // // } else { // logWriter.record("-----------------------------------优先级不足,跳过", 0); // logWriter.record(userinfo.id2config.get(action.id), 1); // } } return bestMatch; } /** * 根据当前信息点,历史信息点,判断是否满足该action的条件,match关键字指引擎识别的关键字包含在action相应的关键词列表中,这里可以根据特征添加其他操作。 * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 * * @param action 配置文件(状态表)的一行 * @return 满足条件就为True, 不满足就为False */ public boolean conditionSatisfy(Action action) { boolean flag = true; String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; HashSet keywordSet = null; logWriter.record("-----------------------------------检索到配置条目", 0); logWriter.record(userinfo.id2config.get(action.id), 1); if (action.featureMap.containsKey("match")) { Iterator it = action.currentPremise.keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); actionName = comparePair[0]; cmpType = comparePair[1]; keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); if (keyword == null) { flag = false; if(flag == false){ logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } break; } keywordSet = action.currentPremise.get(premiseStr); if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; if(flag == false){ logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } } it = action.historyPremise.keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); cmpType = comparePair[1]; actionName = comparePair[0]; //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.featureMap.containsKey("includeCurInfo"), actionName); if (keyword == null) { flag = false; if(flag == false){ logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } break; } keywordSet = action.historyPremise.get(premiseStr); if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; if(flag == false){ logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); } } } return flag; } /** * 单个条件的匹配,判断是否满足条件 * 比较类型分为 match、number、time、variable, * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 * * @param keyword * @param cmpType 比较类型 * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 * @return 返回匹配或者不匹配 */ public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { boolean flag = true; String operator = ""; try { String splitPair[] = cmpType.split("-", 2); if (splitPair.length > 1) { operator = splitPair[1]; cmpType = splitPair[0]; } if (cmpType.equals("match")) { if(operator.equals("Keyword") || operator.equals("Include")) { if (!keywordSet.contains(keyword)) { flag = false; } if (flag == false && keyword.contains(":")) { String ks[] = keyword.split(":"); for (String k : ks) { if (keywordSet.contains(k)) flag = true; } } } else if(operator.equals("Exclude")) { if(keyword.contains(":")){ String ks[] = keyword.split(":", 2); if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) flag = false; }else { if (keywordSet.contains(keyword)) { flag = false; } } }else if(operator.equals("Have")){ for(String key:keywordSet){ if(key.equals("")) continue; if(!keyword.contains(key)){ flag = false; break; } } }else{ flag = false; } } else if (cmpType.equals("number") && !keyword.equals("")) { int candidateA = 0; int candidateB = 0; if (keyword.contains(":")) { String ks[] = keyword.split(":"); for (String k : ks) { if(StringUtils.isNumeric(k)) keyword = k; } } if(!StringUtils.isNumeric(keyword)){ return false; } candidateA = Integer.parseInt(keyword); for (String k : keywordSet) { if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } } if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; else if (operator.equals("Smaller")) flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; else if (operator.equals("NotEqual")) flag = candidateA != candidateB; } else if (cmpType.equals("time")) { long candidateA, candidateB = 0; if (keyword.contains(":")) { String ks[] = keyword.split(":"); for (String k : ks) { if(k.contains("年") && k.contains("月") && k.contains("日")) keyword = k; } } candidateA = MyFunc.transferToMillisecond(keyword); for (String k : keywordSet) { if (!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } if (operator.equals("Early")) flag = candidateA < candidateB; else if (operator.equals("Later")) flag = candidateA > candidateB; } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { String conditionName2 = "", conditionValue2 = ""; for (String k : keywordSet) { if (!k.equals("")) { conditionName2 = k; break; } } if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); }else { flag = false; } if(flag ){ /** * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true */ flag = false; if(operator.equals("Equal")){ flag = keyword.equals(conditionValue2); }else if(keyword.contains(":") && conditionValue2.contains(":")){ String relPair1[] = keyword.split(":", 2), keyword1 = ""; String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; boolean similar = false; if(relPair1[0].equals(relPair2[0])){ similar = true; keyword1 = relPair1[1]; keyword2 = relPair2[1]; }else if (relPair1[1].equals(relPair2[1])){ similar = true; keyword1 = relPair1[0]; keyword2 = relPair2[0]; } if(similar){ if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ int candidateA = Integer.parseInt(keyword1); int candidateB = Integer.parseInt(keyword2); if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; else if (operator.equals("Smaller")) flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; else if (operator.equals("NotEqual")) flag = candidateA != candidateB; } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ long candidateA = MyFunc.transferToMillisecond(keyword1); long candidateB = MyFunc.transferToMillisecond(keyword2); if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; else if (operator.equals("Smaller")) flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; else if (operator.equals("NotEqual")) flag = candidateA != candidateB; // 操作符为等于时可以比较两个字符串是否相同 } } }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ int candidateA = Integer.parseInt(keyword); int candidateB = Integer.parseInt(conditionValue2); if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; else if (operator.equals("Smaller")) flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; else if (operator.equals("NotEqual")) flag = candidateA != candidateB; } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ long candidateA = MyFunc.transferToMillisecond(keyword); long candidateB = MyFunc.transferToMillisecond(conditionValue2); if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; else if (operator.equals("Smaller")) flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; else if (operator.equals("NotEqual")) flag = candidateA != candidateB; // 操作符为等于时可以比较两个字符串是否相同 } } } } else if (cmpType.equals("any")) { if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 flag = false; } else { flag = false; } } catch (IndexOutOfBoundsException e) { System.out.println("配置文件格式有误"); flag = false; e.printStackTrace(); } catch (ParseException e) { System.out.println("时间解析错误"); e.printStackTrace(); flag = false; } catch (Exception e) { System.out.println("操作符有误"); e.printStackTrace(); flag = false; } return flag; } /** * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 * * @return 返回给引擎的数据 */ public Solution getSolution(Action ansAction, ServletContext context, UserInfo userinfo) throws IOException, ParseException { Iterator it = curInfoPoint.keySet().iterator(); String actionName, reply, variable; Solution ans = new Solution(0, "", ""); //如果一条配置文件有多个答案,则随 // 机选择一个答案 //System.out.println(ans.getAnswer()); //post关键字 if (ansAction.featureMap.containsKey("post")) { logWriter.record("---------------------进入表单结束",1); ans = postToServer(ans, ansAction); logWriter.record("---------------------提交表单结束",1); //nextNext关键字 } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //updateKnowledge关键字 if (ansAction.featureMap.containsKey("updateKnowledge")) { logWriter.record("---------------------进入更新答案【略】",1); updateKnowledge(ansAction); logWriter.record("---------------------更新答案结束",1); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- if (ansAction.featureMap.containsKey("newNext")) { logWriter.record("---------------------进入判断下一步【略】",1); ans = findNewNext(ans, ansAction); logWriter.record("---------------------判断下一步结束",1); //上一步 } else if (ansAction.featureMap.containsKey("return-1")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) ans.setNext("nextStep=" + activeList[activeList.length - 1]); else { ans.setNext("nextStep=" + activeList[activeList.length - 2]); } //停留 } else if (ansAction.featureMap.containsKey("return-0")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if(activeList.length > 0) ans.setNext("nextStep=" + activeList[activeList.length - 1]); else ans.setNext("nextStep= "); //激活 } else if (ansAction.featureMap.containsKey("activate") || ansAction.featureMap.containsKey("activate:after")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) ans.setNext("nextStep=" + activeList[activeList.length - 1]); else { ans.setNext("nextStep=" + activeList[activeList.length - 2]); } } try { reply = MyFunc.randStr(ansAction.answer); reply = botUtil.varSlotReplace(reply); //reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansAction, logWriter); ans.setAnswer(reply); botUtil.extraOperation(ansAction, ans); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- if (ans.getNext().equals("")) { ans.setNext("nextStep=" + ansAction.nextStep); } } catch (Exception e) { e.printStackTrace(); } return ans; } /** * 请求处理结束后台将当前信息的信息点转移到已知信息 * @param ans * @param context * @param debugFlag */ public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { //将当前信息点更新至历史信息点 Iterator it = curInfoPoint.keySet().iterator(); String actionName, lastReply; String next = ans.getNext().split("=", 2)[1]; //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx historyInfoPoint.put("currentAction", next); historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); HashSet skipSet = new HashSet() { { add("chat_key"); add("action_name"); add("bot_name"); add("emptySet"); add("query_text"); } }; // if (debugFlag) // lastReply = ans.getAnswer().split(")")[2]; // else // lastReply = ans.getAnswer(); // historyInfoPoint.put("lastReply", lastReply); try { String keyword1, keyword2; while (it.hasNext()) { actionName = it.next(); if(skipSet.contains(actionName)) continue; keyword1 = curInfoPoint.get(actionName); keyword2 = historyInfoPoint.get(actionName); if (keyword2 == null) { historyInfoPoint.put(actionName, keyword1); }else if (historyInfoPoint.get(actionName).equals("do_reset")){ historyInfoPoint.put(actionName, ""); }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); } historyInfoPoint.put("临时变量reply", ""); historyInfoPoint.put("临时变量condition", ""); historyInfoPoint.put("临时变量3", ""); //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); } catch (Exception e) { e.printStackTrace(); } } /** * 如果接收到的表单中包含debug_mode这个参数, 后台会将存储的变量值返回给前段,用于调试 * * @param ans 最终返回的数据 * @param context */ public void appendDebugInfo(Solution ans, ServletContext context) { Iterator it = null; String key, values, value; HashSet skipSet = new HashSet() { { add("activeList"); add("currentAction"); add("lastUpdateTime"); add("bot_name"); add("action_name"); add("lastReply"); add("unknownTextList"); add("finalUnknownText"); add("unknownText"); add("randKey"); add("userKey"); } }; it = curInfoPoint.keySet().iterator(); String debugInfo = ""; debugInfo += "(识别:"; while (it.hasNext()) { key = it.next(); values = curInfoPoint.get(key); if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { if (key.endsWith("_backup")) { key = key.substring(0, key.length() - 7); } debugInfo += (" " + key + ":\'" + values + "\' "); } } debugInfo += ")"; if(curInfoPoint.containsKey("debug_mode")) { debugInfo = debugInfo.replace("-)", ""); debugInfo += "(已知:"; it = historyInfoPoint.keySet().iterator(); while (it.hasNext()) { key = it.next(); value = historyInfoPoint.get(key); if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition")) debugInfo += (" " + key + ":\'" + value + "\' "); } } ans.setAnswer(debugInfo + ")" + ans.getAnswer()); } /** * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) * * @param ans 返回给用户的数据 * @param ansAction 满足条件最多的condition(配置文件的某一行) */ public Solution postToServer(Solution ans, Action ansAction) throws IOException { String url = null, elem[], subElem[], key,keys, postType = "all"; Map infoMap = new HashMap(); List pairList = new ArrayList(); Iterator k_iter = null; FormsPoster poster = new FormsPoster(logWriter); HashSet skipSet = new HashSet() { { add("activeList"); add("currentAction"); add("lastUpdateTime"); add("lastReply"); } }; elem = ansAction.featureMap.get("post").split("\\|"); url = elem[0]; postType = elem[1]; if(postType.equals("all")){ poster.postAll(curInfoPoint, historyInfoPoint, ans, url); }else if(postType.equals("term")){ poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); }else if(postType.equals("gameQA")){ poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); } return ans; } public Solution findNewNext(Solution ans, Action ansAction) { String nextOptions[] = ansAction.nextStep.split(","); String conditionName, premises[], cpPair[]; boolean flag = true; String activeList = historyInfoPoint.get("activeList"); for (String option : nextOptions) { flag = true; cpPair = option.split(":"); conditionName = cpPair[0]; if (cpPair.length == 1) { ans.setNext("nextStep=" + conditionName); break; } premises = cpPair[1].split("-"); for (String premise : premises) { if (premise.equals("known")) { //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); //只有前两者都为假时,conditionExist才为真 boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); if (conditionExist) flag = false; } if (premise.equals("active")) { boolean isActive = activeList.contains(conditionName); if (isActive) flag = false; } } if (flag) { ans.setNext("nextStep=" + conditionName); break; } } return ans; } public void updateKnowledge(Action action) throws ParseException { String keyword, variableName, updateValue, returnStr = "1"; Iterator iit = action.updateKnowledge.keySet().iterator(); while (iit.hasNext()) { variableName = iit.next(); keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); updateValue = botUtil.knowledgeProcess(variableName, action.updateKnowledge.get(variableName)); try { //做数字加法 if (updateValue.startsWith("+")) { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { long time = MyFunc.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = String.valueOf(number + offset); } //做数字减法 } else if (updateValue.startsWith("-")) { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { long time = MyFunc.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = String.valueOf(number - offset); } //做字符串累加 } else if (updateValue.startsWith("str+")) { if (keyword == null || keyword.equals("")) keyword = ""; updateValue = keyword + updateValue.substring(4); //做字符串删除 } else if (updateValue.startsWith("str-")) { if (keyword == null || keyword.equals("")) keyword = ""; updateValue = keyword.replace(updateValue.substring(4), ""); } else if (updateValue.startsWith("int+=")) { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { long time = MyFunc.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(5)); updateValue = String.valueOf(number + offset); } //做数字减法 } else if (updateValue.startsWith("int-=")) { if (keyword == null || keyword.equals("")) keyword = "0"; if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { long time = MyFunc.transferToMillisecond(keyword); int offset = Integer.parseInt(updateValue.substring(5)); updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); } else if (StringUtils.isNumeric(keyword)) { int number = Integer.parseInt(keyword); int offset = Integer.parseInt(updateValue.substring(1)); updateValue = String.valueOf(number - offset); } //做字符串累加 } else if (updateValue.startsWith("str+=")) { if (keyword == null || keyword.equals("")) keyword = ""; updateValue = keyword + updateValue.substring(5); //做字符串删除 } else if (updateValue.startsWith("str-=")) { if (keyword == null || keyword.equals("")) keyword = ""; updateValue = keyword.replace(updateValue.substring(5), ""); //变量提取 } else if (updateValue.startsWith("var=")) { String conditionName = updateValue.substring(5, updateValue.length() - 3); if (updateValue.endsWith("-1}")) { if (curInfoPoint.get(conditionName) != null) { updateValue = curInfoPoint.get(conditionName); } else { updateValue = ""; } } else if (updateValue.endsWith("-2}")) { if (historyInfoPoint.get(conditionName) != null) { updateValue = historyInfoPoint.get(conditionName); } else { updateValue = ""; } //提取配置条目的下一步 } else if (updateValue.endsWith("nextStep-3}")) { updateValue = action.nextStep; //提取配置条目的回答 } else if (updateValue.endsWith("reply-3}")) { updateValue = MyFunc.randStr(action.answer); } //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue if (variableName.startsWith("process-nextStep")) { action.nextStep = updateValue; updateValue = ""; } } } catch (Exception e) { e.printStackTrace(); continue; } if(updateValue.equals("")) { curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 curInfoPoint.put(variableName, ""); } botUtil.putKeyword(variableName, updateValue); } } public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority, String activateList, ServletContext context) throws IOException { UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); String configStr = ""; Integer configId; Action newAction, originAction; List originActionList = new ArrayList(); for (String configIdStr : activateList.split(",")) { logWriter.record("------激活-------" + configIdStr + "-------
", 0); try { if (StringUtils.isNumeric(configIdStr)) { configId = Integer.parseInt(configIdStr); configStr = userinfo.id2config.get(configId); originAction = userinfo.id2condition.get(configId); originActionList.add(originAction); } else { if (configIdStr.endsWith("*")) { String prefix = configIdStr.substring(0, configIdStr.length()-1); for(String name:userinfo.name2condition.keySet()){ if (name.startsWith(prefix)){ originActionList.add(userinfo.name2condition.get(name)); } } } else { originActionList.add(userinfo.name2condition.get(configIdStr)); } } } catch (Exception e) { e.printStackTrace(); logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); } } for (Action action : originActionList){ originAction = action; try { configId = originAction.id; newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); //action = ActionMatcher.buildCondition(action, configStr); //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 if (activatedMap.containsKey(configId)) { if(newAction.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; if(newAction.activePriority > activatedMap.get(configId).activePriority) activatedMap.get(configId).activePriority = newAction.activePriority; } else if (!activatedMap.containsKey(configId)) { activatedMap.put(configId, newAction); activatedQueue.add(newAction); } }catch (Exception e) { e.printStackTrace(); logWriter.record("----------激活失败:" + action.configName, 5); } } } /** * 一个提交表单后在激活的操作 * @param ansAction * @param context * @param userinfo * @return * @throws IOException * @throws ParseException */ public Solution postActivate(Action ansAction, Solution oldBestMatch, ServletContext context, UserInfo userinfo) throws IOException, ParseException { Queue activatedQueue = new LinkedList(); Solution bestMatch = oldBestMatch; Action newAction1 = ansAction, newAction2; // activateCondition(activatedQueue, userinfo.botAccount, ansAction.priority, ansAction.auxiliaryPriority, ansAction.nextStep, context); // ansAction = activatedQueueMatching(ansAction, activatedQueue, context); // // bestMatch = getSolution(ansAction, context, userinfo); while ((newAction1.featureMap.containsKey("activate") && newAction1.featureMap.containsKey("post")) || newAction1.featureMap.containsKey("activate:after")) { //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 activateCondition(activatedQueue, userinfo.botAccount, newAction1.priority, newAction1.auxiliaryPriority, newAction1.nextStep, context); newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); if(newAction1 == newAction2) break; bestMatch = getSolution(newAction2, context, userinfo); newAction1 = newAction2; } return bestMatch; } }