diff --git a/src/c3p0-config.xml b/src/c3p0-config.xml new file mode 100644 index 0000000..1cfc976 --- /dev/null +++ b/src/c3p0-config.xml @@ -0,0 +1,33 @@ + + + + + 10 + 30 + 100 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + admin + 10 + 30 + 100 + 10 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/db/C3p0Utils.java b/src/db/C3p0Utils.java new file mode 100644 index 0000000..f1efcd6 --- /dev/null +++ b/src/db/C3p0Utils.java @@ -0,0 +1,57 @@ +package db; + + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import org.apache.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class C3p0Utils { + static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); + + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); + + //从连接池中取用一个连接 + public static Connection getConnection() throws SQLException { + try { + return dataSource.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //释放连接回连接池 + public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + if (pst != null) { + try { + pst.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + } +} diff --git a/src/db/DB.java b/src/db/DB.java index b01bcbe..bd93fd6 100644 --- a/src/db/DB.java +++ b/src/db/DB.java @@ -5,17 +5,17 @@ import java.sql.DriverManager; public class DB { private static String driver = "com.mysql.jdbc.Driver"; - private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; - private static String user = "root"; - private static String pwd = "admin"; + private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; + private static String user = "root"; + private static String pwd = "admin"; - public static Connection getConnection(){ + public static Connection getConnection() { Connection conn = null; - try{ + try { Class.forName(driver); - conn = DriverManager.getConnection(url,user,pwd); + conn = DriverManager.getConnection(url, user, pwd); - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } diff --git a/src/db/DBCPUtils.java b/src/db/DBCPUtils.java index 41d167e..c99f015 100644 --- a/src/db/DBCPUtils.java +++ b/src/db/DBCPUtils.java @@ -14,7 +14,8 @@ import java.util.Properties; public class DBCPUtils { private static DataSource ds;//定义一个连接池对象 - static{ + + static { try { Properties pro = new Properties(); File file = new File("dbcpconfig.properties"); @@ -25,13 +26,14 @@ public class DBCPUtils { //throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); } } + //从池中获取一个连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } - public static void closeAll(ResultSet rs, Statement stmt, Connection conn){ - if(rs!=null){ + public static void closeAll(ResultSet rs, Statement stmt, Connection conn) { + if (rs != null) { try { rs.close(); } catch (SQLException e) { @@ -39,7 +41,7 @@ public class DBCPUtils { } } - if(stmt!=null){ + if (stmt != null) { try { stmt.close(); } catch (SQLException e) { @@ -47,7 +49,7 @@ public class DBCPUtils { } } - if(conn!=null){ + if (conn != null) { try { conn.close();//关闭 } catch (SQLException e) { diff --git a/src/db/DBUtils.java b/src/db/DBUtils.java new file mode 100644 index 0000000..c81615e --- /dev/null +++ b/src/db/DBUtils.java @@ -0,0 +1,4 @@ +package db; + +public class DBUtils { +} diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 9f91cf6..8076e0b 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -3,10 +3,12 @@ package db; import com.alibaba.fastjson.JSONObject; import entity.JConfig; import entity.QuestionKeyWord; +import gameDesign.ElementConstructor; import processing.MyFunc; import java.sql.*; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; public class SqlHelper { @@ -18,15 +20,15 @@ public class SqlHelper { */ public SqlHelper() throws SQLException { - conn = DBCPUtils.getConnection(); + conn = C3p0Utils.getConnection(); } - public void destroy(){ - if (conn != null){ - try{ + public void destroy() { + if (conn != null) { + try { conn.close(); - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } @@ -82,20 +84,25 @@ public class SqlHelper { } */ - public String queryUsernameByKey(String chat_key){ + private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException { + C3p0Utils.close(_conn, _st, _rs); + } + + public String queryUsernameByKey(String chat_key) { String sql = "select * from chats where chat_key = ?"; String userName = ""; String result = "empty"; - try{ + try { PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1,chat_key); + ps.setString(1, chat_key); ResultSet rs = ps.executeQuery(); - if(rs.next()) + if (rs.next()) result = rs.getString("bot"); - rs.close(); + ps.close(); + rs.close(); - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } return result; @@ -107,9 +114,9 @@ public class SqlHelper { boolean firstValue = true; int batchSize = idGroup.size(); - for (int i=0; i < batchSize; i++) { + for (int i = 0; i < batchSize; i++) { inClause.append('?'); - if ( firstValue ) { + if (firstValue) { firstValue = false; } else { inClause.append(','); @@ -120,27 +127,49 @@ public class SqlHelper { String userName = ""; boolean b = true; - try{ + try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(botId)); b = ps.execute(); + ps.close(); + return b; - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } return b; } - public boolean deleteConfigByBotId(int botId){ - String sql = "delete from chatbot_config where botId= ?"; + public boolean deleteConfigByBotId(int botId) { boolean b; - try{ + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); + ps1.setString(1, String.valueOf(botId)); + b = ps1.execute(); + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除旧数据失败"); + e.printStackTrace(); + return false; + } + } + + public boolean deleteVariableByBotId(int botId) { + String sql = "delete from chatbot_variable where botId= ?"; + boolean b; + + try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(botId)); b = ps.execute(); + ps.close(); + return b; } catch (SQLException e) { @@ -150,7 +179,64 @@ public class SqlHelper { } } - public boolean batchInsertConfigByBotId(int botId, List jConfigList, List idList) { + public boolean batchInsertVariableByBotId(int botId, ElementConstructor constructor) { + + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; + PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + Iterator iit = constructor.getVarInitialMap().keySet().iterator(); + while (iit.hasNext()) { + varName = iit.next(); + varValue = constructor.getVarInitialMap().get(varName); + if (constructor.getConditionDescription().get(varName) == null) + description = ""; + else + description = constructor.getConditionDescription().get(varName); + + ps2.setString(1, String.valueOf(botId)); + ps2.setString(2, varName); + ps2.setString(3, description); + ps2.setString(4, varValue); + ps2.addBatch(); + } + + count = ps2.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + ps2.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + public boolean batchInsertConfigByBotId(int botId, ElementConstructor constructor, List idList) { int count[]; boolean insertFlag = true; String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; @@ -160,10 +246,10 @@ public class SqlHelper { conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - for (JConfig jConfig : jConfigList) { + for (JConfig jConfig : constructor.getjConfigList()) { ps.setString(1, String.valueOf(botId)); ps.setString(2, String.valueOf(0)); - ps.setString(3, jConfig.toJson().toJSONString()); + ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString()); ps.setString(4, ""); ps.addBatch(); } @@ -179,16 +265,19 @@ public class SqlHelper { } } + ResultSet rs = ps.getGeneratedKeys(); - while(rs.next()) + while (rs.next()) idList.add(rs.getInt(1)); + ps.close(); rs.close(); } catch (SQLException e) { try { conn.rollback(); + } catch (SQLException e1) { e1.printStackTrace(); } @@ -196,23 +285,25 @@ public class SqlHelper { e.printStackTrace(); } - return insertFlag ; + return insertFlag; } - public JSONObject queryGameElementsByBotId(int id){ + + public JSONObject queryGameElementsByBotId(int id) { String sql = "select * from generate_json_tb where id = ?"; String userName = ""; String result = "empty"; - try{ + try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(id)); ResultSet rs = ps.executeQuery(); - if(rs.next()) + if (rs.next()) result = rs.getString("json_text"); - rs.close(); + ps.close(); + rs.close(); - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } @@ -220,7 +311,28 @@ public class SqlHelper { } + public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) { + String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + boolean b = true; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ps.setString(2, variableName); + ps.setString(3, description); + ps.setString(4, defaultValue); + b = ps.execute(); + + ps.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } } diff --git a/src/entity/Condition.java b/src/entity/Condition.java index f852da5..24ba36b 100644 --- a/src/entity/Condition.java +++ b/src/entity/Condition.java @@ -14,14 +14,14 @@ public class Condition { public int activePriority = 0; //如果本condition被其他condition激活 public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 public HashSet keywordSet = new HashSet(); - public HashMap> historyPremise = new HashMap>(); - public HashMap> currentPremise = new HashMap>(); + public HashMap> historyPremise = new HashMap>(); + public HashMap> currentPremise = new HashMap>(); public HashMap updateKnowledge = new HashMap(); public String[] answer = {"",}; public String nextStep = ""; public HashMap featureMap = new HashMap(); public String indexName = ""; - public int id =0; + public int id = 0; public String status = "waiting"; //public ArrayList indexName = new ArrayList(); diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index 8389edb..07da09a 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -16,7 +16,6 @@ public class JConfig { private String jFeature = ""; - private String jNextStep = ""; private String jReply = ""; private String jAuxiliaryPriority = "0"; @@ -26,7 +25,6 @@ public class JConfig { private String hisPremise = ""; - private String feature = ""; private String reply = ""; private String nextStep = ""; @@ -42,12 +40,12 @@ public class JConfig { private String updateKnowledge = ""; private String nextStepStatus = "return"; - Map statusMap = new HashMap(){ + Map statusMap = new HashMap() { { - put("return","return"); - put("return-1","back"); - put("return-0","stay"); - put("activate","activate"); + put("return", "return"); + put("return-1", "back"); + put("return-0", "stay"); + put("activate", "activate"); } }; @@ -55,16 +53,16 @@ public class JConfig { public void setAuxiliaryPriority(String auxiliaryPriority) { this.auxiliaryPriority = auxiliaryPriority; } + public void setNextStepStatus(String nextStepStatus) { this.nextStepStatus = nextStepStatus; } - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) - { + public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { this.curPremise = curPremise; this.hisPremise = hisPremise; this.feature = feature; - if(!updateKnowledge.equals("")) + if (!updateKnowledge.equals("")) this.updateKnowledge += "-<-" + updateKnowledge; this.reply = reply; @@ -72,7 +70,7 @@ public class JConfig { } - public JConfig(List curPremise, List hisPremise , Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority){ + public JConfig(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { this.curPremise = appendPremiseStr(curPremise, extraCP); this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); @@ -82,44 +80,44 @@ public class JConfig { this.auxiliaryPriority = auxiliaryPriority; } - public String appendPremiseStr(List premises, String extraPM){ + public String appendPremiseStr(List premises, String extraPM) { StringBuffer sb = new StringBuffer(); String premiseStr = ""; - for (String premise:premises) - sb.append("," + premise); - if(sb.length() > 0) + for (String premise : premises) + sb.append("," + premise); + if (sb.length() > 0) sb.deleteCharAt(0); //删除第一个逗号 - if(!extraPM.equals("")){ - if(sb.length() == 0) + if (!extraPM.equals("")) { + if (sb.length() == 0) sb.append(extraPM); else sb.append("," + extraPM); - }else if(sb.length() == 0){ - sb.append(" "); + } else if (sb.length() == 0) { + sb.append(" "); } premiseStr = sb.toString(); return premiseStr; } - public String appendKnowledgeStr(Map knowledge, String extraKL){ + public String appendKnowledgeStr(Map knowledge, String extraKL) { StringBuffer sb = new StringBuffer(); String varName = "", varValue = "", knowledgeStr; Iterator iit = knowledge.keySet().iterator(); - while(iit.hasNext()){ + while (iit.hasNext()) { varName = iit.next(); varValue = knowledge.get(varName); sb.append("-<-" + varName + ":" + varValue); } - if(!extraKL.equals("")){ + if (!extraKL.equals("")) { sb.append("-<-" + extraKL); } - if(sb.length() > 0) + if (sb.length() > 0) knowledgeStr = "updateKnowledge" + sb.toString(); else knowledgeStr = ""; @@ -128,9 +126,10 @@ public class JConfig { } - public void appendJPremise(JSONArray premiseList, String premise){ + public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { + //System.out.println(premise); - String pair1[] = premise.split("="); + String pair1[] = premise.split("=", 2); String key = pair1[0]; String keywords = pair1[1]; String pair2[] = key.split("::"); @@ -138,26 +137,33 @@ public class JConfig { String pair3[] = pair2[1].split("-"); String cmpType = pair3[0]; String operator = ""; - if(pair3.length > 1) + if (pair3.length > 1) operator = pair3[1]; + String question = ""; + if (conditionDescription.get(conditionName) != null) + question = conditionDescription.get(conditionName); + JSONObject premiseJ = new JSONObject(); premiseJ.put("keywords", keywords); premiseJ.put("actionName", conditionName); premiseJ.put("cmpType", cmpType); - premiseJ.put("question", "不知"); + premiseJ.put("question", question); premiseJ.put("operator", operator); premiseList.add(premiseJ); } - public void appendJKnowledge(JSONArray knowledgeList, String knowledge){ + public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { String pair[] = knowledge.split(":"); - if(knowledge.equals("") || pair.length < 2) + if (knowledge.equals("") || pair.length < 2) return; + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); JSONObject knowledgeJ = new JSONObject(); knowledgeJ.put("variableName", pair[0]); @@ -166,35 +172,40 @@ public class JConfig { knowledgeList.add(knowledgeJ); } - public void appendJNextStep(JSONArray nextStepList, String next){ - String pair[] = next.split("-"); + public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { + String pair[] = next.split("-"); JSONObject nextStepJ = new JSONObject(); JSONArray exceptJ = new JSONArray(); - for(int i = 1;i < pair.length;i++) + for (int i = 1; i < pair.length; i++) exceptJ.add(pair[i]); + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + nextStepJ.put("nextStep", pair[0]); nextStepJ.put("except", exceptJ); + nextStepJ.put("nextStepText", question); nextStepList.add(nextStepJ); } - public JSONObject toJson(){ + public JSONObject toJson(Map conditionDescription) { JSONObject data = new JSONObject(); JSONArray curPremiseList = new JSONArray(); JSONArray hisPremiseList = new JSONArray(); //添加当前对话内容 - for(String premise:curPremise.split(",")){ - if(!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise); + for (String premise : curPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(curPremiseList, premise, conditionDescription); } data.put("currentPremiseList", curPremiseList); //添加已知信息的内容 - for(String premise:hisPremise.split(",")){ - if(!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise); + for (String premise : hisPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(hisPremiseList, premise, conditionDescription); } data.put("historyPremiseList", hisPremiseList); @@ -207,10 +218,22 @@ public class JConfig { //添加config状态 data.put("configStatus", 0); + + boolean doPost = false; + String postURL = "", postType = "all", pair[]; + + for (String feat : feature.split(",")) { + if (feat.startsWith("post")) { + doPost = true; + pair = feat.substring(0, feat.length() - 1).split("\\(", 2); + postURL = pair[1]; + postType = pair[0].split("::")[1]; + } + } //添加post参数 - data.put("doPost", false); - data.put("postURL", ""); - data.put("postType", "all"); + data.put("doPost", doPost); + data.put("postURL", postURL); + data.put("postType", postType); //添加回答 data.put("reply", reply); @@ -223,17 +246,17 @@ public class JConfig { //添加更新答案处的信息 JSONArray knowledgeList = new JSONArray(); - if(!updateKnowledge.equals("")) { + if (!updateKnowledge.equals("")) { for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge); + appendJKnowledge(knowledgeList, knowledge, conditionDescription); } - data.put("updateKnowledge", knowledgeList); } + data.put("updateKnowledge", knowledgeList); //添加下一步 JSONArray nextStepList = new JSONArray(); - for(String next: nextStep.split(",")){ - appendJNextStep(nextStepList, next); + for (String next : nextStep.split(",")) { + appendJNextStep(nextStepList, next, conditionDescription); } data.put("nextStepList", nextStepList); @@ -241,7 +264,7 @@ public class JConfig { } - public String toString(){ + public String toString() { String text = curPremise + "|" + hisPremise + "|" + diff --git a/src/entity/QuestionKeyWord.java b/src/entity/QuestionKeyWord.java index 22b85d8..ffbff35 100644 --- a/src/entity/QuestionKeyWord.java +++ b/src/entity/QuestionKeyWord.java @@ -1,7 +1,6 @@ package entity; - /** * 暂时没用 */ diff --git a/src/entity/Solution.java b/src/entity/Solution.java index 8bd6b94..715b117 100644 --- a/src/entity/Solution.java +++ b/src/entity/Solution.java @@ -18,7 +18,6 @@ public class Solution { } - public void setAnswer(String answer) { this.answer = answer; } @@ -35,10 +34,12 @@ public class Solution { this.next = next; } - public Solution(int status, String answers, String next){ + public Solution(int status, String answers, String next) { this.answer = answers; this.next = next; this.status = status; } - public Solution(){} + + public Solution() { + } } diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java index 2ceeffa..45cc825 100644 --- a/src/entity/UserInfo.java +++ b/src/entity/UserInfo.java @@ -7,13 +7,13 @@ import java.util.List; * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 */ public class UserInfo { - public UserInfo(String userName){ + public UserInfo(String userName) { this.conditionTable = new HashMap>(); this.configStr = ""; this.userName = userName; - this.extraInfo = new HashMap(){ + this.extraInfo = new HashMap() { { - put("activeAction"," "); + put("activeAction", " "); } }; this.id2config = new HashMap(); @@ -21,15 +21,14 @@ public class UserInfo { this.varInitialMap = new HashMap(); } - public HashMap> conditionTable; + public HashMap> conditionTable; public String configStr; public String userName; - public HashMap extraInfo; + public HashMap extraInfo; public HashMap id2config; public HashMap id2condition; //存储需要初始化的变量 public HashMap varInitialMap; - } diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index 36fab14..028a642 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -8,7 +8,7 @@ import entity.UserInfo; import java.util.Iterator; import java.util.Map; -public class CharacterConstructor extends ElementConstructor{ +public class CharacterConstructor extends ElementConstructor { public CharacterConstructor(SqlHelper helper, int botId) { super(); @@ -16,13 +16,13 @@ public class CharacterConstructor extends ElementConstructor{ this.botId = botId; } - public void construct(JSONObject jsonObject, UserInfo userinfo){ + public void construct(JSONObject jsonObject, UserInfo userinfo) { String category, name, description, attrName, attrValue; JSONArray allNPC = jsonObject.getJSONArray("npc"); Map attribute = null; Iterator attrIter = null; - for(JSONObject npc:allNPC.toJavaList(JSONObject.class)) { + for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) { category = (String) npc.get("category"); JSONArray characters = npc.getJSONArray("characters"); for (JSONObject character : characters.toJavaList(JSONObject.class)) { @@ -33,7 +33,7 @@ public class CharacterConstructor extends ElementConstructor{ while (attrIter.hasNext()) { attrName = attrIter.next(); attrValue = attribute.get(attrName); - configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n"); + varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); } } } diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index 607aad1..5d38752 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -13,38 +13,66 @@ import java.util.Map; public class ElementConstructor { + int botId = 0; SqlHelper helper = null; List configDataList = new ArrayList(); List jConfigList = new ArrayList(); - String userName; + String CHITCHAT_URL = "http:192.168.1.178:1111/test", userName; StringBuffer configText = new StringBuffer(); JConfig jConfig = null; + Map varInitialMap = new HashMap(); Map conditionDescription = new HashMap(); - public void construct(JSONObject jsonObject, UserInfo userinfo){} - public List getjConfigList() { return jConfigList; } - public List getConfigDataList() { return configDataList; } - public void ElementConstructor(String userName){ this.userName = userName; } - public String getConfigText() { return configText.toString(); } + public Map getVarInitialMap() { + return varInitialMap; + } + + public void construct(JSONObject jsonObject, UserInfo userinfo) { + } + + public List getjConfigList() { + return jConfigList; + } + + public Map getConditionDescription() { + return conditionDescription; + } - public void generateConfigText(List idList){ + public List getConfigDataList() { + return configDataList; + } + + public void ElementConstructor(String userName) { + this.userName = userName; + } + + public String getConfigText() { + return configText.toString(); + } + + public void generateConfigText(List idList) { int id, length = idList.size(); + String varValue; JConfig jConfig = null; - for(int i = 0; i< length;i++){ + for (int i = 0; i < length; i++) { jConfig = jConfigList.get(i); id = idList.get(i); configText.append(jConfig.toString() + id + "\n"); } + for (String varName : varInitialMap.keySet()) { + varValue = varInitialMap.get(varName); + configText.append("-varInitial-|" + varName + "|" + varValue + "\n"); + } } /** * 构造参数配置文件的json版 */ - public void buildJconfig(){ + public void buildJconfig() { } diff --git a/src/gameDesign/Floyd.java b/src/gameDesign/Floyd.java index 4599361..027ad23 100644 --- a/src/gameDesign/Floyd.java +++ b/src/gameDesign/Floyd.java @@ -6,17 +6,21 @@ package gameDesign; public class Floyd { - - /** 表示正无穷 */ + /** + * 表示正无穷 + */ int MAX_WEIGHT = Integer.MAX_VALUE; - /**路径矩阵*/ + /** + * 路径矩阵 + */ int[][] pathMatirx; - /**前驱表*/ + /** + * 前驱表 + */ int[][] preTable; - - public void findShortestPath(int[][] matrix, int length){ + public void findShortestPath(int[][] matrix, int length) { //路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。 pathMatirx = new int[length][length]; //前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值 @@ -50,7 +54,7 @@ public class Floyd { int mn = pathMatirx[m][n]; int mk = pathMatirx[m][k]; int kn = pathMatirx[k][n]; - int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT)? MAX_WEIGHT : mk + kn; + int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn; if (mn > addedPath) { //如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个 @@ -80,7 +84,6 @@ public class Floyd { public void printPath(int[][] matrix, int length) { - for (int m = 0; m < length; m++) { for (int n = m + 1; n < length; n++) { diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java index 0bec8df..a3ceea8 100644 --- a/src/gameDesign/GlobalVariableConstructor.java +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -8,7 +8,7 @@ import entity.UserInfo; import java.util.Iterator; import java.util.Map; -public class GlobalVariableConstructor extends ElementConstructor{ +public class GlobalVariableConstructor extends ElementConstructor { public GlobalVariableConstructor(SqlHelper helper, int botId) { super(); @@ -16,20 +16,20 @@ public class GlobalVariableConstructor extends ElementConstructor{ this.botId = botId; } - public void construct(JSONObject jsonObject, UserInfo userinfo){ + public void construct(JSONObject jsonObject, UserInfo userinfo) { String category, name, description, attrName, attrValue; JSONArray globalVariable = jsonObject.getJSONArray("globalVariable"); Map attribute = null; Iterator attrIter = null; - for(JSONObject variableList:globalVariable.toJavaList(JSONObject.class)) { + for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) { category = (String) variableList.get("category"); attribute = JSONObject.toJavaObject(variableList.getJSONObject("variables"), Map.class); attrIter = attribute.keySet().iterator(); - while(attrIter.hasNext()){ + while (attrIter.hasNext()) { attrName = attrIter.next(); attrValue = attribute.get(attrName); - configText.append("-varInitial-|" + category + "_" + attrName + "|" + attrValue + "\n"); + varInitialMap.put(category + "_" + attrName, attrValue); } } } diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index 2217790..38578af 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -8,7 +8,7 @@ import entity.UserInfo; import java.util.Iterator; import java.util.Map; -public class ItemConstructor extends ElementConstructor{ +public class ItemConstructor extends ElementConstructor { public ItemConstructor(SqlHelper helper, int botId) { @@ -18,13 +18,13 @@ public class ItemConstructor extends ElementConstructor{ } - public void construct(JSONObject jsonObject, UserInfo userinfo){ + public void construct(JSONObject jsonObject, UserInfo userinfo) { String category, name, description, attrName, attrValue; JSONArray goods = jsonObject.getJSONArray("goods"); Map attribute = null; Iterator attrIter = null; - for(JSONObject good:goods.toJavaList(JSONObject.class)) { + for (JSONObject good : goods.toJavaList(JSONObject.class)) { category = (String) good.get("category"); JSONArray items = good.getJSONArray("items"); @@ -36,7 +36,7 @@ public class ItemConstructor extends ElementConstructor{ while (attrIter.hasNext()) { attrName = attrIter.next(); attrValue = attribute.get(attrName); - configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n"); + varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); } } } diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index ca604f8..c6ea0be 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -10,7 +10,7 @@ import java.io.BufferedReader; import java.io.StringReader; import java.util.*; -public class MapConstructor extends ElementConstructor{ +public class MapConstructor extends ElementConstructor { int[][] matrix; int locationNum; @@ -60,11 +60,11 @@ public class MapConstructor extends ElementConstructor{ } - } - public void construct(JSONObject jsonObject, UserInfo userinfo){ - conditionDescription.put("site","当前地点"); + public void construct(JSONObject jsonObject, UserInfo userinfo) { + conditionDescription.put("site", "当前地点"); + varInitialMap.put("site", ""); JSONObject map = jsonObject.getJSONObject("map"); Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); JSONArray locations = map.getJSONArray("locations"); @@ -87,62 +87,61 @@ public class MapConstructor extends ElementConstructor{ /** * 生成‘我在哪里’所需要的配置文件 */ - public void generateWhereIam(JSONObject jsonObject){ + public void generateWhereIam(JSONObject jsonObject) { String zainaKeywords = question2keyword.get("zaina"); jConfig = new JConfig( "zaina::match-Keyword=" + zainaKeywords, " ", - "match", "你在{site-2}", "yaobuyao","" + "match", "你在{site-2}", "yaobuyao", "" ); jConfigList.add(jConfig); - - } /** * 生成‘怎么去哪里’所需要的配置文件 */ - public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ + public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { String placeA, placeB, descriptionB, placeKeywords, text, pathNode; - String zenmequKeywords = question2keyword.get("zenmequ"); + String zenmequKeywords = question2keyword.get("zenmequ"); - for(int i = 0;i < locationNum;i++){ - for(int j = 0;j < locationNum;j++){ + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { - placeA = (String)locations.getJSONObject(i).get("name"); - placeB = (String)locations.getJSONObject(j).get("name"); + placeA = (String) locations.getJSONObject(i).get("name"); + placeB = (String) locations.getJSONObject(j).get("name"); placeKeywords = zenmequKeywords.replace("地点", placeB); - if(i == j){ + if (i == j) { jConfig = new JConfig( "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, - "match", "你已经在" + placeB + "了", "yaobuyao","" + "match", "你已经在" + placeB + "了", "yaobuyao", "" ); jConfigList.add(jConfig); continue; - }; - if(pathMatirx[i][j] == 1){ + } + ; + if (pathMatirx[i][j] == 1) { jConfig = new JConfig( "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "match", placeB + "就在附近哦", "yaobuyao", "" ); jConfigList.add(jConfig); - }else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){ + } else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) { int k = preTable[i][j]; pathNode = ""; while (k != j) { - pathNode += (String)locations.getJSONObject(k).get("name"); + pathNode += (String) locations.getJSONObject(k).get("name"); k = preTable[k][j]; } jConfig = new JConfig( "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, - "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao","" + "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", "" ); jConfigList.add(jConfig); } @@ -154,16 +153,16 @@ public class MapConstructor extends ElementConstructor{ /** * 生成‘我能去哪里’所需要的配置文件 */ - public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ + public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { String nengqunaKeywords = question2keyword.get("nengquna"); String placeA, placeB, pathNode; - for(int i = 0;i < locationNum;i++){ - placeA = (String)locations.getJSONObject(i).get("name"); + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); pathNode = ""; - for(int j = 0;j < locationNum;j++){ - if(pathMatirx[i][j] == 1) { + for (int j = 0; j < locationNum; j++) { + if (pathMatirx[i][j] == 1) { placeB = (String) locations.getJSONObject(j).get("name"); pathNode += "、" + placeB; } @@ -176,7 +175,6 @@ public class MapConstructor extends ElementConstructor{ jConfigList.add(jConfig); - } @@ -186,32 +184,31 @@ public class MapConstructor extends ElementConstructor{ /** * 生成‘我要去那里’所需要的配置文件 */ - public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ + public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { String placeA, placeB, descriptionB, placeKeywords, text, pathNode; - String qunaKeywords = question2keyword.get("quna"); + String qunaKeywords = question2keyword.get("quna"); - - for(int i = 0;i < locationNum;i++){ - for(int j = 0;j < locationNum;j++){ - placeA = (String)locations.getJSONObject(i).get("name"); - placeB = (String)locations.getJSONObject(j).get("name"); - descriptionB = (String)locations.getJSONObject(j).get("description"); + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { + placeA = (String) locations.getJSONObject(i).get("name"); + placeB = (String) locations.getJSONObject(j).get("name"); + descriptionB = (String) locations.getJSONObject(j).get("description"); placeKeywords = qunaKeywords.replace("地点", placeB); - - if(i == j){ + if (i == j) { jConfig = new JConfig( "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "match", "你已经在" + placeB + "了", "yaobuyao", "" - ); + ); jConfigList.add(jConfig); continue; - }; + } + ; //如果两点相邻 - if(pathMatirx[i][j] == 1){ + if (pathMatirx[i][j] == 1) { jConfig = new JConfig( "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "match", "" + descriptionB, "yaobuyao", "site:" + placeB @@ -219,12 +216,12 @@ public class MapConstructor extends ElementConstructor{ jConfigList.add(jConfig); - //如果两点不是相邻点 - }else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){ + //如果两点不是相邻点 + } else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) { int k = preTable[i][j]; pathNode = ""; while (k != j) { - pathNode += (String)locations.getJSONObject(k).get("name"); + pathNode += (String) locations.getJSONObject(k).get("name"); k = preTable[k][j]; } jConfig = new JConfig( diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index 0c89447..c3325f8 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -9,56 +9,64 @@ import entity.UserInfo; import java.util.*; -public class PlotConstructor extends ElementConstructor{ +public class PlotConstructor extends ElementConstructor { JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); + HashMap> adjList = new HashMap>(); + HashMap> revAdjList = new HashMap>(); HashMap id2j = new HashMap(); HashMap visited = new HashMap(); - - public PlotConstructor(SqlHelper helper, int botId){ + public PlotConstructor(SqlHelper helper, int botId) { super(); this.helper = helper; this.botId = botId; } - public void construct(JSONObject jsonObject, UserInfo userinfo){ + public void construct(JSONObject jsonObject, UserInfo userinfo) { JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String)jsonObject.get("start"); - userinfo.varInitialMap.put(start, "1"); - userinfo.varInitialMap.put("unknownText", "你说啥?"); + String start = (String) jsonObject.get("start"); + this.plots = plots; constructAdjList(plots); - BFSGenerate2(id2j.get(start)); + String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, start); + varInitialMap.put("unknownText", "你说啥?"); + conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); + + + BFSGenerate3(id2j.get(start), userinfo); + + varInitialMap.put(start, "0"); + } //根据id构造邻接表 - public void constructAdjList(JSONArray plots){ + public void constructAdjList(JSONArray plots) { int length = plots.size(), branchSize; String id = "", nextPlotId = ""; JSONObject plot = null; JSONArray branch = null; - for(int i = 0;i < length;i++){ + for (int i = 0; i < length; i++) { plot = plots.getJSONObject(i); - id = (String)plot.get("id"); + id = (String) plot.get("id"); plot.put("index", i); - if(adjList.get(id) == null){ + if (adjList.get(id) == null) { adjList.put(id, new ArrayList<>()); } //添加branch中的下一个plot branch = plot.getJSONArray("branch"); branchSize = branch.size(); - for(int j =0;j < branchSize;j++) { - nextPlotId = (String)branch.getJSONObject(j).get("nextPlotId"); - if(revAdjList.get(nextPlotId) == null){ + for (int j = 0; j < branchSize; j++) { + nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); + if (revAdjList.get(nextPlotId) == null) { revAdjList.put(nextPlotId, new ArrayList<>()); } adjList.get(id).add(nextPlotId); @@ -69,9 +77,9 @@ public class PlotConstructor extends ElementConstructor{ } } - public void BFSGenerate(JSONObject root){ - String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName, keywordOptions, conditionName, - unknownReply1, unknownReply2, nextCondition; + public void BFSGenerate(JSONObject root, UserInfo userinfo) { + String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + nextUnknownText, curUnknownText, nextCondition; boolean newBranch, manyParent; JSONObject node = null, branchNode = null, adjNode = null; JSONArray branch = null; @@ -82,73 +90,79 @@ public class PlotConstructor extends ElementConstructor{ root.put("priority", 0); root.put("taskName", id); root.put("taskStep", 0); + root.put("nextUnknownText", varInitialMap.get("unknownText")); + ; Queue queue = new LinkedList(); queue.add(root); - while(!queue.isEmpty()){ + while (!queue.isEmpty()) { node = queue.remove(); - id = (String)node.get("id"); + id = (String) node.get("id"); + conditionDescription.put(id, "剧情" + id + "进度"); + varInitialMap.put(id, ""); + - taskName = (String)node.get("taskName"); - priority = (Integer)node.get("priority"); - taskStep = (Integer)node.get("taskStep"); - conditionName = (String)node.get("conditionName"); + taskName = (String) node.get("taskName"); + priority = (Integer) node.get("priority"); + taskStep = (Integer) node.get("taskStep"); + conditionName = (String) node.get("conditionName"); + curUnknownText = (String) node.get("nextUnknownText"); //初始化 newBranch = false; manyParent = false; adjNodeList = adjList.get(id); - visited.put(id ,true); + visited.put(id, true); //查看是否存在多个子结点,如果有就是一个分支 - if(adjNodeList.size() > 1) + if (adjNodeList.size() > 1) newBranch = true; //查看是否存在多个父节点 - if(revAdjList.get(id) != null) + if (revAdjList.get(id) != null) manyParent = revAdjList.get(id).size() > 1; - if(newBranch){ + if (newBranch) { //多个分支时nextTaskName为子结点的id名,不在这里设 nextTaskStep = 1; - } - else{ - if(manyParent){ + } else { + if (manyParent) { nextTaskName = id; nextTaskStep = 1; priority++; - } - else{ + } else { nextTaskName = taskName; nextTaskStep = taskStep + 1; } } - branch = node.getJSONArray("branch"); branchSize = branch.size(); //当两次出现unknown时给用户一下候选项 keywordOptions = ""; - extraHP = taskName + "::match-Keyword=" + taskStep; - for(int i =0;i < branchSize;i++) { + for (int i = 0; i < branchSize; i++) { branchNode = branch.getJSONObject(i); - nextId = (String)branchNode.get("nextPlotId"); - if(id2j.get(nextId) != null) - nextCondition = (String)id2j.get(nextId).get("conditionName"); + nextId = (String) branchNode.get("nextPlotId"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + nextUnknownText = updateKnowledge.get("unknownText"); + + + if (id2j.get(nextId) != null) + nextCondition = (String) id2j.get(nextId).get("conditionName"); else nextCondition = " "; //unknown计数器更新为0, 当前任务状态+1 - if(newBranch) + if (newBranch) extraUK = taskName + ":" + taskStep; //多余步骤,以后要处理掉 @@ -156,54 +170,66 @@ public class PlotConstructor extends ElementConstructor{ extraUK = taskName + ":" + (taskStep + 1); - if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) - extraUK += "-<-" + nextId + ":" + 1; + extraHP = taskName + "::match-Keyword=" + taskStep; + if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) + extraHP += "," + nextId + "::match-Keyword=null"; + extraUK += "-<-" + nextId + ":" + 1; jConfig = new JConfig( JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), - JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class), + updateKnowledge, "", extraHP, extraUK, "match", (String) branchNode.get("reply"), (String) nextCondition, String.valueOf(priority) ); jConfigList.add(jConfig); - try{ + + try { keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - if(branchNode.get("nextPlotId") != null){ - adjId = (String)branchNode.get("nextPlotId"); - if(visited.get(adjId) == null && id2j.get(adjId) != null) { - adjNode = id2j.get(adjId); - - - adjNode.put("taskStep", nextTaskStep); - if(newBranch){ - adjNode.put("priority", priority+1); - adjNode.put("taskName", adjId); - }else{ - adjNode.put("priority", priority); - adjNode.put("taskName", taskName); + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null) { + if (id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + adjNode.put("nextUnknownText", nextUnknownText); + adjNode.put("taskStep", nextTaskStep); + if (newBranch) { + adjNode.put("priority", priority + 1); + adjNode.put("taskName", adjId); + } else { + adjNode.put("priority", priority); + adjNode.put("taskName", taskName); + } + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); } - queue.add(adjNode); } } } - /* + //对于unknown的特殊处理 - jConfig = new JConfig( - conditionName + "::match-Keyword=unknown", - extraHP + ",unknown_counter::number-SmallOrEqual=0,unknownReply::match-Keyword=null", - "match", - "{lastReply-2}", - " ", - "unknown_counter:+1" - ); + if (curUnknownText.equals("")) { + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP = taskName + "::match-Keyword=" + taskStep, + "match,return-0,post::all(" + CHITCHAT_URL + ")", + " ", + " ", + "" + ); + jConfigList.add(jConfig); + } + /* jConfig.setNextStepStatus("return-0"); jConfigList.add(jConfig); jConfig = new JConfig( @@ -230,8 +256,6 @@ public class PlotConstructor extends ElementConstructor{ */ - - } //unknown时的处理 jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); @@ -239,13 +263,12 @@ public class PlotConstructor extends ElementConstructor{ jConfigList.add(jConfig); - - } - public void BFSGenerate2(JSONObject root){ - String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName, keywordOptions, conditionName, + //每个结点分为0、1、2三种状态 + public void BFSGenerate2(JSONObject root) { + String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, unknownReply1, unknownReply2, nextCondition; boolean newBranch, manyParent; JSONObject node = null, branchNode = null, adjNode = null; @@ -263,9 +286,9 @@ public class PlotConstructor extends ElementConstructor{ queue.add(root); - while(!queue.isEmpty()){ + while (!queue.isEmpty()) { node = queue.remove(); - id = (String)node.get("id"); + id = (String) node.get("id"); //初始化 @@ -273,7 +296,7 @@ public class PlotConstructor extends ElementConstructor{ manyParent = false; adjNodeList = adjList.get(id); - visited.put(id ,true); + visited.put(id, true); /* //查看是否存在多个子结点,如果有就是一个分支 @@ -302,7 +325,6 @@ public class PlotConstructor extends ElementConstructor{ */ - branch = node.getJSONArray("branch"); branchSize = branch.size(); //当两次出现unknown时给用户一下候选项 @@ -310,12 +332,12 @@ public class PlotConstructor extends ElementConstructor{ extraHP = id + "::match-Keyword=" + 1; - for(int i =0;i < branchSize;i++) { + for (int i = 0; i < branchSize; i++) { branchNode = branch.getJSONObject(i); - nextId = (String)branchNode.get("nextPlotId"); - if(id2j.get(nextId) != null) - nextCondition = (String)id2j.get(nextId).get("conditionName"); + nextId = (String) branchNode.get("nextPlotId"); + if (id2j.get(nextId) != null) + nextCondition = (String) id2j.get(nextId).get("conditionName"); else nextCondition = " "; @@ -335,16 +357,16 @@ public class PlotConstructor extends ElementConstructor{ ); jConfigList.add(jConfig); - try{ + try { keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - if(branchNode.get("nextPlotId") != null){ - adjId = (String)branchNode.get("nextPlotId"); - if(visited.get(adjId) == null && id2j.get(adjId) != null) { + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null && id2j.get(adjId) != null) { adjNode = id2j.get(adjId); queue.add(adjNode); @@ -353,7 +375,6 @@ public class PlotConstructor extends ElementConstructor{ } - } //unknown时的处理 jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); @@ -361,6 +382,163 @@ public class PlotConstructor extends ElementConstructor{ jConfigList.add(jConfig); + } + + + public void BFSGenerate3(JSONObject root, UserInfo userinfo) { + String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName; + boolean newBranch, manyParent; + JSONObject node = null, branchNode = null, adjNode = null; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("nextUnknownText", varInitialMap.get("unknownText")); + root.put("parentId", "null"); + + + Queue queue = new LinkedList(); + + queue.add(root); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + parentId = (String) node.get("parentId"); + location = (String) node.get("place"); + conditionName = (String) node.get("conditionName"); + curUnknownText = (String) node.get("nextUnknownText"); + taskLineName = "任务线_" + location + "进度"; + + + if (!varInitialMap.containsKey(taskLineName)) { + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, ""); + } + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id, true); + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + + + for (int i = 0; i < branchSize; i++) { + + branchNode = branch.getJSONObject(i); + + nextId = (String) branchNode.get("nextPlotId"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + nextUnknownText = updateKnowledge.get("unknownText"); + + + if (id2j.get(nextId) != null) { + nextCondition = (String) id2j.get(nextId).get("conditionName"); + nextLocation = (String) id2j.get(nextId).get("place"); + nTaskLineName = "任务线_" + nextLocation + "进度"; + } else { + nextCondition = " "; + nTaskLineName = taskLineName; + } + + + extraHP = taskLineName + "::match-Keyword=" + id; + extraUK = nTaskLineName + ":" + nextId; + + jConfig = new JConfig( + JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), + JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), + updateKnowledge, + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, "0" + ); + jConfigList.add(jConfig); + jConfig = new JConfig( + "yaobuyao::match-Keyword=" + location, + extraHP, + "match", (String) branchNode.get("reply"), (String) nextCondition, "0" + ); + jConfigList.add(jConfig); + + + try { + keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null) { + if (id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + adjNode.put("parentId", id); + adjNode.put("nextUnknownText", nextUnknownText); + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); + } + } + } + } + + + //对于unknown的特殊处理 + if (curUnknownText.equals("")) { + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId, + "match,return-0,post::all(" + CHITCHAT_URL + ")", + " ", + " ", + "" + ); + jConfigList.add(jConfig); + } + /* + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP + ",unknown_counter::number-SmallOrEqual=0", + "match", + "{unknownReply-2}", + " ", + "unknown_counter:+1" + ); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP + ",unknown_counter::number-BiggerOrEqual=1", + "match", + "你可以说" + keywordOptions, + " ", + "unknown_counter:+1" + ); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + + */ + + + } + //unknown时的处理 + jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); } diff --git a/src/log4j.properties b/src/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index 817fdd7..faf5192 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -11,24 +11,25 @@ public class ChatCacheController { /** * 通过chat_key获得后台保存的历史信息点 * chatCache:存储了chatKye相对应的对话记录(历史信息点) + * * @return 历史信息点,对话过程中引擎提取的用户信息 */ - public static synchronized Map getChatCache(String chatKey, ServletContext context){ + public static synchronized Map getChatCache(String chatKey, ServletContext context) { Map historyInfoPoint = null; Map> chatCache = null; - if(context.getAttribute("chatCache") == null) { + if (context.getAttribute("chatCache") == null) { chatCache = new HashMap>(); context.setAttribute("chatCache", chatCache); - } else{ + } else { chatCache = (Map>) context.getAttribute("chatCache"); } String chatkey; - try{ + try { historyInfoPoint = chatCache.get(chatKey); //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - }catch(Exception e){ + } catch (Exception e) { //可整合 historyInfoPoint = null; @@ -42,10 +43,10 @@ public class ChatCacheController { /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ - public static synchronized void updateChatCache4Delete(ServletContext context){ + public static synchronized void updateChatCache4Delete(ServletContext context) { String chatKey; - long lastChatTime,now; - Map history = new HashMap(); + long lastChatTime, now; + Map history = new HashMap(); Map> chatCache = (Map>) context.getAttribute("chatCache"); @@ -65,15 +66,15 @@ public class ChatCacheController { /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ - public static synchronized void updateChatCache4Insert(Map curInfoPoint,Map historyInfoPoint,ServletContext context){ - historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis())); - Map> keyCache = (Map>) context.getAttribute("chatCache"); - keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint); - context.setAttribute("chatCache",keyCache); + public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, ServletContext context) { + historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + Map> keyCache = (Map>) context.getAttribute("chatCache"); + keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint); + context.setAttribute("chatCache", keyCache); } public static boolean saveChatCache(String userName, HashMap infoPoints) throws IOException { - String fileDir = System.getProperty("user.dir")+"/ChatCache"; + String fileDir = System.getProperty("user.dir") + "/ChatCache"; String key; boolean saveFlag = true; try { @@ -91,25 +92,25 @@ public class ChatCacheController { } fw.close(); - }catch (Exception e){ + } catch (Exception e) { saveFlag = false; } return saveFlag; } - public static boolean loadChatCache(String userName, ServletContext context){ - String fileDir = System.getProperty("user.dir")+"/ChatCache"; - String line,pair[]; + public static boolean loadChatCache(String userName, ServletContext context) { + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; Map infoPoints = new HashMap(); - try{ + try { File file = new File(fileDir + "/" + userName + ".txt"); - if(!file.exists()) { + if (!file.exists()) { return false; - }else { + } else { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); - while ((line = br.readLine()) != null){ + while ((line = br.readLine()) != null) { pair = line.trim().split("-----"); infoPoints.put(pair[0], pair[1]); } diff --git a/src/processing/ConditionTableController.java b/src/processing/ConditionTableController.java index e1fadce..f30b9e8 100644 --- a/src/processing/ConditionTableController.java +++ b/src/processing/ConditionTableController.java @@ -17,13 +17,12 @@ public class ConditionTableController { public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { int id = Integer.parseInt(configId); Condition condition = new Condition(); - ProcessQuestion process = new ProcessQuestion(); UserInfoController userInfoController = new UserInfoController(); //data=configLine+"---"+conditionNameList String conditionNameList[] = data.split(","); String conditionName = ""; - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userInfo = (UserInfo) context.getAttribute(userName); @@ -34,15 +33,10 @@ public class ConditionTableController { try { Condition oldCondition = userInfo.id2condition.get(id); conditionName = oldCondition.indexName; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - //------------------- - //Condition oldCondition = new Condition(); - //oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(id)); - //String conditionName = oldCondition.indexName; - if (userInfo.conditionTable.get(conditionName) != null) { List conditionList = userInfo.conditionTable.get(conditionName); @@ -57,7 +51,7 @@ public class ConditionTableController { userInfo.id2config.remove(id); userInfo.id2condition.remove(id); - } else{ + } else { System.out.println("未找到要删除的configId"); } @@ -66,23 +60,17 @@ public class ConditionTableController { public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { Condition condition = new Condition(); - ProcessQuestion process = new ProcessQuestion(); - //data=configLine+"---"+conditionNameList String conditionName = ""; - for(int configId:idGroup) { + for (int configId : idGroup) { if (userInfo.id2config.containsKey(configId)) { try { Condition oldCondition = userInfo.id2condition.get(configId); conditionName = oldCondition.indexName; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - //Condition oldCondition = new Condition(); - //oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId)); - //String conditionName = oldCondition.indexName; - if (userInfo.conditionTable.get(conditionName) != null) { List conditionList = userInfo.conditionTable.get(conditionName); @@ -107,10 +95,8 @@ public class ConditionTableController { } - public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { Condition condition = new Condition(); - ProcessQuestion process = new ProcessQuestion(); //data=configLine+"---"+conditionNameList String dataPair[] = data.split("---"); String configLine = dataPair[0]; @@ -120,12 +106,12 @@ public class ConditionTableController { condition = userInfoController.buildCondition(condition, configLine); - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); - if(userinfo.conditionTable.get(condition.indexName) == null){ + if (userinfo.conditionTable.get(condition.indexName) == null) { List conditionList = new ArrayList(); userinfo.conditionTable.put(condition.indexName, conditionList); } @@ -139,41 +125,37 @@ public class ConditionTableController { public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { Condition condition = new Condition(); - ProcessQuestion process = new ProcessQuestion(); //data=configLine+"---"+conditionNameList String dataPair[] = data.split("---", -1); - String name = dataPair[0],value = dataPair[1]; + String name = dataPair[0], value = dataPair[1]; UserInfoController userInfoController = new UserInfoController(); - if(context.getAttribute(userName) == null){ + 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 { - Condition condition = new Condition(); - ProcessQuestion process = new ProcessQuestion(); //data=configLine+"---"+conditionNameList String name = data; UserInfoController userInfoController = new UserInfoController(); - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); userinfo.varInitialMap.remove(name); - return true; } @@ -183,13 +165,13 @@ public class ConditionTableController { UserInfoController userInfoController = new UserInfoController(); - if(context.getAttribute(userName) == null){ + 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]); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); return true; } @@ -199,15 +181,15 @@ public class ConditionTableController { System.out.println("p"); System.out.println(userName); - String CONFIG_DIR = System.getProperty("user.dir")+"/config", configText; + 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"); + File dir = new File(System.getProperty("user.dir") + "/config"); String returnMessage = "success"; - if(!dir.exists()) + if (!dir.exists()) dir.mkdir(); - if(!file.exists()){ + if (!file.exists()) { file.createNewFile(); } @@ -217,7 +199,7 @@ public class ConditionTableController { Iterator keyIter = userinfo.extraInfo.keySet().iterator(); while (keyIter.hasNext()) { String info = keyIter.next(); - if(!userinfo.extraInfo.get(info).equals("")) + if (!userinfo.extraInfo.get(info).equals("")) bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); } @@ -233,10 +215,10 @@ public class ConditionTableController { bw.write(userinfo.id2config.get(id) + "\n"); } bw.write("\n"); - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); returnMessage = "config file write error"; - }finally { + } finally { bw.close(); fw.close(); } diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java index a1e7ea8..1421c94 100644 --- a/src/processing/MyFunc.java +++ b/src/processing/MyFunc.java @@ -24,24 +24,26 @@ public class MyFunc { jobj.put("process", ans.getNext()); return jobj.toString(); } - public static String toJson(String returnStr){ + + public static String toJson(String returnStr) { JSONObject jobj = new JSONObject(); - jobj.put("returnString",returnStr); + jobj.put("returnString", returnStr); return jobj.toString(); } /** * 当请求中的数据是json格式时,该函数用于提取request中的json数据 + * * @param request * @return json字符串 */ - public static String readJSONString(HttpServletRequest request){ + public static String readJSONString(HttpServletRequest request) { StringBuffer json = new StringBuffer(); String line = null; - try{ + try { BufferedReader reader = request.getReader(); - while((line = reader.readLine()) != null){ + while ((line = reader.readLine()) != null) { json.append(line); } } catch (IOException e) { @@ -54,10 +56,10 @@ public class MyFunc { /** * 通过get方法传递参数时需要对参数的编码进行转换 */ - public static String convert2Utf8(String s){ - if(s==null)return null; + public static String convert2Utf8(String s) { + if (s == null) return null; try { - s=new String(s.getBytes("iso-8859-1"),"utf-8"); + s = new String(s.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -71,7 +73,7 @@ public class MyFunc { System.out.println(keyword); String timeSeries[] = {"时", "分", "秒"}; - for(String f : timeSeries){ + for (String f : timeSeries) { if (!keyword.contains(f)) keyword += "0" + f; } @@ -81,6 +83,7 @@ public class MyFunc { return time; } + public static String transferToStandardTime(long time) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); @@ -91,6 +94,4 @@ public class MyFunc { } - - } diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java new file mode 100644 index 0000000..bb33123 --- /dev/null +++ b/src/processing/QuestionMatcher.java @@ -0,0 +1,888 @@ +package processing; + +import entity.Solution; +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.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.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class QuestionMatcher { + + static Map activatedMap = new HashMap(); + + + static String POST_DATA_ERROR = "post数据有误"; + static String POST_ERROR = "数据post时出错了"; + static String API_ERROR = "api处理过程中出错了"; + static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + +/* + 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 boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo) { + + String return_str = "", k; + boolean debugFlag = false; + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + + //输出所有actionName的值 + Iterator iit = curInfoPoint.keySet().iterator(); + while (iit.hasNext()) { + 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()) { + k = iit.next(); + String values[] = curInfoPoint.get(k); + if (skipSet.contains(k)) + 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 getBestMatch(Map curInfoPoint, Map historyInfoPoint, HashMap> conditionTable, ServletContext context) throws IOException { + + Integer configId = 0; + List conditionList = null; + Condition bestMatch = new Condition(-1), iterCon; + Iterator it = curInfoPoint.keySet().iterator(); + Queue activatedQueue = new LinkedList(); + Queue activatedCondition = new LinkedList(); + + + 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.featureMap.get("instantPost") != null) { + + + } + //Post后还是可以激活 + + if (condition.featureMap.get("activate") != null) { + bestMatch = condition; + + activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); + } else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) + bestMatch = condition; + } + } + } + } + + bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); + + + return bestMatch; + } + + public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, Map curInfoPoint, Map historyInfoPoint, ServletContext context) { + Condition condition; + //待激活配置条目被激活后的匹配 + while (!activatedQueue.isEmpty()) { + condition = activatedQueue.remove(); + activatedMap.remove(condition.id); + + if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { + if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { + bestMatch = condition; + activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); + } else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) { + bestMatch = condition; + } + } + + } + + 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.featureMap.containsKey("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) { + 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) { + 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; + + } + + /** + * 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) + * + * @param keyword + * @param cmpType 比较类型 + * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 + * @return 返回匹配或者不匹配 + */ + public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { + boolean flag = true; + String operator = ""; + + try { + String splitPair[] = cmpType.split("-"); + if (splitPair.length > 1) { + operator = splitPair[1]; + cmpType = splitPair[0]; + } + + + 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("number") && !keyword.equals("")) { + int candidateA = 0; + int candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(StringUtils.isNumeric(k)) + keyword = k; + + } + } + + if(!StringUtils.isNumeric(keyword)){ + return false; + + } + + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + + } else if (cmpType.equals("time")) { + + long candidateA, candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(k.startsWith("20") && k.endsWith("日")) + keyword = k; + + } + } + + candidateA = MyFunc.transferToMillisecond(keyword); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = MyFunc.transferToMillisecond(k); + break; + } + } + if (operator.equals("Early")) + flag = candidateA < candidateB; + else if (operator.equals("Later")) + flag = candidateA > candidateB; + + + } + //-------------------------------------------------------------------- + //为兼容旧数据 + else if (cmpType.equals("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 (IndexOutOfBoundsException e) { + System.out.println("配置文件格式有误"); + e.printStackTrace(); + } catch (Exception e) { + System.out.println("操作符有误"); + e.printStackTrace(); + flag = false; + } + + return flag; + } + + /** + * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 + * + * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 + * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 + * @return 返回给引擎的数据 + */ + public Solution getSolution(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, reply, variable; + Solution ans = new Solution(0, "", ""); + + + //如果一条配置文件有多个答案,则随 + // 机选择一个答案 + int randNum = (int) (Math.random() * ansCondition.answer.length); + ans.setAnswer(ansCondition.answer[randNum]); + //System.out.println(ans.getAnswer()); + + //post关键字 + if (ansCondition.featureMap.containsKey("post")) { + ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint); + + //nextNext关键字 + } else if (ansCondition.featureMap.containsKey("newNext")) { + ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); + //上一步 + } else if (ansCondition.featureMap.containsKey("return-1")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + //停留 + } else if (ansCondition.featureMap.containsKey("return-0")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + //激活 + } else if (ansCondition.featureMap.containsKey("activate")) { + 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]); + } + } + + //updateKnowledge关键字 + if (ansCondition.featureMap.containsKey("updateKnowledge")) { + updateKnowledge(ansCondition, historyInfoPoint); + } + + if (ans.getNext().equals("")) { + ans.setNext("nextStep=" + ansCondition.nextStep); + } + + + try { + + /* + 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)); + + } + */ + + + //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 + reply = ans.getAnswer(); + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1).substring(1, m.group(1).length() - 3); + if (m.group(1).endsWith("-1}")) { + if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals("")) + reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]); + } else if (m.group(1).endsWith("-2}")) { + if (historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")) + reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); + } + } + ans.setAnswer(reply); + + } catch (Exception e) { + e.printStackTrace(); + } + + return ans; + } + + public void infoTransfer(Map curInfoPoint, Map historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag) { + //将当前信息点更新至历史信息点 + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, lastReply; + String next = ans.getNext().split("=", 2)[1]; + + //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx + historyInfoPoint.put("currentAction", next); + historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); + + 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); + } + + + ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); + //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 + * + * @param ans 最终返回的数据 + * @param curInfoPoint 当前对话识别到的信息点 + * @param historyInfoPoint 在当前对话之前采集到的所有用户信息点 + * @param context + */ + public void appendDebugInfo(Solution 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 Solution postToServer(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint) throws IOException { + String url = null, elem[], subElem[], key, postType = "all"; + Map infoMap = new HashMap(); + List pairList = new ArrayList(); + Iterator k_iter = null; + + elem = ansCondition.featureMap.get("post").split("\\|"); + url = elem[0]; + postType = elem[1]; + + //提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 + 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)); + if (key.equals("game_step")) + pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); + else + pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); + } + + //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 + } 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])); + } + + 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; + + + 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((String) jobj.get(keyName)); + historyInfoPoint.put("process", (String) jobj.get(keyName)); + } else if (keyName.equals("solution")) { + ans.setAnswer((String) jobj.get(keyName)); + } else { + ans.setNext("nextStep=" + ansCondition.nextStep); + historyInfoPoint.put(keyName, jobj.getString(keyName)); + } + } + } else { + ans.setAnswer(API_ERROR); + } + } catch (Exception e) { + e.printStackTrace(); + + ans.setAnswer(POST_ERROR + url); + return ans; + } + + return ans; + + } + + public Solution findNewNext(Solution 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 keyword, variableName, updateValue; + + Iterator iit = condition.updateKnowledge.keySet().iterator(); + while (iit.hasNext()) { + + variableName = iit.next(); + updateValue = condition.updateKnowledge.get(variableName); + keyword = historyInfoPoint.get(variableName); + + try { + //做数字加法 + if (updateValue.startsWith("+")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("-")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(4); + //做字符串删除 + } else if (updateValue.startsWith("str-")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(4), ""); + } + } catch (Exception e) { + e.printStackTrace(); + continue; + } + historyInfoPoint.put(variableName, updateValue); + } + + + } + + + public void activateCondition(Queue activatedQueue, String userName, int basePriority, String activateList, ServletContext context) { + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + String configStr = ""; + Integer configId; + Condition newCondition, originCondition; + + for (String configIdStr : activateList.split(",")) { + if (!StringUtils.isNumeric(configIdStr)) + continue; + configId = Integer.parseInt(configIdStr); + + configStr = userinfo.id2config.get(configId); + if (configStr != null) { + originCondition = userinfo.id2condition.get(configId); + newCondition = new Condition(originCondition, basePriority); + //condition = QuestionMatcher.buildCondition(condition, configStr); + + if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { + activatedMap.get(configId).activePriority = newCondition.activePriority; + } else if (!activatedMap.containsKey(configId)) { + activatedMap.put(configId, newCondition); + activatedQueue.add(newCondition); + } + } + } + + + } + + public Solution postActivate(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + Queue activatedQueue = new LinkedList(); + Solution bestMatch = null; + activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context); + ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); + + bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + + return bestMatch; + + + } + + +} diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index 5977e72..7faf8d5 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -13,7 +13,7 @@ import java.util.List; public class UserInfoController { - static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; + static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; static String FILE_ERROR = ".txt文件有误"; @@ -25,9 +25,9 @@ public class UserInfoController { String line; File dir = new File(CONFIG_DIR); - if(!dir.exists()) + if (!dir.exists()) dir.mkdir(); - for(File configFile: dir.listFiles()) { + for (File configFile : dir.listFiles()) { FileReader reader = new FileReader(configFile); BufferedReader br = new BufferedReader(reader); @@ -36,8 +36,8 @@ public class UserInfoController { try { userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ + context.setAttribute(userinfo.userName, userinfo); + } catch (Exception e) { System.out.println(userinfo.userName + FILE_ERROR); e.printStackTrace(); } @@ -50,27 +50,27 @@ public class UserInfoController { public static void userConfigInit(String userName, ServletContext context) throws IOException { String line; - File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); - if(!userFile.exists()){ + 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, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ + context.setAttribute(userinfo.userName, userinfo); + } catch (Exception e) { System.out.println(userinfo.userName + FILE_ERROR); e.printStackTrace(); } - }else { + } else { FileReader reader = new FileReader(userFile); BufferedReader br = new BufferedReader(reader); UserInfo userinfo = new UserInfo(userName); try { userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ + context.setAttribute(userinfo.userName, userinfo); + } catch (Exception e) { System.out.println(userinfo.userName + FILE_ERROR); e.printStackTrace(); } @@ -81,8 +81,8 @@ public class UserInfoController { } - public static Condition buildCondition(Condition condition, String line){ - String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName; + public static Condition buildCondition(Condition condition, String line) { + String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName; try { @@ -122,14 +122,14 @@ public class UserInfoController { int length = knowledge.length; condition.featureMap.put("updateKnowledge", ""); for (int i = 1; i < length; i++) { - if(knowledge[i].equals("") || knowledge[i].equals(" ")) + if (knowledge[i].equals("") || knowledge[i].equals(" ")) continue; - pair = knowledge[i].split(":"); + pair = knowledge[i].split(":", 2); condition.updateKnowledge.put(pair[0], pair[1]); } } else if (feat.startsWith("post")) { - pair = feature.split("\\(", 2); + pair = feat.split("\\(", 2); url = pair[1]; url = url.substring(0, url.length() - 1); pair = pair[0].split("::"); @@ -140,10 +140,10 @@ public class UserInfoController { } - insertPremise(condition.currentPremise,cur_premises); - insertPremise(condition.historyPremise,history_premises); + insertPremise(condition.currentPremise, cur_premises); + insertPremise(condition.historyPremise, history_premises); //满足条件越多,优先级越大 - condition.priority = condition.historyPremise.size()+condition.currentPremise.size(); + condition.priority = condition.historyPremise.size() + condition.currentPremise.size(); condition.activePriority = condition.priority; /* for(String premise:cur_premises){ @@ -152,12 +152,13 @@ public class UserInfoController { } */ firstCnditionName = cur_premises[0]; - if(firstCnditionName.equals(" ")) + if (firstCnditionName.equals(" ")) condition.indexName = "emptySet"; else condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; - }catch (IndexOutOfBoundsException e){ + } catch (IndexOutOfBoundsException e) { e.printStackTrace(); + System.out.println(line); System.out.println("文本格式有误"); } return condition; @@ -165,24 +166,25 @@ public class UserInfoController { /** - * * @param br * @param userinfo - * @param overRide 覆盖之前的状态表 + * @param overRide 覆盖之前的状态表 * @return * @throws IOException */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { - String line,infoName,extraElements[]; + String line, infoName, extraElements[]; HashMap> conditionTable = null; //是否覆盖原有的数据 - if(overRide) { + if (overRide) { conditionTable = new HashMap>(); userinfo.id2condition.clear(); userinfo.id2config.clear(); userinfo.configStr = ""; - }else { + userinfo.varInitialMap.clear(); + + } else { conditionTable = userinfo.conditionTable; } @@ -215,10 +217,10 @@ public class UserInfoController { } } - } catch(ArrayIndexOutOfBoundsException e){ + } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数据格式有误"); e.printStackTrace(); - } catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -230,22 +232,23 @@ public class UserInfoController { /** * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) - * @param premiseMap 前提条件哈希表 + * + * @param premiseMap 前提条件哈希表 */ - public static void insertPremise(HashMap> premiseMap, String[] premisesString){ + public static void insertPremise(HashMap> premiseMap, String[] premisesString) { String pair[]; HashSet keyWordSet = null; - for(String premise:premisesString) { + for (String premise : premisesString) { // System.out.println(premise); if (premise.equals("") || premise.equals(" ")) continue; pair = premise.split("=", 2); - keyWordSet = new HashSet(); + 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); + if (keyword.equals("null")) keyWordSet.add(""); + else if (!keyword.equals("")) keyWordSet.add(keyword); + premiseMap.put(pair[0], keyWordSet); } } @@ -268,13 +271,13 @@ public class UserInfoController { */ String userName = bot_name; UserInfo userinfo = null; - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { userConfigInit(userName, context); } - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { userinfo = new UserInfo(userName); userinfo.conditionTable = new HashMap>(); - }else { + } else { userinfo = (UserInfo) context.getAttribute(userName); } //helper.destroy(); diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 1091be9..000eb42 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -1,13 +1,10 @@ package servlet; -import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import db.SqlHelper; -import entity.Condition; import entity.UserInfo; import gameDesign.*; import processing.MyFunc; -import processing.ProcessQuestion; import processing.ConditionTableController; import processing.UserInfoController; @@ -26,7 +23,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -@WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"}) +@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) public class GameDesignServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Integer botId, projectId, dataId; @@ -47,23 +44,22 @@ public class GameDesignServlet extends HttpServlet { String jsonStr = MyFunc.readJSONString(request); - if(jsonStr != null && !jsonStr.equals("")){ + if (jsonStr != null && !jsonStr.equals("")) { JSONObject jsonObject = JSONObject.parseObject(jsonStr); - dataId = (Integer)jsonObject.get("id"); + dataId = (Integer) jsonObject.get("id"); JSONObject gameElements = helper.queryGameElementsByBotId(dataId); - botId = (Integer)gameElements.get("botId"); - userName = (String)gameElements.get("userName"); + botId = (Integer) gameElements.get("botId"); + userName = (String) gameElements.get("userName"); //假设重新重新建用户信息 - if(context.getAttribute(userName) == null){ + if (context.getAttribute(userName) == null) { UserInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); - //UserInfo userinfo = new UserInfo(userName); //清空之前生成的配置条目 @@ -77,7 +73,7 @@ public class GameDesignServlet extends HttpServlet { Iterator moduleIter = gameElements.keySet().iterator(); StringBuffer mergedConfigText = new StringBuffer(); - while(moduleIter.hasNext()) { + while (moduleIter.hasNext()) { moduleName = moduleIter.next(); switch (moduleName) { case "map": @@ -103,10 +99,10 @@ public class GameDesignServlet extends HttpServlet { constructor.construct(gameElements, userinfo); //先清空再插入 idList.clear(); - if(moduleName.equals("map") || moduleName.equals("plots")) { - helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList); - constructor.generateConfigText(idList); - } + helper.batchInsertVariableByBotId(botId, constructor); + helper.batchInsertConfigByBotId(botId, constructor, idList); + constructor.generateConfigText(idList); + mergedConfigText.append(constructor.getConfigText()); @@ -132,8 +128,8 @@ public class GameDesignServlet extends HttpServlet { } public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { - boolean deleteFlag = helper.deleteConfigByBotId(botId); - - return deleteFlag; + boolean deleteConfigFlag = helper.deleteConfigByBotId(botId); + boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); + return deleteConfigFlag && deleteVariableFlag; } } diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 91912bb..2ee9c17 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -5,7 +5,7 @@ import entity.Condition; import entity.UserInfo; import processing.ChatCacheController; import processing.MyFunc; -import processing.ProcessQuestion; +import processing.QuestionMatcher; import processing.UserInfoController; import javax.servlet.ServletContext; @@ -21,30 +21,29 @@ import java.text.ParseException; import java.util.*; -@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"}) +@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/"}) public class GetAnswerServlet extends HttpServlet { /** * GetAnswerServlet就是处理post请求并返回答案的入口 */ String NAME_MISSING_ERROR = "没找到bot名?"; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); - Map curInfoPoint = new HashMap<>(request.getParameterMap()); + Map curInfoPoint = new HashMap<>(request.getParameterMap()); Map historyInfoPoint = null; Solution bestMatch = null; Condition ansCondition = null; - String ansJ,return_str="",state = ""; + String ansJ, return_str = "", state = ""; String chatKey = curInfoPoint.get("chat_key")[0]; - ProcessQuestion process = new ProcessQuestion(); + QuestionMatcher matcher = new QuestionMatcher(); OutputStream out = response.getOutputStream(); ServletContext context = this.getServletContext(); boolean debugFlag = false; //获得用户历史信息 - historyInfoPoint = ChatCacheController.getChatCache(chatKey,context); - StringBuffer curInfoRecord = new StringBuffer(); - StringBuffer hisInfoRecord = new StringBuffer(); - + historyInfoPoint = ChatCacheController.getChatCache(chatKey, context); UserInfo userinfo = null; @@ -52,46 +51,46 @@ public class GetAnswerServlet extends HttpServlet { try { //userinfo = process.userInfoQuery(chatKey,context); //从servlet根据用户名查询用户信息 - userinfo = uiController.userInfoQuery(request.getParameter("bot_name"),context); + userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); } catch (SQLException e) { state = NAME_MISSING_ERROR; e.printStackTrace(); } //如果historyInfoPoint不存在,就新建一个 - if(historyInfoPoint == null) { + if (historyInfoPoint == null) { String k; - historyInfoPoint = new HashMap(); + historyInfoPoint = new HashMap(); Iterator iit = curInfoPoint.keySet().iterator(); - while (iit.hasNext()){ + while (iit.hasNext()) { k = iit.next(); - historyInfoPoint.put(k,""); + historyInfoPoint.put(k, ""); } //变量初始化 iit = userinfo.varInitialMap.keySet().iterator(); - while(iit.hasNext()){ + while (iit.hasNext()) { k = iit.next(); historyInfoPoint.put(k, userinfo.varInitialMap.get(k)); } } //信息点预处理 - debugFlag = process.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, curInfoRecord); + debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo); /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ //process.removeTimeoutChatkey(context); //System.out.println(userinfo.conditionTable); //测试 - ansCondition = process.getBestMatch(curInfoPoint,historyInfoPoint,userinfo.conditionTable, context); + ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context); if (state.equals("") && ansCondition.priority == -1) state = "我不理解,"; if (state.equals("")) { try { - bestMatch = process.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + bestMatch = matcher.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); - if(ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")){ + if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) { //如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = process.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + bestMatch = matcher.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); } } catch (ParseException e) { e.printStackTrace(); @@ -104,16 +103,16 @@ public class GetAnswerServlet extends HttpServlet { context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); } //bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); - }else{ - bestMatch = new Solution(0," \n" + return_str + "\n " +state,"nextStep=" + historyInfoPoint.get("currentAction")); + } else { + bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); } - if(debugFlag) { - process.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context); + if (debugFlag) { + matcher.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context); } - process.infoTransition(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); + matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); ansJ = MyFunc.toJson(bestMatch); diff --git a/src/servlet/GetConfigServlet.java b/src/servlet/GetConfigServlet.java index 8e70c6f..c3e3053 100644 --- a/src/servlet/GetConfigServlet.java +++ b/src/servlet/GetConfigServlet.java @@ -7,24 +7,24 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; -@WebServlet(name = "GetConfigServlet",urlPatterns = {"/getConfig"}) +@WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"}) public class GetConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String userName = request.getParameter("userName"); - String path = System.getProperty("user.dir")+"/config/"+userName+".txt"; + String path = System.getProperty("user.dir") + "/config/" + userName + ".txt"; File file = new File(path); OutputStream out = response.getOutputStream(); - if(file.exists()){ + if (file.exists()) { - FileReader fr= new FileReader(file); + FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; - while ((line = br.readLine()) != null){ + while ((line = br.readLine()) != null) { line = line + "\n"; out.write(line.getBytes()); } @@ -32,7 +32,7 @@ public class GetConfigServlet extends HttpServlet { fr.close(); br.close(); - } else{ + } else { out.write("查无此bot".getBytes()); } out.flush(); diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java index 1fe8840..bd1a1f0 100644 --- a/src/servlet/ReloadConfigServlet.java +++ b/src/servlet/ReloadConfigServlet.java @@ -1,8 +1,6 @@ package servlet; import entity.UserInfo; -import processing.MyFunc; -import processing.ProcessQuestion; import processing.UserInfoController; import javax.servlet.ServletContext; @@ -17,31 +15,31 @@ import java.io.*; /** * 发请求从本地文件夹重新加载某用户的配置文件 */ -@WebServlet(name = "ReloadConfigServlet",urlPatterns = {"/reload","/reload/"}) +@WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"}) public class ReloadConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String userName = request.getParameter("userName"); boolean flag = true; UserInfo userinfo = new UserInfo(userName); - File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt"); + File configFile = new File(System.getProperty("user.dir") + "/config/" + userName + ".txt"); System.out.println(configFile.getAbsolutePath()); ServletContext context = this.getServletContext(); - if(!configFile.exists()) { + if (!configFile.exists()) { response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); - out.println("文件不存在: "+userName); + out.println("文件不存在: " + userName); - }else{ + } else { FileReader reader = new FileReader(configFile); BufferedReader br = new BufferedReader(reader); try { userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ + context.setAttribute(userinfo.userName, userinfo); + } catch (Exception e) { flag = false; System.out.println(userinfo.userName + ".txt 有误"); e.printStackTrace(); @@ -50,18 +48,17 @@ public class ReloadConfigServlet extends HttpServlet { reader.close(); br.close(); - if(!flag) { + if (!flag) { //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); response.setStatus(111); PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + userName +".txt\\\n"); + out.println("更新失败配置文件有误:" + userName + ".txt\\\n"); - } - else{ + } else { response.setCharacterEncoding("utf-8"); - response.setContentType( "text/plain"); + response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("重新加载成功"); out.flush(); @@ -75,7 +72,6 @@ public class ReloadConfigServlet extends HttpServlet { } - } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index 4ec098e..e3b5f80 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -3,7 +3,6 @@ package servlet; import entity.Condition; import entity.UserInfo; import processing.MyFunc; -import processing.ProcessQuestion; import processing.UserInfoController; import javax.servlet.ServletContext; @@ -21,12 +20,12 @@ import java.util.List; /** * 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。 */ -@WebServlet(name = "UpdateServlet",urlPatterns = {"/update"}) +@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"}) public class UpdateServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。 request.setCharacterEncoding("UTF-8"); - String line,extraElements[]; + String line, extraElements[]; ArrayList errorList = new ArrayList(); ServletContext context = this.getServletContext(); String userName = request.getParameter("userName"); @@ -42,35 +41,35 @@ public class UpdateServlet extends HttpServlet { String errorStr = ""; - while((line = br.readLine()) != null){ + while ((line = br.readLine()) != null) { System.out.println(line); - if(line.trim().equals("")) + if (line.trim().equals("")) continue; - line = line.replace("\n",""); + line = line.replace("\n", ""); //在用户信息中添加额外信息,如设为active的action - if(line.indexOf("-extraInfo-") != -1){ + if (line.indexOf("-extraInfo-") != -1) { extraElements = line.split("\\|"); - userinfo.extraInfo.put(extraElements[1],extraElements[2]); - userinfo.configStr += line+"\n"; + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + userinfo.configStr += line + "\n"; continue; } //line = MyFunc.convert2Utf8(line.trim()); - userinfo.configStr += line+"\n"; + userinfo.configStr += line + "\n"; Condition condition = new Condition(); try { - condition = UserInfoController.buildCondition(condition,line); + condition = UserInfoController.buildCondition(condition, line); conditionList = userinfo.conditionTable.get(condition.indexName); - if(conditionList == null) + if (conditionList == null) conditionList = new ArrayList(); conditionList.add(condition); - userinfo.conditionTable.put(condition.indexName,conditionList); + userinfo.conditionTable.put(condition.indexName, conditionList); /* for(String name:condition.indexName){ userinfo.conditionTable.put() } */ - } catch(Exception e ){ + } catch (Exception e) { System.out.println("配置文件有误!"); flag = false; errorList.add(line); @@ -80,23 +79,22 @@ public class UpdateServlet extends HttpServlet { } br.close(); - if(!flag) { + if (!flag) { //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); - String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr +"\\\n"); + String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); out.println("更新失败,以下行有误: "); - for(String error:errorList) - out.println("---"+error); + for (String error : errorList) + out.println("---" + error); out.flush(); out.close(); System.out.println("error"); - } - else{ + } else { response.setCharacterEncoding("utf-8"); - response.setContentType( "text/plain"); + response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("更新成功+ “ "); out.flush(); @@ -104,14 +102,14 @@ public class UpdateServlet extends HttpServlet { System.out.println("success"); //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - context.setAttribute(userName,userinfo); - String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt"; + context.setAttribute(userName, userinfo); + String path = System.getProperty("user.dir") + "/config/" + userinfo.userName + ".txt"; File file = new File(path); - File dir = new File(System.getProperty("user.dir")+"/config"); + File dir = new File(System.getProperty("user.dir") + "/config"); - if(!dir.exists()) + if (!dir.exists()) dir.mkdir(); - if(!file.exists()){ + if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java index 056ea1a..8af5e44 100644 --- a/src/servlet/UpdateSingleConfigServlet.java +++ b/src/servlet/UpdateSingleConfigServlet.java @@ -1,7 +1,6 @@ package servlet; import entity.UserInfo; -import processing.ProcessQuestion; import processing.ConditionTableController; import processing.UserInfoController; @@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; -@WebServlet(name = "UpdateSingleConfigServlet",urlPatterns = {"/update2"}) +@WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"}) public class UpdateSingleConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); @@ -22,9 +21,9 @@ public class UpdateSingleConfigServlet extends HttpServlet { String processType = request.getParameter("type"); String configId = request.getParameter("configId"); String data = request.getParameter("configData"); - System.out.println("userName:"+userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); + System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); - if(context.getAttribute(userName) != null) { + if (context.getAttribute(userName) != null) { switch (processType) { case "insert_config": ConditionTableController.insertConfig(userName, configId, data, context); @@ -56,17 +55,17 @@ public class UpdateSingleConfigServlet extends HttpServlet { writeConfig(userName, context); response.setStatus(200); - }else if(processType.equals("batch_update")){ + } else if (processType.equals("batch_update")) { batchUpdate(userName, data, context); writeConfig(userName, context); response.setStatus(200); - }else{ + } else { response.setStatus(111); } response.setCharacterEncoding("utf-8"); - response.setContentType( "text/plain"); + response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.write("success"); out.flush(); @@ -93,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet { BufferedReader br = new BufferedReader(new StringReader(data)); UserInfo userinfo = new UserInfo(userName); userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); + context.setAttribute(userinfo.userName, userinfo); System.out.println("batchupdate"); } }