Commit 3fa80652 by hxw

routine

parent db12838b
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;
}
}
package GameEnvironment;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Util {
public static String getJsonString(String fullName) {
Reader reader = null;
String jsonString = "";
try {
// System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[256];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fullName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
// System.out.println(tempchars);
jsonString = jsonString + String.valueOf(tempchars);
// System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
jsonString = jsonString+tempchars[i];
// System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return jsonString;
}
}
package GameEnvironment.bean;
public class Attr {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Attr [name=" + name + ", value=" + value + "]";
}
}
package GameEnvironment.bean;
public class GoodsInstance extends SuperClass{
private Place place;
private NpcInstance npc;
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public NpcInstance getNpc() {
return npc;
}
public void setNpc(NpcInstance npc) {
this.npc = npc;
}
@Override
public String toString() {
String placeName = "";
if(place != null) {
placeName = place.getName();
}
String npcName = "";
if(npc != null) {
npcName = npc.getName();
}
return super.toString()+"GoodsInstance [placeName=" + placeName + ", npcName=" + npcName + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class NpcInstance extends SuperClass{
private Place place;
private List<GoodsInstance> goodsInstances;
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> 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 + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class Place {
private String name;
private String intro;
private List<Place> ableGo;
private List<NpcInstance> npcInstances;
private List<GoodsInstance> 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<Place> getAbleGo() {
return ableGo;
}
public void setAbleGo(List<Place> ableGo) {
this.ableGo = ableGo;
}
public List<NpcInstance> getNpcInstances() {
return npcInstances;
}
public void setNpcInstances(List<NpcInstance> npcInstances) {
this.npcInstances = npcInstances;
}
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> 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 + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class SuperClass {
private String name;
private String intro;
private List<Attr> attrs;
private List<GoodsInstance> goodsInstances;
private List<NpcInstance> npcInstances;
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> goodsInstances) {
this.goodsInstances = goodsInstances;
}
public List<NpcInstance> getNpcInstances() {
return npcInstances;
}
public void setNpcInstances(List<NpcInstance> 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<Attr> getAttrs() {
return attrs;
}
public void setAttrs(List<Attr> 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 + "]";
}
}
......@@ -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 {
}
}
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<String, String> infoPoint = null;
private World world = null;
private GameEnv gameEnv = null;
public Map<String, String> 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<String, String[]> curInfoPoint, UserInfo userInfo) {
world = new World();
public ChatCache(UserInfo userInfo) throws Exception {
gameEnv = new GameEnv(userInfo.botAccount);
String k;
infoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, "");
}
//变量初始化
iit = userInfo.varInitialMap.keySet().iterator();
Iterator<String> iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k));
......
......@@ -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);
......
......@@ -7,10 +7,10 @@ import java.util.List;
* 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里
*/
public class UserInfo {
public UserInfo(String userName) {
public UserInfo(String botAccount) {
this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = "";
this.userName = userName;
this.botAccount = botAccount;
this.extraInfo = new HashMap<String, String>() {
{
put("activeAction", " ");
......@@ -23,7 +23,7 @@ public class UserInfo {
public HashMap<String, List<Condition>> conditionTable;
public String configStr;
public String userName;
public String botAccount;
public HashMap<String, String> extraInfo;
public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition;
......
......@@ -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<String, String> attribute = null;
Iterator<String> attrIter = null;
String conditionName1 = "wenzainali";
HashSet<String> classSet = new HashSet<String>();
//与npc属性相关的所有condition
ArrayList<String> relateConditions = new ArrayList<String>(){
{
add("wenzainali");
add("shishenme");
}
};
//与npc类相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){
{
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);
}
}
}
......@@ -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<String, String> attribute = null;
Iterator<String> attrIter = null;
String conditionName1 = "nums";
String keywords1 = "";
HashSet<String> classSet = new HashSet<String>();
//与物品属性查询相关的所有condition
ArrayList<String> attrRelateConditions = new ArrayList<String>(){
{
add("nums");
add("shishenme");
}
};
//与物品类查询相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){
{
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);
}
}
}
......@@ -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<String, String> 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);
}
......
......@@ -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<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
......@@ -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<JSONObject> queue = new LinkedList<JSONObject>();
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<Integer> 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);
}
}
}
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<String, String> getChatCache(String chatKey, ServletContext context) {
World world = new World();
Map<String, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCache = new HashMap<String, Map<String, String>>();
context.setAttribute("chatCache", chatCache);
} else {
chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
}
String chatkey;
try {
historyInfoPoint = chatCache.get(chatKey);
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) {
//可整合
historyInfoPoint = null;
}
return historyInfoPoint;
}
// public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) {
//
// GameEnv gameEnv = new GameEnv(chatKey);
// Map<String, String> historyInfoPoint = null;
// Map<String, Map<String, String>> chatCache = null;
// if (context.getAttribute("chatCache") == null) {
// chatCache = new HashMap<String, Map<String, String>>();
// context.setAttribute("chatCache", chatCache);
// } else {
// chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
// }
// String chatkey;
//
//
// try {
// historyInfoPoint = chatCache.get(chatKey);
// //historyInfoPoint = (Map<String, String>) 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<String, String> history = new HashMap<String, String>();
Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
Iterator<String> 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<String, String> history = new HashMap<String, String>();
// Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
//
//
// Iterator<String> 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<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint);
context.setAttribute("chatCache", keyCache);
}
// public static synchronized void updateChatCache4Insert(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
// historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
// Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
// keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint);
// context.setAttribute("chatCache", keyCache);
// }
public static boolean saveChatCache(String userName, HashMap<String, String> 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<String, String[]> curInfoPoint, UserInfo userinfo) {
public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, UserInfo userinfo) throws Exception {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>();
chatCacheMap.put(chatKey, new ChatCache(curInfoPoint, userinfo));
chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) 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<String, String>) 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<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, World world, ServletContext context) {
public static synchronized void updateChatCache4Insert2(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) 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<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) 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 "成功";
}
}
}
package processing;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class LogWriter {
private PrintWriter recorder = null;
String PRINT_PATTERN = "<font color=\"%s\">%s" +
"----------------------------------------------------------------------------<br></font>";
Map<Integer, String> colerMap = new HashMap<Integer, String>(){
{
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("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>log</title>\n" +
"</head>");
}
public void record(String text, int level){
recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), text));
}
public void close(){
recorder.close();
}
}
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;
}
}
......@@ -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<String, List<Condition>>();
} else {
userinfo = (UserInfo) context.getAttribute(userName);
userinfo = (UserInfo) context.getAttribute(botAccount);
}
//helper.destroy();
......
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<String, String[]> currentInfoPoint, Map<String, String>historyInfoPoint){
public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map<String, String> currentInfoPoint, Map<String, String>historyInfoPoint){
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<String> 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<String> textList = null;
String subValuePair[] = null;
}else if (varName.startsWith("map")){
List<String> 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<String> 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;
}
......
......@@ -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 {
......
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<String, String[]> curInfoPoint = new HashMap<>(request.getParameterMap());
Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap());
Map<String ,String> curInfoPoint = new HashMap<String, String>();
Map<String, String> 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("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>log</title>\n" +
"</head>");
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("<br><br>" +
"-----------------------------------------对话处理结束-----------------------------------<br><br><br>");
bw.close();
fw.close();
logWriter.record("<br><br>" +
"------------------------------------------------对话处理结束", 0);
logWriter.close();
ansJ = MyFunc.toJson(bestMatch);
System.out.println(ansJ);
out.write(ansJ.getBytes());
......
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 {
}
}
......@@ -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");
......
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<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)context.getAttribute("chatCache");
ChatCache chatCache = chatCacheMap.get(chatKey);
message = ChatCacheController.saveChatCache(chatKey, context);
out.write(message.getBytes());
out.flush();
}
}
......@@ -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<String> errorList = new ArrayList<String>();
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<String, List<Condition>>();
List<Condition> 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");
......
......@@ -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");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment