package processing; import entity.AnswerNextStep; import entity.Condition; import entity.UserInfo; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.servlet.ServletContext; import java.io.*; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class ProcessQuestion { static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; /* public void updateDB(QuestionKeyWord qkw) throws SQLException { SqlHelper helper = new SqlHelper(); String result = helper.queryActionByKey(qkw.getChatKey()); if(result != "empty") //待添加 //qkw.setActionName(result+"+"+qkw.getActionName()); helper.updateAction(qkw); else helper.insertAction(qkw); helper.destroy(); } */ /** * 根据本地配置文件生成用户信息 */ public static void configInit(ServletContext context) throws IOException { String line; File dir = new File(CONFIG_DIR); if(!dir.exists()) dir.mkdir(); for(File configFile: dir.listFiles()) { FileReader reader = new FileReader(configFile); BufferedReader br = new BufferedReader(reader); String fileName = configFile.getName(); UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); try { userinfo = buildUserInfo(br, userinfo); context.setAttribute(userinfo.userName,userinfo); }catch(Exception e){ System.out.println(userinfo.userName + ".txt 有误"); e.printStackTrace(); } reader.close(); br.close(); } } public static void userConfigInit(String userName, ServletContext context) throws IOException { String line; File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); if(!userFile.exists()){ BufferedReader br = new BufferedReader(new StringReader("")); UserInfo userinfo = new UserInfo(userName); try { userinfo = buildUserInfo(br, userinfo); context.setAttribute(userinfo.userName,userinfo); }catch(Exception e){ System.out.println(userinfo.userName + "-post数据有误"); e.printStackTrace(); } }else { FileReader reader = new FileReader(userFile); BufferedReader br = new BufferedReader(reader); UserInfo userinfo = new UserInfo(userName); try { userinfo = buildUserInfo(br, userinfo); context.setAttribute(userinfo.userName,userinfo); }catch(Exception e){ System.out.println(userinfo.userName + ".txt 有误"); e.printStackTrace(); } reader.close(); br.close(); } } public static Condition buildCondition(Condition condition,String line){ String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[],firstCnditionName; line = line.split("---")[0]; element = line.replace("\n","").split("\\|=\\>\\|"); premises = element[0].split("\\|"); //System.out.println("element[0]:" + element[0]); feature = premises[2]; cur_premises = premises[0].split(","); history_premises = premises[1].split(","); next = element[1].split("\\|"); if(next.length < 4) return condition; condition.answer = next[0].split("~"); //condition.nextStep = next[1]; //第二处 condition.nextStep = next[1].split("=")[1]; condition.id = Integer.parseInt(next[3].split("=")[1]); condition.status = next[2].split("=")[1]; condition.feature = feature; ProcessQuestion.insertPremise(condition.currentPremise,cur_premises); ProcessQuestion.insertPremise(condition.historyPremise,history_premises); //满足条件越多,优先级越大 condition.priority = condition.historyPremise.size()+condition.currentPremise.size(); condition.activePriority = condition.priority; /* for(String premise:cur_premises){ pair = premise.split("="); condition.indexName.add(pair[0]); } */ firstCnditionName = cur_premises[0]; if(firstCnditionName.equals(" ")) condition.indexName = "emptySet"; else condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; return condition; } /** * 逐行读取用户配置文件,并保存在userinfo.conditionTable中 */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException { String line,infoName,extraElements[]; HashMap> conditionTable = new HashMap>(); List conditionList = null; while ((line = br.readLine()) != null) { if (line.trim().equals("")) continue; line = line.replace("\n",""); //在用户信息中添加额外信息,如设为active的action if(line.indexOf("-extraInfo-") != -1){ extraElements = line.split("\\|"); userinfo.extraInfo.put(extraElements[1],extraElements[2]); }else { Condition condition = new Condition(); condition = buildCondition(condition, line); conditionList = conditionTable.get(condition.indexName); if (conditionList == null) conditionList = new ArrayList(); conditionList.add(condition); conditionTable.put(condition.indexName, conditionList); if(condition.id != 0) userinfo.id2config.put(condition.id, line); } } userinfo.conditionTable = conditionTable; return userinfo; } /** * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) * @param premiseMap 前提条件哈希表 */ public static void insertPremise(HashMap> premiseMap,String[] premisesString){ String pair[]; HashSet keyWordSet = null; for(String premise:premisesString) { if (premise.equals("") || premise.equals(" ")) continue; pair = premise.split("="); keyWordSet = new HashSet(); for (String keyword : pair[1].split("\\+")) //为了处理条件不满足(为空)时的特殊情况, if(keyword.equals("null")) keyWordSet.add(""); else if(!keyword.equals("")) keyWordSet.add(keyword); premiseMap.put(pair[0],keyWordSet); } } /** * 原为通过用户chat_key从数据库中获得用户名 * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) * 如果context中没有,就重新加载本地配置文件(即初始化) * 初始化后还是没有就创建一个userinfo * ------------- * 修改后直接从request获得用户名,并从context根据用户名获得userinfo * * @param bot_name 用户名 * @return 用户信息 */ public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { /*根据数据库得到userName改为直接得到 SqlHelper helper = new SqlHelper(); String userName = helper.queryUsernameByKey(chat_key); */ String userName = bot_name; UserInfo userinfo = null; if(context.getAttribute(userName) == null){ ProcessQuestion.userConfigInit(userName, context); } if(context.getAttribute(userName) == null){ userinfo = new UserInfo(userName); userinfo.conditionTable = new HashMap>(); }else { userinfo = (UserInfo) context.getAttribute(userName); } //helper.destroy(); return userinfo; } public boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, StringBuffer curInfoRecord){ String return_str = ""; boolean debugFlag = false; //输出所有actionName的值 Iterator iit = curInfoPoint.keySet().iterator(); while(iit.hasNext()){ String k = iit.next(); // System.out.print(k+": "); if(k.equals("debug_mode")) debugFlag = true; String values[] = curInfoPoint.get(k); for(String v:values) { System.out.print(v + " "); } System.out.println(); if(values[0].equals(":")){ values[0] = ""; curInfoPoint.put(k, values); } } //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown iit = curInfoPoint.keySet().iterator(); boolean unknown_flag = true; while(iit.hasNext()){ String k = iit.next(); String values[] = curInfoPoint.get(k); if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name") || k.equals("emptySet")) continue; if(values != null && !values[0].equals("")) { unknown_flag = false; break; } } String currentAction = ""; if(historyInfoPoint.containsKey("currentAction")) currentAction = historyInfoPoint.get("currentAction"); else if(userinfo.extraInfo.containsKey("activeAction")) { currentAction = userinfo.extraInfo.get("activeAction"); historyInfoPoint.put("currentAction", currentAction); }else currentAction = ""; curInfoPoint.put("emptySet", new String[]{" ",}); if(historyInfoPoint.get("activeList") == null){ historyInfoPoint.put("activeList", currentAction); } if(unknown_flag && !currentAction.equals("")){ String i[] = {"unknown",}; curInfoPoint.put(currentAction,i); } return debugFlag; } /** * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @return bestMatch 状态表中满足条件最多的一条 */ public Condition getAnswer(Map curInfoPoint,Map historyInfoPoint,HashMap> conditionTable, ServletContext context) throws IOException { Integer configId = 0; List conditionList = null; Condition bestMatch = new Condition(-1); Iterator it = curInfoPoint.keySet().iterator(); HashMap extraActivatedConfig = new HashMap(); while (it.hasNext()) { String conditionName = it.next(); String[] keywords = curInfoPoint.get(conditionName); String keyword = null; if (keywords != null && !keywords[0].equals("")) keyword = keywords[0]; if (keyword != null && conditionTable.get(conditionName) != null) { conditionList = conditionTable.get(conditionName); for (Condition condition : conditionList) { if(condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ if(condition.feature.contains("activate")){ activateConfig(extraActivatedConfig, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); } else if(condition.priority > bestMatch.priority) bestMatch = condition; } } } } Iterator extraConfigIter = extraActivatedConfig.keySet().iterator(); Condition extraCondition = null; while(extraConfigIter.hasNext()){ configId = extraConfigIter.next(); extraCondition = extraActivatedConfig.get(configId); if(extraCondition.activePriority > bestMatch.activePriority && conditionSatisfy(curInfoPoint, historyInfoPoint, extraCondition)){ bestMatch = extraCondition; } } return bestMatch; } /** * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param condition 配置文件(状态表)的一行 * @return 满足条件就为True,不满足就为False */ public boolean conditionSatisfy(Map curInfoPoint,Map historyInfoPoint,Condition condition){ boolean flag = true; String actionName,keywords[],keyword,comparePair[],cmpType,premiseStr; HashSet keywordSet = null; if(condition.feature.contains("match")){ Iterator it = condition.currentPremise.keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); actionName = comparePair[0]; keywords = curInfoPoint.get(actionName); if (keywords == null || keywords[0].equals("")) { flag = false; break; } keyword = keywords[0]; if (comparePair.length == 1) cmpType = "match"; else cmpType = comparePair[1]; keywordSet = condition.currentPremise.get(premiseStr); if(!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; } it = condition.historyPremise.keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); actionName = comparePair[0]; keyword = historyInfoPoint.get(actionName); if(keyword == null || keyword.equals("")){ flag = false; break; } if (comparePair.length == 1) cmpType = "match"; else cmpType = comparePair[1]; keywordSet = condition.historyPremise.get(premiseStr); if(!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; } } return flag; } public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet){ boolean flag = true; try { if (cmpType.equals("match")) { 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 (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = Integer.parseInt(k); break; } } flag = candidateA > candidateB; } else if (cmpType.equals("numberBiggerOrEqual") && StringUtils.isNumeric(keyword)) { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = Integer.parseInt(k); break; } } flag = candidateA >= candidateB; } else if (cmpType.equals("numberSmaller") && StringUtils.isNumeric(keyword)) { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = Integer.parseInt(k); break; } } flag = candidateA < candidateB; } else if (cmpType.equals("numberSmallerOrEqual") && StringUtils.isNumeric(keyword)) { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = Integer.parseInt(k); break; } } flag = candidateA <= candidateB; } else if (cmpType.equals("timeEarly")){ long candidateA,candidateB = 0; candidateA = MyFunc.transferToMillisecond(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } flag = candidateA < candidateB; } else if (cmpType.equals("timeLater")){ long candidateA,candidateB = 0; candidateA = MyFunc.transferToMillisecond(keyword); for(String k: keywordSet){ if(!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } flag = candidateA > candidateB; } else if (cmpType.equals("any")){ if(keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 flag = false; }else { flag = false; } }catch (Exception e){ e.printStackTrace(); flag = false; } return flag; } /** * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @return 返回给引擎的数据 */ public AnswerNextStep getBestMatch(Condition ansCondition,Map curInfoPoint,Map historyInfoPoint,ServletContext context,UserInfo userinfo) throws IOException, ParseException { Iterator it = curInfoPoint.keySet().iterator(); String actionName; AnswerNextStep ans = new AnswerNextStep(0, "", ""); //如果一条配置文件有多个答案,则随机选择一个答案 int randNum = (int) (Math.random() * ansCondition.answer.length); ans.setAnswer(ansCondition.answer[randNum]); //System.out.println(ans.getAnswer()); System.out.println("feature="+ansCondition.feature); //post关键字 if(ansCondition.feature.contains("post")){ ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); //nextNext关键字 }else if(ansCondition.feature.contains("newNext")){ ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); }else if (ansCondition.feature.contains("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 (ansCondition.feature.contains("return-0")){ String activeList[] = historyInfoPoint.get("activeList").split("\\|"); ans.setNext("nextStep=" + activeList[activeList.length - 1]); } //updateKnowledge关键字 if (ansCondition.feature.contains("updateKnowledge")){ updateKnowledge(ansCondition, historyInfoPoint); } if(ans.getNext().equals("")){ ans.setNext("nextStep=" + ansCondition.nextStep); } try { /* String keyword1, keyword2; while (it.hasNext()) { actionName = it.next(); keyword1 = curInfoPoint.get(actionName)[0]; keyword2 = historyInfoPoint.get(actionName); if (keyword2 != null && !keyword2.equals(" ") && !keyword2.equals("")) { ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2)); } if (keyword1 != null) { ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里 } } */ it = historyInfoPoint.keySet().iterator(); String keyword1, keyword2; while (it.hasNext()) { actionName = it.next(); if(curInfoPoint.get(actionName) != null) { keyword1 = curInfoPoint.get(actionName)[0]; ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里 } keyword2 = historyInfoPoint.get(actionName); ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2)); } }catch(Exception e){ e.printStackTrace(); } return ans; } public void infoTransition(Map curInfoPoint,Map historyInfoPoint, AnswerNextStep ans, ServletContext context, boolean debugFlag){ //将当前信息点更新至历史信息点,并且替换答案中的相应变量,变量结构为{xxx-1}或者{xxx-2} Iterator it = curInfoPoint.keySet().iterator(); String actionName, lastReply; String next = ans.getNext().split("=")[1]; //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx historyInfoPoint.put("currentAction",next); historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); 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(); keyword1 = curInfoPoint.get(actionName)[0]; keyword2 = historyInfoPoint.get(actionName); if (keyword2 == null) historyInfoPoint.put(actionName, keyword1); else if (keyword2 != null && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); } /* // 根据hisInfoPoint中的key来更新历史信息,前提是在关键词单元不加simple_post it = historyInfoPoint.keySet().iterator(); String keyword1, keyword2; while (it.hasNext()) { actionName = it.next(); if(curInfoPoint.get(actionName) != null){ keyword1 = curInfoPoint.get(actionName)[0]; keyword2 = historyInfoPoint.get(actionName); if(! keyword2.equals("")){ historyInfoPoint.put(actionName, keyword1); } } } */ ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); }catch(Exception e){ e.printStackTrace(); } } public void appendDebugInfo(AnswerNextStep ans,Map curInfoPoint,Map historyInfoPoint,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("chat_key"); add("lastReply"); } }; it = curInfoPoint.keySet().iterator(); String debugInfo = ""; debugInfo += "(识别:"; while(it.hasNext()) { key = it.next(); values = curInfoPoint.get(key); if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key)) debugInfo += (" " + key + ":" + values[0] + " "); } 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)) debugInfo += (" " + key + ":" + value + " "); } ans.setAnswer( debugInfo + ")" + ans.getAnswer()); } /** * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) * @param ans 返回给用户的数据 * @param ansCondition 满足条件最多的condition(配置文件的某一行) */ public AnswerNextStep postToServer(AnswerNextStep ans, Condition ansCondition, Map curInfoPoint,Map historyInfoPoint) throws IOException { String url = null,features[] = ansCondition.feature.trim().split(","),elem[], subElem[], key, postType = "all"; Map infoMap = new HashMap(); List pairList = new ArrayList(); Iterator k_iter = null; for(String feature:features){ elem = feature.split("\\("); if(elem[0].contains("post")){ url = elem[elem.length-1]; url = url.substring(0,url.length()-1); subElem = elem[0].split("::"); if(subElem.length == 1) postType = "all"; else postType = subElem[1]; } } if(postType.equals("all")){ k_iter = curInfoPoint.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next(); if(curInfoPoint.get(key)[0] != "") //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); } k_iter = historyInfoPoint.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next(); if(historyInfoPoint.get(key) != "") //infoMap.put(key + "_his", historyInfoPoint.get(key)); pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); } }else if(postType.equals("term")){ k_iter = ansCondition.currentPremise.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next().split("::")[0]; if(curInfoPoint.get(key)[0] != "") pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); } k_iter = ansCondition.historyPremise.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next().split("::")[0]; if(historyInfoPoint.get(key) != "") pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); //infoMap.put(key + "_his", historyInfoPoint.get(key)); } } HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; String keyName = null; /* JSONObject jsonParam = new JSONObject(); jsonParam.put("curInfoPoint", infoMap); jsonParam.put("historyInfoPoint", historyInfoPoint); StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题 entity.setContentEncoding("UTF-8"); */ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); try { HttpResponse resp = client.execute(httpPost); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); JSONObject jobj = JSONObject.fromString(respContent); Iterator kit = jobj.keys(); while (kit.hasNext()) { keyName = kit.next(); if (keyName.equals("process")) { ans.setNext("nextStep=" + jobj.get(keyName)); } else if (keyName.equals("solution")) { ans.setAnswer((String) jobj.get(keyName)); } else { ans.setAnswer(ans.getAnswer().replace("{" + keyName + "}", jobj.getString(keyName))); } } } else { ans.setAnswer("api处理出错!"); } }catch (Exception e){ e.printStackTrace(); ans.setNext("提交失败了:"+url); } return ans; } public AnswerNextStep findNewNext(AnswerNextStep ans, Condition ansCondition, Map curInfoPoint,Map historyInfoPoint){ String nextOptions[] = ansCondition.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)[0].equals("") && !curInfoPoint.get(conditionName)[0].equals("unknown"); boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown"); //只有前两者都为假时,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(Condition condition, Map historyInfoPoint) throws ParseException { String features[] = condition.feature.split(","); String pair[],keyword; for(String feature: features){ if (feature.contains("updateKnowledge")){ for (String knowledge: feature.split("-<-")){ pair = knowledge.split(":"); keyword = historyInfoPoint.get(pair[0]); if(pair.length > 1) { try { if (pair[1].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(pair[1].substring(1)); pair[1] = MyFunc.transferToStandardTime(time + (1000 * offset)); }else if (StringUtils.isNumeric(keyword)){ int number = Integer.parseInt(keyword); int offset = Integer.parseInt(pair[1].substring(1)); pair[1] = String.valueOf(number + offset); } } else if (pair[1].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(pair[1].substring(1)); pair[1] = MyFunc.transferToStandardTime(time - (1000 * offset)); }else if (StringUtils.isNumeric(keyword)){ int number = Integer.parseInt(keyword); int offset = Integer.parseInt(pair[1].substring(1)); pair[1] = String.valueOf(number - offset); } } else if (pair[1].startsWith("str+")) { if(keyword == null || keyword.equals("")) keyword = ""; pair[1] = keyword + pair[1].substring(4); } else if (pair[1].startsWith("str-")) { if(keyword == null || keyword.equals("")) keyword = ""; pair[1] = keyword.replace(pair[1].substring(4), ""); } }catch (Exception e){ e.printStackTrace(); continue; } historyInfoPoint.put(pair[0], pair[1]); } } } } } public void activateConfig(HashMap extraActivatedConfig, String userName, int basePriority, String activateList, ServletContext context){ UserInfo userinfo = (UserInfo) context.getAttribute(userName); String configStr = ""; Integer configId; for(String configIdStr:activateList.split(",")){ configId = Integer.parseInt(configIdStr); Condition condition = new Condition(); configStr = userinfo.id2config.get(configId); if(configStr != null) { condition = ProcessQuestion.buildCondition(condition, configStr); if (extraActivatedConfig.containsKey(configId) && condition.priority + basePriority > extraActivatedConfig.get(configId).activePriority) { extraActivatedConfig.get(configId).activePriority = condition.priority + basePriority; } else if (!extraActivatedConfig.containsKey(configId)) { condition.activePriority = condition.priority + basePriority; extraActivatedConfig.put(configId, condition); } } } } }