Commit 7d840a91 by hxw

routine

parent f8d00711
package db; package com.qiwu.chatbotbackend.db;
import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.ComboPooledDataSource;
......
package db; package com.qiwu.chatbotbackend.db;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
......
package db; package com.qiwu.chatbotbackend.db;
import org.apache.commons.dbcp.BasicDataSourceFactory; import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.io.File; import java.io.File;
......
package db; package com.qiwu.chatbotbackend.db;
public class DBUtils { public class DBUtils {
} }
package db; package com.qiwu.chatbotbackend.db;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import entity.QuestionKeyWord; import com.qiwu.chatbotbackend.entity.QuestionKeyWord;
import gameDesign.ElementConstructor; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor;
import processing.MyFunc; import com.qiwu.chatbotbackend.processing.MyFunc;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.*;
import java.util.Iterator;
import java.util.List;
public class SqlHelper { public class SqlHelper {
private Connection conn = null; private Connection conn = null;
...@@ -153,7 +151,7 @@ public class SqlHelper { ...@@ -153,7 +151,7 @@ public class SqlHelper {
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("删除旧数据失败"); System.out.println("删除旧数据config失败");
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
...@@ -173,7 +171,28 @@ public class SqlHelper { ...@@ -173,7 +171,28 @@ public class SqlHelper {
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("删除旧数据失败"); System.out.println("删除旧数据variable失败");
e.printStackTrace();
return false;
}
}
public boolean deleteCategoryByBotId(int botId) {
String sql = "delete from config_categories where botId= ?";
boolean b;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId));
b = ps.execute();
ps.close();
return b;
} catch (SQLException e) {
System.out.println("删除旧数据category失败");
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
...@@ -236,7 +255,7 @@ public class SqlHelper { ...@@ -236,7 +255,7 @@ public class SqlHelper {
} }
public boolean batchInsertConfigByBotId(int botId, ElementConstructor constructor, List<Integer> idList) { public boolean batchInsertConfigByBotId(int botId, List<JSONObject> jsonList, List<Integer> idList, int categoryId) {
int count[]; int count[];
boolean insertFlag = true; boolean insertFlag = true;
String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
...@@ -246,11 +265,11 @@ public class SqlHelper { ...@@ -246,11 +265,11 @@ public class SqlHelper {
conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (JConfig jConfig : constructor.getjConfigList()) { for (JSONObject json : jsonList) {
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0)); ps.setString(2, String.valueOf(categoryId));
ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString()); ps.setString(3, json.toJSONString());
ps.setString(4, ""); ps.setString(4, (String)json.get("configName"));
ps.addBatch(); ps.addBatch();
} }
...@@ -289,6 +308,72 @@ public class SqlHelper { ...@@ -289,6 +308,72 @@ public class SqlHelper {
} }
public boolean batchInsertCategoryByBotId(int botId, Map<String, Integer> categoryMap) {
int count[], iterNum = 0, id;
boolean insertFlag = true;
String sql = "", varName, varValue, description;
ArrayList<String> nameList = new ArrayList<String>();
try {
conn.setAutoCommit(false);
sql = "insert into config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, -1, ?, 'avaliable')";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Iterator<String> iit = categoryMap.keySet().iterator();
while (iit.hasNext()) {
varName = iit.next();
nameList.add(varName);
ps.setString(1, String.valueOf(botId));
ps.setString(2, varName);
ps.addBatch();
}
count = ps.executeBatch();
conn.commit();
for (int i : count) {
if (i == 0) {
conn.rollback();
System.out.println("======出现异常,回滚=========");
insertFlag = false;
}
}
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()){
id = rs.getInt(1);
categoryMap.put(nameList.get(iterNum), id);
iterNum++;
}
ps.close();
rs.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("------出现异常,回滚----------");
e.printStackTrace();
}
return insertFlag;
}
public JSONObject queryGameElementsByBotId(int id) { public JSONObject queryGameElementsByBotId(int id) {
String sql = "select * from generate_json_tb where project_id = ?"; String sql = "select * from generate_json_tb where project_id = ?";
String userName = ""; String userName = "";
...@@ -347,6 +432,7 @@ public class SqlHelper { ...@@ -347,6 +432,7 @@ public class SqlHelper {
b = ps.execute(); b = ps.execute();
ps.close(); ps.close();
conn.commit();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -356,27 +442,29 @@ public class SqlHelper { ...@@ -356,27 +442,29 @@ public class SqlHelper {
} }
public boolean insertConfigByBotId(int botId, ElementConstructor constructor, JConfig jConfig, List<Integer> idList) { public boolean insertConfigByBotId(int botId, JSONObject json, List<Integer> idList, int categoryId) {
String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
String userName = "";
String result = "empty";
ResultSet rs = null;
int id = 0; int id = 0;
boolean b = true; boolean b = true;
int bNum = 0;
try { try {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0)); ps.setString(2, String.valueOf(categoryId));
ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString()); ps.setString(3, json.toJSONString());
ps.setString(4, ""); ps.setString(4, (String)json.get("configName"));
ps.executeUpdate(); System.out.println(ps.toString());
rs = ps.getGeneratedKeys();
bNum = ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if(rs.next()){ if(rs.next()){
id = rs.getInt(1); id = rs.getInt(1);
idList.add(id); idList.add(id);
} }
ps.close(); ps.close();
rs.close();
conn.commit();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -386,6 +474,37 @@ public class SqlHelper { ...@@ -386,6 +474,37 @@ public class SqlHelper {
} }
// public boolean insertCategoryByBotId(int botId, String categoryName) {
// String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
// int id = 0;
// boolean b = true;
// int bNum = 0;
// try {
// PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// ps.setString(1, String.valueOf(botId));
// ps.setString(2, "0");
// ps.setString(4, jConfig.getConfigName());
//
// System.out.println(ps.toString());
//
// bNum = ps.executeUpdate();
// ResultSet rs = ps.getGeneratedKeys();
// if(rs.next()){
// id = rs.getInt(1);
// idList.add(id);
// }
// ps.close();
// rs.close();
// conn.commit();
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return b;
//
// }
......
package entity; package com.qiwu.chatbotbackend.entity;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import GameEnvironment.GameEnv; import java.util.concurrent.ExecutionException;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
public class ChatCache { public class ChatCache {
private Map<String, String> infoPoint = null; private Map<String, String> infoPoint = null;
private GameEnv gameEnv = null; private GameEnv gameEnv = null;
...@@ -27,8 +29,17 @@ public class ChatCache { ...@@ -27,8 +29,17 @@ public class ChatCache {
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
} }
public ChatCache(GameEnv gameEnv, Map<String, String> infoPoint){
this.gameEnv = gameEnv;
this.infoPoint = infoPoint;
}
public ChatCache(UserInfo userInfo) throws Exception { public ChatCache(UserInfo userInfo) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount); gameEnv = new GameEnv(userInfo.botAccount);
}catch (Exception e){
System.out.println("游戏平台初始化失败");
}
String k; String k;
infoPoint = new HashMap<String, String>(); infoPoint = new HashMap<String, String>();
......
package entity; package com.qiwu.chatbotbackend.entity;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
......
package entity; package com.qiwu.chatbotbackend.entity;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
...@@ -38,6 +38,10 @@ public class JConfig { ...@@ -38,6 +38,10 @@ public class JConfig {
this.configName = configName; this.configName = configName;
} }
public String getConfigName() {
return configName;
}
private String configName = ""; private String configName = "";
public String getCurPremise() { public String getCurPremise() {
...@@ -56,7 +60,7 @@ public class JConfig { ...@@ -56,7 +60,7 @@ public class JConfig {
put("return", "return"); put("return", "return");
put("return-1", "back"); put("return-1", "back");
put("return-0", "stay"); put("return-0", "stay");
put("activate", "activate"); put("active", "activate");
} }
}; };
...@@ -125,7 +129,6 @@ public class JConfig { ...@@ -125,7 +129,6 @@ public class JConfig {
varName = iit.next(); varName = iit.next();
varValue = knowledge.get(varName); varValue = knowledge.get(varName);
sb.append("-<-" + varName + ":" + varValue); sb.append("-<-" + varName + ":" + varValue);
} }
if (!extraKL.equals("")) { if (!extraKL.equals("")) {
sb.append("-<-" + extraKL); sb.append("-<-" + extraKL);
...@@ -275,7 +278,6 @@ public class JConfig { ...@@ -275,7 +278,6 @@ public class JConfig {
data.put("nextStepList", nextStepList); data.put("nextStepList", nextStepList);
return data; return data;
} }
public String toString() { public String toString() {
......
package entity; package com.qiwu.chatbotbackend.entity;
/** /**
......
package entity; package com.qiwu.chatbotbackend.entity;
/** /**
......
package entity; package com.qiwu.chatbotbackend.entity;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
......
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.ArrayList; import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class CharacterConstructor extends ElementConstructor { public class CharacterConstructor extends ElementConstructor {
public CharacterConstructor(SqlHelper helper, int botId) { public CharacterConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
this.exceptRelation = exceptRelation;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject gameElements, UserInfo userinfo) {
String category, name, className, description, attrName, attrValue; String category, name, className, description, attrName, attrValue;
JSONArray allNPC = jsonObject.getJSONArray("npc");
try {
JSONArray allNPC = gameElements.getJSONArray("npc");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
HashSet<String> classSet = new HashSet<String>(); HashSet<String> classSet = new HashSet<String>();
//与npc属性相关的所有condition //与npc属性相关的所有condition
ArrayList<String> relateConditions = new ArrayList<String>(){ ArrayList<String> relateConditions = new ArrayList<String>() {
{ {
add("wenzainali"); add("wenzainali");
add("shishenme"); add("shishenme");
} }
}; };
//与npc类相关的所有condition //与npc类相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){ ArrayList<String> classRelateConditions = new ArrayList<String>() {
{ {
add("know_exist_what"); add("know_exist_what");
} }
}; };
//在condition的三元组中添加与NPC相关的关键词
String conditionValue = "哪里:人称", repValue; String conditionValue = "哪里:人称", repValue;
StringBuffer keywords = new StringBuffer(); StringBuffer keywords = new StringBuffer();
StringBuffer classKeywords = new StringBuffer(); StringBuffer classKeywords = new StringBuffer();
...@@ -47,15 +50,15 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -47,15 +50,15 @@ public class CharacterConstructor extends ElementConstructor {
for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { for (JSONObject character : allNPC.toJavaList(JSONObject.class)) {
name = (String) character.get("name"); name = (String) character.get("name");
className = (String)character.get("class"); className = (String) character.get("class");
if(!classSet.contains(className)) { if (!classSet.contains(className)) {
classSet.add(className); classSet.add(className);
classKeywords.append("+周围:" + className + "+附近" + className); classKeywords.append("+周围:" + className + "+附近:" + className);
} }
attribute = JSONObject.toJavaObject(character.getJSONObject("attr"), Map.class); attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class);
attrIter = attribute.keySet().iterator(); attrIter = attribute.keySet().iterator();
repValue = conditionValue.replace("人称", name); repValue = conditionValue.replace("人称", name);
keywords.append("+" + repValue); keywords.append("+" + repValue);
...@@ -64,11 +67,12 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -64,11 +67,12 @@ public class CharacterConstructor extends ElementConstructor {
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
} }
System.out.println(name); System.out.println(name);
} }
//根据根据NPC名字和属性查询属性值 //根据根据NPC名字和属性查询属性值
for(String conditionName: relateConditions) { for (String conditionName : relateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + keywords, " ", conditionName + "::match-Include=" + keywords, " ",
"match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName
...@@ -76,12 +80,17 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -76,12 +80,17 @@ public class CharacterConstructor extends ElementConstructor {
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
//根据根据NPC类别和地点属性查询所有NPC实例 //根据根据NPC类别和地点属性查询所有NPC实例
for(String conditionName: relateConditions) { for (String conditionName : relateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + classKeywords, " ", conditionName + "::match-Include=" + classKeywords, " ",
"match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAroundNpcByClassName:" + conditionName "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAroundNpcByClassName:" + conditionName
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
}catch (Exception e){
operationStatus = 0;
message = "NPC接口处理出现异常";
return;
}
} }
} }
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ElementConstructor { public class ElementConstructor {
int botId = 0; int botId = 0;
int operationStatus = 1;
SqlHelper helper = null; SqlHelper helper = null;
HashSet<String> exceptRelation = null;
JConfig jConfig = null;
String CHITCHAT_URL = "http:192.168.1.178:1111/test";
String userName;
String message = "";
List<JSONObject> configDataList = new ArrayList<JSONObject>(); List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<JConfig> jConfigList = new ArrayList<JConfig>(); List<JConfig> jConfigList = new ArrayList<JConfig>();
String CHITCHAT_URL = "http:192.168.1.178:1111/test", userName;
StringBuffer configText = new StringBuffer(); StringBuffer configText = new StringBuffer();
JConfig jConfig = null;
Map<String, String> varInitialMap = new HashMap<String, String>(); Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>(); Map<String, String> conditionDescription = new HashMap<String, String>();
public String getMessage() { return message; }
public int getOperationStatus() { return operationStatus; }
public Map<String, String> getVarInitialMap() { public Map<String, String> getVarInitialMap() {
return varInitialMap; return varInitialMap;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject gameElements, UserInfo userinfo) { }
}
public List<JConfig> getjConfigList() { public List<JConfig> getjConfigList() {
return jConfigList; return jConfigList;
...@@ -64,16 +76,51 @@ public class ElementConstructor { ...@@ -64,16 +76,51 @@ public class ElementConstructor {
} }
for (String varName : varInitialMap.keySet()) { for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName); varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue + "\n"); configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n");
}
} }
public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation){
String conditionName, pair[];
for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){
conditionName = (String) premise.get("actionName");
if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>());
}
for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
if(keyword.equals("")){
continue;
} else if(keyword.contains(":")){
pair = keyword.split(":");
relationKeywords.get(conditionName + "_head").add(pair[0]);
relationKeywords.get(conditionName + "_tail").add(pair[1]);
} else {
relationKeywords.get(conditionName + "_tail").add(keyword);
}
}
}
}
} }
/** /**
* 根据插入的数据做后处理 * 根据插入的数据做后处理
* @param idList * @param idList
*/ */
public void postProcessing(List<Integer> idList){} public void postProcessing(List<Integer> idList, int categoryId){}
/** /**
* 构造参数配置文件的json版 * 构造参数配置文件的json版
......
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
/** /**
* 弗洛伊德算法,用于构造地图时求最短路径 * 弗洛伊德算法,用于构造地图时求最短路径
......
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class GlobalVariableConstructor extends ElementConstructor { public class GlobalVariableConstructor extends ElementConstructor {
public GlobalVariableConstructor(SqlHelper helper, int botId) { public GlobalVariableConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
this.exceptRelation = exceptRelation;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject gameElements, UserInfo userinfo) {
try {
String category, name, description, attrName, attrValue; String category, name, description, attrName, attrValue;
JSONArray globalVariable = jsonObject.getJSONArray("globalVariable"); JSONArray globalVariable = gameElements.getJSONArray("globalVariable");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) { for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) {
category = (String) variableList.get("category"); category = (String) variableList.get("category");
attribute = JSONObject.toJavaObject(variableList.getJSONObject("variables"), Map.class); attribute = gameElements.toJavaObject(variableList.getJSONObject("variables"), Map.class);
attrIter = attribute.keySet().iterator(); attrIter = attribute.keySet().iterator();
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
...@@ -32,5 +37,10 @@ public class GlobalVariableConstructor extends ElementConstructor { ...@@ -32,5 +37,10 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put(category + "_" + attrName, attrValue); varInitialMap.put(category + "_" + attrName, attrValue);
} }
} }
}catch (Exception e){
operationStatus = 0;
message = "全局变量处理出现异常";
return;
}
} }
} }
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.ArrayList; import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class ItemConstructor extends ElementConstructor { public class ItemConstructor extends ElementConstructor {
public ItemConstructor(SqlHelper helper, int botId) { public ItemConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
this.exceptRelation = exceptRelation;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject gameElements, UserInfo userinfo) {
try {
String category, name, className, description, attrName, attrValue; String category, name, className, description, attrName, attrValue;
JSONArray goods = jsonObject.getJSONArray("goods"); JSONArray goods = gameElements.getJSONArray("goods");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
HashSet<String> classSet = new HashSet<String>(); HashSet<String> classSet = new HashSet<String>();
//与物品属性查询相关的所有condition //与物品属性查询相关的所有condition
ArrayList<String> attrRelateConditions = new ArrayList<String>(){ ArrayList<String> attrRelateConditions = new ArrayList<String>() {
{ {
add("nums"); add("nums");
add("shishenme"); add("shishenme");
} }
}; };
//与物品类查询相关的所有condition //与物品类查询相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){ ArrayList<String> classRelateConditions = new ArrayList<String>() {
{ {
add("know_exist_what"); add("know_exist_what");
} }
...@@ -47,20 +46,20 @@ public class ItemConstructor extends ElementConstructor { ...@@ -47,20 +46,20 @@ public class ItemConstructor extends ElementConstructor {
for (JSONObject good : goods.toJavaList(JSONObject.class)) { for (JSONObject good : goods.toJavaList(JSONObject.class)) {
name = (String) good.get("name"); name = (String) good.get("name");
className = (String)good.get("class"); className = (String) good.get("class");
if(!classSet.contains(className)) { if (!classSet.contains(className)) {
classSet.add(className); classSet.add(className);
//添加周围有什么士兵等关于类别的关键词 //添加周围有什么士兵等关于类别的关键词
classKeywords.append("+周围:" + className + "+附近" + className); classKeywords.append("+周围:" + className + "+附近:" + className);
} }
attribute = JSONObject.toJavaObject(good.getJSONObject("attr"), Map.class); attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class);
attrIter = attribute.keySet().iterator(); attrIter = attribute.keySet().iterator();
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
keywords.append( "+" + name + ":" + attrName) ; keywords.append("+" + name + ":" + attrName);
} }
...@@ -68,7 +67,7 @@ public class ItemConstructor extends ElementConstructor { ...@@ -68,7 +67,7 @@ public class ItemConstructor extends ElementConstructor {
} }
//根据根据物品名字和属性查询属性值 //根据根据物品名字和属性查询属性值
for(String conditionName : attrRelateConditions) { for (String conditionName : attrRelateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + keywords, " ", conditionName + "::match-Include=" + keywords, " ",
"match,return-0", "match,return-0",
...@@ -80,7 +79,7 @@ public class ItemConstructor extends ElementConstructor { ...@@ -80,7 +79,7 @@ public class ItemConstructor extends ElementConstructor {
} }
//根据类名和地点查询所有实例 //根据类名和地点查询所有实例
for(String conditionName : attrRelateConditions) { for (String conditionName : attrRelateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + classKeywords, " ", conditionName + "::match-Include=" + classKeywords, " ",
"match,return-0", "match,return-0",
...@@ -90,6 +89,11 @@ public class ItemConstructor extends ElementConstructor { ...@@ -90,6 +89,11 @@ public class ItemConstructor extends ElementConstructor {
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
} catch(Exception e){
operationStatus = 0;
message = "物品处理出现异常";
return;
}
} }
} }
package gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -16,10 +16,11 @@ public class MapConstructor extends ElementConstructor { ...@@ -16,10 +16,11 @@ public class MapConstructor extends ElementConstructor {
Map<String, String> question2keyword = new HashMap<String, String>(); Map<String, String> question2keyword = new HashMap<String, String>();
JSONArray locations = null; JSONArray locations = null;
public MapConstructor(SqlHelper helper, int botId) { public MapConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
this.exceptRelation = exceptRelation;
} }
...@@ -51,6 +52,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -51,6 +52,7 @@ public class MapConstructor extends ElementConstructor {
List<Integer> neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); List<Integer> neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class);
for (int neighbourId : neighbours) { for (int neighbourId : neighbours) {
JSONObject neighbourObject = id2j.get(neighbourId); JSONObject neighbourObject = id2j.get(neighbourId);
System.out.println(neighbourObject);
index = (Integer) neighbourObject.get("index"); index = (Integer) neighbourObject.get("index");
matrix[i][index] = 1; matrix[i][index] = 1;
matrix[index][i] = 1; matrix[index][i] = 1;
...@@ -58,13 +60,16 @@ public class MapConstructor extends ElementConstructor { ...@@ -58,13 +60,16 @@ public class MapConstructor extends ElementConstructor {
} }
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) {
public void construct(JSONObject gameElements, UserInfo userinfo) {
try {
conditionDescription.put("site", "当前地点"); conditionDescription.put("site", "当前地点");
varInitialMap.put("site", "海边"); varInitialMap.put("site", "海边");
JSONObject map = jsonObject.getJSONObject("map"); JSONObject map = gameElements.getJSONObject("map");
Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class);
JSONArray locations = map.getJSONArray("locations"); JSONArray locations = map.getJSONArray("locations");
String userName = (String)jsonObject.get("userName"); String userName = (String) gameElements.get("userName");
this.locations = locations; this.locations = locations;
this.question2keyword = question2keyword; this.question2keyword = question2keyword;
//通过邻接表构造邻接矩阵 //通过邻接表构造邻接矩阵
...@@ -74,21 +79,28 @@ public class MapConstructor extends ElementConstructor { ...@@ -74,21 +79,28 @@ public class MapConstructor extends ElementConstructor {
Floyd floyd = new Floyd(); Floyd floyd = new Floyd();
floyd.findShortestPath(matrix, locationNum); floyd.findShortestPath(matrix, locationNum);
floyd.printPath(matrix, locationNum); floyd.printPath(matrix, locationNum);
generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements);
generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject); generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements);
generateWhereIam(jsonObject, userName); generateWhereIam(gameElements, userName);
generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements);
generateSurroundingItem(); generateSurroundingItem();
generateSurroundingPeople(); generateSurroundingPeople();
generateSurroundThings();
} catch(Exception e){
operationStatus = 0;
message = "地图处理出现异常";
return;
}
} }
/** /**
* 生成‘我在哪里’所需要的配置文件 * 生成‘我在哪里’所需要的配置文件
*/ */
public void generateWhereIam(JSONObject jsonObject, String botName) { public void generateWhereIam(JSONObject gameElements, String botName) {
String conditionName = "rencheng"; String conditionName = "rencheng";
String conditionKeywords = "botName:哪里+botName:哪"; String conditionKeywords = "qiwu:哪里+qiwu:哪+现在:哪里+现在:哪";
String zainaliKeywords = conditionKeywords.replace("botName", botName); String zainaliKeywords = conditionKeywords.replace("botName", botName);
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + zainaliKeywords, " ", conditionName + "::match-Include=" + zainaliKeywords, " ",
...@@ -105,7 +117,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -105,7 +117,7 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) {
String conditionName = "want_know_zenmezuo"; String conditionName = "want_know_zenmezuo";
String conditionKeywords = "去:地点"; String conditionKeywords = "去:地点";
...@@ -158,8 +170,8 @@ public class MapConstructor extends ElementConstructor { ...@@ -158,8 +170,8 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 生成‘我能去哪里’所需要的配置文件 * 生成‘我能去哪里’所需要的配置文件
*/ */
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) {
String conditionKeywords = "能去:哪+能去:哪里+能去:哪儿"; String conditionKeywords = "去:哪里+能去:哪+能去:哪里+能去:哪儿";
String conditionName = "choose_gowhere"; String conditionName = "choose_gowhere";
String placeA, placeB, pathNode; String placeA, placeB, pathNode;
...@@ -186,15 +198,28 @@ public class MapConstructor extends ElementConstructor { ...@@ -186,15 +198,28 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 生成‘我要去那里’所需要的配置文件 * 生成‘我要去那里’所需要的配置文件
*/ */
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) { public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) {
String placeA, placeB, descriptionB, placeKeywords, text, pathNode, lastTaskCondition, lastTaskReply; String placeA, placeB, descriptionB, placeKeywords, text, pathNode, lastTaskCondition, lastTaskReply;
String conditionName = "quna"; String conditionName = "yaobuyao";
String conditionKeywords = "地点"; String conditionKeywords = "地点";
String start = (String)gameElements.get("start");
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
for (int j = 0; j < locationNum; j++) {
placeA = (String) locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
/**
* 添加初始化变量
*/
if(!varInitialMap.containsKey("任务线" + placeA + "最后一个condition")) {
varInitialMap.put("任务线" + placeA + "最后一个condition", "yaobuyao");
varInitialMap.put("任务线" + placeA + "最后的回答", "你来到了" + placeA + ",现在什么都没有, 请继续之前的剧情,接着往下玩吧!");
conditionDescription.put("任务线" + placeA + "最后一个condition", "任务线" + placeA + "最后一个condition");
conditionDescription.put("任务线" + placeA + "最后的回答", "任务线" + placeA + "最后的回答");
}
for (int j = 0; j < locationNum; j++) {
placeB = (String) locations.getJSONObject(j).get("name"); placeB = (String) locations.getJSONObject(j).get("name");
descriptionB = (String) locations.getJSONObject(j).get("description"); descriptionB = (String) locations.getJSONObject(j).get("description");
placeKeywords = conditionKeywords.replace("地点", placeB); placeKeywords = conditionKeywords.replace("地点", placeB);
...@@ -229,6 +254,8 @@ public class MapConstructor extends ElementConstructor { ...@@ -229,6 +254,8 @@ public class MapConstructor extends ElementConstructor {
//如果两点不是相邻点 //如果两点不是相邻点
} else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) { } else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) {
int k = preTable[i][j]; int k = preTable[i][j];
pathNode = ""; pathNode = "";
while (k != j) { while (k != j) {
...@@ -252,7 +279,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -252,7 +279,7 @@ public class MapConstructor extends ElementConstructor {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + conditionKeywords, " ", conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:" "match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
...@@ -263,7 +290,18 @@ public class MapConstructor extends ElementConstructor { ...@@ -263,7 +290,18 @@ public class MapConstructor extends ElementConstructor {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + conditionKeywords, " ", conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:" "match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:"
);
jConfigList.add(jConfig);
}
public void generateSurroundThings(){
String conditionName = "know_exist_what_mohu";
String conditionKeywords = "有什么:周围+有什么:附近";
jConfig = new JConfig(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundAllBySite:"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
......
Manifest-Version: 1.0
Main-Class: com.qiwu.chatbotbackend.ChatbotBackendApplication
package com.qiwu.chatbotbackend.GameEnvironment;
import com.qiwu.chatbotbackend.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 com.qiwu.chatbotbackend.GameEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectFileUtil {
// obj 任意可以序列化的对象 fileAllName 文件全名
public static boolean writeObjectToFile(Object obj, String fileAllName) {
File file =new File(fileAllName);
FileOutputStream out;
try {
out = new FileOutputStream(file);
ObjectOutputStream objOut=new ObjectOutputStream(out);
objOut.writeObject(obj);
objOut.flush();
objOut.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
// fileAllName 文件全名
public static Object readObjectFromFile(String fileAllName)
{
Object temp=null;
File file =new File(fileAllName);
FileInputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream objIn=new ObjectInputStream(in);
temp=objIn.readObject();
objIn.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return temp;
}
}
package com.qiwu.chatbotbackend.GameEnvironment;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 com.qiwu.chatbotbackend.GameEnvironment.bean;
import java.io.Serializable;
public class Attr implements Serializable{
private static final long serialVersionUID = 1L;
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 com.qiwu.chatbotbackend.GameEnvironment.bean;
import java.io.Serializable;
import java.util.List;
public class GoodsInstance extends SuperClass implements Serializable{
private static final long serialVersionUID = 1L;
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 com.qiwu.chatbotbackend.GameEnvironment.bean;
import java.io.Serializable;
import java.util.List;
public class NpcInstance extends SuperClass implements Serializable{
private static final long serialVersionUID = 1L;
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 com.qiwu.chatbotbackend.GameEnvironment.bean;
import java.io.Serializable;
import java.util.List;
public class Place implements Serializable{
private static final long serialVersionUID = 1L;
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 com.qiwu.chatbotbackend.GameEnvironment.bean;
import java.io.Serializable;
import java.util.List;
public class SuperClass implements Serializable{
private static final long serialVersionUID = 1L;
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 + "]";
}
}
package com.qiwu.chatbotbackend.db;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class C3p0Utils {
static Logger logger = Logger.getLogger(C3p0Utils.class.getName());
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
//从连接池中取用一个连接
public static Connection getConnection() throws SQLException {
try {
return dataSource.getConnection();
} catch (Exception e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
//释放连接回连接池
public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
}
}
package com.qiwu.chatbotbackend.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DB {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN";
private static String user = "root";
private static String pwd = "admin";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
package com.qiwu.chatbotbackend.db;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBCPUtils {
private static DataSource ds;//定义一个连接池对象
static {
try {
Properties pro = new Properties();
File file = new File("dbcpconfig.properties");
pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"));
ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象
} catch (Exception e) {
e.printStackTrace();
//throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!");
}
}
//从池中获取一个连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();//关闭
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
\ No newline at end of file
package com.qiwu.chatbotbackend.db;
public class DBUtils {
}
package com.qiwu.chatbotbackend.entity;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
public class ChatCache {
private Map<String, String> infoPoint = null;
private GameEnv gameEnv = null;
public Map<String, String> getInfoPoint() {
return infoPoint;
}
public void setInfoPoint(Map<String, String> infoPoint) {
this.infoPoint = infoPoint;
}
public GameEnv getGameEnv() {
return gameEnv;
}
public void setGameEnv(GameEnv gameEnv) {
this.gameEnv = gameEnv;
}
public ChatCache(UserInfo userInfo) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount);
}catch (Exception e){
System.out.println("游戏平台初始化失败");
}
String k;
infoPoint = new HashMap<String, String>();
Iterator<String> iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k));
}
}
}
package com.qiwu.chatbotbackend.entity;
import java.util.HashMap;
import java.util.HashSet;
/**
* 保存配置文件每一行(单行)解析后的信息的实体类。
* 独立于引擎的另一种condition
*/
public class Condition {
public int priority = -1;
public int activePriority = 0; //如果本condition被其他condition激活
public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级
public HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, String> updateKnowledge = new HashMap<String, String>();
public String[] answer = {"",};
public String nextStep = "";
public HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = "";
public int id = 0;
public String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>();
public Condition(int priority) {
this.priority = priority;
this.activePriority = priority;
}
public Condition(Condition originCondition, int basePriority, int baseAuxiliaryPriority) {
this.priority = originCondition.priority;
this.keywordSet = originCondition.keywordSet;
this.historyPremise = originCondition.historyPremise;
this.currentPremise = originCondition.currentPremise;
this.answer = originCondition.answer;
this.nextStep = originCondition.nextStep;
this.featureMap = originCondition.featureMap;
this.updateKnowledge = originCondition.updateKnowledge;
this.indexName = originCondition.indexName;
this.id = originCondition.id;
this.status = originCondition.status;
this.activePriority = originCondition.activePriority + basePriority;
this.auxiliaryPriority = originCondition.auxiliaryPriority + baseAuxiliaryPriority;
}
public Condition() {
}
}
package com.qiwu.chatbotbackend.entity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class JConfig {
private int id = 0;
private String jCurPremise = "";
private String jHisPremise = "";
private String jFeature = "";
private String jNextStep = "";
private String jReply = "";
private String jAuxiliaryPriority = "0";
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
private int jStatus = 0;
private String curPremise = "";
private String hisPremise = "";
private String feature = "";
private String reply = "";
private String nextStep = "";
public void setConfigName(String configName) {
this.configName = configName;
}
public String getConfigName() {
return configName;
}
private String configName = "";
public String getCurPremise() {
return curPremise;
}
private String auxiliaryPriority = "0";
private String status = "waiting";
private String updateKnowledge = "";
private String nextStepStatus = "return";
Map<String, String> statusMap = new HashMap<String, String>() {
{
put("return", "return");
put("return-1", "back");
put("return-0", "stay");
put("active", "activate");
}
};
public void setStatus(String status) {
this.status = status;
}
public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority;
}
public void setNextStepStatus(String nextStepStatus) {
this.nextStepStatus = nextStepStatus;
}
public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) {
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
if (!updateKnowledge.equals(""))
this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply;
this.nextStep = nextStep;
}
public JConfig(List<String> curPremise, List<String> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
this.feature = feature;
this.reply = reply;
this.nextStep = nextStep;
this.auxiliaryPriority = auxiliaryPriority;
}
public String appendPremiseStr(List<String> premises, String extraPM) {
StringBuffer sb = new StringBuffer();
String premiseStr = "";
for (String premise : premises)
sb.append("," + premise);
if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号
if (!extraPM.equals("")) {
if (sb.length() == 0)
sb.append(extraPM);
else
sb.append("," + extraPM);
} else if (sb.length() == 0) {
sb.append(" ");
}
premiseStr = sb.toString();
return premiseStr;
}
public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator();
while (iit.hasNext()) {
varName = iit.next();
varValue = knowledge.get(varName);
sb.append("-<-" + varName + ":" + varValue);
}
if (!extraKL.equals("")) {
sb.append("-<-" + extraKL);
}
if (sb.length() > 0)
knowledgeStr = "updateKnowledge" + sb.toString();
else
knowledgeStr = "";
return knowledgeStr;
}
public void appendJPremise(JSONArray premiseList, String premise, Map<String, String> conditionDescription) {
//System.out.println(premise);
String pair1[] = premise.split("=", 2);
String key = pair1[0];
String keywords = pair1[1];
String pair2[] = key.split("::");
String conditionName = pair2[0];
String pair3[] = pair2[1].split("-");
String cmpType = pair3[0];
String operator = "";
if (pair3.length > 1)
operator = pair3[1];
String question = "";
if (conditionDescription.get(conditionName) != null)
question = conditionDescription.get(conditionName);
JSONObject premiseJ = new JSONObject();
premiseJ.put("keywords", keywords);
premiseJ.put("actionName", conditionName);
premiseJ.put("cmpType", cmpType);
premiseJ.put("question", question);
premiseJ.put("operator", operator);
premiseList.add(premiseJ);
}
public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) {
String pair[] = knowledge.split(":", 2);
if (knowledge.equals("") || pair.length < 2)
return;
String question = "";
if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]);
JSONObject knowledgeJ = new JSONObject();
knowledgeJ.put("variableName", pair[0]);
knowledgeJ.put("keyword", pair[1]);
knowledgeList.add(knowledgeJ);
}
public void appendJNextStep(JSONArray nextStepList, String next, Map<String, String> conditionDescription) {
String pair[] = next.split("-");
JSONObject nextStepJ = new JSONObject();
JSONArray exceptJ = new JSONArray();
for (int i = 1; i < pair.length; i++)
exceptJ.add(pair[i]);
String question = "";
if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]);
nextStepJ.put("nextStep", pair[0]);
nextStepJ.put("except", exceptJ);
nextStepJ.put("nextStepText", question);
nextStepList.add(nextStepJ);
}
public JSONObject toJson(Map<String, String> conditionDescription) {
JSONObject data = new JSONObject();
JSONArray curPremiseList = new JSONArray();
JSONArray hisPremiseList = new JSONArray();
//添加当前对话内容
for (String premise : curPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" "))
appendJPremise(curPremiseList, premise, conditionDescription);
}
data.put("currentPremiseList", curPremiseList);
//添加已知信息的内容
for (String premise : hisPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" "))
appendJPremise(hisPremiseList, premise, conditionDescription);
}
data.put("historyPremiseList", hisPremiseList);
//添加下一步状态
data.put("nextStepStatus", statusMap.get(nextStepStatus));
//添加configName
data.put("configName", configName);
//添加config状态
data.put("configStatus", jStatus);
boolean doPost = false;
String postURL = "", postType = "all", pair[];
for (String feat : feature.split(",")) {
if (feat.startsWith("post")) {
doPost = true;
pair = feat.substring(0, feat.length() - 1).split("\\(", 2);
postURL = pair[1];
postType = pair[0].split("::")[1];
}
}
//添加post参数
data.put("doPost", doPost);
data.put("postURL", postURL);
data.put("postType", postType);
//添加回答
data.put("reply", reply);
//添加config类别id
data.put("categoryId", 0);
//添加辅助优先级
data.put("auxiliaryPriority", auxiliaryPriority);
//添加更新答案处的信息
JSONArray knowledgeList = new JSONArray();
if (!updateKnowledge.equals("")) {
for (String knowledge : updateKnowledge.split("-<-")) {
appendJKnowledge(knowledgeList, knowledge, conditionDescription);
}
}
data.put("updateKnowledge", knowledgeList);
//添加下一步
JSONArray nextStepList = new JSONArray();
for (String next : nextStep.split(",")) {
appendJNextStep(nextStepList, next, conditionDescription);
}
data.put("nextStepList", nextStepList);
return data;
}
public String toString() {
String text = curPremise + "|" +
hisPremise + "|" +
feature + "," + updateKnowledge + "," + nextStepStatus + "|" +
"auxiliaryPriority=" + auxiliaryPriority + "|=>|" +
reply + "|" +
"nextStep=" + nextStep + "|" +
"status=" + status + "|" +
"configId=";
return text;
}
}
package com.qiwu.chatbotbackend.entity;
/**
* 暂时没用
*/
public class QuestionKeyWord {
private String actionName;
private String chatKey;
private String keyWord;
public String getActionName() {
return actionName;
}
public String getChatKey() {
return chatKey;
}
public String getKeyWord() {
return keyWord;
}
public void setActionName(String actionName) {
this.actionName = actionName;
}
public void setChatKey(String chatKey) {
this.chatKey = chatKey;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
}
package com.qiwu.chatbotbackend.entity;
/**
* 包含后台返回数据的实体类。
*/
public class Solution {
private int status = 0;
private String answer;
private String next;
public String getAnswer() {
return answer;
}
public int getStatus() {
return status;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public void setStatus(int status) {
this.status = status;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public Solution(int status, String answers, String next) {
this.answer = answers;
this.next = next;
this.status = status;
}
public Solution() {
}
}
package com.qiwu.chatbotbackend.entity;
import java.util.HashMap;
import java.util.List;
/**
* 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里
*/
public class UserInfo {
public UserInfo(String botAccount) {
this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = "";
this.botAccount = botAccount;
this.extraInfo = new HashMap<String, String>() {
{
put("activeAction", " ");
}
};
this.id2config = new HashMap<Integer, String>();
this.id2condition = new HashMap<Integer, Condition>();
this.varInitialMap = new HashMap<String, String>();
}
public HashMap<String, List<Condition>> conditionTable;
public String configStr;
public String botAccount;
public HashMap<String, String> extraInfo;
public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition;
//存储需要初始化的变量
public HashMap<String, String> varInitialMap;
}
package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*;
public class CharacterConstructor extends ElementConstructor {
public CharacterConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super();
this.helper = helper;
this.botId = botId;
this.exceptRelation = exceptRelation;
}
public void construct(JSONObject gameElements, UserInfo userinfo) {
String category, name, className, description, attrName, attrValue;
try {
JSONArray allNPC = gameElements.getJSONArray("npc");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
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");
}
};
//在condition的三元组中添加与NPC相关的关键词
String conditionValue = "哪里:人称", repValue;
StringBuffer keywords = new StringBuffer();
StringBuffer classKeywords = new StringBuffer();
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 = gameElements.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);
}
}catch (Exception e){
operationStatus = 0;
message = "NPC接口处理出现异常";
return;
}
}
}
package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*;
public class ElementConstructor {
int botId = 0;
int operationStatus = 1;
SqlHelper helper = null;
HashSet<String> exceptRelation = null;
JConfig jConfig = null;
String CHITCHAT_URL = "http:192.168.1.178:1111/test";
String userName;
String message = "";
List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<JConfig> jConfigList = new ArrayList<JConfig>();
StringBuffer configText = new StringBuffer();
Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>();
public String getMessage() { return message; }
public int getOperationStatus() { return operationStatus; }
public Map<String, String> getVarInitialMap() {
return varInitialMap;
}
public void construct(JSONObject gameElements, UserInfo userinfo) { }
public List<JConfig> getjConfigList() {
return jConfigList;
}
public Map<String, String> getConditionDescription() {
return conditionDescription;
}
public List<JSONObject> getConfigDataList() {
return configDataList;
}
public void ElementConstructor(String userName) {
this.userName = userName;
}
public String getConfigText() {
return configText.toString();
}
public void generateConfigText(List<Integer> idList) {
int id, length = idList.size();
String varValue;
JConfig jConfig = null;
for (int i = 0; i < length; i++) {
jConfig = jConfigList.get(i);
id = idList.get(i);
configText.append(jConfig.toString() + id + "\n");
}
for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n");
}
}
public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation){
String conditionName, pair[];
for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){
conditionName = (String) premise.get("actionName");
if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>());
}
for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
if(keyword.equals("")){
continue;
} else if(keyword.contains(":")){
pair = keyword.split(":");
relationKeywords.get(conditionName + "_head").add(pair[0]);
relationKeywords.get(conditionName + "_tail").add(pair[1]);
} else {
relationKeywords.get(conditionName + "_tail").add(keyword);
}
}
}
}
}
/**
* 根据插入的数据做后处理
* @param idList
*/
public void postProcessing(List<Integer> idList, int categoryId){}
/**
* 构造参数配置文件的json版
*/
public void buildJconfig() {
}
}
package com.qiwu.chatbotbackend.gameDesign;
/**
* 弗洛伊德算法,用于构造地图时求最短路径
*/
public class Floyd {
/**
* 表示正无穷
*/
int MAX_WEIGHT = Integer.MAX_VALUE;
/**
* 路径矩阵
*/
int[][] pathMatirx;
/**
* 前驱表
*/
int[][] preTable;
public void findShortestPath(int[][] matrix, int length) {
//路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。
pathMatirx = new int[length][length];
//前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值
preTable = new int[length][length];
/*
System.out.println("matrix");
for (int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
*/
//初始化D,P
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
pathMatirx[i][j] = matrix[i][j];
preTable[i][j] = j;
}
}
//循环 中间经过顶点
for (int k = 0; k < length; k++) {
//循环所有路径
for (int m = 0; m < length; m++) {
for (int n = 0; n < length; n++) {
int mn = pathMatirx[m][n];
int mk = pathMatirx[m][k];
int kn = pathMatirx[k][n];
int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn;
if (mn > addedPath) {
//如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个
pathMatirx[m][n] = addedPath;
//前驱设置为经过下标为k的顶点
preTable[m][n] = preTable[m][k];
}
}
}
}
/*
System.out.println("pathMatrix");
for (int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
System.out.print(pathMatirx[i][j] + " ");
}
System.out.println();
}
*/
}
/**
* 打印 所有最短路径
*/
public void printPath(int[][] matrix, int length) {
for (int m = 0; m < length; m++) {
for (int n = m + 1; n < length; n++) {
int k = preTable[m][n];
System.out.print("(" + m + "," + n + ")" + pathMatirx[m][n] + ": ");
System.out.print(m);
while (k != n) {
System.out.print("->" + k);
k = preTable[k][n];
}
System.out.println("->" + n);
}
System.out.println();
}
}
}
package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class GlobalVariableConstructor extends ElementConstructor {
public GlobalVariableConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super();
this.helper = helper;
this.botId = botId;
this.exceptRelation = exceptRelation;
}
public void construct(JSONObject gameElements, UserInfo userinfo) {
try {
String category, name, description, attrName, attrValue;
JSONArray globalVariable = gameElements.getJSONArray("globalVariable");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) {
category = (String) variableList.get("category");
attribute = gameElements.toJavaObject(variableList.getJSONObject("variables"), Map.class);
attrIter = attribute.keySet().iterator();
while (attrIter.hasNext()) {
attrName = attrIter.next();
attrValue = attribute.get(attrName);
varInitialMap.put(category + "_" + attrName, attrValue);
}
}
}catch (Exception e){
operationStatus = 0;
message = "全局变量处理出现异常";
return;
}
}
}
package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*;
public class ItemConstructor extends ElementConstructor {
public ItemConstructor(SqlHelper helper, int botId, HashSet<String> exceptRelation) {
super();
this.helper = helper;
this.botId = botId;
this.exceptRelation = exceptRelation;
}
public void construct(JSONObject gameElements, UserInfo userinfo) {
try {
String category, name, className, description, attrName, attrValue;
JSONArray goods = gameElements.getJSONArray("goods");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
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);
}
attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class);
attrIter = attribute.keySet().iterator();
while (attrIter.hasNext()) {
attrName = attrIter.next();
attrValue = attribute.get(attrName);
keywords.append("+" + name + ":" + attrName);
}
}
//根据根据物品名字和属性查询属性值
for (String conditionName : attrRelateConditions) {
jConfig = new JConfig(
conditionName + "::match-Include=" + keywords, " ",
"match,return-0",
"{goods_query-2}",
" ",
"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);
}
} catch(Exception e){
operationStatus = 0;
message = "物品处理出现异常";
return;
}
}
}
package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.alibaba.fastjson.JSON;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ChatCacheController {
/**
* 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点)
*
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
// 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);
// }
/**
* 根据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 boolean saveChatCache(String userName, HashMap<String, String> infoPoints) throws IOException {
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String key;
boolean saveFlag = true;
try {
File dir = new File(fileDir);
if (!dir.exists())
dir.mkdir();
File file = new File(fileDir + "/" + userName + ".txt");
FileWriter fw = new FileWriter(file);
Iterator<String> infoIter = infoPoints.keySet().iterator();
while (infoIter.hasNext()) {
key = infoIter.next();
fw.write(key + "-----" + infoPoints.get(key) + "\n");
}
fw.close();
} catch (Exception e) {
saveFlag = false;
}
return saveFlag;
}
public static boolean loadChatCache(String userName, ServletContext context) {
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>();
try {
File file = new File(fileDir + "/" + userName + ".txt");
if (!file.exists()) {
return false;
} else {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
pair = line.trim().split("-----");
infoPoints.put(pair[0], pair[1]);
}
// context.setAttribute(userName, );
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static synchronized ChatCache getChatCache(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(userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
}
String chatkey;
try {
chatCache = chatCacheMap.get(chatKey);
if(chatCache == null){
chatCache = new ChatCache(userinfo);
chatCacheMap.put(chatKey, chatCache);
}
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) {
//可整合
chatCache = new ChatCache(userinfo);
}
return chatCache;
}
/**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/
public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context) {
String chatKey;
ChatCache chatCache = null;
long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>();
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
Iterator<String> it = chatCacheMap.keySet().iterator();
while (it.hasNext()) {
chatKey = it.next();
if(curChatKey.equals(chatKey))
continue;
history = chatCacheMap.get(chatKey).getInfoPoint();
lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis();
if (now - lastChatTime > 300000) {
chatCache = chatCacheMap.get(chatKey);
saveChatCache(chatKey, chatCache);
it.remove();
}
}
context.setAttribute("chatCache", chatCacheMap);
}
/**
* 根据chatKey更新chatCache的数据,并修改最后更新时间
*/
public static synchronized void updateChatCache4Insert(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"));
chatCache.setInfoPoint(historyInfoPoint);
chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap);
}
public static synchronized String saveChatCache(String chatKey, ChatCache chatCache){
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 com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId);
Condition condition = new Condition();
UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
String conditionName = "";
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userInfo = (UserInfo) context.getAttribute(userName);
if (userInfo.id2config.containsKey(id)) {
//-------------------
try {
Condition oldCondition = userInfo.id2condition.get(id);
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == id) {
condIter.remove();
}
}
}
userInfo.id2config.remove(id);
userInfo.id2condition.remove(id);
} else {
System.out.println("未找到要删除的configId");
}
return true;
}
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition();
String conditionName = "";
for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) {
try {
Condition oldCondition = userInfo.id2condition.get(configId);
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == configId) {
condIter.remove();
}
}
}
userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId);
} else {
System.out.println("未找到要删除的configId:" + configId);
}
}
return true;
}
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[];
UserInfoController userInfoController = new UserInfoController();
int id = Integer.parseInt(configId);
condition = userInfoController.buildCondition(condition, configLine);
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.conditionTable.get(condition.indexName) == null) {
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(condition.indexName, conditionList);
}
userinfo.conditionTable.get(condition.indexName).add(condition);
userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, condition);
return true;
}
public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---", -1);
String name = dataPair[0], value = dataPair[1];
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.put(name, value);
return true;
}
public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException {
//data=configLine+"---"+conditionNameList
String name = data;
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.remove(name);
return true;
}
public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
return true;
}
public static String writeConfigText(String userName, UserInfo userinfo) throws IOException {
System.out.println("p");
System.out.println(userName);
String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText;
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir") + "/config");
String returnMessage = "success";
if (!dir.exists())
dir.mkdir();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if (!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
keyIter = userinfo.varInitialMap.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n");
}
Iterator<Integer> idIter = userinfo.id2config.keySet().iterator();
while (idIter.hasNext()) {
int id = idIter.next();
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
} catch (Exception e) {
e.printStackTrace();
returnMessage = "config file write error";
} finally {
bw.close();
fw.close();
}
return returnMessage;
}
}
package com.qiwu.chatbotbackend.processing;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
public class LogWriter {
private PrintWriter recorder = null;
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss");
LocalDateTime ldt = null;
String PRINT_PATTERN = "<font color=\"%s\">[%s] %s" +
"----------------------------------------------------------------------------<br></font>";
Map<Integer, String> colerMap = new HashMap<Integer, String>(){
{
put(0, "black");
put(1, "gray");
put(2, "green");
put(3, "yellow");
put(4, "green");
put(5, "red");
}
};
public LogWriter(String filePath, String fileName) throws IOException {
File file = new File(filePath + "/" + fileName + ".html");
System.out.println(file.getAbsolutePath());
if (!file.exists()) {
file.createNewFile();
}
file.setReadable(true,false);
FileWriter fw = new FileWriter(file, true);
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){
ldt = LocalDateTime.now();
recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), ldt.format(dtf), text));
}
public void writeln(){
recorder.println("<br>");
}
public void close(){
recorder.close();
}
}
package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.Solution;
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;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class MyFunc {
/**
* 将后台返回的数据转成json格式
*/
public static String toJson(Solution ans) {
JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus());
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject();
jobj.put("returnString", returnStr);
return jobj.toString();
}
/**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据
*
* @param request
* @return json字符串
*/
public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
json.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 通过get方法传递参数时需要对参数的编码进行转换
*/
public static String convert2Utf8(String s) {
if (s == null) return null;
try {
s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
public static long transferToMillisecond(String keyword) throws ParseException {
long time;
System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"};
for (String f : timeSeries) {
if (!keyword.contains(f))
keyword += "0" + f;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
time = format.parse(keyword).getTime();
return time;
}
public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
Date date = new Date(time);
return format.format(date);
}
public static boolean isInteger(String str){
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;
}
}
package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.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 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;
List<String> textList = null;
String subValuePair[] = null;
logWriter.record(String.format("---------------------key:%s, value:%s", varName, varValue), 0);
if(valuePair[0].startsWith("query")){ //查询专用
if(varName.startsWith("goods_")) {
switch (valuePair[0]) {
case "queryGoodsIntro":
subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]);
if(returnStr == null )
returnStr = "无";
break;
case "queryAttrByGoodsName":
subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
subValuePair[0] = subValuePair[0].replace("哪里", "location");
returnStr = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]);
if(returnStr == null)
returnStr = "无";
break;
case "queryAllAttrByGoodsName":
textList = gameEnv.queryGoodsAllAttrByGoodsName(varName);
if(textList == null || textList.size() == 0)
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 || textList.size() == 0)
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 || sites.size() == 0)
returnStr = "啥都没有";
else {
returnStr = "有";
if(sites.size() > 0) {
for (String site : sites)
returnStr += "、" + site;
}else{
returnStr = "啥都没有";
}
}
}
}else { //增删改统一使用
gameEnv.CUD(varName, valuePair[0], valuePair[1]);
}
logWriter.record("---------------------return:" + returnStr, 0);
return returnStr;
}
}
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.processing.*;
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.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"})
public class GetAnswerServlet extends HttpServlet {
/**
* GetAnswerServlet就是处理post请求并返回答案的入口
*/
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[]> 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 = receiveParamters.get("chat_key")[0];
String botName = receiveParamters.get("bot_name")[0];
OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext();
boolean debugFlag = false;
LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
UserInfo userinfo = null;
UserInfoController uiController = new UserInfoController();
try {
//userinfo = process.userInfoQuery(chatKey,context);
//从servlet根据用户名查询用户信息
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context);
} catch (SQLException e) {
state = NAME_MISSING_ERROR;
e.printStackTrace();
}
if(userinfo != null) {
//获得用户历史信息
ChatCache chatCache = null;
try {
chatCache = ChatCacheController.getChatCache(chatKey, context, userinfo);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
historyInfoPoint = chatCache.getInfoPoint();
//信息点预处理
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(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,";
if (state.equals("")) {
try {
bestMatch = matcher.getSolution(ansCondition, context, userinfo);
if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansCondition, context, userinfo);
}
} catch (ParseException e) {
e.printStackTrace();
}
//清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > 300000) {
ChatCacheController.updateChatCache4Delete(chatKey, context);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
}
//bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
} else {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction"));
}
if (debugFlag) {
matcher.appendDebugInfo(bestMatch, context);
}
matcher.infoTransfer(bestMatch, context, debugFlag);
ansJ = MyFunc.toJson(bestMatch);
} else {
ansJ = "找不到配置文件";
}
logWriter.writeln();
logWriter.writeln();
logWriter.record("-----------------------------------------对话处理结束", 0);
logWriter.writeln();
logWriter.writeln();
logWriter.close();
System.out.println(ansJ);
out.write(ansJ.getBytes());
out.flush();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("do get method");
}
}
package com.qiwu.chatbotbackend.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.*;
@WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"})
public class GetConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String path = "config/" + userName + ".txt";
File file = new File(path);
OutputStream out = response.getOutputStream();
if (file.exists()) {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
line = line + "\n";
out.write(line.getBytes());
}
fr.close();
br.close();
} else {
out.write("查无此bot".getBytes());
}
out.flush();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.qiwu.chatbotbackend.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 {
}
}
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.UserInfoController;
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.*;
/**
* 发请求从本地文件夹重新加载某用户的配置文件
*/
@WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"})
public class ReloadConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String botAccount = request.getParameter("botAccount");
boolean flag = true;
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("文件不存在: " + botAccount);
} else {
FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader);
try {
userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) {
flag = false;
System.out.println(userinfo.botAccount + ".txt 有误");
e.printStackTrace();
}
reader.close();
br.close();
if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(111);
PrintWriter out = response.getWriter();
out.println("更新失败配置文件有误:" + botAccount + ".txt\\\n");
} else {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("重新加载成功");
out.flush();
out.close();
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.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();
}
}
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.MyFunc;
import com.qiwu.chatbotbackend.processing.UserInfoController;
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.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。
*/
@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"})
public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。
request.setCharacterEncoding("UTF-8");
String line, extraElements[];
ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext();
String botAccount = request.getParameter("botAccount");
UserInfo userinfo = new UserInfo(botAccount);
userinfo.conditionTable = new HashMap<String, List<Condition>>();
List<Condition> conditionList = null;
HashSet<String> keyWordSet = null;
BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string")));
boolean flag = true;
String errorStr = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
if (line.trim().equals(""))
continue;
line = line.replace("\n", "");
//在用户信息中添加额外信息,如设为active的action
if (line.indexOf("-extraInfo-") != -1) {
extraElements = line.split("\\|");
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
userinfo.configStr += line + "\n";
continue;
}
//line = MyFunc.convert2Utf8(line.trim());
userinfo.configStr += line + "\n";
Condition condition = new Condition();
try {
condition = UserInfoController.buildCondition(condition, line);
conditionList = userinfo.conditionTable.get(condition.indexName);
if (conditionList == null)
conditionList = new ArrayList<Condition>();
conditionList.add(condition);
userinfo.conditionTable.put(condition.indexName, conditionList);
/*
for(String name:condition.indexName){
userinfo.conditionTable.put()
}
*/
} catch (Exception e) {
System.out.println("配置文件有误!");
flag = false;
errorList.add(line);
}
}
br.close();
if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n");
out.println("更新失败,以下行有误: ");
for (String error : errorList)
out.println("---" + error);
out.flush();
out.close();
System.out.println("error");
} else {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("更新成功+ “ ");
out.flush();
out.close();
System.out.println("success");
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
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");
if (!dir.exists())
dir.mkdir();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(userinfo.configStr);
bw.close();
fw.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.ConditionTableController;
import com.qiwu.chatbotbackend.processing.UserInfoController;
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.*;
@WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"})
public class UpdateSingleConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
ServletContext context = this.getServletContext();
String userName = request.getParameter("userName");
String processType = request.getParameter("type");
String configId = request.getParameter("configId");
String data = request.getParameter("configData");
System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data);
if (context.getAttribute(userName) != null) {
switch (processType) {
case "insert_config":
ConditionTableController.insertConfig(userName, configId, data, context);
break;
case "update_config":
ConditionTableController.deleteConfig(userName, configId, data, context);
ConditionTableController.insertConfig(userName, configId, data, context);
break;
case "delete_config":
ConditionTableController.deleteConfig(userName, configId, data, context);
break;
case "insert_variable":
ConditionTableController.updateVariable(userName, configId, data, context);
break;
case "delete_variable":
ConditionTableController.deleteVariable(userName, configId, data, context);
break;
case "update_variable":
ConditionTableController.updateVariable(userName, configId, data, context);
break;
case "extra_info":
ConditionTableController.updateExtraInfo(userName, data, context);
break;
case "batch_update":
batchUpdate(userName, data, context);
}
writeConfig(userName, context);
response.setStatus(200);
} else if (processType.equals("batch_update")) {
batchUpdate(userName, data, context);
writeConfig(userName, context);
response.setStatus(200);
} else {
response.setStatus(111);
}
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.write("success");
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public String writeConfig(String userName, ServletContext context) throws IOException {
String returnMessage = "";
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
returnMessage = ConditionTableController.writeConfigText(userName, userinfo);
return returnMessage;
}
public void batchUpdate(String userName, String data, ServletContext context) throws IOException {
BufferedReader br = new BufferedReader(new StringReader(data));
UserInfo userinfo = new UserInfo(userName);
userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.botAccount, userinfo);
System.out.println("batchupdate");
}
}
server.port=8081
server.servlet.context-path=/bot
endpoints.shutdown.enabled=true
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">admin</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
\ No newline at end of file
### 设置###
log4j.rootLogger=debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold=INFO
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志文件设置 ###
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File=vincent_player_debug.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志文件设置 ###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=vincent_player_error.log
log4j.appender.E.Append=true
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/SimplifiedBot?useUnicode=true&amp;characterEncoding=UTF8
</property>
<property name="user">root</property>
<property name="password">3g9^pWQs#ft7</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
\ No newline at end of file
### 设置###
log4j.rootLogger=debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold=INFO
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志文件设置 ###
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File=vincent_player_debug.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志文件设置 ###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=vincent_player_error.log
log4j.appender.E.Append=true
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
\ No newline at end of file
<!DOCTYPE HTML>
<html>
<head>
<title>配置文件 v2.2.4</title>
<script src="./js/jquery-3.3.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p><input type="button" value="查询" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
<p><input type="button" value="批量更新" onclick="batch_update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "getConfig",//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
function batch_update() {
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: hxw
Date: 18-5-8
Time: 下午1:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>配置文件 v2.2.4</title>
<script src="../static/js/jquery-3.3.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p><input type="button" value="查询" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
<p><input type="button" value="批量更新" onclick="batch_update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "getConfig",//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
function batch_update() {
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title> 配置文件 </title>
<script src="./js/jquery-3.1.1.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:autopx;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<br/><textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password"
id="config_string" tabindex="2" value=""></textarea></p>
<p>关键词替换:<br/><textarea style="width:700px;height:100px;word-break:break-all" name="macro" type="password"
id="macro" tabindex="2" value=""></textarea></p>
<p><input type="button" value="登录" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
var macroStr = document.getElementById("macro").value;
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
if (macroStr != "") {
var macro = macroStr.split("\n");
for (var i = 0; i < macro.length; i++) {
if (macro[i] != "") {
pair = macro[i].split("|");
if (pair.length == 1) {
alert("格式有误");
}
text = text.replace(pair[0], pair[1]);
}
}
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "http://qcloud-sh1.chewrobot.com:8081/bot/update2",//url
data: {
"userName": document.getElementById("txtUserName").value,
"configData": text,
"type": "batch_update",
"configId": 0
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0; i < list.length; i++) {
str += '<div>' + list[i] + '</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error: function (res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
package processing; package com.qiwu.chatbotbackend.processing;
import GameEnvironment.GameEnv; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import entity.ChatCache; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil;
import entity.UserInfo; import com.qiwu.chatbotbackend.GameEnvironment.Util;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class ChatCacheController { public class ChatCacheController {
public static long TIME_OUT = 5000;
private static String CHAT_CACHE_DIR = "ChatCache";
private static String ENV_PATH = CHAT_CACHE_DIR + "/%s env.data";
private static String INFO_PATH = CHAT_CACHE_DIR + "/%s info.data";
/** /**
* 通过chat_key获得后台保存的历史信息点 * 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点) * chatCache:存储了chatKye相对应的对话记录(历史信息点)
...@@ -80,58 +92,69 @@ public class ChatCacheController { ...@@ -80,58 +92,69 @@ public class ChatCacheController {
// context.setAttribute("chatCache", keyCache); // context.setAttribute("chatCache", keyCache);
// } // }
public static boolean saveChatCache(String userName, HashMap<String, String> infoPoints) throws IOException { public static boolean saveChatCache(String chatKey, ChatCache chatCache) throws IOException {
String fileDir = System.getProperty("user.dir") + "/ChatCache"; LocalDateTime now = LocalDateTime.now();
String key; DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String nowStr = now .format(format);
boolean saveFlag = true; boolean saveFlag = true;
try { try {
File dir = new File(fileDir); File dir = new File(CHAT_CACHE_DIR);
if (!dir.exists()) if (!dir.exists())
dir.mkdir(); dir.mkdir();
File file = new File(fileDir + "/" + userName + ".txt"); ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, chatKey.split("~")[0]));
File file = new File(String.format(INFO_PATH, chatKey.split("~")[0]));
FileWriter fw = new FileWriter(file); FileWriter fw = new FileWriter(file);
Iterator<String> infoIter = infoPoints.keySet().iterator(); String jsonString = JSON.toJSONString(chatCache.getInfoPoint());
while (infoIter.hasNext()) { fw.write(jsonString);
key = infoIter.next();
fw.write(key + "-----" + infoPoints.get(key) + "\n");
}
fw.close(); fw.close();
} catch (Exception e) { } catch (Exception e) {
System.out.println("游戏存档时发生异常");
saveFlag = false; saveFlag = false;
} }
return saveFlag; return saveFlag;
} }
public static boolean loadChatCache(String userName, ServletContext context) { public static ChatCache loadChatCache(String chatKey, ServletContext context, UserInfo userInfo) throws Exception {
ChatCache chatCache = null;
GameEnv gameEnv = null;
Map<String ,String> infoPoint = null;
String key = chatKey.split("~")[0];
String fileDir = System.getProperty("user.dir") + "/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[]; String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
File file = new File(fileDir + "/" + userName + ".txt"); gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, key));
if (!file.exists()) {
return false;
} else { File file = new File(String.format(INFO_PATH, key));
FileReader fr = new FileReader(file); FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) { String jsonStr = br.readLine();
pair = line.trim().split("-----"); infoPoint = (Map)JSON.parseObject(jsonStr);
infoPoints.put(pair[0], pair[1]);
}
// context.setAttribute(userName, ); // context.setAttribute(userName, );
chatCache = new ChatCache(gameEnv, infoPoint);
fr.close(); fr.close();
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
chatCache = new ChatCache(userInfo);
} }
return true; return chatCache;
} }
...@@ -139,9 +162,15 @@ public class ChatCacheController { ...@@ -139,9 +162,15 @@ public class ChatCacheController {
public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, UserInfo userinfo) throws Exception { public static synchronized ChatCache getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Boolean loadCache) throws Exception {
Map<String, ChatCache> chatCacheMap = null; Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null; ChatCache chatCache = null;
if(loadCache){
loadChatCache(chatKey, context, userinfo);
}
if (context.getAttribute("chatCache") == null) { if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>(); chatCacheMap = new HashMap<String, ChatCache>();
chatCacheMap.put(chatKey, new ChatCache(userinfo)); chatCacheMap.put(chatKey, new ChatCache(userinfo));
...@@ -152,6 +181,7 @@ public class ChatCacheController { ...@@ -152,6 +181,7 @@ public class ChatCacheController {
String chatkey; String chatkey;
try { try {
chatCache = chatCacheMap.get(chatKey); chatCache = chatCacheMap.get(chatKey);
if(chatCache == null){ if(chatCache == null){
...@@ -172,7 +202,7 @@ public class ChatCacheController { ...@@ -172,7 +202,7 @@ public class ChatCacheController {
/** /**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/ */
public static synchronized void updateChatCache4Delete2(String curChatKey, ServletContext context) { public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context) throws IOException {
String chatKey; String chatKey;
ChatCache chatCache = null; ChatCache chatCache = null;
long lastChatTime, now; long lastChatTime, now;
...@@ -188,7 +218,9 @@ public class ChatCacheController { ...@@ -188,7 +218,9 @@ public class ChatCacheController {
history = chatCacheMap.get(chatKey).getInfoPoint(); history = chatCacheMap.get(chatKey).getInfoPoint();
lastChatTime = Long.valueOf(history.get("lastUpdateTime")); lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis(); now = System.currentTimeMillis();
if (now - lastChatTime > 300000) { if (now - lastChatTime > ChatCacheController.TIME_OUT) {
chatCache = chatCacheMap.get(chatKey);
saveChatCache("1909509284", chatCache);
it.remove(); it.remove();
} }
} }
...@@ -198,7 +230,7 @@ public class ChatCacheController { ...@@ -198,7 +230,7 @@ public class ChatCacheController {
/** /**
* 根据chatKey更新chatCache的数据,并修改最后更新时间 * 根据chatKey更新chatCache的数据,并修改最后更新时间
*/ */
public static synchronized void updateChatCache4Insert2(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context) { public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key"));
...@@ -207,27 +239,26 @@ public class ChatCacheController { ...@@ -207,27 +239,26 @@ public class ChatCacheController {
context.setAttribute("chatCache", keyCacheMap); context.setAttribute("chatCache", keyCacheMap);
} }
public static synchronized String saveChatCache(String chatKey, ServletContext context){ // public static synchronized String saveChatCache(String chatKey, ChatCache chatCache){
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); //
ChatCache chatCache = chatCacheMap.get(chatKey); //
// if(chatCache == null){
if(chatCache == null){ // return "chat_key不存在或者已失效";
return "chat_key不存在或者已失效"; // }else {
}else { // String jChatCache = JSON.toJSONString(chatCache);
String jChatCache = JSON.toJSONString(chatCache); // System.out.println(jChatCache);
System.out.println(jChatCache); //
//
//
// chatCache = JSON.parseObject(jChatCache,ChatCache.class);
chatCache = JSON.parseObject(jChatCache,ChatCache.class); // System.out.println(chatCache.getInfoPoint().size());
System.out.println(chatCache.getInfoPoint().size()); //
// return "成功";
return "成功"; // }
} //
//
//
// }
}
} }
package processing; package com.qiwu.chatbotbackend.processing;
import entity.Condition; import com.qiwu.chatbotbackend.entity.Condition;
import entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.BufferedWriter; import java.io.BufferedWriter;
......
package processing; package com.qiwu.chatbotbackend.processing;
import java.io.*; import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class LogWriter { public class LogWriter {
private PrintWriter recorder = null; private PrintWriter recorder = null;
String PRINT_PATTERN = "<font color=\"%s\">%s" + DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss");
LocalDateTime ldt = null;
String PRINT_PATTERN = "<font color=\"%s\">[%s] %s" +
"----------------------------------------------------------------------------<br></font>"; "----------------------------------------------------------------------------<br></font>";
Map<Integer, String> colerMap = new HashMap<Integer, String>(){ Map<Integer, String> colerMap = new HashMap<Integer, String>(){
{ {
put(0, "black"); put(0, "black");
put(1, "gray"); put(1, "gray");
put(2, "green"); put(2, "green");
put(3, "red"); put(3, "yellow");
put(4, "green");
put(5, "red");
} }
}; };
public LogWriter(String filePath, String fileName) throws IOException { public LogWriter(String filePath, String fileName) throws IOException {
File file = new File(filePath + "/" + fileName + ".html"); File file = new File(filePath + "/" + fileName + ".html");
System.out.println(file.getAbsolutePath());
if (!file.exists()) { if (!file.exists()) {
file.createNewFile(); file.createNewFile();
} }
file.setReadable(true,false); file.setReadable(true,false);
FileWriter fw = new FileWriter(file, true); FileWriter fw = new FileWriter(file, true);
//BufferedWriter bw = new BufferedWriter(fos, "UTF-8");
//context.setAttribute("logWriter", bw);
BufferedWriter bw = new BufferedWriter(fw); BufferedWriter bw = new BufferedWriter(fw);
...@@ -40,7 +47,11 @@ public class LogWriter { ...@@ -40,7 +47,11 @@ public class LogWriter {
} }
public void record(String text, int level){ public void record(String text, int level){
recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), text)); ldt = LocalDateTime.now();
recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), ldt.format(dtf), text));
}
public void writeln(){
recorder.println("<br>");
} }
public void close(){ public void close(){
......
package processing; package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
......
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