From 3fa806523583fd1d613cdd97bd0c25cbcc01be72 Mon Sep 17 00:00:00 2001 From: hxw Date: Sat, 17 Nov 2018 09:07:12 +0800 Subject: [PATCH] routine --- src/GameEnvironment/DBUtil.java | 40 ++++++++++++++++++++++++++++++++++++++++ src/GameEnvironment/GameEnv.java | 469 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/GameEnvironment/Util.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/GameEnvironment/bean/Attr.java | 23 +++++++++++++++++++++++ src/GameEnvironment/bean/GoodsInstance.java | 31 +++++++++++++++++++++++++++++++ src/GameEnvironment/bean/NpcInstance.java | 33 +++++++++++++++++++++++++++++++++ src/GameEnvironment/bean/Place.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/GameEnvironment/bean/SuperClass.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/db/SqlHelper.java | 26 +++++++++++++++++++++++++- src/entity/ChatCache.java | 25 +++++++++++-------------- src/entity/JConfig.java | 25 ++----------------------- src/entity/UserInfo.java | 6 +++--- src/gameDesign/CharacterConstructor.java | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------- src/gameDesign/ItemConstructor.java | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++--------------- src/gameDesign/MapConstructor.java | 47 +++++++++++++++++++++-------------------------- src/gameDesign/PlotConstructor.java | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------- src/processing/ChatCacheController.java | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------ src/processing/LogWriter.java | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ src/processing/MyFunc.java | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/processing/QuestionMatcher.java | 533 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/UserInfoController.java | 36 ++++++++++++++++++------------------ src/processing/WorldController.java | 183 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------- src/servlet/GameDesignServlet.java | 28 ++++++++++++++++------------ src/servlet/GetAnswerServlet.java | 64 +++++++++++++++++++++++++--------------------------------------- src/servlet/ReloadChatCacheServlet.java | 19 +++++++++++++++++++ src/servlet/ReloadConfigServlet.java | 14 +++++++------- src/servlet/SaveChatCacheServlet.java | 40 ++++++++++++++++++++++++++++++++++++++++ src/servlet/UpdateServlet.java | 10 +++++----- src/servlet/UpdateSingleConfigServlet.java | 2 +- 29 files changed, 1700 insertions(+), 589 deletions(-) create mode 100644 src/GameEnvironment/DBUtil.java create mode 100644 src/GameEnvironment/GameEnv.java create mode 100644 src/GameEnvironment/Util.java create mode 100644 src/GameEnvironment/bean/Attr.java create mode 100644 src/GameEnvironment/bean/GoodsInstance.java create mode 100644 src/GameEnvironment/bean/NpcInstance.java create mode 100644 src/GameEnvironment/bean/Place.java create mode 100644 src/GameEnvironment/bean/SuperClass.java create mode 100644 src/processing/LogWriter.java create mode 100644 src/servlet/ReloadChatCacheServlet.java create mode 100644 src/servlet/SaveChatCacheServlet.java diff --git a/src/GameEnvironment/DBUtil.java b/src/GameEnvironment/DBUtil.java new file mode 100644 index 0000000..20e5af7 --- /dev/null +++ b/src/GameEnvironment/DBUtil.java @@ -0,0 +1,40 @@ +package GameEnvironment; + +import db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class DBUtil { + + public static String queryEnvJsonByBotName(String botName) throws Exception{ + Connection conn = C3p0Utils.getConnection(); + String sql = "select * from generate_json_tb where bot_name = ?"; + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + return result; + } + +} diff --git a/src/GameEnvironment/GameEnv.java b/src/GameEnvironment/GameEnv.java new file mode 100644 index 0000000..5f861ee --- /dev/null +++ b/src/GameEnvironment/GameEnv.java @@ -0,0 +1,469 @@ +package GameEnvironment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; + +import GameEnvironment.bean.Attr; +import GameEnvironment.bean.GoodsInstance; +import GameEnvironment.bean.SuperClass; +import GameEnvironment.bean.NpcInstance; +import GameEnvironment.bean.Place; + +public class GameEnv { + public Map npcClassIndex = null; + public Map npcInstanceIndex = null; + public Map goodsClassIndex = null; + public Map goodsInstanceIndex = null; + public Map placeIndex = null; + + public GameEnv(String botName) throws Exception { + + // 通过文件来初始化游戏环境 +// String fullName = "E:\\projects\\env\\"+projectId+".json"; +// +// String jsonString = Util.getJsonString(fullName); + + + + try { + String jsonString = "";//DBUtil.queryEnvJsonByBotName(botName); + Map gameProjectMap = JSON.parseObject(jsonString); + Map map = (Map) gameProjectMap.get("map"); + this.placeIndex = new HashMap(); + Map placeMapTmp = new HashMap(); + + for (String key : map.keySet()) { + Map one = (Map) map.get(key); + placeMapTmp.put(key, (String) one.get("name")); + Place place = new Place(); + place.setIntro((String) one.get("intro")); + place.setName((String) one.get("name")); + placeIndex.put((String) one.get("name"), place); + } + for (String tmp : placeMapTmp.keySet()) { + List ableGos = new ArrayList(); + List ableGoLongs = (List) ((Map) map.get(tmp)).get("canGo"); + for (int j = 0; j < ableGoLongs.size(); j++) { + String idName = String.valueOf(ableGoLongs.get(j)); + ableGos.add(placeIndex.get(placeMapTmp.get(idName))); + } + placeIndex.get(placeMapTmp.get(tmp)).setAbleGo(ableGos); + } + // npc + // npc class + Map npcClasses = (Map) gameProjectMap.get("npc"); + Map npcNames = new HashMap(); + this.npcClassIndex = new HashMap(); + this.npcInstanceIndex = new HashMap(); + for (String classKey : npcClasses.keySet()) { + Map one = (Map) npcClasses.get(classKey); + // class + Map oneClass = (Map) one.get("class"); + SuperClass npcClass = new SuperClass(); + npcClass.setName(classKey); + npcClass.setIntro((String) oneClass.get("intro")); + + List attrs = new ArrayList(); + for (String attrKey : oneClass.keySet()) { + if (attrKey != "intro") { + Attr attr = new Attr(); + attr.setName(attrKey); + attr.setValue((String) oneClass.get(attrKey)); + attrs.add(attr); + } + } + npcClass.setAttrs(attrs); + // instance + Map instances = (Map) one.get("instance"); + for (String instanceKey : instances.keySet()) { + Map instance = new HashMap(); + NpcInstance npcInstance = new NpcInstance(); + Map instanceAttrMap = (Map) instances.get(instanceKey); + npcNames.put(instanceKey, (String) instanceAttrMap.get("name")); + npcInstance.setName((String) instanceAttrMap.get("name")); + npcInstance.setIntro((String) instanceAttrMap.get("intro")); + List npcInstanceAttrs = new ArrayList(); + for (String instanceAttrKey : instanceAttrMap.keySet()) { + if (instanceAttrKey != "name" && instanceAttrKey != "intro" && instanceAttrKey != "placeId") { + Attr attr = new Attr(); + attr.setName(instanceAttrKey); + attr.setValue((String) instanceAttrMap.get(instanceAttrKey)); + npcInstanceAttrs.add(attr); + } + } + npcInstance.setAttrs(npcInstanceAttrs); + Place place = placeIndex.get(((Map) map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name")); + + List npcInstances = place.getNpcInstances(); + if (npcInstances == null) { + npcInstances = new ArrayList(); + } + npcInstances.add(npcInstance); + place.setNpcInstances(npcInstances); + List npcInstanceClass = npcClass.getNpcInstances(); + if (npcInstanceClass == null) { + npcInstanceClass = new ArrayList(); + } + npcInstanceClass.add(npcInstance); + npcClass.setNpcInstances(npcInstanceClass); + npcInstance.setPlace(place); + this.npcInstanceIndex.put((String) instanceAttrMap.get("name"), npcInstance); + } + this.npcClassIndex.put(classKey, npcClass); + } + // goods + Map goodsClasses = (Map) gameProjectMap.get("goods"); + this.goodsClassIndex = new HashMap(); + this.goodsInstanceIndex = new HashMap(); + for (String classKey : goodsClasses.keySet()) { + Map one = (Map) goodsClasses.get(classKey); + // class + Map oneClass = (Map) one.get("class"); + SuperClass goodsClass = new SuperClass(); + goodsClass.setName(classKey); + goodsClass.setIntro((String) oneClass.get("intro")); + + List attrs = new ArrayList(); + for (String attrKey : oneClass.keySet()) { + if (attrKey != "intro") { + Attr attr = new Attr(); + attr.setName(attrKey); + attr.setValue((String) oneClass.get(attrKey)); + attrs.add(attr); + } + } + goodsClass.setAttrs(attrs); + + // instance + Map instances = (Map) one.get("instance"); + + for (String instanceKey : instances.keySet()) { + Map instance = new HashMap(); + GoodsInstance goodsInstance = new GoodsInstance(); + Map instanceAttrMap = (Map) instances.get(instanceKey); + goodsInstance.setName((String) instanceAttrMap.get("name")); + goodsInstance.setIntro((String) instanceAttrMap.get("intro")); + List goodsInstanceAttrs = new ArrayList(); + for (String instanceAttrKey : instanceAttrMap.keySet()) { + if (instanceAttrKey != "placeId" && instanceAttrKey != "npcId" && instanceAttrKey != "name" && instanceAttrKey != "intro") { + Attr attr = new Attr(); + attr.setName(instanceAttrKey); + attr.setValue((String) instanceAttrMap.get(instanceAttrKey)); + goodsInstanceAttrs.add(attr); + } + } + goodsInstance.setAttrs(goodsInstanceAttrs); + Place place = placeIndex.get(((Map) map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name")); + goodsInstance.setPlace(place); + List placeGoodsInstances = place.getGoodsInstances(); + if (placeGoodsInstances == null) { + placeGoodsInstances = new ArrayList(); + } + placeGoodsInstances.add(goodsInstance); + place.setGoodsInstances(placeGoodsInstances); + + NpcInstance npc = this.npcInstanceIndex.get(npcNames.get(String.valueOf(instanceAttrMap.get("npcId")))); + goodsInstance.setNpc(npc); + List npcGoodsInstances = npc.getGoodsInstances(); + if (npcGoodsInstances == null) { + npcGoodsInstances = new ArrayList(); + } + npcGoodsInstances.add(goodsInstance); + npc.setGoodsInstances(npcGoodsInstances); + List goodsInstancesClass = goodsClass.getGoodsInstances(); + if (goodsInstancesClass == null) { + goodsInstancesClass = new ArrayList(); + } + goodsInstancesClass.add(goodsInstance); + goodsClass.setGoodsInstances(goodsInstancesClass); + this.goodsInstanceIndex.put((String) instanceAttrMap.get("name"), goodsInstance); + } + this.goodsClassIndex.put(classKey, goodsClass); + } + }catch(Exception e){ + System.out.println("处理有误"); + } + } + + /********************************************地点******************************************/ + // 周围有什么 + public List queryAroundAllBySite(String site){ + List queryGoods = this.queryAroundGoodsBySite(site); + List queryNpc = this.queryAroundNpcBySite(site); + queryGoods.addAll(queryNpc); + return queryGoods; + } + // 周围有什么人 + public List queryAroundNpcBySite(String site){ + Place place = this.placeIndex.get(site); + List queryNpc = new ArrayList(); + List npcInstances = place.getNpcInstances(); + if(npcInstances!=null) { + for(int i=0; i queryAroundGoodsBySite(String site){ + Place place = this.placeIndex.get(site); + List queryGoods = new ArrayList(); + List goodsInstances = place.getGoodsInstances(); + if(goodsInstances!=null) { + for(int i=0; i queryCanGoBySite(String site){ + List ableGoString = new ArrayList(); + Place place = this.placeIndex.get(site); + List ableGos = place.getAbleGo(); + for(int i=0; i queryPathBySite(String start, String destination){ + return null; + } + + /**************************************物品***************************/ + // 通过类和地点查询所有物品名称 + public List queryGoodsByClassAndSite(String className, String site){ + List goodsNames = new ArrayList(); + List placeGoodsInstances = this.placeIndex.get(site).getGoodsInstances(); + List goodsInstances = this.goodsClassIndex.get(className).getGoodsInstances(); + GoodsInstance goodsInstance = new GoodsInstance(); + for(int i=0; i attrs = goodsInstance.getAttrs(); + for(int i=0; i queryGoodsAllAttrByGoodsName(String name){ + List attrnames = new ArrayList(); + GoodsInstance goodsInstance = queryGoodsByGoodsName(name); + if(goodsInstance != null) { + List attrs = goodsInstance.getAttrs(); + for(int i=0; i queryNpcByClassAndSite(String className, String site){ + List npcNames = new ArrayList(); + List placeNpcInstances = this.placeIndex.get(site).getNpcInstances(); + List npcInstances = this.goodsClassIndex.get(className).getNpcInstances(); + NpcInstance npcInstance = new NpcInstance(); + for(int i=0; i attrs = npcInstance.getAttrs(); + for(int i=0; i queryNpcAttrsByNpcName(String name){ + List attrNames = new ArrayList(); + NpcInstance npcInstance = queryNpcByNpcName(name); + if(npcInstance != null) { + List attrs = npcInstance.getAttrs(); + for(int i=0; i goodsClassAttrs = goodsClass.getAttrs(); + GoodsInstance goodsInstance = new GoodsInstance(); + List goodsInstanceAttr = new ArrayList(); + goodsInstance.setName(names[2]); + goodsInstance.setIntro(goodsClass.getIntro()); + for(int i=0; i npcClassAttrs = npcClass.getAttrs(); + NpcInstance npcInstance = new NpcInstance(); + List npcInstanceAttr = new ArrayList(); + npcInstance.setName(names[2]); + npcInstance.setIntro(npcClass.getIntro()); + for(int i=0; i goodsInstancesByClass = this.goodsClassIndex.get(names[1]).getGoodsInstances(); + boolean goodsInstanceBoolean = false; + GoodsInstance goodsInstance = this.goodsInstanceIndex.get(names[2]); + for(int i=0; i attrs = goodsInstance.getAttrs(); + for(int j=0; j npcInstancesByClass = this.npcClassIndex.get(names[1]).getNpcInstances(); + boolean npcInstanceBoolean = false; + NpcInstance npcInstance = this.npcInstanceIndex.get(names[2]); + for(int i=0; i attrs = npcInstance.getAttrs(); + for(int j=0; j goodsInstances; + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + @Override + public String toString() { + String placeName = ""; + if(place != null) { + placeName = place.getName(); + } + int goodsInstancesSize = 0; + if(goodsInstances!=null) { + goodsInstancesSize = goodsInstances.size(); + } + return super.toString()+"NpcInstance [placeName=" + placeName + ", goodsInstancesSize=" + goodsInstancesSize + "]"; + } + +} diff --git a/src/GameEnvironment/bean/Place.java b/src/GameEnvironment/bean/Place.java new file mode 100644 index 0000000..aeb1db2 --- /dev/null +++ b/src/GameEnvironment/bean/Place.java @@ -0,0 +1,59 @@ +package GameEnvironment.bean; + +import java.util.List; + +public class Place { + private String name; + private String intro; + private List ableGo; + private List npcInstances; + private List goodsInstances; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAbleGo() { + return ableGo; + } + public void setAbleGo(List ableGo) { + this.ableGo = ableGo; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + @Override + public String toString() { + int ableGoSize = 0; + int npcInstancesSize = 0; + int goodsInstancesSize = 0; + if(ableGo != null) { + ableGoSize = ableGo.size(); + } + if(npcInstances != null) { + npcInstancesSize = npcInstances.size(); + } + if(goodsInstances != null) { + goodsInstancesSize = goodsInstances.size(); + } + return "Place [name=" + name + ", intro=" + intro + ", ableGo=" + ableGoSize + ", npcInstances=" + npcInstancesSize + + ", goodsInstances=" + goodsInstancesSize + "]"; + } + +} diff --git a/src/GameEnvironment/bean/SuperClass.java b/src/GameEnvironment/bean/SuperClass.java new file mode 100644 index 0000000..bc0029d --- /dev/null +++ b/src/GameEnvironment/bean/SuperClass.java @@ -0,0 +1,51 @@ +package GameEnvironment.bean; + +import java.util.List; + +public class SuperClass { + private String name; + private String intro; + private List attrs; + private List goodsInstances; + private List npcInstances; + + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAttrs() { + return attrs; + } + public void setAttrs(List attrs) { + this.attrs = attrs; + } + @Override + public String toString() { + int goodsInstanceSize = 0; + if(goodsInstances!=null) { + goodsInstanceSize = goodsInstances.size(); + } + return "SuperClass [name=" + name + ", intro=" + intro + "goodsInstancesSize="+goodsInstanceSize+", attrs=" + attrs + "]"; + } + +} diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 131dc07..869bf7e 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -292,7 +292,7 @@ public class SqlHelper { public JSONObject queryGameElementsByBotId(int id) { String sql = "select * from generate_json_tb where project_id = ?"; String userName = ""; - String result = "empty"; + String result = "{}"; try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, String.valueOf(id)); @@ -311,6 +311,28 @@ public class SqlHelper { } + public static String queryEnvJsonByBotName(String botName) throws SQLException { + String sql = "select * from generate_json_tb where bot_name = ?"; + Connection conn = C3p0Utils.getConnection(); + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) { String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; String userName = ""; @@ -365,4 +387,6 @@ public class SqlHelper { } + + } diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index ea972bc..bb13cc6 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -1,12 +1,15 @@ package entity; +import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import GameEnvironment.GameEnv; + public class ChatCache { private Map infoPoint = null; - private World world = null; + private GameEnv gameEnv = null; public Map getInfoPoint() { return infoPoint; @@ -16,26 +19,20 @@ public class ChatCache { this.infoPoint = infoPoint; } - public World getWorld() { - return world; + public GameEnv getGameEnv() { + return gameEnv; } - public void setWorld(World world) { - this.world = world; + public void setGameEnv(GameEnv gameEnv) { + this.gameEnv = gameEnv; } - public ChatCache(Map curInfoPoint, UserInfo userInfo) { - world = new World(); + public ChatCache(UserInfo userInfo) throws Exception { + gameEnv = new GameEnv(userInfo.botAccount); String k; infoPoint = new HashMap(); - Iterator iit = curInfoPoint.keySet().iterator(); - while (iit.hasNext()) { - k = iit.next(); - infoPoint.put(k, ""); - } - //变量初始化 - iit = userInfo.varInitialMap.keySet().iterator(); + Iterator iit = userInfo.varInitialMap.keySet().iterator(); while (iit.hasNext()) { k = iit.next(); infoPoint.put(k, userInfo.varInitialMap.get(k)); diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index a188fe8..957f903 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -124,29 +124,8 @@ public class JConfig { while (iit.hasNext()) { varName = iit.next(); varValue = knowledge.get(varName); - if(varName.startsWith("NPC")) { - - //当名字前为NPC或者items时,需要更新World的状态,所以要在更新信息前加上操作符 - if(varValue.startsWith("update:")){ - sb.append("-<-" + varName + ":" + "updateAttrByNPCName:" + varValue.substring(5)); - } else if(varValue.startsWith("insert:")){ - sb.append("-<-" + varName + ":" + "addNpc:" + varValue.substring(5)); - } else if(varValue.startsWith("delete")){ - sb.append("-<-" + varName + ":" + "deleteNpc:" + varValue.substring(5)); - } - - }else if(varName.startsWith("item_")){ - sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue); - if(varValue.startsWith("update:")){ - sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue.substring(5)); - } else if(varValue.startsWith("insert:")){ - sb.append("-<-" + varName + ":" + "addGoodsBase:" + varValue.substring(5)); - } else if(varValue.startsWith("delete")){ - sb.append("-<-" + varName + ":" + "deleteGoods:" + varValue.substring(5)); - } - }else { - sb.append("-<-" + varName + ":" + varValue); - } + sb.append("-<-" + varName + ":" + varValue); + } if (!extraKL.equals("")) { sb.append("-<-" + extraKL); diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java index 45cc825..7a2f007 100644 --- a/src/entity/UserInfo.java +++ b/src/entity/UserInfo.java @@ -7,10 +7,10 @@ import java.util.List; * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 */ public class UserInfo { - public UserInfo(String userName) { + public UserInfo(String botAccount) { this.conditionTable = new HashMap>(); this.configStr = ""; - this.userName = userName; + this.botAccount = botAccount; this.extraInfo = new HashMap() { { put("activeAction", " "); @@ -23,7 +23,7 @@ public class UserInfo { public HashMap> conditionTable; public String configStr; - public String userName; + public String botAccount; public HashMap extraInfo; public HashMap id2config; public HashMap id2condition; diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index 6c0c851..7ce50d4 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -6,6 +6,8 @@ import db.SqlHelper; import entity.JConfig; import entity.UserInfo; +import java.util.ArrayList; +import java.util.HashSet; import java.util.Iterator; import java.util.Map; @@ -18,34 +20,68 @@ public class CharacterConstructor extends ElementConstructor { } public void construct(JSONObject jsonObject, UserInfo userinfo) { - String category, name, description, attrName, attrValue; + String category, name, className, description, attrName, attrValue; JSONArray allNPC = jsonObject.getJSONArray("npc"); Map attribute = null; Iterator attrIter = null; - String conditionName1 = "wenzainali"; + HashSet classSet = new HashSet(); + + //与npc属性相关的所有condition + ArrayList relateConditions = new ArrayList(){ + { + add("wenzainali"); + add("shishenme"); + } + }; + //与npc类相关的所有condition + ArrayList classRelateConditions = new ArrayList(){ + { + add("know_exist_what"); + } + }; + String conditionValue = "哪里:人称", repValue; + StringBuffer keywords = new StringBuffer(); + StringBuffer classKeywords = new StringBuffer(); - 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); - varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); - repValue = conditionValue.replace("人称", name); - jConfig = new JConfig( - conditionName1 + "::match-Keyword=" + repValue, " ", - "match,return-0", "{NPC_reply-2}", "yaobuyao", "NPC_reply:queryAttrByNPCName:" + conditionName1 - ); - jConfigList.add(jConfig); - - } + for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { + + name = (String) character.get("name"); + className = (String)character.get("class"); + + if(!classSet.contains(className)) { + classSet.add(className); + classKeywords.append("+周围:" + className + "+附近" + className); } + + + attribute = JSONObject.toJavaObject(character.getJSONObject("attr"), Map.class); + attrIter = attribute.keySet().iterator(); + repValue = conditionValue.replace("人称", name); + keywords.append("+" + repValue); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + + } + System.out.println(name); + + } + //根据根据NPC名字和属性查询属性值 + for(String conditionName: relateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywords, " ", + "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName + ); + jConfigList.add(jConfig); + } + //根据根据NPC类别和地点属性查询所有NPC实例 + for(String conditionName: relateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + classKeywords, " ", + "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAroundNpcByClassName:" + conditionName + ); + jConfigList.add(jConfig); } } } diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index 58f41bd..a0b9383 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -6,6 +6,8 @@ import db.SqlHelper; import entity.JConfig; import entity.UserInfo; +import java.util.ArrayList; +import java.util.HashSet; import java.util.Iterator; import java.util.Map; @@ -20,38 +22,74 @@ public class ItemConstructor extends ElementConstructor { public void construct(JSONObject jsonObject, UserInfo userinfo) { - String category, name, description, attrName, attrValue; + String category, name, className, description, attrName, attrValue; JSONArray goods = jsonObject.getJSONArray("goods"); Map attribute = null; Iterator attrIter = null; - String conditionName1 = "nums"; - String keywords1 = ""; + HashSet classSet = new HashSet(); + + //与物品属性查询相关的所有condition + ArrayList attrRelateConditions = new ArrayList(){ + { + add("nums"); + add("shishenme"); + } + }; + //与物品类查询相关的所有condition + ArrayList classRelateConditions = new ArrayList(){ + { + add("know_exist_what"); + } + }; + + StringBuffer keywords = new StringBuffer(); + StringBuffer classKeywords = new StringBuffer(); for (JSONObject good : goods.toJavaList(JSONObject.class)) { + name = (String) good.get("name"); + className = (String)good.get("class"); + + if(!classSet.contains(className)) { + classSet.add(className); + //添加周围有什么士兵等关于类别的关键词 + classKeywords.append("+周围:" + className + "+附近" + className); + } - 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); + attribute = JSONObject.toJavaObject(good.getJSONObject("attr"), Map.class); attrIter = attribute.keySet().iterator(); while (attrIter.hasNext()) { attrName = attrIter.next(); attrValue = attribute.get(attrName); - varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); - keywords1 += "+" + name + ":" + attrName ; + keywords.append( "+" + name + ":" + attrName) ; } - } + + + } + + //根据根据物品名字和属性查询属性值 + for(String conditionName : attrRelateConditions) { jConfig = new JConfig( - conditionName1 + "::match-Keyword=" + keywords1, " ", + conditionName + "::match-Include=" + keywords, " ", "match,return-0", - "{items_reply-2}", + "{goods_query-2}", " ", - "items_reply:queryAttrByGoodsName:" + conditionName1 + "goods_query:queryAttrByGoodsName:" + conditionName ); jConfigList.add(jConfig); } + + //根据类名和地点查询所有实例 + for(String conditionName : attrRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + classKeywords, " ", + "match,return-0", + "{goods_query-2}", + " ", + "goods_query:queryAroundGoodsByClassName:" + conditionName + ); + jConfigList.add(jConfig); + } + } } diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index 0ccdce8..95001f5 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -6,8 +6,6 @@ import db.SqlHelper; import entity.JConfig; import entity.UserInfo; -import java.io.BufferedReader; -import java.io.StringReader; import java.util.*; public class MapConstructor extends ElementConstructor { @@ -66,7 +64,7 @@ public class MapConstructor extends ElementConstructor { JSONObject map = jsonObject.getJSONObject("map"); Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); JSONArray locations = map.getJSONArray("locations"); - String botName = (String)jsonObject.get("botName"); + String userName = (String)jsonObject.get("userName"); this.locations = locations; this.question2keyword = question2keyword; //通过邻接表构造邻接矩阵 @@ -78,8 +76,10 @@ public class MapConstructor extends ElementConstructor { floyd.printPath(matrix, locationNum); generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject); - generateWhereIam(jsonObject, botName); + generateWhereIam(jsonObject, userName); generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); + generateSurroundingItem(); + generateSurroundingPeople(); } @@ -91,7 +91,7 @@ public class MapConstructor extends ElementConstructor { String conditionKeywords = "botName:哪里+botName:哪"; String zainaliKeywords = conditionKeywords.replace("botName", botName); jConfig = new JConfig( - conditionName + "::match-Keyword=" + zainaliKeywords, " ", + conditionName + "::match-Include=" + zainaliKeywords, " ", "match", "你在{site-2}", "yaobuyao", "" ); jConfigList.add(jConfig); @@ -110,7 +110,6 @@ public class MapConstructor extends ElementConstructor { String conditionKeywords = "去:地点"; String placeA, placeB, descriptionB, placeKeywords, text, pathNode; - String want_know_zenmezuoKeywords = question2keyword.get("want_know_zenmezuo"); for (int i = 0; i < locationNum; i++) { @@ -123,7 +122,7 @@ public class MapConstructor extends ElementConstructor { if (i == j) { jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, "match", "你已经在" + placeB + "了", "yaobuyao", "" ); jConfigList.add(jConfig); @@ -132,7 +131,7 @@ public class MapConstructor extends ElementConstructor { ; if (pathMatirx[i][j] == 1) { jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, "match", placeB + "就在附近哦", "yaobuyao", "" ); jConfigList.add(jConfig); @@ -146,7 +145,7 @@ public class MapConstructor extends ElementConstructor { } jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", "" ); jConfigList.add(jConfig); @@ -176,15 +175,11 @@ public class MapConstructor extends ElementConstructor { } jConfig = new JConfig( - conditionName + "::match-Keyword=" + conditionKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + conditionKeywords, "site::match-Include=" + placeA, "match", "你可以去" + pathNode, "yaobuyao", "" ); jConfigList.add(jConfig); - - } - - } @@ -209,7 +204,7 @@ public class MapConstructor extends ElementConstructor { if (i == j) { jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, "match", "你已经在" + placeB + "了", "yaobuyao", "" ); jConfigList.add(jConfig); @@ -220,13 +215,13 @@ public class MapConstructor extends ElementConstructor { //如果两点相邻 if (pathMatirx[i][j] == 1) { jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA + "," + lastTaskCondition + "::match-Keyword=null" + "," + lastTaskReply + "::match-Keyword=null", + conditionName + "::match-Include=" + placeKeywords, + "site::match-Include=" + placeA + "," + lastTaskCondition + "::match-Include=null" + "," + lastTaskReply + "::match-Include=null", "match, reutrn-0", "地点尚未激活", "yaobuyao", "" ); jConfigList.add(jConfig); jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, "match", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeB + "-<-process-nextStep:var={" + lastTaskCondition +"-2}" ); jConfigList.add(jConfig); @@ -241,8 +236,8 @@ public class MapConstructor extends ElementConstructor { k = preTable[k][j]; } jConfig = new JConfig( - conditionName + "::match-Keyword=" + placeKeywords, - "site::match-Keyword=" + placeA, + conditionName + "::match-Include=" + placeKeywords, + "site::match-Include=" + placeA, "match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", "" ); jConfigList.add(jConfig); @@ -253,22 +248,22 @@ public class MapConstructor extends ElementConstructor { public void generateSurroundingPeople(){ String conditionName = "know_exist_what"; - String conditionKeywords = "周围:人"; + String conditionKeywords = "周围:人+附近:人"; jConfig = new JConfig( - conditionName + "::match-Keyword=" + conditionKeywords, " ", - "match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundNpcBySite:" + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:" ); jConfigList.add(jConfig); } public void generateSurroundingItem(){ String conditionName = "know_exist_what"; - String conditionKeywords = "周围:物品,周围:东西"; + String conditionKeywords = "周围:物品+周围:东西+附近:物品+附近:东西"; jConfig = new JConfig( - conditionName + "::match-Keyword=" + conditionKeywords, " ", - "match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundGoodsBySite:" + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:" ); jConfigList.add(jConfig); } diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index 83df7e4..69833ee 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -5,11 +5,15 @@ import com.alibaba.fastjson.JSONObject; import db.SqlHelper; import entity.JConfig; import entity.UserInfo; +import org.apache.http.message.BasicNameValuePair; +import processing.MyFunc; +import java.io.UnsupportedEncodingException; import java.util.*; public class PlotConstructor extends ElementConstructor { + String POST_URL = "http://localhost:1111/conditionProcess"; JSONArray plots = null; HashMap> adjList = new HashMap>(); @@ -26,23 +30,44 @@ public class PlotConstructor extends ElementConstructor { public void construct(JSONObject jsonObject, UserInfo userinfo) { JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"); + String start = (String) jsonObject.get("start"), startCondition; + JSONObject returnMessage = null; this.plots = plots; constructAdjList(plots); if(id2j.containsKey(start)) { - String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, start); - varInitialMap.put("unknownText", "你说啥?"); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); + JSONObject data = new JSONObject(); + startCondition = (String)id2j.get(start).get("conditionName"); + data.put("startCondition", startCondition); + data.put("botName_yhm", (String)jsonObject.get("botName")); + data.put("botName", (String)jsonObject.get("botName")); + data.put("botId", (Integer)jsonObject.get("botId")); + data.put("type", "game_plot_init"); + + userinfo.extraInfo.put("activeAction", startCondition); + try { + returnMessage = MyFunc.postJSON(POST_URL, data); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + if((Integer)returnMessage.get("status") == 1) { + + + String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, start); + varInitialMap.put("unknownText", "你说啥?"); + conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - BFSGenerate4(id2j.get(start), userinfo); + BFSGenerate4(id2j.get(start), userinfo); - varInitialMap.put(start, "1"); + varInitialMap.put(start, "1"); + }else { + System.out.println("剧情初始化失败"); + } } else { System.out.println("start剧情不存在"); @@ -180,9 +205,9 @@ public class PlotConstructor extends ElementConstructor { extraUK = taskName + ":" + (taskStep + 1); - extraHP = taskName + "::match-Keyword=" + taskStep; + extraHP = taskName + "::match-Include=" + taskStep; if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) - extraHP += "," + nextId + "::match-Keyword=null"; + extraHP += "," + nextId + "::match-Include=null"; extraUK += "-<-" + nextId + ":" + 1; jConfig = new JConfig( @@ -230,8 +255,8 @@ public class PlotConstructor extends ElementConstructor { //对于unknown的特殊处理 if (curUnknownText.equals("")) { jConfig = new JConfig( - conditionName + "::match-Keyword=unknown", - extraHP = taskName + "::match-Keyword=" + taskStep, + conditionName + "::match-Include=unknown", + extraHP = taskName + "::match-Include=" + taskStep, "match,return-0,post::all(" + CHITCHAT_URL + ")", " ", " ", @@ -339,7 +364,7 @@ public class PlotConstructor extends ElementConstructor { branchSize = branch.size(); //当两次出现unknown时给用户一下候选项 keywordOptions = ""; - extraHP = id + "::match-Keyword=" + 1; + extraHP = id + "::match-Include=" + 1; for (int i = 0; i < branchSize; i++) { @@ -401,7 +426,7 @@ public class PlotConstructor extends ElementConstructor { * @param userinfo */ public void BFSGenerate3(JSONObject root, UserInfo userinfo) { - String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition; boolean newBranch, manyParent; JSONObject node = null, branchNode = null, adjNode = null; @@ -415,6 +440,7 @@ public class PlotConstructor extends ElementConstructor { Queue queue = new LinkedList(); + System.out.println("rootId"); queue.add(root); @@ -475,9 +501,17 @@ public class PlotConstructor extends ElementConstructor { //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location; + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location; + + + + //测试用 + System.out.println(id); + extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}"; + + jConfig = new JConfig( JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), @@ -519,8 +553,8 @@ public class PlotConstructor extends ElementConstructor { //对于unknown的特殊处理 if (curUnknownText.equals("")) { jConfig = new JConfig( - conditionName + "::match-Keyword=unknown", - extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId, + conditionName + "::match-Include=unknown", + extraHP = "任务线_" + location + "进度::match-Include=" + parentId, "match,return-0,post::all(" + CHITCHAT_URL + ")", " ", " ", @@ -557,7 +591,7 @@ public class PlotConstructor extends ElementConstructor { * @param userinfo */ public void BFSGenerate4(JSONObject root, UserInfo userinfo) { - String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition; boolean newBranch, manyParent; JSONObject node = null, branchNode = null, adjNode = null; @@ -634,7 +668,8 @@ public class PlotConstructor extends ElementConstructor { //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Keyword=null"; + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}" + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1";; @@ -679,8 +714,8 @@ public class PlotConstructor extends ElementConstructor { //对于unknown的特殊处理 if (curUnknownText.equals("")) { jConfig = new JConfig( - conditionName + "::match-Keyword=unknown", - extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId, + conditionName + "::match-Include=unknown", + extraHP = "任务线_" + location + "进度::match-Include=" + parentId, "match,return-0,post::all(" + CHITCHAT_URL + ")", " ", " ", @@ -711,10 +746,13 @@ public class PlotConstructor extends ElementConstructor { @Override public void postProcessing(List idList){ - jConfig = new JConfig(" ", "", "activate", "", idList.get(idList.size()-2) + "," + idList.get(idList.size()-1), ""); + if (idList.size() != 0) { + jConfig = new JConfig(" ", "", "activate", "", idList.get(idList.size() - 2) + "," + idList.get(idList.size() - 1), ""); - jConfigList.add(jConfig); + jConfigList.add(jConfig); + } } + } diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index d0281b8..281beb7 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -1,15 +1,16 @@ package processing; +import GameEnvironment.GameEnv; +import com.alibaba.fastjson.JSON; import entity.ChatCache; import entity.UserInfo; -import entity.World; import javax.servlet.ServletContext; import java.io.*; +import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.Set; public class ChatCacheController { /** @@ -18,66 +19,66 @@ public class ChatCacheController { * * @return 历史信息点,对话过程中引擎提取的用户信息 */ - public static synchronized Map getChatCache(String chatKey, ServletContext context) { - - World world = new World(); - Map historyInfoPoint = null; - Map> chatCache = null; - if (context.getAttribute("chatCache") == null) { - chatCache = new HashMap>(); - context.setAttribute("chatCache", chatCache); - } else { - chatCache = (Map>) context.getAttribute("chatCache"); - } - String chatkey; - - - try { - historyInfoPoint = chatCache.get(chatKey); - //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - } catch (Exception e) { - - //可整合 - historyInfoPoint = null; - - } - - return historyInfoPoint; - } +// public static synchronized Map getChatCache(String chatKey, ServletContext context) { +// +// GameEnv gameEnv = new GameEnv(chatKey); +// Map historyInfoPoint = null; +// Map> chatCache = null; +// if (context.getAttribute("chatCache") == null) { +// chatCache = new HashMap>(); +// context.setAttribute("chatCache", chatCache); +// } else { +// chatCache = (Map>) context.getAttribute("chatCache"); +// } +// String chatkey; +// +// +// try { +// historyInfoPoint = chatCache.get(chatKey); +// //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); +// } catch (Exception e) { +// +// //可整合 +// historyInfoPoint = null; +// +// } +// +// return historyInfoPoint; +// } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ - public static synchronized void updateChatCache4Delete(ServletContext context) { - String chatKey; - long lastChatTime, now; - Map history = new HashMap(); - Map> chatCache = (Map>) context.getAttribute("chatCache"); - - - Iterator it = chatCache.keySet().iterator(); - while (it.hasNext()) { - chatKey = it.next(); - history = chatCache.get(chatKey); - lastChatTime = Long.valueOf(history.get("lastUpdateTime")); - now = System.currentTimeMillis(); - if (now - lastChatTime > 300000) { - it.remove(); - } - } - context.setAttribute("chatCache", chatCache); - } +// public static synchronized void updateChatCache4Delete(ServletContext context) { +// String chatKey; +// long lastChatTime, now; +// Map history = new HashMap(); +// Map> chatCache = (Map>) context.getAttribute("chatCache"); +// +// +// Iterator it = chatCache.keySet().iterator(); +// while (it.hasNext()) { +// chatKey = it.next(); +// history = chatCache.get(chatKey); +// lastChatTime = Long.valueOf(history.get("lastUpdateTime")); +// now = System.currentTimeMillis(); +// if (now - lastChatTime > 300000) { +// it.remove(); +// } +// } +// context.setAttribute("chatCache", chatCache); +// } /** * 根据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"; @@ -138,12 +139,12 @@ public class ChatCacheController { - public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, Map curInfoPoint, UserInfo userinfo) { + public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, UserInfo userinfo) throws Exception { Map chatCacheMap = null; ChatCache chatCache = null; if (context.getAttribute("chatCache") == null) { chatCacheMap = new HashMap(); - chatCacheMap.put(chatKey, new ChatCache(curInfoPoint, userinfo)); + chatCacheMap.put(chatKey, new ChatCache(userinfo)); context.setAttribute("chatCache", chatCacheMap); } else { chatCacheMap = (Map) context.getAttribute("chatCache"); @@ -154,13 +155,13 @@ public class ChatCacheController { try { chatCache = chatCacheMap.get(chatKey); if(chatCache == null){ - chatCache = new ChatCache(curInfoPoint, userinfo); + chatCache = new ChatCache(userinfo); chatCacheMap.put(chatKey, chatCache); } //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); } catch (Exception e) { //可整合 - chatCache = new ChatCache(curInfoPoint, userinfo); + chatCache = new ChatCache(userinfo); } @@ -197,14 +198,36 @@ public class ChatCacheController { /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ - public static synchronized void updateChatCache4Insert2(Map curInfoPoint, Map historyInfoPoint, World world, ServletContext context) { + public static synchronized void updateChatCache4Insert2(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context) { historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); Map keyCacheMap = (Map) context.getAttribute("chatCache"); - ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")[0]); + ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); chatCache.setInfoPoint(historyInfoPoint); - chatCache.setWorld(world); + chatCache.setGameEnv(gameEnv); context.setAttribute("chatCache", keyCacheMap); } + public static synchronized String saveChatCache(String chatKey, ServletContext context){ + Map chatCacheMap = (Map) context.getAttribute("chatCache"); + ChatCache chatCache = chatCacheMap.get(chatKey); + + if(chatCache == null){ + return "chat_key不存在或者已失效"; + }else { + String jChatCache = JSON.toJSONString(chatCache); + System.out.println(jChatCache); + + + + chatCache = JSON.parseObject(jChatCache,ChatCache.class); + System.out.println(chatCache.getInfoPoint().size()); + + return "成功"; + } + + + + } + } diff --git a/src/processing/LogWriter.java b/src/processing/LogWriter.java new file mode 100644 index 0000000..a560ce1 --- /dev/null +++ b/src/processing/LogWriter.java @@ -0,0 +1,49 @@ +package processing; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +public class LogWriter { + private PrintWriter recorder = null; + String PRINT_PATTERN = "%s" + + "----------------------------------------------------------------------------
"; + Map colerMap = new HashMap(){ + { + put(0, "black"); + put(1, "gray"); + put(2, "green"); + put(3, "red"); + } + }; + public LogWriter(String filePath, String fileName) throws IOException { + File file = new File(filePath + "/" + fileName + ".html"); + + if (!file.exists()) { + file.createNewFile(); + } + file.setReadable(true,false); + + FileWriter fw = new FileWriter(file, true); + //BufferedWriter bw = new BufferedWriter(fos, "UTF-8"); + //context.setAttribute("logWriter", bw); + + + BufferedWriter bw = new BufferedWriter(fw); + recorder = new PrintWriter(bw); + recorder.println("\n" + + "\n" + + "\n" + + " \n" + + " log\n" + + ""); + } + + public void record(String text, int level){ + recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), text)); + } + + public void close(){ + recorder.close(); + } +} diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java index 09ba3b5..5c2f4a8 100644 --- a/src/processing/MyFunc.java +++ b/src/processing/MyFunc.java @@ -1,7 +1,17 @@ package processing; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import entity.Solution; -import net.sf.json.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; @@ -9,7 +19,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Date; +import java.util.*; public class MyFunc { @@ -97,5 +107,41 @@ public class MyFunc { return true; } + public static JSONObject postJSON(String url, JSONObject data) throws UnsupportedEncodingException { + + JSONObject jobj = new JSONObject(); + + + + + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + String keyName = null; + + + StringEntity entity = new StringEntity(data.toJSONString(), "utf-8"); + + entity.setContentType("application/json; charset=utf-8"); + httpPost.setEntity(entity); + + try { + HttpResponse resp = client.execute(httpPost); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + + } else { + jobj.put("status", 0); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return jobj; + + } + } diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java index b89fc53..bf3a54a 100644 --- a/src/processing/QuestionMatcher.java +++ b/src/processing/QuestionMatcher.java @@ -1,9 +1,9 @@ package processing; +import GameEnvironment.GameEnv; import entity.Solution; import entity.Condition; import entity.UserInfo; -import entity.World; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; @@ -17,7 +17,6 @@ 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; @@ -34,18 +33,27 @@ public class QuestionMatcher { static String API_ERROR = "api处理过程中出错了"; static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); - public PrintWriter logWriter = null; + + + public LogWriter logWriter = null; public UserInfo userinfo = null; public ServletContext context = null; - public World world = null; - - public QuestionMatcher(PrintWriter logWriter, UserInfo userinfo, ServletContext context, World world) { + public GameEnv gameEnv = null; + public Map curInfoPoint = null; + public Map historyInfoPoint = null; + public WorldController worldController = null; + + public QuestionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv) { + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; this.logWriter = logWriter; this.userinfo = userinfo; this.context = context; - this.world = world; + this.gameEnv = gameEnv; + this.worldController = new WorldController(logWriter); } - /* + + /** public void updateDB(QuestionKeyWord qkw) throws SQLException { SqlHelper helper = new SqlHelper(); String result = helper.queryActionByKey(qkw.getChatKey()); @@ -60,9 +68,10 @@ public class QuestionMatcher { */ - public boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { + public boolean infoPointPreprocessing(Map receiveParameters, Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { String return_str = "", k; + String receiveParameterStr = ""; boolean debugFlag = false; HashSet skipSet = new HashSet() { @@ -77,39 +86,40 @@ public class QuestionMatcher { //输出所有actionName的值 - Iterator iit = curInfoPoint.keySet().iterator(); - logWriter.println("-----------------------------------------识别数据列表-------------------------------------------
"); + Iterator iit = receiveParameters.keySet().iterator(); + receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; while (iit.hasNext()) { k = iit.next(); // - logWriter.write(k + ": "); + receiveParameterStr += k + ": "; + curInfoPoint.put(k, receiveParameters.get(k)[0]); if (k.equals("debug_mode")) debugFlag = true; - String values[] = curInfoPoint.get(k); + String values[] = receiveParameters.get(k); for (String v : values) { - logWriter.write(v + " "); + receiveParameterStr += v + " "; } - logWriter.write("
"); + receiveParameterStr += "
"; if (values[0].equals(":")) { - values[0] = ""; - curInfoPoint.put(k, values); + curInfoPoint.put(k, ""); } + if(! historyInfoPoint.containsKey(k)) + historyInfoPoint.put(k, ""); } - logWriter.println("---------------------------------------------------------------------------------------"); - logWriter.write("
"); + logWriter.record(receiveParameterStr, 0); //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown iit = curInfoPoint.keySet().iterator(); boolean unknown_flag = true; while (iit.hasNext()) { k = iit.next(); - String values[] = curInfoPoint.get(k); + String values = curInfoPoint.get(k); if (skipSet.contains(k)) continue; - if (values != null && !values[0].equals("")) { + if (!values.equals("")) { unknown_flag = false; break; } @@ -125,13 +135,13 @@ public class QuestionMatcher { currentAction = " "; - curInfoPoint.put("emptySet", new String[]{" ",}); + curInfoPoint.put("emptySet", " "); if (historyInfoPoint.get("activeList") == null) { historyInfoPoint.put("activeList", currentAction); } if (unknown_flag && !currentAction.equals("")) { - String i[] = {"unknown",}; + String i = "unknown"; curInfoPoint.put(currentAction, i); } @@ -142,12 +152,10 @@ public class QuestionMatcher { /** * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch * - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @return bestMatch 状态表中满足条件最多的一条 */ - public Condition getBestMatch(Map curInfoPoint, Map historyInfoPoint, HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { + public Condition getBestMatch( HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { Integer configId = 0; List conditionList = null; @@ -160,11 +168,11 @@ public class QuestionMatcher { while (it.hasNext()) { String conditionName = it.next(); - String[] keywords = curInfoPoint.get(conditionName); + String keywords = curInfoPoint.get(conditionName); String keyword = null; - if (keywords != null && !keywords[0].equals("")) - keyword = keywords[0]; + if (keywords != null && !keywords.equals("")) + keyword = keywords; if (keyword != null && conditionTable.get(conditionName) != null) { @@ -173,8 +181,8 @@ public class QuestionMatcher { for (Condition condition : conditionList) { - if (condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { - logWriter.println("-----更新匹配更新为------" + userInfo.id2config.get(condition.id) + "-----------
"); + if (condition.status.equals("waiting") && conditionSatisfy(condition)) { + logWriter.record("-----匹配更新为------" + userInfo.id2config.get(condition.id) + "-----------
", 2); if (condition.featureMap.get("instantPost") != null) { @@ -186,7 +194,7 @@ public class QuestionMatcher { //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 bestMatch = condition; - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); //} else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)) bestMatch = condition; @@ -195,29 +203,38 @@ public class QuestionMatcher { } } + logWriter.record("----------------------匹配结束", 2); - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); + bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); return bestMatch; } - public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, Map curInfoPoint, Map historyInfoPoint, ServletContext context) throws IOException { + /** + * 在激活列表中选择满足匹配且优先级最高的一条配置条目 + * @param bestMatch + * @param activatedQueue + * @param context + * @return + * @throws IOException + */ + public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, ServletContext context) throws IOException { Condition condition; //待激活配置条目被激活后的匹配 while (!activatedQueue.isEmpty()) { condition = activatedQueue.remove(); activatedMap.remove(condition.id); - if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { + if (conditionSatisfy(condition)) { if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { - logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-----------"); + logWriter.record("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-----------", 0); bestMatch = condition; - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); //} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) { } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) { bestMatch = condition; - logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-------
"); + logWriter.record("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-------
", 0); } } @@ -232,17 +249,16 @@ public class QuestionMatcher { * 根据当前信息点,历史信息点,判断是否满足该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) { + public boolean conditionSatisfy(Condition condition) { boolean flag = true; - String actionName, keywords[], keyword, comparePair[], cmpType, premiseStr; + String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; HashSet keywordSet = null; - logWriter.println("
" + "-----检索到配置条目------" + userinfo.id2config.get(condition.id) + "-----------"); + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(condition.id), 1); if (condition.featureMap.containsKey("match")) { Iterator it = condition.currentPremise.keySet().iterator(); @@ -250,26 +266,25 @@ public class QuestionMatcher { premiseStr = it.next(); comparePair = premiseStr.split("::"); actionName = comparePair[0]; - keywords = curInfoPoint.get(actionName); - if (keywords == null) { + cmpType = comparePair[1]; + keyword = getKeyword(curInfoPoint, actionName); + + if (keyword == null) { flag = false; if(flag == false){ - logWriter.println("
" + premiseStr + "不匹配"); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过--------------------------------------------------------" + + "
--------------------------------------------------------", 0); } break; } - keyword = keywords[0]; - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; keywordSet = condition.currentPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint)) + if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; if(flag == false){ - logWriter.println("
" + premiseStr + "不匹配"); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过--------------------------------" + + "
--------------------------------------------------------", 0); } } @@ -277,47 +292,70 @@ public class QuestionMatcher { while (flag && it.hasNext()) { premiseStr = it.next(); comparePair = premiseStr.split("::"); + cmpType = comparePair[1]; actionName = comparePair[0]; - keyword = historyInfoPoint.get(actionName); + keyword = getKeyword(historyInfoPoint, actionName); if (keyword == null) { flag = false; if(flag == false){ - logWriter.println("
" + premiseStr + "不匹配"); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过-----------------------------" + + "
--------------------------------------------------------", 0); } break; } - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; + keywordSet = condition.historyPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint)) + if (!premiseSatisfy(keyword, cmpType, keywordSet)) flag = false; if(flag == false){ - logWriter.println("
" + premiseStr + "不匹配"); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过
", 0); } } } - return flag; } + public String getKeyword(Map infoPoint, String actionName){ + String keyword = ""; + String nameSeries[] = actionName.split("_"); + if(actionName.startsWith("npc_")){ + if(nameSeries.length == 4){ + String keywrod = gameEnv.queryNpcAttrByNpcName(nameSeries[3], nameSeries[4]); + } + + }else if (actionName.startsWith("goods_")){ + if(nameSeries.length == 4){ + keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]); + System.out.println("return" + keyword); + } + }else { + keyword = infoPoint.get(actionName); + + } + + + return keyword; + }; + + /** - * 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) + * 单个条件的匹配,判断是否满足条件 + * 比较类型分为 match、number、time、variable, + * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 * * @param keyword * @param cmpType 比较类型 * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 * @return 返回匹配或者不匹配 */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet, Map curInfoPoint, Map historyInfoPoint) { + public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { boolean flag = true; String operator = ""; @@ -330,17 +368,26 @@ public class QuestionMatcher { 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; + if(operator.equals("Keyword") || operator.equals("Include")) { + 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(operator.equals("Exclude")) { + if (keywordSet.contains(keyword)) { + flag = false; } + }else { + flag = false; } + } else if (cmpType.equals("number") && !keyword.equals("")) { int candidateA = 0; int candidateB = 0; @@ -374,6 +421,8 @@ public class QuestionMatcher { flag = candidateA < candidateB; else if (operator.equals("SmallerOrEqual")) flag = candidateA <= candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; } else if (cmpType.equals("time")) { @@ -411,10 +460,10 @@ public class QuestionMatcher { } } - if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2)[0].equals("")) { - conditionValue2 = curInfoPoint.get(conditionName2)[0]; + if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { + conditionValue2 = getKeyword(curInfoPoint, conditionName2); }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ - conditionValue2 = historyInfoPoint.get(conditionName2); + conditionValue2 = getKeyword(historyInfoPoint, conditionName2); }else { flag = false; } @@ -459,6 +508,8 @@ public class QuestionMatcher { flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ @@ -475,6 +526,8 @@ public class QuestionMatcher { flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; // 操作符为等于时可以比较两个字符串是否相同 } @@ -495,6 +548,8 @@ public class QuestionMatcher { flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ @@ -511,6 +566,8 @@ public class QuestionMatcher { flag = candidateA <= candidateB; else if (operator.equals("Equal")) flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; // 操作符为等于时可以比较两个字符串是否相同 } @@ -623,11 +680,9 @@ public class QuestionMatcher { /** * 替换答案中相应的变量{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 { + public Solution getSolution(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { Iterator it = curInfoPoint.keySet().iterator(); String actionName, reply, variable; @@ -642,7 +697,9 @@ public class QuestionMatcher { //post关键字 if (ansCondition.featureMap.containsKey("post")) { - ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint); + logWriter.record("---------------------进入表单结束",1); + ans = postToServer(ans, ansCondition); + logWriter.record("---------------------提交表单结束",1); //nextNext关键字 } @@ -650,13 +707,17 @@ public class QuestionMatcher { //updateKnowledge关键字 if (ansCondition.featureMap.containsKey("updateKnowledge")) { - updateKnowledge(ansCondition, curInfoPoint, historyInfoPoint); + logWriter.record("---------------------进入更新答案【略】",1); + updateKnowledge(ansCondition); + logWriter.record("---------------------更新答案结束",1); } if (ansCondition.featureMap.containsKey("newNext")) { - ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); + logWriter.record("---------------------进入判断下一步【略】",1); + ans = findNewNext(ans, ansCondition); + logWriter.record("---------------------判断下一步结束",1); //上一步 } else if (ansCondition.featureMap.containsKey("return-1")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); @@ -688,22 +749,6 @@ public class QuestionMatcher { 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(); @@ -711,8 +756,8 @@ public class QuestionMatcher { 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]); + if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) + reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)); } else if (m.group(1).endsWith("-2}")) { if (historyInfoPoint.get(variable) != null) reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); @@ -727,7 +772,13 @@ public class QuestionMatcher { return ans; } - public void infoTransfer(Map curInfoPoint, Map historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag) { + /** + * 请求处理结束后台将当前信息的信息点转移到已知信息 + * @param ans + * @param context + * @param debugFlag + */ + public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { //将当前信息点更新至历史信息点 Iterator it = curInfoPoint.keySet().iterator(); String actionName, lastReply; @@ -761,7 +812,7 @@ public class QuestionMatcher { if(skipSet.contains(actionName)) continue; - keyword1 = curInfoPoint.get(actionName)[0]; + keyword1 = curInfoPoint.get(actionName); keyword2 = historyInfoPoint.get(actionName); if (keyword2 == null) { historyInfoPoint.put(actionName, keyword1); @@ -772,8 +823,8 @@ public class QuestionMatcher { } - ChatCacheController.updateChatCache4Insert2(curInfoPoint, historyInfoPoint, world, context); - //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); + ChatCacheController.updateChatCache4Insert2(curInfoPoint, historyInfoPoint, gameEnv, context); + //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); } catch (Exception e) { @@ -786,13 +837,11 @@ public class QuestionMatcher { * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 * * @param ans 最终返回的数据 - * @param curInfoPoint 当前对话识别到的信息点 - * @param historyInfoPoint 在当前对话之前采集到的所有用户信息点 * @param context */ - public void appendDebugInfo(Solution ans, Map curInfoPoint, Map historyInfoPoint, ServletContext context) { + public void appendDebugInfo(Solution ans, ServletContext context) { Iterator it = null; - String key, values[], value; + String key, values, value; HashSet skipSet = new HashSet() { { @@ -812,8 +861,8 @@ public class QuestionMatcher { 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] + "\' "); + if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) + debugInfo += (" " + key + ":\'" + values + "\' "); } debugInfo += ")(已知:"; @@ -836,8 +885,8 @@ public class QuestionMatcher { * @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"; + public Solution postToServer(Solution ans, Condition ansCondition) throws IOException { + String url = null, elem[], subElem[], key,keys, postType = "all"; Map infoMap = new HashMap(); List pairList = new ArrayList(); Iterator k_iter = null; @@ -860,9 +909,9 @@ public class QuestionMatcher { k_iter = curInfoPoint.keySet().iterator(); while (k_iter.hasNext()) { key = k_iter.next(); - if (curInfoPoint.get(key)[0] != "") + if (curInfoPoint.get(key) != "") //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); - pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)[0])); + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); } k_iter = historyInfoPoint.keySet().iterator(); @@ -879,14 +928,14 @@ public class QuestionMatcher { //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 } else if (postType.equals("term")) { - pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")[0])); - pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")[0])); - pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")[0])); + pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); + pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); + pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); 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])); + if (curInfoPoint.get(key) != "") + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); } k_iter = ansCondition.historyPremise.keySet().iterator(); @@ -898,6 +947,8 @@ public class QuestionMatcher { } } + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); + HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; @@ -913,6 +964,7 @@ public class QuestionMatcher { if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); + logWriter.record("提交表单接收到的数据:
" + respContent, 2); JSONObject jobj = JSONObject.fromString(respContent); Iterator kit = jobj.keys(); @@ -943,7 +995,7 @@ public class QuestionMatcher { } - public Solution findNewNext(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint) { + public Solution findNewNext(Solution ans, Condition ansCondition) { String nextOptions[] = ansCondition.nextStep.split(","); String conditionName, premises[], cpPair[]; boolean flag = true; @@ -962,8 +1014,8 @@ public class QuestionMatcher { 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"); + boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); + boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); //只有前两者都为假时,conditionExist才为真 boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); @@ -989,9 +1041,11 @@ public class QuestionMatcher { } - public void updateKnowledge(Condition condition, Map curInfoPoint, Map historyInfoPoint) throws ParseException { + public void updateKnowledge(Condition condition) throws ParseException { String keyword, variableName, updateValue, returnStr = "1"; + + Iterator iit = condition.updateKnowledge.keySet().iterator(); while (iit.hasNext()) { @@ -1000,116 +1054,120 @@ public class QuestionMatcher { keyword = historyInfoPoint.get(variableName); //如果变量名开头为NPC或者item,就专门交给world处理 - if(variableName.startsWith("NPC_") || variableName.startsWith("item_") || variableName.startsWith("map")){ - returnStr = WorldController.worldOperation(world, variableName, updateValue, curInfoPoint, historyInfoPoint); - historyInfoPoint.put(variableName, returnStr); - break; - } - - 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), ""); - - }else if (updateValue.startsWith("int+=")) { - 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(5)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("int-=")) { - 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(5)); - 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(5); - //做字符串删除 - } else if (updateValue.startsWith("str-=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(5), ""); - + if(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_")){ + try { + returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); + updateValue = returnStr; + }catch (Exception e){ + e.printStackTrace(); + updateValue = "游戏模块处理出错"; } - else if (updateValue.startsWith("var=")) { - String conditionName = updateValue.substring(5, updateValue.length() - 3); - - if(updateValue.endsWith("-1}")){ - if(curInfoPoint.get(conditionName) != null){ - updateValue = curInfoPoint.get(conditionName)[0]; - }else { - updateValue = ""; + }else { + + 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), ""); + + } else if (updateValue.startsWith("int+=")) { + 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(5)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("int-=")) { + 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(5)); + 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(5); + //做字符串删除 + } else if (updateValue.startsWith("str-=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(5), ""); + + } else if (updateValue.startsWith("var=")) { + String conditionName = updateValue.substring(5, updateValue.length() - 3); + + if (updateValue.endsWith("-1}")) { + if (curInfoPoint.get(conditionName) != null) { + updateValue = curInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("-2}")) { + if (historyInfoPoint.get(conditionName) != null) { + updateValue = historyInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("nextStep-3}")) { + updateValue = condition.nextStep; + } else if (updateValue.endsWith("reply-3}")) { + updateValue = condition.answer[0]; } - }else if(updateValue.endsWith("-2}")){ - if(historyInfoPoint.get(conditionName) != null){ - updateValue = historyInfoPoint.get(conditionName); - }else { + if (variableName.startsWith("process-nextStep")) { + condition.nextStep = updateValue; updateValue = ""; } - }else if(updateValue.endsWith("nextStep-3}")){ - updateValue = condition.nextStep; - }else if(updateValue.endsWith("reply-3}")){ - updateValue = condition.answer[0]; - } - if(variableName.startsWith("process-nextStep")){ - condition.nextStep = updateValue; - updateValue = ""; - } + } + } catch (Exception e) { + e.printStackTrace(); + continue; } - } catch (Exception e) { - e.printStackTrace(); - continue; } @@ -1123,8 +1181,8 @@ public class QuestionMatcher { } - public void activateCondition(Queue activatedQueue, String userName, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { - UserInfo userinfo = (UserInfo) context.getAttribute(userName); + public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); String configStr = ""; Integer configId; Condition newCondition, originCondition; @@ -1140,7 +1198,7 @@ public class QuestionMatcher { newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); //condition = QuestionMatcher.buildCondition(condition, configStr); - logWriter.write("------激活-------" + userinfo.id2config.get(configId) + "-------
"); + logWriter.record("------激活-------" + userinfo.id2config.get(configId) + "-------
", 0); if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { activatedMap.get(configId).activePriority = newCondition.activePriority; @@ -1154,13 +1212,22 @@ public class QuestionMatcher { } - public Solution postActivate(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + /** + * 一个提交表单后在激活的操作 + * @param ansCondition + * @param context + * @param userinfo + * @return + * @throws IOException + * @throws ParseException + */ + public Solution postActivate(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { Queue activatedQueue = new LinkedList(); Solution bestMatch = null; - activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); - ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); + activateCondition(activatedQueue, userinfo.botAccount, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); + ansCondition = activatedQueueMatching(ansCondition, activatedQueue, context); - bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + bestMatch = getSolution(ansCondition, context, userinfo); return bestMatch; diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index 7faf8d5..a55babc 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -36,9 +36,9 @@ public class UserInfoController { try { userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName, userinfo); + context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { - System.out.println(userinfo.userName + FILE_ERROR); + System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } @@ -48,30 +48,30 @@ public class UserInfoController { } - public static void userConfigInit(String userName, ServletContext context) throws IOException { + public static void userConfigInit(String botAccount, ServletContext context) throws IOException { String line; - File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); + File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt"); if (!userFile.exists()) { BufferedReader br = new BufferedReader(new StringReader("")); - UserInfo userinfo = new UserInfo(userName); + UserInfo userinfo = new UserInfo(botAccount); try { userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName, userinfo); + context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { - System.out.println(userinfo.userName + FILE_ERROR); + System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } } else { FileReader reader = new FileReader(userFile); BufferedReader br = new BufferedReader(reader); - UserInfo userinfo = new UserInfo(userName); + UserInfo userinfo = new UserInfo(botAccount); try { userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName, userinfo); + context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { - System.out.println(userinfo.userName + FILE_ERROR); + System.out.println(userinfo.botAccount + FILE_ERROR); e.printStackTrace(); } @@ -265,20 +265,20 @@ public class UserInfoController { * @return 用户信息 */ public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { - /*根据数据库得到userName改为直接得到 + /*根据数据库得到botAccount改为直接得到 SqlHelper helper = new SqlHelper(); - String userName = helper.queryUsernameByKey(chat_key); + String botAccount = helper.querybotAccountByKey(chat_key); */ - String userName = bot_name; + String botAccount = bot_name; UserInfo userinfo = null; - if (context.getAttribute(userName) == null) { - userConfigInit(userName, context); + if (context.getAttribute(botAccount) == null) { + userConfigInit(botAccount, context); } - if (context.getAttribute(userName) == null) { - userinfo = new UserInfo(userName); + if (context.getAttribute(botAccount) == null) { + userinfo = new UserInfo(botAccount); userinfo.conditionTable = new HashMap>(); } else { - userinfo = (UserInfo) context.getAttribute(userName); + userinfo = (UserInfo) context.getAttribute(botAccount); } //helper.destroy(); diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index d8a4950..8b13072 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -1,107 +1,120 @@ package processing; -import entity.World; + +import GameEnvironment.GameEnv; import java.util.ArrayList; import java.util.List; import java.util.Map; public class WorldController { + public LogWriter logWriter = null; + public WorldController(LogWriter logWriter) { + this.logWriter = logWriter; + } - public static String worldOperation(World world, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ + public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr=""; String namePair[] = varName.split("_"); boolean operationFlag = true; - if (varName.startsWith("NPC_")) - moduleName = "NPC"; - else if(varName.startsWith("items")) - moduleName = "items"; - - if(varName.startsWith("item_")) { - switch (valuePair[0]) { - case "addGoodsBase": - operationFlag = world.addGoodsBase(namePair[1], namePair[2], valuePair[1]); - break; - case "deleteGoods": - operationFlag = world.deleteGoods(namePair[1], namePair[2]); - break; - case "queryGoodsIntro": - returnStr = world.queryGoodsIntro(varName, historyInfoPoint.get("site")); - break; - case "queryAttrByGoodsName": - String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2); - returnStr = world.queryAttrByGoodsName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site")); - break; - case "queryAllAttrByGoodsName": - List attrs = world.queryAllAttrByGoodsName(varName, historyInfoPoint.get("site")); - break; - case "updateAttrByGoodsName": - operationFlag = world.updateAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]); - break; - case "addAttrByGoodsName": - operationFlag = world.addAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]); - break; - case "deleteAttrByGoodsName": - operationFlag = world.deleteAttrByGoodsName(namePair[1], namePair[2], namePair[3]); - break; - default: - } - }else if(varName.startsWith("NPC")) { - switch(valuePair[0]){ - case "addNpc": - operationFlag = world.addNpc(namePair[1], namePair[2], valuePair[1]); - break; - case "deleteNpc": - operationFlag = world.deleteNpc(namePair[1], namePair[2]); - break; - case "queryNpcIntro": - //operationFlag = world.queryNpcIntro(valuePair[1], namePair[2]); - break; - case "queryAttrByNPCName": - String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2); - subValuePair[1] = subValuePair[1].replace("哪里", "location"); - returnStr = world.queryAttrByNPCName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site")); - break; - case "updateLocationByNPCName": - operationFlag = world.updateLocationByNPCName(namePair[1], namePair[2], namePair[3], ""); - break; - case "addAttrByNPCName": - operationFlag = world.addAttrByNPCName(namePair[1], namePair[2], namePair[3], valuePair[1]); - break; - case "deleteAttrByNPCName": - operationFlag = world.deleteAttrByNPCName(namePair[1], namePair[2], namePair[3]); - break; - default: - } + List textList = null; + String subValuePair[] = null; - }else if (varName.startsWith("map")){ - List sites = new ArrayList<>(); - switch(valuePair[0]){ - case "queryAroundAllBySite": - sites = world.queryAroundAllBySite(historyInfoPoint.get("site")); - break; - case "queryAroundNpcBySite": - sites = world.queryAroundNpcBySite(historyInfoPoint.get("site")); - break; - case "queryAroundGoodsBySite": - sites = world.queryAroundGoodsBySite(historyInfoPoint.get("site")); - break; - case "queryCanGoBySite": - sites = world.queryCanGoBySite(historyInfoPoint.get("site")); - break; - case "queryPathBySite": - sites = world.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]); - break; + logWriter.record(String.format("%s(%s, %s, %s)", varName, varValue, historyInfoPoint.get("site")), 0); - } - for(String site: sites){ - returnStr += site; - } + if(valuePair[0].startsWith("query")){ //查询专用 + if(varName.startsWith("goods_")) { + switch (valuePair[0]) { + case "queryGoodsIntro": + returnStr = gameEnv.queryGoodsIntroByGoodsName(varName); + if(returnStr == null) + returnStr = "无"; + break; + case "queryAttrByGoodsName": + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + break; + case "queryAllAttrByGoodsName": + textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); + if(textList == null) + returnStr = "无"; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + case "queryAroundGoodsByClassName": + textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); + if(textList == null) + returnStr = "无"; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + default: + } + }else if(varName.startsWith("NPC_")) { + switch(valuePair[0]){ + case "queryNpcIntro": + //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + + break; + case "queryAttrByNPCName": + + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + subValuePair[0] = subValuePair[0].replace("哪里", "location"); + returnStr = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + break; + default: + } + }else if (varName.startsWith("map_")) { + List sites = new ArrayList<>(); + switch (valuePair[0]) { + case "queryAroundAllBySite": + sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); + break; + case "queryAroundNpcBySite": + sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + break; + case "queryAroundGoodsBySite": + sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); + break; + case "queryCanGoBySite": + sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); + break; + case "queryPathBySite": + sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]); + break; + } + if(sites == null) + returnStr = "无"; + else { + for (String site : sites) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + } + }else { //增删改统一使用 + gameEnv.CUD(varName, valuePair[0], valuePair[1]); } + + + logWriter.record("return:" + returnStr, 0); return returnStr; } diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index b06a919..2c45989 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -24,7 +24,7 @@ import java.util.List; public class GameDesignServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Integer botId, projectId, dataId; - String userName = null, moduleName; + String botAccount = null, moduleName, userName; ServletContext context = this.getServletContext(); boolean flag; SqlHelper helper = null; @@ -46,18 +46,23 @@ public class GameDesignServlet extends HttpServlet { dataId = (Integer) jsonObject.get("id"); JSONObject gameElements = helper.queryGameElementsByBotId(dataId); - botId = Integer.parseInt((String) gameElements.get("botId")); - userName = (String) gameElements.get("userName"); + botId = (Integer)gameElements.get("botId"); + botAccount = (String) gameElements.get("botAccount"); + userName = (String)gameElements.get("userName"); - //假设重新重新建用户信息 - if (context.getAttribute(userName) == null) { - UserInfoController.userConfigInit(userName, context); + + + System.out.println("botId:" + botId + ",botAccount:" + botAccount); + + //假设重建用户信息 + if (context.getAttribute(botAccount) == null) { + UserInfoController.userConfigInit(botAccount, context); } - UserInfo userinfo = (UserInfo) context.getAttribute(userName); + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - //UserInfo userinfo = new UserInfo(userName); + //UserInfo userinfo = new UserInfo(botAccount); //清空之前生成的配置条目 try { @@ -108,17 +113,16 @@ public class GameDesignServlet extends HttpServlet { StringReader sr = new StringReader(mergedConfigText.toString()); BufferedReader br = new BufferedReader(sr); UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userName, userinfo); - ConditionTableController.writeConfigText(userName, userinfo); + context.setAttribute(botAccount, userinfo); + ConditionTableController.writeConfigText(botAccount, userinfo); helper.destroy(); } response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); - response.setStatus(111); PrintWriter out = response.getWriter(); - out.println("完成\\\n"); + out.println("完成"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 90c79a7..e0a467e 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -1,10 +1,7 @@ package servlet; import entity.*; -import processing.ChatCacheController; -import processing.MyFunc; -import processing.QuestionMatcher; -import processing.UserInfoController; +import processing.*; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -25,42 +22,25 @@ public class GetAnswerServlet extends HttpServlet { */ String NAME_MISSING_ERROR = "没找到bot名?"; + String LOG_PATH = "/var/www/html/logs/"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); - Map curInfoPoint = new HashMap<>(request.getParameterMap()); + Map receiveParamters = new HashMap<>(request.getParameterMap()); + Map curInfoPoint = new HashMap(); Map historyInfoPoint = null; Solution bestMatch = null; Condition ansCondition = null; String ansJ, return_str = "", state = ""; - String chatKey = curInfoPoint.get("chat_key")[0]; + String chatKey = receiveParamters.get("chat_key")[0]; + String botName = receiveParamters.get("bot_name")[0]; OutputStream out = response.getOutputStream(); ServletContext context = this.getServletContext(); boolean debugFlag = false; - String fileName = "/var/www/html/logs/" + chatKey + ".html"; - File file = new File(fileName); - - if (!file.exists()) { - file.createNewFile(); - } - file.setReadable(true,false); - - FileWriter fw = new FileWriter(file, true); - //BufferedWriter bw = new BufferedWriter(fos, "UTF-8"); - //context.setAttribute("logWriter", bw); - - - BufferedWriter bw = new BufferedWriter(fw); - PrintWriter pw = new PrintWriter(bw); - pw.println("\n" + - "\n" + - "\n" + - " \n" + - " log\n" + - ""); + LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); @@ -77,28 +57,35 @@ public class GetAnswerServlet extends HttpServlet { } //获得用户历史信息 - ChatCache chatCache = ChatCacheController.getChatCache2(chatKey, context, curInfoPoint, userinfo); + ChatCache chatCache = null; + try { + chatCache = ChatCacheController.getChatCache2(chatKey, context, userinfo); + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } historyInfoPoint = chatCache.getInfoPoint(); //信息点预处理 - QuestionMatcher matcher = new QuestionMatcher(pw,userinfo, context, chatCache.getWorld()); - debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, context); + QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv()); + debugFlag = matcher.infoPointPreprocessing(receiveParamters, curInfoPoint, historyInfoPoint, userinfo, context); /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ //process.removeTimeoutChatkey(context); //System.out.println(userinfo.conditionTable); //测试 - ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context, userinfo); + ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); if (state.equals("") && ansCondition.priority == -1) state = "我不理解,"; if (state.equals("")) { try { - bestMatch = matcher.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + bestMatch = matcher.getSolution(ansCondition, context, userinfo); if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) { //如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + bestMatch = matcher.postActivate(ansCondition, context, userinfo); } } catch (ParseException e) { e.printStackTrace(); @@ -117,16 +104,15 @@ public class GetAnswerServlet extends HttpServlet { if (debugFlag) { - matcher.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context); + matcher.appendDebugInfo(bestMatch, context); } - matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); + matcher.infoTransfer(bestMatch, context, debugFlag); - bw.write("

" + - "-----------------------------------------对话处理结束-----------------------------------


"); - bw.close(); - fw.close(); + logWriter.record("

" + + "------------------------------------------------对话处理结束", 0); + logWriter.close(); ansJ = MyFunc.toJson(bestMatch); System.out.println(ansJ); out.write(ansJ.getBytes()); diff --git a/src/servlet/ReloadChatCacheServlet.java b/src/servlet/ReloadChatCacheServlet.java new file mode 100644 index 0000000..60b74ba --- /dev/null +++ b/src/servlet/ReloadChatCacheServlet.java @@ -0,0 +1,19 @@ +package servlet; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "ReloadChatCacheServlet", urlPatterns = {"/reloadChatCache"}) +public class ReloadChatCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java index bd1a1f0..af5840e 100644 --- a/src/servlet/ReloadConfigServlet.java +++ b/src/servlet/ReloadConfigServlet.java @@ -19,17 +19,17 @@ import java.io.*; public class ReloadConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); - String userName = request.getParameter("userName"); + String botAccount = request.getParameter("botAccount"); boolean flag = true; - UserInfo userinfo = new UserInfo(userName); - File configFile = new File(System.getProperty("user.dir") + "/config/" + userName + ".txt"); + UserInfo userinfo = new UserInfo(botAccount); + File configFile = new File(System.getProperty("user.dir") + "/config/" + botAccount + ".txt"); System.out.println(configFile.getAbsolutePath()); ServletContext context = this.getServletContext(); if (!configFile.exists()) { response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); - out.println("文件不存在: " + userName); + out.println("文件不存在: " + botAccount); } else { @@ -38,10 +38,10 @@ public class ReloadConfigServlet extends HttpServlet { try { userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.userName, userinfo); + context.setAttribute(userinfo.botAccount, userinfo); } catch (Exception e) { flag = false; - System.out.println(userinfo.userName + ".txt 有误"); + System.out.println(userinfo.botAccount + ".txt 有误"); e.printStackTrace(); } @@ -54,7 +54,7 @@ public class ReloadConfigServlet extends HttpServlet { response.setContentType("text/plain"); response.setStatus(111); PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + userName + ".txt\\\n"); + out.println("更新失败配置文件有误:" + botAccount + ".txt\\\n"); } else { response.setCharacterEncoding("utf-8"); diff --git a/src/servlet/SaveChatCacheServlet.java b/src/servlet/SaveChatCacheServlet.java new file mode 100644 index 0000000..fcbb37d --- /dev/null +++ b/src/servlet/SaveChatCacheServlet.java @@ -0,0 +1,40 @@ +package servlet; + +import entity.ChatCache; +import processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Map; + +@WebServlet(name = "SaveChatCacheServlet", urlPatterns = {"/saveChatCache"}) +public class SaveChatCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String chatKey = request.getParameter("chat_key"), message = ""; + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); + + Map chatCacheMap = (Map)context.getAttribute("chatCache"); + ChatCache chatCache = chatCacheMap.get(chatKey); + + message = ChatCacheController.saveChatCache(chatKey, context); + out.write(message.getBytes()); + out.flush(); + } + +} + + diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index e3b5f80..998064e 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -23,14 +23,14 @@ import java.util.List; @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的命名方式保存至本地。 + //在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。 request.setCharacterEncoding("UTF-8"); String line, extraElements[]; ArrayList errorList = new ArrayList(); ServletContext context = this.getServletContext(); - String userName = request.getParameter("userName"); + String botAccount = request.getParameter("botAccount"); - UserInfo userinfo = new UserInfo(userName); + UserInfo userinfo = new UserInfo(botAccount); userinfo.conditionTable = new HashMap>(); List conditionList = null; @@ -102,8 +102,8 @@ 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(botAccount, userinfo); + String path = System.getProperty("user.dir") + "/config/" + userinfo.botAccount + ".txt"; File file = new File(path); File dir = new File(System.getProperty("user.dir") + "/config"); diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java index 8af5e44..0645027 100644 --- a/src/servlet/UpdateSingleConfigServlet.java +++ b/src/servlet/UpdateSingleConfigServlet.java @@ -92,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.botAccount, userinfo); System.out.println("batchupdate"); } } -- libgit2 0.27.1