Commit f38204e0 by hxw

修复时间比较存在的bug

parent b8dd9e53
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</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">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
\ No newline at end of file
package db;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class C3p0Utils {
static Logger logger = Logger.getLogger(C3p0Utils.class.getName());
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
//从连接池中取用一个连接
public static Connection getConnection() throws SQLException {
try {
return dataSource.getConnection();
} catch (Exception e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
//释放连接回连接池
public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
}
}
......@@ -5,17 +5,17 @@ import java.sql.DriverManager;
public class DB {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN";
private static String user = "root";
private static String pwd = "admin";
private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN";
private static String user = "root";
private static String pwd = "admin";
public static Connection getConnection(){
public static Connection getConnection() {
Connection conn = null;
try{
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd);
conn = DriverManager.getConnection(url, user, pwd);
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
......
......@@ -14,7 +14,8 @@ import java.util.Properties;
public class DBCPUtils {
private static DataSource ds;//定义一个连接池对象
static{
static {
try {
Properties pro = new Properties();
File file = new File("dbcpconfig.properties");
......@@ -25,13 +26,14 @@ public class DBCPUtils {
//throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!");
}
}
//从池中获取一个连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeAll(ResultSet rs, Statement stmt, Connection conn){
if(rs!=null){
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
......@@ -39,7 +41,7 @@ public class DBCPUtils {
}
}
if(stmt!=null){
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
......@@ -47,7 +49,7 @@ public class DBCPUtils {
}
}
if(conn!=null){
if (conn != null) {
try {
conn.close();//关闭
} catch (SQLException e) {
......
package db;
public class DBUtils {
}
......@@ -3,10 +3,12 @@ package db;
import com.alibaba.fastjson.JSONObject;
import entity.JConfig;
import entity.QuestionKeyWord;
import gameDesign.ElementConstructor;
import processing.MyFunc;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SqlHelper {
......@@ -18,15 +20,15 @@ public class SqlHelper {
*/
public SqlHelper() throws SQLException {
conn = DBCPUtils.getConnection();
conn = C3p0Utils.getConnection();
}
public void destroy(){
if (conn != null){
try{
public void destroy() {
if (conn != null) {
try {
conn.close();
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
......@@ -82,20 +84,25 @@ public class SqlHelper {
}
*/
public String queryUsernameByKey(String chat_key){
private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException {
C3p0Utils.close(_conn, _st, _rs);
}
public String queryUsernameByKey(String chat_key) {
String sql = "select * from chats where chat_key = ?";
String userName = "";
String result = "empty";
try{
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,chat_key);
ps.setString(1, chat_key);
ResultSet rs = ps.executeQuery();
if(rs.next())
if (rs.next())
result = rs.getString("bot");
rs.close();
ps.close();
rs.close();
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
return result;
......@@ -107,9 +114,9 @@ public class SqlHelper {
boolean firstValue = true;
int batchSize = idGroup.size();
for (int i=0; i < batchSize; i++) {
for (int i = 0; i < batchSize; i++) {
inClause.append('?');
if ( firstValue ) {
if (firstValue) {
firstValue = false;
} else {
inClause.append(',');
......@@ -120,27 +127,49 @@ public class SqlHelper {
String userName = "";
boolean b = true;
try{
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId));
b = ps.execute();
ps.close();
return b;
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
public boolean deleteConfigByBotId(int botId){
String sql = "delete from chatbot_config where botId= ?";
public boolean deleteConfigByBotId(int botId) {
boolean b;
try{
try {
PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?");
ps1.setString(1, String.valueOf(botId));
b = ps1.execute();
ps1.close();
return b;
} catch (SQLException e) {
System.out.println("删除旧数据失败");
e.printStackTrace();
return false;
}
}
public boolean deleteVariableByBotId(int botId) {
String sql = "delete from chatbot_variable where botId= ?";
boolean b;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId));
b = ps.execute();
ps.close();
return b;
} catch (SQLException e) {
......@@ -150,7 +179,64 @@ public class SqlHelper {
}
}
public boolean batchInsertConfigByBotId(int botId, List<JConfig> jConfigList, List<Integer> idList) {
public boolean batchInsertVariableByBotId(int botId, ElementConstructor constructor) {
int count[];
boolean insertFlag = true;
String sql = "", varName, varValue, description;
try {
conn.setAutoCommit(false);
sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)";
PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Iterator<String> iit = constructor.getVarInitialMap().keySet().iterator();
while (iit.hasNext()) {
varName = iit.next();
varValue = constructor.getVarInitialMap().get(varName);
if (constructor.getConditionDescription().get(varName) == null)
description = "";
else
description = constructor.getConditionDescription().get(varName);
ps2.setString(1, String.valueOf(botId));
ps2.setString(2, varName);
ps2.setString(3, description);
ps2.setString(4, varValue);
ps2.addBatch();
}
count = ps2.executeBatch();
conn.commit();
for (int i : count) {
if (i == 0) {
conn.rollback();
System.out.println("======出现异常,回滚=========");
insertFlag = false;
}
}
ps2.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("------出现异常,回滚----------");
e.printStackTrace();
}
return insertFlag;
}
public boolean batchInsertConfigByBotId(int botId, ElementConstructor constructor, List<Integer> idList) {
int count[];
boolean insertFlag = true;
String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
......@@ -160,10 +246,10 @@ public class SqlHelper {
conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (JConfig jConfig : jConfigList) {
for (JConfig jConfig : constructor.getjConfigList()) {
ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0));
ps.setString(3, jConfig.toJson().toJSONString());
ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString());
ps.setString(4, "");
ps.addBatch();
}
......@@ -179,16 +265,19 @@ public class SqlHelper {
}
}
ResultSet rs = ps.getGeneratedKeys();
while(rs.next())
while (rs.next())
idList.add(rs.getInt(1));
ps.close();
rs.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
......@@ -196,23 +285,25 @@ public class SqlHelper {
e.printStackTrace();
}
return insertFlag ;
return insertFlag;
}
public JSONObject queryGameElementsByBotId(int id){
public JSONObject queryGameElementsByBotId(int id) {
String sql = "select * from generate_json_tb where id = ?";
String userName = "";
String result = "empty";
try{
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(id));
ResultSet rs = ps.executeQuery();
if(rs.next())
if (rs.next())
result = rs.getString("json_text");
rs.close();
ps.close();
rs.close();
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
......@@ -220,7 +311,28 @@ public class SqlHelper {
}
public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) {
String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)";
String userName = "";
String result = "empty";
boolean b = true;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(id));
ps.setString(2, variableName);
ps.setString(3, description);
ps.setString(4, defaultValue);
b = ps.execute();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
}
......@@ -14,14 +14,14 @@ public class Condition {
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, 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 int id = 0;
public String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>();
......
package entity;
/**
* 暂时没用
*/
......
......@@ -18,7 +18,6 @@ public class Solution {
}
public void setAnswer(String answer) {
this.answer = answer;
}
......@@ -35,10 +34,12 @@ public class Solution {
this.next = next;
}
public Solution(int status, String answers, String next){
public Solution(int status, String answers, String next) {
this.answer = answers;
this.next = next;
this.status = status;
}
public Solution(){}
public Solution() {
}
}
......@@ -7,13 +7,13 @@ import java.util.List;
* 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里
*/
public class UserInfo {
public UserInfo(String userName){
public UserInfo(String userName) {
this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = "";
this.userName = userName;
this.extraInfo = new HashMap<String,String>(){
this.extraInfo = new HashMap<String, String>() {
{
put("activeAction"," ");
put("activeAction", " ");
}
};
this.id2config = new HashMap<Integer, String>();
......@@ -21,15 +21,14 @@ public class UserInfo {
this.varInitialMap = new HashMap<String, String>();
}
public HashMap<String,List<Condition>> conditionTable;
public HashMap<String, List<Condition>> conditionTable;
public String configStr;
public String userName;
public HashMap<String,String> extraInfo;
public HashMap<String, String> extraInfo;
public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition;
//存储需要初始化的变量
public HashMap<String, String> varInitialMap;
}
......@@ -8,7 +8,7 @@ import entity.UserInfo;
import java.util.Iterator;
import java.util.Map;
public class CharacterConstructor extends ElementConstructor{
public class CharacterConstructor extends ElementConstructor {
public CharacterConstructor(SqlHelper helper, int botId) {
super();
......@@ -16,13 +16,13 @@ public class CharacterConstructor extends ElementConstructor{
this.botId = botId;
}
public void construct(JSONObject jsonObject, UserInfo userinfo){
public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue;
JSONArray allNPC = jsonObject.getJSONArray("npc");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
for(JSONObject npc:allNPC.toJavaList(JSONObject.class)) {
for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) {
category = (String) npc.get("category");
JSONArray characters = npc.getJSONArray("characters");
for (JSONObject character : characters.toJavaList(JSONObject.class)) {
......@@ -33,7 +33,7 @@ public class CharacterConstructor extends ElementConstructor{
while (attrIter.hasNext()) {
attrName = attrIter.next();
attrValue = attribute.get(attrName);
configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n");
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue);
}
}
}
......
......@@ -13,38 +13,66 @@ import java.util.Map;
public class ElementConstructor {
int botId = 0;
SqlHelper helper = null;
List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<JConfig> jConfigList = new ArrayList<JConfig>();
String userName;
String CHITCHAT_URL = "http:192.168.1.178:1111/test", userName;
StringBuffer configText = new StringBuffer();
JConfig jConfig = null;
Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>();
public void construct(JSONObject jsonObject, UserInfo userinfo){}
public List<JConfig> getjConfigList() { return jConfigList; }
public List<JSONObject> getConfigDataList() { return configDataList; }
public void ElementConstructor(String userName){ this.userName = userName; }
public String getConfigText() { return configText.toString(); }
public Map<String, String> getVarInitialMap() {
return varInitialMap;
}
public void construct(JSONObject jsonObject, UserInfo userinfo) {
}
public List<JConfig> getjConfigList() {
return jConfigList;
}
public Map<String, String> getConditionDescription() {
return conditionDescription;
}
public void generateConfigText(List<Integer> idList){
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++){
for (int i = 0; i < length; i++) {
jConfig = jConfigList.get(i);
id = idList.get(i);
configText.append(jConfig.toString() + id + "\n");
}
for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue + "\n");
}
}
/**
* 构造参数配置文件的json版
*/
public void buildJconfig(){
public void buildJconfig() {
}
......
......@@ -6,17 +6,21 @@ package gameDesign;
public class Floyd {
/** 表示正无穷 */
/**
* 表示正无穷
*/
int MAX_WEIGHT = Integer.MAX_VALUE;
/**路径矩阵*/
/**
* 路径矩阵
*/
int[][] pathMatirx;
/**前驱表*/
/**
* 前驱表
*/
int[][] preTable;
public void findShortestPath(int[][] matrix, int length){
public void findShortestPath(int[][] matrix, int length) {
//路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。
pathMatirx = new int[length][length];
//前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值
......@@ -50,7 +54,7 @@ public class Floyd {
int mn = pathMatirx[m][n];
int mk = pathMatirx[m][k];
int kn = pathMatirx[k][n];
int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT)? MAX_WEIGHT : mk + kn;
int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn;
if (mn > addedPath) {
//如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个
......@@ -80,7 +84,6 @@ public class Floyd {
public void printPath(int[][] matrix, int length) {
for (int m = 0; m < length; m++) {
for (int n = m + 1; n < length; n++) {
......
......@@ -8,7 +8,7 @@ import entity.UserInfo;
import java.util.Iterator;
import java.util.Map;
public class GlobalVariableConstructor extends ElementConstructor{
public class GlobalVariableConstructor extends ElementConstructor {
public GlobalVariableConstructor(SqlHelper helper, int botId) {
super();
......@@ -16,20 +16,20 @@ public class GlobalVariableConstructor extends ElementConstructor{
this.botId = botId;
}
public void construct(JSONObject jsonObject, UserInfo userinfo){
public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue;
JSONArray globalVariable = jsonObject.getJSONArray("globalVariable");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
for(JSONObject variableList:globalVariable.toJavaList(JSONObject.class)) {
for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) {
category = (String) variableList.get("category");
attribute = JSONObject.toJavaObject(variableList.getJSONObject("variables"), Map.class);
attrIter = attribute.keySet().iterator();
while(attrIter.hasNext()){
while (attrIter.hasNext()) {
attrName = attrIter.next();
attrValue = attribute.get(attrName);
configText.append("-varInitial-|" + category + "_" + attrName + "|" + attrValue + "\n");
varInitialMap.put(category + "_" + attrName, attrValue);
}
}
}
......
......@@ -8,7 +8,7 @@ import entity.UserInfo;
import java.util.Iterator;
import java.util.Map;
public class ItemConstructor extends ElementConstructor{
public class ItemConstructor extends ElementConstructor {
public ItemConstructor(SqlHelper helper, int botId) {
......@@ -18,13 +18,13 @@ public class ItemConstructor extends ElementConstructor{
}
public void construct(JSONObject jsonObject, UserInfo userinfo){
public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue;
JSONArray goods = jsonObject.getJSONArray("goods");
Map<String, String> attribute = null;
Iterator<String> attrIter = null;
for(JSONObject good:goods.toJavaList(JSONObject.class)) {
for (JSONObject good : goods.toJavaList(JSONObject.class)) {
category = (String) good.get("category");
JSONArray items = good.getJSONArray("items");
......@@ -36,7 +36,7 @@ public class ItemConstructor extends ElementConstructor{
while (attrIter.hasNext()) {
attrName = attrIter.next();
attrValue = attribute.get(attrName);
configText.append("-varInitial-|" + category + "_" + name + "_" + attrName + "|" + attrValue + "\n");
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue);
}
}
}
......
......@@ -10,7 +10,7 @@ import java.io.BufferedReader;
import java.io.StringReader;
import java.util.*;
public class MapConstructor extends ElementConstructor{
public class MapConstructor extends ElementConstructor {
int[][] matrix;
int locationNum;
......@@ -60,11 +60,11 @@ public class MapConstructor extends ElementConstructor{
}
}
public void construct(JSONObject jsonObject, UserInfo userinfo){
conditionDescription.put("site","当前地点");
public void construct(JSONObject jsonObject, UserInfo userinfo) {
conditionDescription.put("site", "当前地点");
varInitialMap.put("site", "");
JSONObject map = jsonObject.getJSONObject("map");
Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class);
JSONArray locations = map.getJSONArray("locations");
......@@ -87,62 +87,61 @@ public class MapConstructor extends ElementConstructor{
/**
* 生成‘我在哪里’所需要的配置文件
*/
public void generateWhereIam(JSONObject jsonObject){
public void generateWhereIam(JSONObject jsonObject) {
String zainaKeywords = question2keyword.get("zaina");
jConfig = new JConfig(
"zaina::match-Keyword=" + zainaKeywords, " ",
"match", "你在{site-2}", "yaobuyao",""
"match", "你在{site-2}", "yaobuyao", ""
);
jConfigList.add(jConfig);
}
/**
* 生成‘怎么去哪里’所需要的配置文件
*/
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String zenmequKeywords = question2keyword.get("zenmequ");
String zenmequKeywords = question2keyword.get("zenmequ");
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
for (int i = 0; i < locationNum; i++) {
for (int j = 0; j < locationNum; j++) {
placeA = (String)locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name");
placeA = (String) locations.getJSONObject(i).get("name");
placeB = (String) locations.getJSONObject(j).get("name");
placeKeywords = zenmequKeywords.replace("地点", placeB);
if(i == j){
if (i == j) {
jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao",""
"match", "你已经在" + placeB + "了", "yaobuyao", ""
);
jConfigList.add(jConfig);
continue;
};
if(pathMatirx[i][j] == 1){
}
;
if (pathMatirx[i][j] == 1) {
jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", placeB + "就在附近哦", "yaobuyao", ""
);
jConfigList.add(jConfig);
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
} else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) {
int k = preTable[i][j];
pathNode = "";
while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name");
pathNode += (String) locations.getJSONObject(k).get("name");
k = preTable[k][j];
}
jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao",""
"match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", ""
);
jConfigList.add(jConfig);
}
......@@ -154,16 +153,16 @@ public class MapConstructor extends ElementConstructor{
/**
* 生成‘我能去哪里’所需要的配置文件
*/
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String nengqunaKeywords = question2keyword.get("nengquna");
String placeA, placeB, pathNode;
for(int i = 0;i < locationNum;i++){
placeA = (String)locations.getJSONObject(i).get("name");
for (int i = 0; i < locationNum; i++) {
placeA = (String) locations.getJSONObject(i).get("name");
pathNode = "";
for(int j = 0;j < locationNum;j++){
if(pathMatirx[i][j] == 1) {
for (int j = 0; j < locationNum; j++) {
if (pathMatirx[i][j] == 1) {
placeB = (String) locations.getJSONObject(j).get("name");
pathNode += "、" + placeB;
}
......@@ -176,7 +175,6 @@ public class MapConstructor extends ElementConstructor{
jConfigList.add(jConfig);
}
......@@ -186,32 +184,31 @@ public class MapConstructor extends ElementConstructor{
/**
* 生成‘我要去那里’所需要的配置文件
*/
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject) {
String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String qunaKeywords = question2keyword.get("quna");
String qunaKeywords = question2keyword.get("quna");
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
placeA = (String)locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name");
descriptionB = (String)locations.getJSONObject(j).get("description");
for (int i = 0; i < locationNum; i++) {
for (int j = 0; j < locationNum; j++) {
placeA = (String) locations.getJSONObject(i).get("name");
placeB = (String) locations.getJSONObject(j).get("name");
descriptionB = (String) locations.getJSONObject(j).get("description");
placeKeywords = qunaKeywords.replace("地点", placeB);
if(i == j){
if (i == j) {
jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", ""
);
);
jConfigList.add(jConfig);
continue;
};
}
;
//如果两点相邻
if(pathMatirx[i][j] == 1){
if (pathMatirx[i][j] == 1) {
jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "" + descriptionB, "yaobuyao", "site:" + placeB
......@@ -219,12 +216,12 @@ public class MapConstructor extends ElementConstructor{
jConfigList.add(jConfig);
//如果两点不是相邻点
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
//如果两点不是相邻点
} else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) {
int k = preTable[i][j];
pathNode = "";
while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name");
pathNode += (String) locations.getJSONObject(k).get("name");
k = preTable[k][j];
}
jConfig = new JConfig(
......
### 设置###
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
......@@ -11,24 +11,25 @@ public class ChatCacheController {
/**
* 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点)
*
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context){
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) {
Map<String, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = null;
if(context.getAttribute("chatCache") == null) {
if (context.getAttribute("chatCache") == null) {
chatCache = new HashMap<String, Map<String, String>>();
context.setAttribute("chatCache", chatCache);
} else{
} else {
chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
}
String chatkey;
try{
try {
historyInfoPoint = chatCache.get(chatKey);
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
}catch(Exception e){
} catch (Exception e) {
//可整合
historyInfoPoint = null;
......@@ -42,10 +43,10 @@ public class ChatCacheController {
/**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/
public static synchronized void updateChatCache4Delete(ServletContext context){
public static synchronized void updateChatCache4Delete(ServletContext context) {
String chatKey;
long lastChatTime,now;
Map<String,String> history = new HashMap<String,String>();
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");
......@@ -65,15 +66,15 @@ public class ChatCacheController {
/**
* 根据chatKey更新chatCache的数据,并修改最后更新时间
*/
public static synchronized void updateChatCache4Insert(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,ServletContext context){
historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis()));
Map<String,Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint);
context.setAttribute("chatCache",keyCache);
public static synchronized void updateChatCache4Insert(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint);
context.setAttribute("chatCache", keyCache);
}
public static boolean saveChatCache(String userName, HashMap<String, String> infoPoints) throws IOException {
String fileDir = System.getProperty("user.dir")+"/ChatCache";
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String key;
boolean saveFlag = true;
try {
......@@ -91,25 +92,25 @@ public class ChatCacheController {
}
fw.close();
}catch (Exception e){
} catch (Exception e) {
saveFlag = false;
}
return saveFlag;
}
public static boolean loadChatCache(String userName, ServletContext context){
String fileDir = System.getProperty("user.dir")+"/ChatCache";
String line,pair[];
public static boolean loadChatCache(String userName, ServletContext context) {
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>();
try{
try {
File file = new File(fileDir + "/" + userName + ".txt");
if(!file.exists()) {
if (!file.exists()) {
return false;
}else {
} else {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null){
while ((line = br.readLine()) != null) {
pair = line.trim().split("-----");
infoPoints.put(pair[0], pair[1]);
}
......
......@@ -17,13 +17,12 @@ public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId);
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
String conditionName = "";
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userInfo = (UserInfo) context.getAttribute(userName);
......@@ -34,15 +33,10 @@ public class ConditionTableController {
try {
Condition oldCondition = userInfo.id2condition.get(id);
conditionName = oldCondition.indexName;
}catch (Exception e){
} catch (Exception e) {
e.printStackTrace();
}
//-------------------
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(id));
//String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
......@@ -57,7 +51,7 @@ public class ConditionTableController {
userInfo.id2config.remove(id);
userInfo.id2condition.remove(id);
} else{
} else {
System.out.println("未找到要删除的configId");
}
......@@ -66,23 +60,17 @@ public class ConditionTableController {
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String conditionName = "";
for(int configId:idGroup) {
for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) {
try {
Condition oldCondition = userInfo.id2condition.get(configId);
conditionName = oldCondition.indexName;
}catch (Exception e){
} catch (Exception e) {
e.printStackTrace();
}
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId));
//String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
......@@ -107,10 +95,8 @@ public class ConditionTableController {
}
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
......@@ -120,12 +106,12 @@ public class ConditionTableController {
condition = userInfoController.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(userinfo.conditionTable.get(condition.indexName) == null){
if (userinfo.conditionTable.get(condition.indexName) == null) {
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(condition.indexName, conditionList);
}
......@@ -139,41 +125,37 @@ public class ConditionTableController {
public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---", -1);
String name = dataPair[0],value = dataPair[1];
String name = dataPair[0], value = dataPair[1];
UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.put(name, value);
return true;
}
public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String name = data;
UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.remove(name);
return true;
}
......@@ -183,13 +165,13 @@ public class ConditionTableController {
UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
return true;
}
......@@ -199,15 +181,15 @@ public class ConditionTableController {
System.out.println("p");
System.out.println(userName);
String CONFIG_DIR = System.getProperty("user.dir")+"/config", configText;
String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText;
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
File dir = new File(System.getProperty("user.dir") + "/config");
String returnMessage = "success";
if(!dir.exists())
if (!dir.exists())
dir.mkdir();
if(!file.exists()){
if (!file.exists()) {
file.createNewFile();
}
......@@ -217,7 +199,7 @@ public class ConditionTableController {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if(!userinfo.extraInfo.get(info).equals(""))
if (!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
......@@ -233,10 +215,10 @@ public class ConditionTableController {
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
returnMessage = "config file write error";
}finally {
} finally {
bw.close();
fw.close();
}
......
......@@ -24,24 +24,26 @@ public class MyFunc {
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr){
public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject();
jobj.put("returnString",returnStr);
jobj.put("returnString", returnStr);
return jobj.toString();
}
/**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据
*
* @param request
* @return json字符串
*/
public static String readJSONString(HttpServletRequest request){
public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try{
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
while ((line = reader.readLine()) != null) {
json.append(line);
}
} catch (IOException e) {
......@@ -54,10 +56,10 @@ public class MyFunc {
/**
* 通过get方法传递参数时需要对参数的编码进行转换
*/
public static String convert2Utf8(String s){
if(s==null)return null;
public static String convert2Utf8(String s) {
if (s == null) return null;
try {
s=new String(s.getBytes("iso-8859-1"),"utf-8");
s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
......@@ -71,7 +73,7 @@ public class MyFunc {
System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"};
for(String f : timeSeries){
for (String f : timeSeries) {
if (!keyword.contains(f))
keyword += "0" + f;
}
......@@ -81,6 +83,7 @@ public class MyFunc {
return time;
}
public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
......@@ -91,6 +94,4 @@ public class MyFunc {
}
}
......@@ -13,7 +13,7 @@ import java.util.List;
public class UserInfoController {
static String CONFIG_DIR = System.getProperty("user.dir")+"/config";
static String CONFIG_DIR = System.getProperty("user.dir") + "/config";
static String FILE_ERROR = ".txt文件有误";
......@@ -25,9 +25,9 @@ public class UserInfoController {
String line;
File dir = new File(CONFIG_DIR);
if(!dir.exists())
if (!dir.exists())
dir.mkdir();
for(File configFile: dir.listFiles()) {
for (File configFile : dir.listFiles()) {
FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader);
......@@ -36,8 +36,8 @@ public class UserInfoController {
try {
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
context.setAttribute(userinfo.userName, userinfo);
} catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace();
}
......@@ -50,27 +50,27 @@ public class UserInfoController {
public static void userConfigInit(String userName, ServletContext context) throws IOException {
String line;
File userFile = new File(CONFIG_DIR + "/" + userName + ".txt");
if(!userFile.exists()){
File userFile = new File(CONFIG_DIR + "/" + userName + ".txt");
if (!userFile.exists()) {
BufferedReader br = new BufferedReader(new StringReader(""));
UserInfo userinfo = new UserInfo(userName);
try {
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
context.setAttribute(userinfo.userName, userinfo);
} catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace();
}
}else {
} else {
FileReader reader = new FileReader(userFile);
BufferedReader br = new BufferedReader(reader);
UserInfo userinfo = new UserInfo(userName);
try {
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
context.setAttribute(userinfo.userName, userinfo);
} catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace();
}
......@@ -81,8 +81,8 @@ public class UserInfoController {
}
public static Condition buildCondition(Condition condition, String line){
String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName;
public static Condition buildCondition(Condition condition, String line) {
String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName;
try {
......@@ -122,14 +122,14 @@ public class UserInfoController {
int length = knowledge.length;
condition.featureMap.put("updateKnowledge", "");
for (int i = 1; i < length; i++) {
if(knowledge[i].equals("") || knowledge[i].equals(" "))
if (knowledge[i].equals("") || knowledge[i].equals(" "))
continue;
pair = knowledge[i].split(":");
pair = knowledge[i].split(":", 2);
condition.updateKnowledge.put(pair[0], pair[1]);
}
} else if (feat.startsWith("post")) {
pair = feature.split("\\(", 2);
pair = feat.split("\\(", 2);
url = pair[1];
url = url.substring(0, url.length() - 1);
pair = pair[0].split("::");
......@@ -140,10 +140,10 @@ public class UserInfoController {
}
insertPremise(condition.currentPremise,cur_premises);
insertPremise(condition.historyPremise,history_premises);
insertPremise(condition.currentPremise, cur_premises);
insertPremise(condition.historyPremise, history_premises);
//满足条件越多,优先级越大
condition.priority = condition.historyPremise.size()+condition.currentPremise.size();
condition.priority = condition.historyPremise.size() + condition.currentPremise.size();
condition.activePriority = condition.priority;
/*
for(String premise:cur_premises){
......@@ -152,12 +152,13 @@ public class UserInfoController {
}
*/
firstCnditionName = cur_premises[0];
if(firstCnditionName.equals(" "))
if (firstCnditionName.equals(" "))
condition.indexName = "emptySet";
else
condition.indexName = firstCnditionName.split("=")[0].split("::")[0];
}catch (IndexOutOfBoundsException e){
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println(line);
System.out.println("文本格式有误");
}
return condition;
......@@ -165,24 +166,25 @@ public class UserInfoController {
/**
*
* @param br
* @param userinfo
* @param overRide 覆盖之前的状态表
* @param overRide 覆盖之前的状态表
* @return
* @throws IOException
*/
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException {
String line,infoName,extraElements[];
String line, infoName, extraElements[];
HashMap<String, List<Condition>> conditionTable = null;
//是否覆盖原有的数据
if(overRide) {
if (overRide) {
conditionTable = new HashMap<String, List<Condition>>();
userinfo.id2condition.clear();
userinfo.id2config.clear();
userinfo.configStr = "";
}else {
userinfo.varInitialMap.clear();
} else {
conditionTable = userinfo.conditionTable;
}
......@@ -215,10 +217,10 @@ public class UserInfoController {
}
}
} catch(ArrayIndexOutOfBoundsException e){
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数据格式有误");
e.printStackTrace();
} catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
}
......@@ -230,22 +232,23 @@ public class UserInfoController {
/**
* 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟)
* @param premiseMap 前提条件哈希表
*
* @param premiseMap 前提条件哈希表
*/
public static void insertPremise(HashMap<String,HashSet<String>> premiseMap, String[] premisesString){
public static void insertPremise(HashMap<String, HashSet<String>> premiseMap, String[] premisesString) {
String pair[];
HashSet<String> keyWordSet = null;
for(String premise:premisesString) {
for (String premise : premisesString) {
// System.out.println(premise);
if (premise.equals("") || premise.equals(" "))
continue;
pair = premise.split("=", 2);
keyWordSet = new HashSet<String>();
keyWordSet = new HashSet<String>();
for (String keyword : pair[1].split("\\+"))
//为了处理条件不满足(为空)时的特殊情况,
if(keyword.equals("null")) keyWordSet.add("");
else if(!keyword.equals("")) keyWordSet.add(keyword);
premiseMap.put(pair[0],keyWordSet);
if (keyword.equals("null")) keyWordSet.add("");
else if (!keyword.equals("")) keyWordSet.add(keyword);
premiseMap.put(pair[0], keyWordSet);
}
}
......@@ -268,13 +271,13 @@ public class UserInfoController {
*/
String userName = bot_name;
UserInfo userinfo = null;
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userConfigInit(userName, context);
}
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
userinfo = new UserInfo(userName);
userinfo.conditionTable = new HashMap<String, List<Condition>>();
}else {
} else {
userinfo = (UserInfo) context.getAttribute(userName);
}
//helper.destroy();
......
package servlet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import db.SqlHelper;
import entity.Condition;
import entity.UserInfo;
import gameDesign.*;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.ConditionTableController;
import processing.UserInfoController;
......@@ -26,7 +23,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"})
@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer botId, projectId, dataId;
......@@ -47,23 +44,22 @@ public class GameDesignServlet extends HttpServlet {
String jsonStr = MyFunc.readJSONString(request);
if(jsonStr != null && !jsonStr.equals("")){
if (jsonStr != null && !jsonStr.equals("")) {
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
dataId = (Integer)jsonObject.get("id");
dataId = (Integer) jsonObject.get("id");
JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
botId = (Integer)gameElements.get("botId");
userName = (String)gameElements.get("userName");
botId = (Integer) gameElements.get("botId");
userName = (String) gameElements.get("userName");
//假设重新重新建用户信息
if(context.getAttribute(userName) == null){
if (context.getAttribute(userName) == null) {
UserInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
//UserInfo userinfo = new UserInfo(userName);
//清空之前生成的配置条目
......@@ -77,7 +73,7 @@ public class GameDesignServlet extends HttpServlet {
Iterator<String> moduleIter = gameElements.keySet().iterator();
StringBuffer mergedConfigText = new StringBuffer();
while(moduleIter.hasNext()) {
while (moduleIter.hasNext()) {
moduleName = moduleIter.next();
switch (moduleName) {
case "map":
......@@ -103,10 +99,10 @@ public class GameDesignServlet extends HttpServlet {
constructor.construct(gameElements, userinfo);
//先清空再插入
idList.clear();
if(moduleName.equals("map") || moduleName.equals("plots")) {
helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList);
constructor.generateConfigText(idList);
}
helper.batchInsertVariableByBotId(botId, constructor);
helper.batchInsertConfigByBotId(botId, constructor, idList);
constructor.generateConfigText(idList);
mergedConfigText.append(constructor.getConfigText());
......@@ -132,8 +128,8 @@ public class GameDesignServlet extends HttpServlet {
}
public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException {
boolean deleteFlag = helper.deleteConfigByBotId(botId);
return deleteFlag;
boolean deleteConfigFlag = helper.deleteConfigByBotId(botId);
boolean deleteVariableFlag = helper.deleteVariableByBotId(botId);
return deleteConfigFlag && deleteVariableFlag;
}
}
......@@ -5,7 +5,7 @@ import entity.Condition;
import entity.UserInfo;
import processing.ChatCacheController;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.QuestionMatcher;
import processing.UserInfoController;
import javax.servlet.ServletContext;
......@@ -21,30 +21,29 @@ import java.text.ParseException;
import java.util.*;
@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"})
@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/"})
public class GetAnswerServlet extends HttpServlet {
/**
* GetAnswerServlet就是处理post请求并返回答案的入口
*/
String NAME_MISSING_ERROR = "没找到bot名?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String,String[]> curInfoPoint = new HashMap<>(request.getParameterMap());
Map<String, String[]> curInfoPoint = new HashMap<>(request.getParameterMap());
Map<String, String> historyInfoPoint = null;
Solution bestMatch = null;
Condition ansCondition = null;
String ansJ,return_str="",state = "";
String ansJ, return_str = "", state = "";
String chatKey = curInfoPoint.get("chat_key")[0];
ProcessQuestion process = new ProcessQuestion();
QuestionMatcher matcher = new QuestionMatcher();
OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext();
boolean debugFlag = false;
//获得用户历史信息
historyInfoPoint = ChatCacheController.getChatCache(chatKey,context);
StringBuffer curInfoRecord = new StringBuffer();
StringBuffer hisInfoRecord = new StringBuffer();
historyInfoPoint = ChatCacheController.getChatCache(chatKey, context);
UserInfo userinfo = null;
......@@ -52,46 +51,46 @@ public class GetAnswerServlet extends HttpServlet {
try {
//userinfo = process.userInfoQuery(chatKey,context);
//从servlet根据用户名查询用户信息
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"),context);
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context);
} catch (SQLException e) {
state = NAME_MISSING_ERROR;
e.printStackTrace();
}
//如果historyInfoPoint不存在,就新建一个
if(historyInfoPoint == null) {
if (historyInfoPoint == null) {
String k;
historyInfoPoint = new HashMap<String,String>();
historyInfoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()){
while (iit.hasNext()) {
k = iit.next();
historyInfoPoint.put(k,"");
historyInfoPoint.put(k, "");
}
//变量初始化
iit = userinfo.varInitialMap.keySet().iterator();
while(iit.hasNext()){
while (iit.hasNext()) {
k = iit.next();
historyInfoPoint.put(k, userinfo.varInitialMap.get(k));
}
}
//信息点预处理
debugFlag = process.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, curInfoRecord);
debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试
ansCondition = process.getBestMatch(curInfoPoint,historyInfoPoint,userinfo.conditionTable, context);
ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context);
if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,";
if (state.equals("")) {
try {
bestMatch = process.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
bestMatch = matcher.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
if(ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")){
if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) {
//如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = process.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
bestMatch = matcher.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
}
} catch (ParseException e) {
e.printStackTrace();
......@@ -104,16 +103,16 @@ public class GetAnswerServlet extends HttpServlet {
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
}
//bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
}else{
bestMatch = new Solution(0," \n" + return_str + "\n " +state,"nextStep=" + historyInfoPoint.get("currentAction"));
} else {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction"));
}
if(debugFlag) {
process.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context);
if (debugFlag) {
matcher.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context);
}
process.infoTransition(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag);
matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag);
ansJ = MyFunc.toJson(bestMatch);
......
......@@ -7,24 +7,24 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet(name = "GetConfigServlet",urlPatterns = {"/getConfig"})
@WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"})
public class GetConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String path = System.getProperty("user.dir")+"/config/"+userName+".txt";
String path = System.getProperty("user.dir") + "/config/" + userName + ".txt";
File file = new File(path);
OutputStream out = response.getOutputStream();
if(file.exists()){
if (file.exists()) {
FileReader fr= new FileReader(file);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null){
while ((line = br.readLine()) != null) {
line = line + "\n";
out.write(line.getBytes());
}
......@@ -32,7 +32,7 @@ public class GetConfigServlet extends HttpServlet {
fr.close();
br.close();
} else{
} else {
out.write("查无此bot".getBytes());
}
out.flush();
......
package servlet;
import entity.UserInfo;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.UserInfoController;
import javax.servlet.ServletContext;
......@@ -17,31 +15,31 @@ import java.io.*;
/**
* 发请求从本地文件夹重新加载某用户的配置文件
*/
@WebServlet(name = "ReloadConfigServlet",urlPatterns = {"/reload","/reload/"})
@WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"})
public class ReloadConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
boolean flag = true;
UserInfo userinfo = new UserInfo(userName);
File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt");
File configFile = new File(System.getProperty("user.dir") + "/config/" + userName + ".txt");
System.out.println(configFile.getAbsolutePath());
ServletContext context = this.getServletContext();
if(!configFile.exists()) {
if (!configFile.exists()) {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("文件不存在: "+userName);
out.println("文件不存在: " + userName);
}else{
} else {
FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader);
try {
userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
context.setAttribute(userinfo.userName, userinfo);
} catch (Exception e) {
flag = false;
System.out.println(userinfo.userName + ".txt 有误");
e.printStackTrace();
......@@ -50,18 +48,17 @@ public class ReloadConfigServlet extends HttpServlet {
reader.close();
br.close();
if(!flag) {
if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</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("更新失败配置文件有误:" + userName +".txt\\\n");
out.println("更新失败配置文件有误:" + userName + ".txt\\\n");
}
else{
} else {
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("重新加载成功");
out.flush();
......@@ -75,7 +72,6 @@ public class ReloadConfigServlet extends HttpServlet {
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
......
......@@ -3,7 +3,6 @@ package servlet;
import entity.Condition;
import entity.UserInfo;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.UserInfoController;
import javax.servlet.ServletContext;
......@@ -21,12 +20,12 @@ import java.util.List;
/**
* 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。
*/
@WebServlet(name = "UpdateServlet",urlPatterns = {"/update"})
@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"})
public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。
request.setCharacterEncoding("UTF-8");
String line,extraElements[];
String line, extraElements[];
ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext();
String userName = request.getParameter("userName");
......@@ -42,35 +41,35 @@ public class UpdateServlet extends HttpServlet {
String errorStr = "";
while((line = br.readLine()) != null){
while ((line = br.readLine()) != null) {
System.out.println(line);
if(line.trim().equals(""))
if (line.trim().equals(""))
continue;
line = line.replace("\n","");
line = line.replace("\n", "");
//在用户信息中添加额外信息,如设为active的action
if(line.indexOf("-extraInfo-") != -1){
if (line.indexOf("-extraInfo-") != -1) {
extraElements = line.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
userinfo.configStr += line+"\n";
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
userinfo.configStr += line + "\n";
continue;
}
//line = MyFunc.convert2Utf8(line.trim());
userinfo.configStr += line+"\n";
userinfo.configStr += line + "\n";
Condition condition = new Condition();
try {
condition = UserInfoController.buildCondition(condition,line);
condition = UserInfoController.buildCondition(condition, line);
conditionList = userinfo.conditionTable.get(condition.indexName);
if(conditionList == null)
if (conditionList == null)
conditionList = new ArrayList<Condition>();
conditionList.add(condition);
userinfo.conditionTable.put(condition.indexName,conditionList);
userinfo.conditionTable.put(condition.indexName, conditionList);
/*
for(String name:condition.indexName){
userinfo.conditionTable.put()
}
*/
} catch(Exception e ){
} catch (Exception e) {
System.out.println("配置文件有误!");
flag = false;
errorList.add(line);
......@@ -80,23 +79,22 @@ public class UpdateServlet extends HttpServlet {
}
br.close();
if(!flag) {
if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</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");
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n");
out.println("更新失败,以下行有误: ");
for(String error:errorList)
out.println("---"+error);
for (String error : errorList)
out.println("---" + error);
out.flush();
out.close();
System.out.println("error");
}
else{
} else {
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("更新成功+ “ ");
out.flush();
......@@ -104,14 +102,14 @@ public class UpdateServlet extends HttpServlet {
System.out.println("success");
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
context.setAttribute(userName,userinfo);
String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt";
context.setAttribute(userName, userinfo);
String path = System.getProperty("user.dir") + "/config/" + userinfo.userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
File dir = new File(System.getProperty("user.dir") + "/config");
if(!dir.exists())
if (!dir.exists())
dir.mkdir();
if(!file.exists()){
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
......
package servlet;
import entity.UserInfo;
import processing.ProcessQuestion;
import processing.ConditionTableController;
import processing.UserInfoController;
......@@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet(name = "UpdateSingleConfigServlet",urlPatterns = {"/update2"})
@WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"})
public class UpdateSingleConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
......@@ -22,9 +21,9 @@ public class UpdateSingleConfigServlet extends HttpServlet {
String processType = request.getParameter("type");
String configId = request.getParameter("configId");
String data = request.getParameter("configData");
System.out.println("userName:"+userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data);
System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data);
if(context.getAttribute(userName) != null) {
if (context.getAttribute(userName) != null) {
switch (processType) {
case "insert_config":
ConditionTableController.insertConfig(userName, configId, data, context);
......@@ -56,17 +55,17 @@ public class UpdateSingleConfigServlet extends HttpServlet {
writeConfig(userName, context);
response.setStatus(200);
}else if(processType.equals("batch_update")){
} else if (processType.equals("batch_update")) {
batchUpdate(userName, data, context);
writeConfig(userName, context);
response.setStatus(200);
}else{
} else {
response.setStatus(111);
}
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.write("success");
out.flush();
......@@ -93,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet {
BufferedReader br = new BufferedReader(new StringReader(data));
UserInfo userinfo = new UserInfo(userName);
userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
context.setAttribute(userinfo.userName, userinfo);
System.out.println("batchupdate");
}
}
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