diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 7a2b0a5..9f91cf6 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -1,7 +1,9 @@ package db; +import com.alibaba.fastjson.JSONObject; import entity.JConfig; import entity.QuestionKeyWord; +import processing.MyFunc; import java.sql.*; import java.util.ArrayList; @@ -130,6 +132,24 @@ public class SqlHelper { return b; } + public boolean deleteConfigByBotId(int botId){ + String sql = "delete from chatbot_config 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) { + System.out.println("删除旧数据失败"); + e.printStackTrace(); + return false; + } + } + public boolean batchInsertConfigByBotId(int botId, List jConfigList, List idList) { int count[]; boolean insertFlag = true; @@ -149,11 +169,11 @@ public class SqlHelper { } count = ps.executeBatch(); - conn.commit(); //提交事务,这个非常重要 + conn.commit(); for (int i : count) { if (i == 0) { - conn.rollback(); // 回滚,非常重要 + conn.rollback(); System.out.println("======出现异常,回滚========="); insertFlag = false; } @@ -168,7 +188,7 @@ public class SqlHelper { } catch (SQLException e) { try { - conn.rollback(); // 回滚,非常重要 + conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } @@ -179,6 +199,27 @@ public class SqlHelper { return insertFlag ; } + public JSONObject queryGameElementsByBotId(int id){ + String sql = "select * from generate_json_tb where id = ?"; + String userName = ""; + String result = "empty"; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ResultSet rs = ps.executeQuery(); + if(rs.next()) + result = rs.getString("json_text"); + rs.close(); + ps.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + + return JSONObject.parseObject(result); + + } + diff --git a/src/entity/Condition.java b/src/entity/Condition.java index af8371e..f852da5 100644 --- a/src/entity/Condition.java +++ b/src/entity/Condition.java @@ -16,9 +16,9 @@ public class Condition { public HashSet keywordSet = new HashSet(); public HashMap> historyPremise = new HashMap>(); public HashMap> currentPremise = new HashMap>(); + public HashMap updateKnowledge = new HashMap(); public String[] answer = {"",}; public String nextStep = ""; - public String feature = ""; public HashMap featureMap = new HashMap(); public String indexName = ""; public int id =0; @@ -38,8 +38,8 @@ public class Condition { this.currentPremise = originCondition.currentPremise; this.answer = originCondition.answer; this.nextStep = originCondition.nextStep; - this.feature = originCondition.feature; this.featureMap = originCondition.featureMap; + this.updateKnowledge = originCondition.updateKnowledge; this.indexName = originCondition.indexName; this.id = originCondition.id; this.status = originCondition.status; diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index 22839f1..8389edb 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -23,17 +24,21 @@ public class JConfig { private String curPremise = ""; private String hisPremise = ""; + + + private String feature = ""; private String reply = ""; private String nextStep = ""; + + public String getCurPremise() { + return curPremise; + } + private String auxiliaryPriority = "0"; private String status = "waiting"; - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - private String updateKnowledge = ""; private String nextStepStatus = "return"; @@ -46,78 +51,80 @@ public class JConfig { } }; - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep) + + 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) { this.curPremise = curPremise; this.hisPremise = hisPremise; this.feature = feature; + if(!updateKnowledge.equals("")) + this.updateKnowledge += "-<-" + updateKnowledge; + this.reply = reply; this.nextStep = nextStep; } - public JConfig(List curPremise, List hisPremise, String extraCP, String extraHP, String feature, String reply, String nextStep) - { - String curPremiseStr = ""; - String hisPremiseStr = ""; - String extraCurPremise = ""; - String extraHisPremise = ""; - - for(String premise: curPremise) - curPremiseStr += "," + premise; - for(String premise: hisPremise) - hisPremiseStr += "," + premise; - - if(!extraCP.equals("")) - curPremiseStr += "," + extraCP; - if(!extraHP.equals("")) - hisPremiseStr += "," + extraHP; - - - this.curPremise = curPremiseStr.substring(1, curPremiseStr.length()); - this.hisPremise = hisPremiseStr.substring(1, hisPremiseStr.length()); + 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); this.feature = feature; this.reply = reply; this.nextStep = nextStep; + this.auxiliaryPriority = auxiliaryPriority; } - public JConfig(List curPremise, List hisPremise, String extraCP, String extraHP, String feature, String reply, String nextStep, List updateKnowledgeList, String extraUK) - { - String curPremiseStr = ""; - String hisPremiseStr = ""; - String extraCurPremise = ""; - String extraHisPremise = ""; - - for(String premise: curPremise) - curPremiseStr += "," + premise; - for(String premise: hisPremise) - hisPremiseStr += "," + premise; - - if(!extraCP.equals("")) - curPremiseStr += "," + extraCP; - if(!extraHP.equals("")) - hisPremiseStr += "," + extraHP; - - for(String knowledge:updateKnowledgeList) - updateKnowledge += "-<-" + knowledge; - - updateKnowledge += "-<-" + extraUK; - this.curPremise = curPremiseStr.substring(1, curPremiseStr.length()); - this.hisPremise = hisPremiseStr.substring(1, hisPremiseStr.length()); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; + public String appendPremiseStr(List premises, String extraPM){ + StringBuffer sb = new StringBuffer(); + String premiseStr = ""; + + for (String premise:premises) + sb.append("," + premise); + if(sb.length() > 0) + sb.deleteCharAt(0); //删除第一个逗号 + + + if(!extraPM.equals("")){ + if(sb.length() == 0) + sb.append(extraPM); + else + sb.append("," + extraPM); + }else if(sb.length() == 0){ + sb.append(" "); + } + premiseStr = sb.toString(); + + return premiseStr; } - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) - { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = "-<-" + updateKnowledge; + public String appendKnowledgeStr(Map knowledge, String extraKL){ + StringBuffer sb = new StringBuffer(); + String varName = "", varValue = "", knowledgeStr; + Iterator iit = knowledge.keySet().iterator(); - this.reply = reply; - this.nextStep = nextStep; + while(iit.hasNext()){ + varName = iit.next(); + varValue = knowledge.get(varName); + sb.append("-<-" + varName + ":" + varValue); + } + if(!extraKL.equals("")){ + sb.append("-<-" + extraKL); + } + + if(sb.length() > 0) + knowledgeStr = "updateKnowledge" + sb.toString(); + else + knowledgeStr = ""; + + return knowledgeStr; } @@ -146,10 +153,12 @@ public class JConfig { } public void appendJKnowledge(JSONArray knowledgeList, String knowledge){ - if(knowledge.equals("")) + String pair[] = knowledge.split(":"); + + if(knowledge.equals("") || pair.length < 2) return; - String pair[] = knowledge.split(":"); + JSONObject knowledgeJ = new JSONObject(); knowledgeJ.put("variableName", pair[0]); knowledgeJ.put("keyword", pair[1]); @@ -234,12 +243,9 @@ public class JConfig { public String toString(){ - if(!updateKnowledge.equals("")) - updateKnowledge = ",updateKnowledge" + updateKnowledge; - String text = curPremise + "|" + hisPremise + "|" + - feature + updateKnowledge + "|" + + feature + "," + updateKnowledge + "," + nextStepStatus + "|" + "auxiliaryPriority=" + auxiliaryPriority + "|=>|" + reply + "|" + "nextStep=" + nextStep + "|" + diff --git a/src/entity/QuestionKeyWord.java b/src/entity/QuestionKeyWord.java index 35e6529..22b85d8 100644 --- a/src/entity/QuestionKeyWord.java +++ b/src/entity/QuestionKeyWord.java @@ -6,9 +6,9 @@ package entity; * 暂时没用 */ public class QuestionKeyWord { - String actionName; - String chatKey; - String keyWord; + private String actionName; + private String chatKey; + private String keyWord; public String getActionName() { return actionName; diff --git a/src/entity/Solution.java b/src/entity/Solution.java index 9465e04..8bd6b94 100644 --- a/src/entity/Solution.java +++ b/src/entity/Solution.java @@ -5,9 +5,9 @@ package entity; * 包含后台返回数据的实体类。 */ public class Solution { - int status = 0; - String answer; - String next; + private int status = 0; + private String answer; + private String next; public String getAnswer() { return answer; diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java index 5037d71..2ceeffa 100644 --- a/src/entity/UserInfo.java +++ b/src/entity/UserInfo.java @@ -13,11 +13,12 @@ public class UserInfo { this.userName = userName; this.extraInfo = new HashMap(){ { - put("activeAction",""); + put("activeAction"," "); } }; this.id2config = new HashMap(); this.id2condition = new HashMap(); + this.varInitialMap = new HashMap(); } public HashMap> conditionTable; @@ -26,6 +27,8 @@ public class UserInfo { public HashMap extraInfo; public HashMap id2config; public HashMap id2condition; + //存储需要初始化的变量 + public HashMap varInitialMap; diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java new file mode 100644 index 0000000..36fab14 --- /dev/null +++ b/src/gameDesign/CharacterConstructor.java @@ -0,0 +1,41 @@ +package gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import db.SqlHelper; +import entity.UserInfo; + +import java.util.Iterator; +import java.util.Map; + +public class CharacterConstructor extends ElementConstructor{ + + public CharacterConstructor(SqlHelper helper, int botId) { + super(); + this.helper = helper; + this.botId = botId; + } + + 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)) { + category = (String) npc.get("category"); + JSONArray characters = npc.getJSONArray("characters"); + for (JSONObject character : characters.toJavaList(JSONObject.class)) { + name = (String) character.get("name"); + description = (String) character.get("intro"); + attribute = JSONObject.toJavaObject(character.getJSONObject("attr"), Map.class); + attrIter = attribute.keySet().iterator(); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n"); + } + } + } + } +} diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index 7856b32..607aad1 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -4,10 +4,12 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import db.SqlHelper; import entity.JConfig; +import entity.UserInfo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public class ElementConstructor { @@ -16,18 +18,17 @@ public class ElementConstructor { List configDataList = new ArrayList(); List jConfigList = new ArrayList(); String userName; - String configText = ""; + StringBuffer configText = new StringBuffer(); JConfig jConfig = null; + Map conditionDescription = new HashMap(); + public void construct(JSONObject jsonObject, UserInfo userinfo){} public List getjConfigList() { return jConfigList; } - public void construct(JSONObject jsonObject){} - public List getConfigDataList() { return configDataList; } - public void ElementConstructor(String userName){ this.userName = userName; } + public String getConfigText() { return configText.toString(); } - public String getConfigText() { return configText; } public void generateConfigText(List idList){ int id, length = idList.size(); JConfig jConfig = null; @@ -35,7 +36,7 @@ public class ElementConstructor { jConfig = jConfigList.get(i); id = idList.get(i); - configText += jConfig.toString() + id + "\n"; + configText.append(jConfig.toString() + id + "\n"); } } diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java new file mode 100644 index 0000000..0bec8df --- /dev/null +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -0,0 +1,36 @@ +package gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import db.SqlHelper; +import entity.UserInfo; + +import java.util.Iterator; +import java.util.Map; + +public class GlobalVariableConstructor extends ElementConstructor{ + + public GlobalVariableConstructor(SqlHelper helper, int botId) { + super(); + this.helper = helper; + this.botId = botId; + } + + 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)) { + category = (String) variableList.get("category"); + attribute = JSONObject.toJavaObject(variableList.getJSONObject("variables"), Map.class); + attrIter = attribute.keySet().iterator(); + while(attrIter.hasNext()){ + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + configText.append("-varInitial-|" + category + "_" + attrName + "|" + attrValue + "\n"); + } + } + } +} diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java new file mode 100644 index 0000000..2217790 --- /dev/null +++ b/src/gameDesign/ItemConstructor.java @@ -0,0 +1,44 @@ +package gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import db.SqlHelper; +import entity.UserInfo; + +import java.util.Iterator; +import java.util.Map; + +public class ItemConstructor extends ElementConstructor{ + + + public ItemConstructor(SqlHelper helper, int botId) { + super(); + this.helper = helper; + this.botId = botId; + } + + + 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)) { + + category = (String) good.get("category"); + JSONArray items = good.getJSONArray("items"); + for (JSONObject item : items.toJavaList(JSONObject.class)) { + name = (String) item.get("name"); + description = (String) item.get("intro"); + attribute = JSONObject.toJavaObject(item.getJSONObject("attr"), Map.class); + attrIter = attribute.keySet().iterator(); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n"); + } + } + } + } +} diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index c35d8d4..ca604f8 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -8,27 +8,16 @@ import entity.UserInfo; import java.io.BufferedReader; import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; +import java.util.*; public class MapConstructor extends ElementConstructor{ int[][] matrix; int locationNum; HashMap id2j = new HashMap(); - - - - + Map question2keyword = new HashMap(); JSONArray locations = null; - - - - - public MapConstructor(SqlHelper helper, int botId) { super(); this.helper = helper; @@ -74,9 +63,13 @@ public class MapConstructor extends ElementConstructor{ } - public void construct(JSONObject jsonObject){ - JSONArray locations = jsonObject.getJSONArray("locations"); + public void construct(JSONObject jsonObject, UserInfo userinfo){ + conditionDescription.put("site","当前地点"); + JSONObject map = jsonObject.getJSONObject("map"); + Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); + JSONArray locations = map.getJSONArray("locations"); this.locations = locations; + this.question2keyword = question2keyword; //通过邻接表构造邻接矩阵 constructGreph(locations); @@ -89,21 +82,16 @@ public class MapConstructor extends ElementConstructor{ generateWhereIam(jsonObject); generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); - - } /** * 生成‘我在哪里’所需要的配置文件 */ public void generateWhereIam(JSONObject jsonObject){ - String zainaKeywords = (String)jsonObject.get("zaina"); + String zainaKeywords = question2keyword.get("zaina"); jConfig = new JConfig( - "zaina::match-Keyword=" + zainaKeywords, - " ", - "match", - "你在{site-2}", - "yaobuyao" + "zaina::match-Keyword=" + zainaKeywords, " ", + "match", "你在{site-2}", "yaobuyao","" ); jConfigList.add(jConfig); @@ -118,7 +106,7 @@ public class MapConstructor extends ElementConstructor{ public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ String placeA, placeB, descriptionB, placeKeywords, text, pathNode; - String zenmequKeywords = (String)jsonObject.get("zenmequ"); + String zenmequKeywords = question2keyword.get("zenmequ"); for(int i = 0;i < locationNum;i++){ @@ -131,22 +119,16 @@ public class MapConstructor extends ElementConstructor{ if(i == j){ jConfig = new JConfig( - "zenmequ::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, - "match", - "你已经在" + placeB + "了", - "yaobuyao" + "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + "match", "你已经在" + placeB + "了", "yaobuyao","" ); jConfigList.add(jConfig); continue; }; if(pathMatirx[i][j] == 1){ jConfig = new JConfig( - "zenmequ::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, - "match", - placeB + "就在附近哦", - "yaobuyao" + "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + "match", placeB + "就在附近哦", "yaobuyao", "" ); jConfigList.add(jConfig); @@ -159,11 +141,8 @@ public class MapConstructor extends ElementConstructor{ } jConfig = new JConfig( - "zenmequ::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, - "match", - "经过" + pathNode + "就可以到达" + placeB, - "yaobuyao" + "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao","" ); jConfigList.add(jConfig); } @@ -176,7 +155,7 @@ public class MapConstructor extends ElementConstructor{ * 生成‘我能去哪里’所需要的配置文件 */ public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ - String nengqunaKeywords = (String)jsonObject.get("nengquna"); + String nengqunaKeywords = question2keyword.get("nengquna"); String placeA, placeB, pathNode; for(int i = 0;i < locationNum;i++){ @@ -191,11 +170,8 @@ public class MapConstructor extends ElementConstructor{ } jConfig = new JConfig( - "nengquna::match-Keyword=" + nengqunaKeywords, - "site::match-Keyword=" + placeA, - "match", - "你可以去" + pathNode, - "yaobuyao" + "nengquna::match-Keyword=" + nengqunaKeywords, "site::match-Keyword=" + placeA, + "match", "你可以去" + pathNode, "yaobuyao", "" ); jConfigList.add(jConfig); @@ -212,7 +188,7 @@ public class MapConstructor extends ElementConstructor{ */ public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){ String placeA, placeB, descriptionB, placeKeywords, text, pathNode; - String qunaKeywords = (String)jsonObject.get("quna"); + String qunaKeywords = question2keyword.get("quna"); @@ -227,26 +203,23 @@ public class MapConstructor extends ElementConstructor{ if(i == j){ jConfig = new JConfig( - "quna::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, - "match", - "你已经在" + placeB + "了", - "yaobuyao" + "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + "match", "你已经在" + placeB + "了", "yaobuyao", "" ); jConfigList.add(jConfig); continue; }; + //如果两点相邻 if(pathMatirx[i][j] == 1){ jConfig = new JConfig( - "quna::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, - "match,updateKnowledge-<-site:" + placeB, - "" + descriptionB, - "yaobuyao" + "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + "match", "" + descriptionB, "yaobuyao", "site:" + placeB ); jConfigList.add(jConfig); + + //如果两点不是相邻点 }else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){ int k = preTable[i][j]; pathNode = ""; @@ -257,9 +230,7 @@ public class MapConstructor extends ElementConstructor{ jConfig = new JConfig( "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, - "match", - "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, - "yaobuyao" + "match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", "" ); jConfigList.add(jConfig); } diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index c4c1085..0c89447 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import db.SqlHelper; import entity.JConfig; +import entity.UserInfo; import java.util.*; @@ -24,13 +25,15 @@ public class PlotConstructor extends ElementConstructor{ this.botId = botId; } - public void construct(JSONObject jsonObject){ + 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", "你说啥?"); this.plots = plots; constructAdjList(plots); - BFSGenerate(id2j.get(start)); + BFSGenerate2(id2j.get(start)); } @@ -67,7 +70,8 @@ public class PlotConstructor extends ElementConstructor{ } public void BFSGenerate(JSONObject root){ - String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName; + 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; JSONArray branch = null; @@ -79,6 +83,7 @@ public class PlotConstructor extends ElementConstructor{ root.put("taskName", id); root.put("taskStep", 0); + Queue queue = new LinkedList(); queue.add(root); @@ -90,6 +95,7 @@ public class PlotConstructor extends ElementConstructor{ taskName = (String)node.get("taskName"); priority = (Integer)node.get("priority"); taskStep = (Integer)node.get("taskStep"); + conditionName = (String)node.get("conditionName"); //初始化 newBranch = false; @@ -109,7 +115,6 @@ public class PlotConstructor extends ElementConstructor{ if(newBranch){ //多个分支时nextTaskName为子结点的id名,不在这里设 nextTaskStep = 1; - priority++; } else{ if(manyParent){ @@ -127,38 +132,47 @@ public class PlotConstructor extends ElementConstructor{ branch = node.getJSONArray("branch"); branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + extraHP = taskName + "::match-Keyword=" + taskStep; for(int i =0;i < branchSize;i++) { branchNode = branch.getJSONObject(i); nextId = (String)branchNode.get("nextPlotId"); - if(node == root) - extraHP = " "; + if(id2j.get(nextId) != null) + nextCondition = (String)id2j.get(nextId).get("conditionName"); else - extraHP = taskName + "::match-Keyword=" + taskStep; + nextCondition = " "; + + + //unknown计数器更新为0, 当前任务状态+1 + if(newBranch) + extraUK = taskName + ":" + taskStep; + //多余步骤,以后要处理掉 - if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) - extraUK = nextId + ":" + 1; else extraUK = taskName + ":" + (taskStep + 1); + + if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) + extraUK += "-<-" + nextId + ":" + 1; + jConfig = new JConfig( JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), - "", - extraHP, - "match", - (String) branchNode.get("reply"), - (String) branchNode.get("nextStep"), - JSONArray.parseArray(branchNode.getJSONArray("updateKnowledge").toJSONString(), String.class), - extraUK + JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class), + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, String.valueOf(priority) ); - - jConfig.setAuxiliaryPriority("" + priority); jConfigList.add(jConfig); - + try{ + keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; + }catch (Exception e){ + e.printStackTrace(); + } if(branchNode.get("nextPlotId") != null){ @@ -166,11 +180,13 @@ public class PlotConstructor extends ElementConstructor{ if(visited.get(adjId) == null && id2j.get(adjId) != null) { adjNode = id2j.get(adjId); - adjNode.put("priority", priority); + 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); @@ -178,9 +194,171 @@ public class PlotConstructor extends ElementConstructor{ } } + /* + //对于unknown的特殊处理 + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP + ",unknown_counter::number-SmallOrEqual=0,unknownReply::match-Keyword=null", + "match", + "{lastReply-2}", + " ", + "unknown_counter:+1" + ); + 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); + + + + + } + + + 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; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("priority", 0); + root.put("taskName", id); + root.put("taskStep", 0); + + + Queue queue = new LinkedList(); + + queue.add(root); + + while(!queue.isEmpty()){ + node = queue.remove(); + id = (String)node.get("id"); + + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id ,true); + + /* + //查看是否存在多个子结点,如果有就是一个分支 + if(adjNodeList.size() > 1) + newBranch = true; + + //查看是否存在多个父节点 + if(revAdjList.get(id) != null) + manyParent = revAdjList.get(id).size() > 1; + + if(newBranch){ + //多个分支时nextTaskName为子结点的id名,不在这里设 + nextTaskStep = 1; + } + else{ + if(manyParent){ + nextTaskName = id; + nextTaskStep = 1; + priority++; + } + else{ + nextTaskName = taskName; + nextTaskStep = taskStep + 1; + } + } + */ + + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + extraHP = id + "::match-Keyword=" + 1; + + + 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"); + else + nextCondition = " "; + + + extraUK = id + ":" + "+1-<-" + nextId + ":" + "+1"; + + + //if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) + // 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), + "", extraHP, extraUK, + "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 && id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + queue.add(adjNode); + } + } + } + } + //unknown时的处理 + jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); diff --git a/src/processing/ConditionTableController.java b/src/processing/ConditionTableController.java index 3d6f8c8..e1fadce 100644 --- a/src/processing/ConditionTableController.java +++ b/src/processing/ConditionTableController.java @@ -18,12 +18,13 @@ public class ConditionTableController { 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){ - process.userConfigInit(userName, context); + userInfoController.userConfigInit(userName, context); } UserInfo userInfo = (UserInfo) context.getAttribute(userName); @@ -114,12 +115,13 @@ public class ConditionTableController { String dataPair[] = data.split("---"); String configLine = dataPair[0]; String conditionNameList[]; + UserInfoController userInfoController = new UserInfoController(); int id = Integer.parseInt(configId); - condition = process.buildCondition(condition, configLine); + condition = userInfoController.buildCondition(condition, configLine); if(context.getAttribute(userName) == null){ - process.userConfigInit(userName, context); + userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); @@ -135,13 +137,54 @@ 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]; - public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { + UserInfoController userInfoController = new UserInfoController(); + + + if(context.getAttribute(userName) == null){ + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + 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){ + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.remove(name); + + + + return true; + + } + + + public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { + UserInfoController userInfoController = new UserInfoController(); if(context.getAttribute(userName) == null){ - process.userConfigInit(userName, context); + userInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); @@ -177,6 +220,13 @@ public class ConditionTableController { if(!userinfo.extraInfo.get(info).equals("")) bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); } + + keyIter = userinfo.varInitialMap.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); + } + Iterator idIter = userinfo.id2config.keySet().iterator(); while (idIter.hasNext()) { int id = idIter.next(); diff --git a/src/processing/ProcessQuestion.java b/src/processing/ProcessQuestion.java index fce2fa9..9c4a77a 100644 --- a/src/processing/ProcessQuestion.java +++ b/src/processing/ProcessQuestion.java @@ -13,20 +13,26 @@ 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 ProcessQuestion { static Map activatedMap = new HashMap(); - static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; + + + 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 { @@ -43,256 +49,19 @@ public class ProcessQuestion { */ - /** - * 根据本地配置文件生成用户信息 - */ - public static void configInit(ServletContext context) throws IOException { - - String line; - - File dir = new File(CONFIG_DIR); - if(!dir.exists()) - dir.mkdir(); - for(File configFile: dir.listFiles()) { - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - String fileName = configFile.getName(); - UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); - - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ - System.out.println(userinfo.userName + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - } - - } - - public static void userConfigInit(String userName, ServletContext context) throws IOException { - String line; - File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); - if(!userFile.exists()){ - BufferedReader br = new BufferedReader(new StringReader("")); - UserInfo userinfo = new UserInfo(userName); - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ - System.out.println(userinfo.userName + "-post数据有误"); - e.printStackTrace(); - } - - }else { - FileReader reader = new FileReader(userFile); - BufferedReader br = new BufferedReader(reader); - UserInfo userinfo = new UserInfo(userName); - - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ - System.out.println(userinfo.userName + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - } - } - - - public static Condition buildCondition(Condition condition,String line){ - String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName; - - line = line.split("---")[0]; - - element = line.replace("\n","").split("\\|=\\>\\|"); - premises = element[0].split("\\|"); - //System.out.println("element[0]:" + element[0]); - feature = premises[2]; - cur_premises = premises[0].split(","); - history_premises = premises[1].split(","); - - if(premises.length < 4) - condition.auxiliaryPriority = 0; - else - condition.auxiliaryPriority = Integer.parseInt(premises[3].split("=")[1]); - - - next = element[1].split("\\|"); - if(next.length < 4) - return condition; - condition.answer = next[0].split("~"); - //condition.nextStep = next[1]; - //第二处 - condition.nextStep = next[1].split("=")[1]; - condition.id = Integer.parseInt(next[3].split("=")[1]); - condition.status = next[2].split("=")[1]; - condition.feature = feature; - - - //featureMap的构建 - features = feature.split(","); - for (String feat:features){ - if(feat.equals("") || feat.equals(" ")){ - continue; - }else if(feat.startsWith("updateKnowledge")){ - pair = feat.split("-<-",2); - condition.featureMap.put(pair[0], pair[1]); - }else if(feat.startsWith("post")){ - pair = feature.split("\\(",2); - url = pair[1]; - url = url.substring(0,url.length()-1); - condition.featureMap.put("post", url); - }else{ - condition.featureMap.put(feat, ""); - } - } - - ProcessQuestion.insertPremise(condition.currentPremise,cur_premises); - ProcessQuestion.insertPremise(condition.historyPremise,history_premises); - //满足条件越多,优先级越大 - condition.priority = condition.historyPremise.size()+condition.currentPremise.size(); - condition.activePriority = condition.priority; - /* - for(String premise:cur_premises){ - pair = premise.split("="); - condition.indexName.add(pair[0]); - } - */ - firstCnditionName = cur_premises[0]; - if(firstCnditionName.equals(" ")) - condition.indexName = "emptySet"; - else - condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; - return condition; - } - - - /** - * - * @param br - * @param userinfo - * @param overRide 覆盖之前的状态表 - * @return - * @throws IOException - */ - public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { - String line,infoName,extraElements[]; - HashMap> conditionTable = null; - - - if(overRide) { - conditionTable = new HashMap>(); - userinfo.id2condition.clear(); - userinfo.id2config.clear(); - userinfo.extraInfo.clear(); - userinfo.configStr = ""; - }else { - conditionTable = userinfo.conditionTable; - } - - List conditionList = null; - - - while ((line = br.readLine()) != null) { - if (line.trim().equals("")) - continue; - line = line.replace("\n",""); - //在用户信息中添加额外信息,如设为active的action - if(line.indexOf("-extraInfo-") != -1){ - extraElements = line.split("\\|"); - userinfo.extraInfo.put(extraElements[1],extraElements[2]); - }else { - Condition condition = new Condition(); - condition = buildCondition(condition, line); - conditionList = conditionTable.get(condition.indexName); - if (conditionList == null) - conditionList = new ArrayList(); - conditionList.add(condition); - conditionTable.put(condition.indexName, conditionList); - if(condition.id != 0) { - userinfo.id2config.put(condition.id, line); - userinfo.id2condition.put(condition.id, condition); - } - - } - } - userinfo.conditionTable = conditionTable; - - return userinfo; - } - - /** - * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) - * @param premiseMap 前提条件哈希表 - */ - public static void insertPremise(HashMap> premiseMap,String[] premisesString){ - String pair[]; - HashSet keyWordSet = null; - for(String premise:premisesString) { - // System.out.println(premise); - if (premise.equals("") || premise.equals(" ")) - continue; - pair = premise.split("=", 2); - keyWordSet = new HashSet(); - for (String keyword : pair[1].split("\\+")) - //为了处理条件不满足(为空)时的特殊情况, - if(keyword.equals("null")) keyWordSet.add(""); - else if(!keyword.equals("")) keyWordSet.add(keyword); - premiseMap.put(pair[0],keyWordSet); - } - } - - - /** - * 原为通过用户chat_key从数据库中获得用户名 - * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) - * 如果context中没有,就重新加载本地配置文件(即初始化) - * 初始化后还是没有就创建一个userinfo - * ------------- - * 修改后直接从request获得用户名,并从context根据用户名获得userinfo - * - * @param bot_name 用户名 - * @return 用户信息 - */ - public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { - /*根据数据库得到userName改为直接得到 - SqlHelper helper = new SqlHelper(); - String userName = helper.queryUsernameByKey(chat_key); - */ - String userName = bot_name; - UserInfo userinfo = null; - if(context.getAttribute(userName) == null){ - ProcessQuestion.userConfigInit(userName, context); - } - if(context.getAttribute(userName) == null){ - userinfo = new UserInfo(userName); - userinfo.conditionTable = new HashMap>(); - }else { - userinfo = (UserInfo) context.getAttribute(userName); - } - //helper.destroy(); - - return userinfo; - } public boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, StringBuffer curInfoRecord){ - String return_str = ""; + String return_str = "", k ; boolean debugFlag = false; + + //输出所有actionName的值 Iterator iit = curInfoPoint.keySet().iterator(); while(iit.hasNext()){ - String k = iit.next(); + k = iit.next(); // System.out.print(k+": "); @@ -316,7 +85,7 @@ public class ProcessQuestion { iit = curInfoPoint.keySet().iterator(); boolean unknown_flag = true; while(iit.hasNext()){ - String k = iit.next(); + k = iit.next(); String values[] = curInfoPoint.get(k); if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name") || k.equals("emptySet")) continue; @@ -412,7 +181,7 @@ public class ProcessQuestion { activatedMap.remove(condition.id); if(conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ - if(condition.feature.contains("activate")){ + if(condition.featureMap.containsKey("activate")){ 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)){ @@ -439,7 +208,7 @@ public class ProcessQuestion { String actionName,keywords[],keyword,comparePair[],cmpType,premiseStr; HashSet keywordSet = null; - if(condition.feature.contains("match")){ + if(condition.featureMap.containsKey("match")){ Iterator it = condition.currentPremise.keySet().iterator(); while (flag && it.hasNext()) { premiseStr = it.next(); @@ -488,17 +257,25 @@ public class ProcessQuestion { } + /** + * 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) + * @param keyword + * @param cmpType 比较类型 + * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 + * @return 返回匹配或者不匹配 + */ public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet){ boolean flag = true; String operator = ""; - String splitPair[] = cmpType.split("-"); - if (splitPair.length > 1){ - operator = splitPair[1]; - cmpType = splitPair[0]; - } - 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; @@ -515,13 +292,13 @@ public class ProcessQuestion { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } } - if(operator.equals("Bigger")) + if (operator.equals("Bigger")) flag = candidateA > candidateB; else if (operator.equals("BiggerOrEqual")) flag = candidateA >= candidateB; @@ -530,19 +307,19 @@ public class ProcessQuestion { else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; - } else if (cmpType.equals("time")){ - long candidateA,candidateB = 0; + } else if (cmpType.equals("time")) { + long candidateA, candidateB = 0; candidateA = MyFunc.transferToMillisecond(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } - if(operator.equals("Early")) + if (operator.equals("Early")) flag = candidateA < candidateB; - else if(operator.equals("Later")) + else if (operator.equals("Later")) flag = candidateA > candidateB; @@ -553,8 +330,8 @@ public class ProcessQuestion { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } @@ -565,8 +342,8 @@ public class ProcessQuestion { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } @@ -577,8 +354,8 @@ public class ProcessQuestion { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } @@ -589,46 +366,50 @@ public class ProcessQuestion { int candidateA = 0; int candidateB = 0; candidateA = Integer.parseInt(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = Integer.parseInt(k); break; } } flag = candidateA <= candidateB; - } else if (cmpType.equals("timeEarly")){ - long candidateA,candidateB = 0; + } else if (cmpType.equals("timeEarly")) { + long candidateA, candidateB = 0; candidateA = MyFunc.transferToMillisecond(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } flag = candidateA < candidateB; - } else if (cmpType.equals("timeLater")){ - long candidateA,candidateB = 0; + } else if (cmpType.equals("timeLater")) { + long candidateA, candidateB = 0; candidateA = MyFunc.transferToMillisecond(keyword); - for(String k: keywordSet){ - if(!k.equals("")) { + for (String k : keywordSet) { + if (!k.equals("")) { candidateB = MyFunc.transferToMillisecond(k); break; } } flag = candidateA > candidateB; - } else if (cmpType.equals("any")){ - if(keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + } else if (cmpType.equals("any")) { + if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 flag = false; - }else { + } else { flag = false; } + } catch (IndexOutOfBoundsException e){ + System.out.println("配置文件格式有误"); + e.printStackTrace(); }catch (Exception e){ + System.out.println("操作符有误"); e.printStackTrace(); flag = false; } @@ -645,36 +426,37 @@ public class ProcessQuestion { public Solution getSolution(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { Iterator it = curInfoPoint.keySet().iterator(); - String actionName; + 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()); - System.out.println("feature="+ansCondition.feature); //post关键字 - if(ansCondition.feature.contains("post")){ + if(ansCondition.featureMap.containsKey("post")){ ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); //nextNext关键字 - }else if(ansCondition.feature.contains("newNext")){ + }else if(ansCondition.featureMap.containsKey("newNext")){ ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); - }else if (ansCondition.feature.contains("return-1")){ + //上一步 + }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.feature.contains("return-0")){ + //停留 + }else if (ansCondition.featureMap.containsKey("return-0")){ String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - ans.setNext("nextStep=" + activeList[activeList.length - 1]); + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + //激活 }else if (ansCondition.featureMap.containsKey("activate")){ String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) @@ -685,7 +467,7 @@ public class ProcessQuestion { } //updateKnowledge关键字 - if (ansCondition.feature.contains("updateKnowledge")){ + if (ansCondition.featureMap.containsKey("updateKnowledge")){ updateKnowledge(ansCondition, historyInfoPoint); } @@ -696,6 +478,7 @@ public class ProcessQuestion { try { + /* it = historyInfoPoint.keySet().iterator(); String keyword1, keyword2; while (it.hasNext()) { @@ -709,6 +492,25 @@ public class ProcessQuestion { 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(); @@ -718,7 +520,7 @@ public class ProcessQuestion { } public void infoTransition(Map curInfoPoint, Map historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag){ - //将当前信息点更新至历史信息点,并且替换答案中的相应变量,变量结构为{xxx-1}或者{xxx-2} + //将当前信息点更新至历史信息点 Iterator it = curInfoPoint.keySet().iterator(); String actionName, lastReply; String next = ans.getNext().split("=")[1]; @@ -743,7 +545,6 @@ public class ProcessQuestion { historyInfoPoint.put(actionName, keyword1); else if (keyword2 != null && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); - } @@ -757,7 +558,13 @@ public class ProcessQuestion { } - + /** + * 在新平台添加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; @@ -777,12 +584,14 @@ public class ProcessQuestion { 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()){ @@ -803,27 +612,17 @@ public class ProcessQuestion { * @param ansCondition 满足条件最多的condition(配置文件的某一行) */ public Solution postToServer(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint) throws IOException { - String url = null,features[] = ansCondition.feature.trim().split(","),elem[], subElem[], key, postType = "all"; + String url = null,elem[], subElem[], key, postType = "all"; Map infoMap = new HashMap(); List pairList = new ArrayList(); Iterator k_iter = null; - for(String feature:features){ - elem = feature.split("\\("); - if(elem[0].contains("post")){ - url = elem[elem.length-1]; - url = url.substring(0,url.length()-1); - - subElem = elem[0].split("::"); - if(subElem.length == 1) - postType = "all"; - else - postType = subElem[1]; - } - } + 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(); @@ -831,25 +630,24 @@ public class ProcessQuestion { //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); } + k_iter = historyInfoPoint.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next(); if(historyInfoPoint.get(key) != "") //infoMap.put(key + "_his", historyInfoPoint.get(key)); pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - } + //提交类型为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])); - - //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); } + k_iter = ansCondition.historyPremise.keySet().iterator(); while(k_iter.hasNext()){ key = k_iter.next().split("::")[0]; @@ -857,20 +655,14 @@ public class ProcessQuestion { pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); //infoMap.put(key + "_his", historyInfoPoint.get(key)); } - } + HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; String keyName = null; - /* - JSONObject jsonParam = new JSONObject(); - jsonParam.put("curInfoPoint", infoMap); - jsonParam.put("historyInfoPoint", historyInfoPoint); - StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题 - entity.setContentEncoding("UTF-8"); - */ + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); @@ -885,21 +677,21 @@ public class ProcessQuestion { while (kit.hasNext()) { keyName = kit.next(); if (keyName.equals("process")) { - ans.setNext("nextStep=" + jobj.get(keyName)); + 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.setAnswer(ans.getAnswer().replace("{" + keyName + "}", jobj.getString(keyName))); historyInfoPoint.put(keyName, jobj.getString(keyName)); } } } else { - ans.setAnswer("api处理出错!"); + ans.setAnswer(API_ERROR); } }catch (Exception e){ e.printStackTrace(); - ans.setNext("提交失败了:"+url); + ans.setNext(POST_ERROR + url); } return ans; @@ -953,62 +745,62 @@ public class ProcessQuestion { } public void updateKnowledge(Condition condition, Map historyInfoPoint) throws ParseException { - String features[] = condition.feature.split(","); - String pair[],keyword; - for(String feature: features){ - if (feature.contains("updateKnowledge")){ - for (String knowledge: feature.split("-<-")){ - pair = knowledge.split(":"); - keyword = historyInfoPoint.get(pair[0]); - - if(pair.length > 1) { - try { - //做数字加法 - if (pair[1].startsWith("+")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(pair[1].substring(1)); - pair[1] = MyFunc.transferToStandardTime(time + (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(pair[1].substring(1)); - pair[1] = String.valueOf(number + offset); - } - //做数字减法 - } else if (pair[1].startsWith("-")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(pair[1].substring(1)); - pair[1] = MyFunc.transferToStandardTime(time - (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(pair[1].substring(1)); - pair[1] = String.valueOf(number - offset); - } - //做字符串累加 - } else if (pair[1].startsWith("str+")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - pair[1] = keyword + pair[1].substring(4); - //做字符串删除 - } else if (pair[1].startsWith("str-")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - pair[1] = keyword.replace(pair[1].substring(4), ""); - } - }catch (Exception e){ - e.printStackTrace(); - continue; - } - historyInfoPoint.put(pair[0], pair[1]); + 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); } + + + } diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java new file mode 100644 index 0000000..5977e72 --- /dev/null +++ b/src/processing/UserInfoController.java @@ -0,0 +1,285 @@ +package processing; + +import entity.Condition; +import entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.*; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +public class UserInfoController { + + static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; + static String FILE_ERROR = ".txt文件有误"; + + + /** + * 根据本地配置文件生成用户信息 + */ + public static void configInit(ServletContext context) throws IOException { + + String line; + + File dir = new File(CONFIG_DIR); + if(!dir.exists()) + dir.mkdir(); + for(File configFile: dir.listFiles()) { + + FileReader reader = new FileReader(configFile); + BufferedReader br = new BufferedReader(reader); + String fileName = configFile.getName(); + UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); + + try { + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.userName,userinfo); + }catch(Exception e){ + System.out.println(userinfo.userName + FILE_ERROR); + e.printStackTrace(); + } + + reader.close(); + br.close(); + } + + } + + public static void userConfigInit(String userName, ServletContext context) throws IOException { + String line; + File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); + if(!userFile.exists()){ + BufferedReader br = new BufferedReader(new StringReader("")); + UserInfo userinfo = new UserInfo(userName); + try { + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.userName,userinfo); + }catch(Exception e){ + System.out.println(userinfo.userName + FILE_ERROR); + e.printStackTrace(); + } + + }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){ + System.out.println(userinfo.userName + FILE_ERROR); + e.printStackTrace(); + } + + reader.close(); + br.close(); + } + } + + + public static Condition buildCondition(Condition condition, String line){ + String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName; + + + try { + line = line.split("---")[0]; + + element = line.replace("\n", "").split("\\|=\\>\\|"); + premises = element[0].split("\\|"); + //System.out.println("element[0]:" + element[0]); + feature = premises[2]; + cur_premises = premises[0].split(","); + history_premises = premises[1].split(","); + + if (premises.length < 4) + condition.auxiliaryPriority = 0; + else + condition.auxiliaryPriority = Integer.parseInt(premises[3].split("=")[1]); + + + next = element[1].split("\\|"); + if (next.length < 4) + return condition; + condition.answer = next[0].split("~"); + //condition.nextStep = next[1]; + //第二处 + condition.nextStep = next[1].split("=")[1]; + condition.id = Integer.parseInt(next[3].split("=")[1]); + condition.status = next[2].split("=")[1]; + + + //featureMap的构建 + features = feature.split(","); + for (String feat : features) { + if (feat.equals("") || feat.equals(" ")) { + continue; + } else if (feat.startsWith("updateKnowledge")) { + String[] knowledge = feat.split("-<-"); + int length = knowledge.length; + condition.featureMap.put("updateKnowledge", ""); + for (int i = 1; i < length; i++) { + if(knowledge[i].equals("") || knowledge[i].equals(" ")) + continue; + + pair = knowledge[i].split(":"); + condition.updateKnowledge.put(pair[0], pair[1]); + } + } else if (feat.startsWith("post")) { + pair = feature.split("\\(", 2); + url = pair[1]; + url = url.substring(0, url.length() - 1); + pair = pair[0].split("::"); + condition.featureMap.put("post", url + "|" + pair[1]); + } else { + condition.featureMap.put(feat, ""); + } + } + + + insertPremise(condition.currentPremise,cur_premises); + insertPremise(condition.historyPremise,history_premises); + //满足条件越多,优先级越大 + condition.priority = condition.historyPremise.size()+condition.currentPremise.size(); + condition.activePriority = condition.priority; + /* + for(String premise:cur_premises){ + pair = premise.split("="); + condition.indexName.add(pair[0]); + } + */ + firstCnditionName = cur_premises[0]; + if(firstCnditionName.equals(" ")) + condition.indexName = "emptySet"; + else + condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; + }catch (IndexOutOfBoundsException e){ + e.printStackTrace(); + System.out.println("文本格式有误"); + } + return condition; + } + + + /** + * + * @param br + * @param userinfo + * @param overRide 覆盖之前的状态表 + * @return + * @throws IOException + */ + public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { + String line,infoName,extraElements[]; + HashMap> conditionTable = null; + + //是否覆盖原有的数据 + if(overRide) { + conditionTable = new HashMap>(); + userinfo.id2condition.clear(); + userinfo.id2config.clear(); + userinfo.configStr = ""; + }else { + conditionTable = userinfo.conditionTable; + } + + List conditionList = null; + + + while ((line = br.readLine()) != null) { + try { + if (line.trim().equals("")) + continue; + line = line.replace("\n", ""); + //在用户信息中添加额外信息,如设为active的action + if (line.contains("extraInfo")) { + extraElements = line.split("\\|", -1); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + } else if (line.contains("varInitial")) { + extraElements = line.split("\\|", -1); + userinfo.varInitialMap.put(extraElements[1], extraElements[2]); + } else { + Condition condition = new Condition(); + condition = buildCondition(condition, line); + conditionList = conditionTable.get(condition.indexName); + if (conditionList == null) + conditionList = new ArrayList(); + conditionList.add(condition); + conditionTable.put(condition.indexName, conditionList); + if (condition.id != 0) { + userinfo.id2config.put(condition.id, line); + userinfo.id2condition.put(condition.id, condition); + } + + } + } catch(ArrayIndexOutOfBoundsException e){ + System.out.println("数据格式有误"); + e.printStackTrace(); + } catch(Exception e){ + e.printStackTrace(); + } + } + + userinfo.conditionTable = conditionTable; + + return userinfo; + } + + /** + * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) + * @param premiseMap 前提条件哈希表 + */ + public static void insertPremise(HashMap> premiseMap, String[] premisesString){ + String pair[]; + HashSet keyWordSet = null; + for(String premise:premisesString) { + // System.out.println(premise); + if (premise.equals("") || premise.equals(" ")) + continue; + pair = premise.split("=", 2); + keyWordSet = new HashSet(); + for (String keyword : pair[1].split("\\+")) + //为了处理条件不满足(为空)时的特殊情况, + if(keyword.equals("null")) keyWordSet.add(""); + else if(!keyword.equals("")) keyWordSet.add(keyword); + premiseMap.put(pair[0],keyWordSet); + } + } + + + /** + * 原为通过用户chat_key从数据库中获得用户名 + * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) + * 如果context中没有,就重新加载本地配置文件(即初始化) + * 初始化后还是没有就创建一个userinfo + * ------------- + * 修改后直接从request获得用户名,并从context根据用户名获得userinfo + * + * @param bot_name 用户名 + * @return 用户信息 + */ + public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { + /*根据数据库得到userName改为直接得到 + SqlHelper helper = new SqlHelper(); + String userName = helper.queryUsernameByKey(chat_key); + */ + String userName = bot_name; + UserInfo userinfo = null; + if(context.getAttribute(userName) == null){ + userConfigInit(userName, context); + } + if(context.getAttribute(userName) == null){ + userinfo = new UserInfo(userName); + userinfo.conditionTable = new HashMap>(); + }else { + userinfo = (UserInfo) context.getAttribute(userName); + } + //helper.destroy(); + + + return userinfo; + } +} diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 22689d2..1091be9 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -5,12 +5,11 @@ import com.alibaba.fastjson.JSONObject; import db.SqlHelper; import entity.Condition; import entity.UserInfo; -import gameDesign.ElementConstructor; -import gameDesign.MapConstructor; -import gameDesign.PlotConstructor; +import gameDesign.*; import processing.MyFunc; import processing.ProcessQuestion; import processing.ConditionTableController; +import processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -24,13 +23,14 @@ import java.io.PrintWriter; import java.io.StringReader; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; @WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"}) public class GameDesignServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Integer botId; - String userName = null, mergedConfigText = ""; + Integer botId, projectId, dataId; + String userName = null, moduleName; ServletContext context = this.getServletContext(); boolean flag; SqlHelper helper = null; @@ -47,56 +47,73 @@ public class GameDesignServlet extends HttpServlet { String jsonStr = MyFunc.readJSONString(request); - if(jsonStr != null && !jsonStr.equals("")){ JSONObject jsonObject = JSONObject.parseObject(jsonStr); - botId = (Integer)jsonObject.get("botId"); - userName = (String)jsonObject.get("userName"); - //moduleType = (String)jsonObject.get("moduleType"); - List idGroup = JSONArray.parseArray(jsonObject.getJSONArray("configIdGroup").toJSONString(), Integer.class); + dataId = (Integer)jsonObject.get("id"); + JSONObject gameElements = helper.queryGameElementsByBotId(dataId); + botId = (Integer)gameElements.get("botId"); + userName = (String)gameElements.get("userName"); - /* - 假设重新重新建用户信息 + //假设重新重新建用户信息 if(context.getAttribute(userName) == null){ - ProcessQuestion.userConfigInit(userName, context); + UserInfoController.userConfigInit(userName, context); } UserInfo userinfo = (UserInfo) context.getAttribute(userName); - */ - UserInfo userinfo = new UserInfo(userName); + + + //UserInfo userinfo = new UserInfo(userName); //清空之前生成的配置条目 - if(idGroup.size() > 0) { - try { - flag = clearOldConfig(botId, idGroup, userinfo, helper); - } catch (SQLException e) { - e.printStackTrace(); - } + try { + flag = clearOldConfig(botId, userinfo, helper); + } catch (SQLException e) { + System.out.println("清空旧数据失败"); + e.printStackTrace(); } - for(String moduleType:jsonObject.parseArray(jsonObject.getJSONArray("moduleType").toJSONString(), String.class)) { - switch (moduleType) { + + Iterator moduleIter = gameElements.keySet().iterator(); + StringBuffer mergedConfigText = new StringBuffer(); + while(moduleIter.hasNext()) { + moduleName = moduleIter.next(); + switch (moduleName) { case "map": constructor = new MapConstructor(helper, botId); break; - case "plot": + case "plots": constructor = new PlotConstructor(helper, botId); break; + case "goods": + constructor = new ItemConstructor(helper, botId); + break; + case "globalVarialbe": + constructor = new GlobalVariableConstructor(helper, botId); + break; + case "npc": + constructor = new CharacterConstructor(helper, botId); + break; + default: + continue; } - constructor.construct(jsonObject); + System.out.println(moduleName); + constructor.construct(gameElements, userinfo); //先清空再插入 idList.clear(); - helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList); - constructor.generateConfigText(idList); - mergedConfigText += constructor.getConfigText(); + if(moduleName.equals("map") || moduleName.equals("plots")) { + helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList); + constructor.generateConfigText(idList); + } + mergedConfigText.append(constructor.getConfigText()); + } - StringReader sr = new StringReader(mergedConfigText); + StringReader sr = new StringReader(mergedConfigText.toString()); BufferedReader br = new BufferedReader(sr); - ProcessQuestion.buildUserInfo(br, userinfo, true); + UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(userName, userinfo); ConditionTableController.writeConfigText(userName, userinfo); helper.destroy(); @@ -114,10 +131,9 @@ public class GameDesignServlet extends HttpServlet { } - public boolean clearOldConfig(int botId, List idGroup, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { - boolean deleteFlag = helper.deleteConfigByIdGroup(botId, idGroup); - boolean deleteFlag2 = ConditionTableController.batchDeleteConfig(userInfo.userName, idGroup, userInfo); + public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { + boolean deleteFlag = helper.deleteConfigByBotId(botId); - return deleteFlag && deleteFlag2; + return deleteFlag; } } diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 304c3f4..91912bb 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -6,6 +6,7 @@ import entity.UserInfo; import processing.ChatCacheController; import processing.MyFunc; import processing.ProcessQuestion; +import processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -25,6 +26,8 @@ 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()); @@ -45,16 +48,16 @@ public class GetAnswerServlet extends HttpServlet { UserInfo userinfo = null; + UserInfoController uiController = new UserInfoController(); try { //userinfo = process.userInfoQuery(chatKey,context); //从servlet根据用户名查询用户信息 - userinfo = process.userInfoQuery(request.getParameter("bot_name"),context); + userinfo = uiController.userInfoQuery(request.getParameter("bot_name"),context); } catch (SQLException e) { - state = "没找到bot名?"; + state = NAME_MISSING_ERROR; e.printStackTrace(); } - //如果historyInfoPoint不存在,就新建一个 if(historyInfoPoint == null) { String k; @@ -64,7 +67,14 @@ public class GetAnswerServlet extends HttpServlet { k = iit.next(); historyInfoPoint.put(k,""); } + //变量初始化 + iit = userinfo.varInitialMap.keySet().iterator(); + while(iit.hasNext()){ + k = iit.next(); + historyInfoPoint.put(k, userinfo.varInitialMap.get(k)); + } } + //信息点预处理 debugFlag = process.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, curInfoRecord); @@ -115,6 +125,6 @@ public class GetAnswerServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - System.out.println("do get m ethod"); + System.out.println("do get method"); } } diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java index 121de20..1fe8840 100644 --- a/src/servlet/ReloadConfigServlet.java +++ b/src/servlet/ReloadConfigServlet.java @@ -3,6 +3,7 @@ package servlet; import entity.UserInfo; import processing.MyFunc; import processing.ProcessQuestion; +import processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -38,7 +39,7 @@ public class ReloadConfigServlet extends HttpServlet { BufferedReader br = new BufferedReader(reader); try { - userinfo = ProcessQuestion.buildUserInfo(br, userinfo, true); + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.userName,userinfo); }catch(Exception e){ flag = false; diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index 17dab86..4ec098e 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -4,6 +4,7 @@ import entity.Condition; import entity.UserInfo; import processing.MyFunc; import processing.ProcessQuestion; +import processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -58,7 +59,7 @@ public class UpdateServlet extends HttpServlet { userinfo.configStr += line+"\n"; Condition condition = new Condition(); try { - condition = ProcessQuestion.buildCondition(condition,line); + condition = UserInfoController.buildCondition(condition,line); conditionList = userinfo.conditionTable.get(condition.indexName); if(conditionList == null) conditionList = new ArrayList(); diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java index ef8111d..056ea1a 100644 --- a/src/servlet/UpdateSingleConfigServlet.java +++ b/src/servlet/UpdateSingleConfigServlet.java @@ -3,6 +3,7 @@ package servlet; import entity.UserInfo; import processing.ProcessQuestion; import processing.ConditionTableController; +import processing.UserInfoController; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -35,9 +36,19 @@ public class UpdateSingleConfigServlet extends HttpServlet { case "delete_config": ConditionTableController.deleteConfig(userName, configId, data, context); break; + case "insert_variable": + ConditionTableController.updateVariable(userName, configId, data, context); + break; + case "delete_variable": + ConditionTableController.deleteVariable(userName, configId, data, context); + break; + case "update_variable": + ConditionTableController.updateVariable(userName, configId, data, context); + break; case "extra_info": ConditionTableController.updateExtraInfo(userName, data, context); break; + case "batch_update": batchUpdate(userName, data, context); @@ -81,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet { public void batchUpdate(String userName, String data, ServletContext context) throws IOException { BufferedReader br = new BufferedReader(new StringReader(data)); UserInfo userinfo = new UserInfo(userName); - userinfo = ProcessQuestion.buildUserInfo(br, userinfo, true); + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(userinfo.userName,userinfo); System.out.println("batchupdate"); }