package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.UserInfo; import javax.servlet.ServletContext; import java.io.*; import java.sql.SQLException; import java.util.*; import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; public class UserInfoController { static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; static String FILE_ERROR = ".txt文件有误"; /** * 根据本地配置文件生成用户信息 */ public static void configInit(ServletContext context) throws IOException { String line; System.out.println("configDir"+ CONFIG_DIR); 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, true); context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } reader.close(); br.close(); } } public static void userConfigInit(String botAccount, ServletContext context) throws IOException { String line; File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt"); System.out.println(userFile.getAbsolutePath()); if (!userFile.exists()) { BufferedReader br = new BufferedReader(new StringReader("")); UserInfo userinfo = new UserInfo(botAccount); try { userinfo = buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } } else { FileReader reader = new FileReader(userFile); BufferedReader br = new BufferedReader(reader); UserInfo userinfo = new UserInfo(botAccount); try { userinfo = buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } reader.close(); br.close(); } } /** * 解析一行配置文件 * @param action * @param line * @return */ public static Action buildCondition(Action action, String line) { String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; try { text = line.split("---"); line = text[0]; if(text.length > 1 && text[1].startsWith("<-")) line += "---" + text[1]; element = line.replace("\n", "").split("\\|=\\>\\|"); premises = element[0].split("\\|"); feature = premises[2]; cur_premises = premises[0].split(","); history_premises = premises[1].split(","); action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); //action.setConfigName(premises[4].split("=", 2)[1]); next = element[1].split("\\|"); if (next.length < 4) return action; if(premises.length < 5) action.setConfigName(""); else action.setConfigName(premises[4].split("=", 2)[1]); //回答可以有多个,然后可随机选择一个 action.setAnswer(next[0].split("~")); //第二处 action.setNextStep(next[1].split("=", 2)[1]); action.setId(Integer.parseInt(next[3].split("=")[1])); action.setStatus(next[2].split("=")[1]); //featureMap的构建 features = feature.split(","); for (String feat : features) { if (feat.equals("") || feat.equals(" ")) { continue; } else if (feat.startsWith("updateKnowledge")) { String[] knowledge = feat.split("-<-"); int length = knowledge.length; action.getFeatureMap().put("updateKnowledge", ""); for (int i = 1; i < length; i++) { if (knowledge[i].equals("") || knowledge[i].equals(" ")) continue; pair = knowledge[i].split(":", 2); action.getUpdateKnowledge().put(pair[0], pair[1]); } } else if (feat.startsWith("post")) { pair = feat.split("\\(", 2); url = pair[1]; url = url.substring(0, url.length() - 1); pair = pair[0].split("::"); action.getFeatureMap().put("post", url + "|" + pair[1]); } else { action.getFeatureMap().put(feat, ""); } } insertPremise(action.getCurrentPremise(), cur_premises); insertPremise(action.getHistoryPremise(), history_premises); //满足条件越多,优先级越大 action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); //action.activePriority = action.priority; /* for(String premise:cur_premises){ pair = premise.split("="); action.indexName.add(pair[0]); } */ firstCnditionName = cur_premises[0]; if (firstCnditionName.equals(" ")) action.setIndexName("emptySet"); else action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); System.out.println(line); System.out.println(TEXT_PARSE_ERROR); } return action; } /** * @param br * @param userinfo * @param overRide 覆盖之前的状态表 * @return * @throws IOException */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { String line, infoName, extraElements[]; HashMap> conditionTable = null; //是否覆盖原有的数据 if (overRide) { conditionTable = new HashMap>(); userinfo.id2condition.clear(); userinfo.id2config.clear(); userinfo.configStr = ""; userinfo.varInitialMap.clear(); userinfo.name2condition.clear(); } else { conditionTable = userinfo.conditionTable; } List actionList = null; while ((line = br.readLine()) != null) { try { if (line.trim().equals("")) continue; line = line.replace("\n", ""); //在用户信息中添加额外信息,如设为active的action if (line.contains("extraInfo")) { extraElements = line.split("\\|", -1); userinfo.extraInfo.put(extraElements[1], extraElements[2]); } else if (line.contains("varInitial")) { extraElements = line.split("\\|", -1); userinfo.varInitialMap.put(extraElements[1], extraElements[2]); } else { Action action = new Action(); action = buildCondition(action, line); actionList = conditionTable.get(action.getIndexName()); if (actionList == null) actionList = new ArrayList(); actionList.add(action); conditionTable.put(action.getIndexName(), actionList); if (action.getId() != 0) { if(!action.getConfigName().equals("")){ userinfo.name2condition.put(action.getConfigName(), action); } userinfo.id2config.put(action.getId(), line); userinfo.id2condition.put(action.getId(), action); } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println(TEXT_PARSE_ERROR); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.out.println(line); } } userinfo.conditionTable = conditionTable; return userinfo; } /** * 通过split方法解析配置文件中的条件部分(如:xihuan::match-Include=+dota+英雄联盟) * * @param premiseMap 前提条件哈希表 */ public static void insertPremise(HashMap> premiseMap, String[] premisesString) { String pair[]; HashSet keyWordSet = null; for (String premise : premisesString) { // System.out.println(premise); if (premise.equals("") || premise.equals(" ")) continue; pair = premise.split("=", 2); 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 { /*根据数据库得到botAccount改为直接得到 SqlHelper helper = new SqlHelper(); String botAccount = helper.querybotAccountByKey(chat_key); */ String botAccount = bot_name; UserInfo userinfo = null; if (context.getAttribute(botAccount) == null) { userConfigInit(botAccount, context); } if (context.getAttribute(botAccount) == null) { return null; //userinfo = new UserInfo(botAccount); //userinfo.conditionTable = new HashMap>(); } else { userinfo = (UserInfo) context.getAttribute(botAccount); } //helper.destroy(); return userinfo; } public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { int id = Integer.parseInt(configId); Action action = new Action(); UserInfoController userInfoController = new UserInfoController(); //data=configLine+"---"+conditionNameList String conditionNameList[] = data.split(","); String conditionName = ""; if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userInfo = (UserInfo) context.getAttribute(userName); if (userInfo.id2config.containsKey(id)) { Action oldAction = userInfo.id2condition.get(id); //------------------- try { conditionName = oldAction.getIndexName(); } catch (Exception e) { e.printStackTrace(); } if (userInfo.conditionTable.get(conditionName) != null) { List actionList = userInfo.conditionTable.get(conditionName); Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); while (condIter.hasNext()) { Action c = condIter.next(); if (c.getId() == id) { condIter.remove(); } } } userInfo.name2condition.remove(oldAction.getConfigName()); userInfo.id2config.remove(id); userInfo.id2condition.remove(id); } else { System.out.println("未找到要删除的configId"); } return true; } public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { Action action = new Action(); String conditionName = ""; for (int configId : idGroup) { if (userInfo.id2config.containsKey(configId)) { Action oldAction = userInfo.id2condition.get(configId); try { conditionName = oldAction.getIndexName(); } catch (Exception e) { e.printStackTrace(); } if (userInfo.conditionTable.get(conditionName) != null) { List actionList = userInfo.conditionTable.get(conditionName); Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); while (condIter.hasNext()) { Action c = condIter.next(); if (c.getId() == configId) { condIter.remove(); } } } userInfo.name2condition.remove(oldAction.getConfigName()); userInfo.id2config.remove(configId); userInfo.id2condition.remove(configId); } else { System.out.println("未找到要删除的configId:" + configId); } } return true; } public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { Action action = new Action(); //data=configLine+"---"+conditionNameList String dataPair[] = data.split("---"); String configLine = dataPair[0]; String conditionNameList[]; UserInfoController userInfoController = new UserInfoController(); int id = Integer.parseInt(configId); action = userInfoController.buildCondition(action, configLine); if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); if (userinfo.conditionTable.get(action.getIndexName()) == null) { List actionList = new ArrayList(); userinfo.conditionTable.put(action.getIndexName(), actionList); } if(!action.getConfigName().equals("")){ userinfo.name2condition.put(action.getConfigName(), action); } userinfo.conditionTable.get(action.getIndexName()).add(action); userinfo.id2config.put(id, configLine); userinfo.id2condition.put(id, action); return true; } public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { Action action = new Action(); //data=configLine+"---"+conditionNameList String dataPair[] = data.split("---", -1); String name = dataPair[0], value = dataPair[1]; UserInfoController userInfoController = new UserInfoController(); if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); userinfo.varInitialMap.put(name, value); return true; } public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { //data=configLine+"---"+conditionNameList String name = data; UserInfoController userInfoController = new UserInfoController(); if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); userinfo.varInitialMap.remove(name); return true; } public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { UserInfoController userInfoController = new UserInfoController(); if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); String extraElements[] = data.split("\\|"); userinfo.extraInfo.put(extraElements[1], extraElements[2]); return true; } public static String writeConfigText(String userName, UserInfo userinfo) throws IOException { String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText; String path = CONFIG_DIR + "/" + userName + ".txt"; File file = new File(path); File dir = new File(System.getProperty("user.dir") + "/config"); System.out.println(userName); System.out.println("config_dir" + dir.getAbsolutePath()); String returnMessage = "success"; if (!dir.exists()) dir.mkdir(); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); try { Iterator keyIter = userinfo.extraInfo.keySet().iterator(); while (keyIter.hasNext()) { String info = keyIter.next(); if (!userinfo.extraInfo.get(info).equals("")) bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); } keyIter = userinfo.varInitialMap.keySet().iterator(); while (keyIter.hasNext()) { String info = keyIter.next(); bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); } Iterator idIter = userinfo.id2config.keySet().iterator(); while (idIter.hasNext()) { int id = idIter.next(); bw.write(userinfo.id2config.get(id) + "\n"); } bw.write("\n"); } catch (Exception e) { e.printStackTrace(); returnMessage = "config file write error"; } finally { bw.close(); fw.close(); } return returnMessage; } }