Commit 115271fa by 赵国君

过滤表单字段

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