package processing; import entity.AnswerNextStep; import entity.Condition; import entity.UserInfo; import net.sf.json.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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.util.EntityUtils; import javax.servlet.ServletContext; import java.io.*; import java.sql.SQLException; 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 Condition buildCondition(Condition condition,String line){ String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[]; element = line.trim().split("\\|=\\>\\|"); premises = element[0].split("\\|"); feature = premises[2]; cur_premises = premises[0].split(","); history_premises = premises[1].split(","); next = element[1].split("\\|"); condition.Answer = next[0]; //condition.nextStep = next[1]; //第二处 condition.nextStep = next[1].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(); /* for(String premise:cur_premises){ pair = premise.split("="); condition.indexName.add(pair[0]); } */ condition.indexName = cur_premises[0].split("=")[0]; return condition; } /** * 逐行读取用户配置文件,并保存在userinfo.conditionTable中 */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException { String line; HashMap> conditionTable = new HashMap>(); List conditionList = null; while ((line = br.readLine()) != null) { if (line.trim().equals("")) continue; userinfo.configStr += line + '\n'; 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); } 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.configInit(context); } if(context.getAttribute(userName) == null){ userinfo = new UserInfo(userName); userinfo.conditionTable = new HashMap>(); }else { userinfo = (UserInfo) context.getAttribute(userName); } //helper.destroy(); return userinfo; } /** * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @return bestMatch 状态表中满足条件最多的一条 */ public Condition getAnswer(Map curInfoPoint,Map historyInfoPoint,HashMap> conditionTable) throws IOException { List conditionList = null; Condition bestMatch = new Condition(0); Iterator it = curInfoPoint.keySet().iterator(); 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) { conditionList = conditionTable.get(conditionName); if (conditionList != null) { for (Condition condition : conditionList) { if (condition.priority > bestMatch.priority && satisfy(curInfoPoint, historyInfoPoint, condition)) bestMatch = condition; } } } } return bestMatch; } /** * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param condition 配置文件(状态表)的一行 * @return 满足条件就为True,不满足就为False */ public boolean satisfy(Map curInfoPoint,Map historyInfoPoint,Condition condition){ boolean flag = true; String actionName,keywords[],keyword; HashSet keywordSet = null; if(condition.feature.indexOf("match")!= -1){ Iterator it = condition.currentPremise.keySet().iterator(); while (flag && it.hasNext()) { actionName = it.next(); keywords = curInfoPoint.get(actionName); if (keywords == null){ flag = false; break; } keyword = keywords[0]; keywordSet = condition.currentPremise.get(actionName); if (!keywordSet.contains(keyword)) { flag = false; } } it = condition.historyPremise.keySet().iterator(); while (flag && it.hasNext()) { if (historyInfoPoint == null) { flag = false; break; } actionName = it.next(); keyword = historyInfoPoint.get(actionName); keywordSet = condition.historyPremise.get(actionName); if (!keywordSet.contains(keyword)) { flag = false; } } } return flag; } /** * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @return 返回给引擎的数据 */ public AnswerNextStep updateInfoGetBestMatch(Condition ansCondition,Map curInfoPoint,Map historyInfoPoint,ServletContext context,UserInfo userinfo) throws IOException { Iterator it = curInfoPoint.keySet().iterator(); String actionName; AnswerNextStep ans = new AnswerNextStep(); ans.setAnswer(ansCondition.Answer); //System.out.println(ans.getAnswer()); System.out.println("feature="+ansCondition.feature); if(ansCondition.feature.indexOf("post") != -1){ postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); } try { String keyword1, keyword2; if (historyInfoPoint == null) historyInfoPoint = new HashMap(); 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) { if (keyword2 == null) historyInfoPoint.put(actionName, keyword1); else if (keyword2 != null && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里 } } ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); ans.setNext("nextStep=" + ansCondition.nextStep); }catch(Exception e){ e.printStackTrace(); } return ans; } /** * 重新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[]; System.out.println("there"); for(String feature:features){ elem = feature.split("\\("); if(elem[0].equals("post")){ url = "http://"+elem[elem.length-1]; url = url.substring(0,url.length()-1); break; } } HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; String keyName = null; JSONObject jsonParam = new JSONObject(); jsonParam.put("curInfoPoint", curInfoPoint); jsonParam.put("historyInfoPoint", historyInfoPoint); StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题 entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); 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{ ans.setAnswer(ans.getAnswer().replace("{"+keyName+"}",jobj.getString(keyName))); } } }else{ ans.setAnswer("api有误!"); } return ans; } }