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; ...@@ -5,17 +5,17 @@ import java.sql.DriverManager;
public class DB { public class DB {
private static String driver = "com.mysql.jdbc.Driver"; private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN";
private static String user = "root"; private static String user = "root";
private static String pwd = "admin"; private static String pwd = "admin";
public static Connection getConnection(){ public static Connection getConnection() {
Connection conn = null; Connection conn = null;
try{ try {
Class.forName(driver); Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd); conn = DriverManager.getConnection(url, user, pwd);
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -14,7 +14,8 @@ import java.util.Properties; ...@@ -14,7 +14,8 @@ import java.util.Properties;
public class DBCPUtils { public class DBCPUtils {
private static DataSource ds;//定义一个连接池对象 private static DataSource ds;//定义一个连接池对象
static{
static {
try { try {
Properties pro = new Properties(); Properties pro = new Properties();
File file = new File("dbcpconfig.properties"); File file = new File("dbcpconfig.properties");
...@@ -25,13 +26,14 @@ public class DBCPUtils { ...@@ -25,13 +26,14 @@ public class DBCPUtils {
//throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); //throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!");
} }
} }
//从池中获取一个连接 //从池中获取一个连接
public static Connection getConnection() throws SQLException { public static Connection getConnection() throws SQLException {
return ds.getConnection(); return ds.getConnection();
} }
public static void closeAll(ResultSet rs, Statement stmt, Connection conn){ public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if(rs!=null){ if (rs != null) {
try { try {
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
...@@ -39,7 +41,7 @@ public class DBCPUtils { ...@@ -39,7 +41,7 @@ public class DBCPUtils {
} }
} }
if(stmt!=null){ if (stmt != null) {
try { try {
stmt.close(); stmt.close();
} catch (SQLException e) { } catch (SQLException e) {
...@@ -47,7 +49,7 @@ public class DBCPUtils { ...@@ -47,7 +49,7 @@ public class DBCPUtils {
} }
} }
if(conn!=null){ if (conn != null) {
try { try {
conn.close();//关闭 conn.close();//关闭
} catch (SQLException e) { } catch (SQLException e) {
......
package db;
public class DBUtils {
}
...@@ -3,10 +3,12 @@ package db; ...@@ -3,10 +3,12 @@ package db;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import entity.JConfig; import entity.JConfig;
import entity.QuestionKeyWord; import entity.QuestionKeyWord;
import gameDesign.ElementConstructor;
import processing.MyFunc; import processing.MyFunc;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
public class SqlHelper { public class SqlHelper {
...@@ -18,15 +20,15 @@ public class SqlHelper { ...@@ -18,15 +20,15 @@ public class SqlHelper {
*/ */
public SqlHelper() throws SQLException { public SqlHelper() throws SQLException {
conn = DBCPUtils.getConnection(); conn = C3p0Utils.getConnection();
} }
public void destroy(){ public void destroy() {
if (conn != null){ if (conn != null) {
try{ try {
conn.close(); conn.close();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -82,20 +84,25 @@ public class SqlHelper { ...@@ -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 sql = "select * from chats where chat_key = ?";
String userName = ""; String userName = "";
String result = "empty"; String result = "empty";
try{ try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,chat_key); ps.setString(1, chat_key);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()) if (rs.next())
result = rs.getString("bot"); result = rs.getString("bot");
rs.close();
ps.close(); ps.close();
rs.close();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
...@@ -107,9 +114,9 @@ public class SqlHelper { ...@@ -107,9 +114,9 @@ public class SqlHelper {
boolean firstValue = true; boolean firstValue = true;
int batchSize = idGroup.size(); int batchSize = idGroup.size();
for (int i=0; i < batchSize; i++) { for (int i = 0; i < batchSize; i++) {
inClause.append('?'); inClause.append('?');
if ( firstValue ) { if (firstValue) {
firstValue = false; firstValue = false;
} else { } else {
inClause.append(','); inClause.append(',');
...@@ -120,27 +127,49 @@ public class SqlHelper { ...@@ -120,27 +127,49 @@ public class SqlHelper {
String userName = ""; String userName = "";
boolean b = true; boolean b = true;
try{ try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
b = ps.execute(); b = ps.execute();
ps.close(); ps.close();
return b; return b;
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return b; return b;
} }
public boolean deleteConfigByBotId(int botId){ public boolean deleteConfigByBotId(int botId) {
String sql = "delete from chatbot_config where botId= ?";
boolean b; 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); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
b = ps.execute(); b = ps.execute();
ps.close(); ps.close();
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
...@@ -150,7 +179,64 @@ public class SqlHelper { ...@@ -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[]; 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 (?, ?, ?, ?)";
...@@ -160,10 +246,10 @@ public class SqlHelper { ...@@ -160,10 +246,10 @@ 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 : jConfigList) { for (JConfig jConfig : constructor.getjConfigList()) {
ps.setString(1, String.valueOf(botId)); ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0)); ps.setString(2, String.valueOf(0));
ps.setString(3, jConfig.toJson().toJSONString()); ps.setString(3, jConfig.toJson(constructor.getConditionDescription()).toJSONString());
ps.setString(4, ""); ps.setString(4, "");
ps.addBatch(); ps.addBatch();
} }
...@@ -179,16 +265,19 @@ public class SqlHelper { ...@@ -179,16 +265,19 @@ public class SqlHelper {
} }
} }
ResultSet rs = ps.getGeneratedKeys(); ResultSet rs = ps.getGeneratedKeys();
while(rs.next()) while (rs.next())
idList.add(rs.getInt(1)); idList.add(rs.getInt(1));
ps.close(); ps.close();
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
try { try {
conn.rollback(); conn.rollback();
} catch (SQLException e1) { } catch (SQLException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
...@@ -196,23 +285,25 @@ public class SqlHelper { ...@@ -196,23 +285,25 @@ public class SqlHelper {
e.printStackTrace(); 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 sql = "select * from generate_json_tb where id = ?";
String userName = ""; String userName = "";
String result = "empty"; String result = "empty";
try{ try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(id)); ps.setString(1, String.valueOf(id));
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()) if (rs.next())
result = rs.getString("json_text"); result = rs.getString("json_text");
rs.close();
ps.close(); ps.close();
rs.close();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -220,7 +311,28 @@ public class SqlHelper { ...@@ -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 { ...@@ -14,14 +14,14 @@ public class Condition {
public int activePriority = 0; //如果本condition被其他condition激活 public int activePriority = 0; //如果本condition被其他condition激活
public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级
public HashSet<String> keywordSet = new HashSet<String>(); public HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String,HashSet<String>> historyPremise = 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, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, String> updateKnowledge = new HashMap<String, String>(); public HashMap<String, String> updateKnowledge = new HashMap<String, String>();
public String[] answer = {"",}; public String[] answer = {"",};
public String nextStep = ""; public String nextStep = "";
public HashMap<String, String> featureMap = new HashMap<String, String>(); public HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = ""; public String indexName = "";
public int id =0; public int id = 0;
public String status = "waiting"; public String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>(); //public ArrayList<String> indexName = new ArrayList<String>();
......
...@@ -16,7 +16,6 @@ public class JConfig { ...@@ -16,7 +16,6 @@ public class JConfig {
private String jFeature = ""; private String jFeature = "";
private String jNextStep = ""; private String jNextStep = "";
private String jReply = ""; private String jReply = "";
private String jAuxiliaryPriority = "0"; private String jAuxiliaryPriority = "0";
...@@ -26,7 +25,6 @@ public class JConfig { ...@@ -26,7 +25,6 @@ public class JConfig {
private String hisPremise = ""; private String hisPremise = "";
private String feature = ""; private String feature = "";
private String reply = ""; private String reply = "";
private String nextStep = ""; private String nextStep = "";
...@@ -42,12 +40,12 @@ public class JConfig { ...@@ -42,12 +40,12 @@ public class JConfig {
private String updateKnowledge = ""; private String updateKnowledge = "";
private String nextStepStatus = "return"; private String nextStepStatus = "return";
Map<String, String> statusMap = new HashMap<String, String>(){ Map<String, String> statusMap = new HashMap<String, String>() {
{ {
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("activate", "activate");
} }
}; };
...@@ -55,16 +53,16 @@ public class JConfig { ...@@ -55,16 +53,16 @@ public class JConfig {
public void setAuxiliaryPriority(String auxiliaryPriority) { public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public void setNextStepStatus(String nextStepStatus) { public void setNextStepStatus(String nextStepStatus) {
this.nextStepStatus = nextStepStatus; this.nextStepStatus = nextStepStatus;
} }
public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) {
{
this.curPremise = curPremise; this.curPremise = curPremise;
this.hisPremise = hisPremise; this.hisPremise = hisPremise;
this.feature = feature; this.feature = feature;
if(!updateKnowledge.equals("")) if (!updateKnowledge.equals(""))
this.updateKnowledge += "-<-" + updateKnowledge; this.updateKnowledge += "-<-" + updateKnowledge;
this.reply = reply; this.reply = reply;
...@@ -72,7 +70,7 @@ public class JConfig { ...@@ -72,7 +70,7 @@ public class JConfig {
} }
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){ 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.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
...@@ -82,44 +80,44 @@ public class JConfig { ...@@ -82,44 +80,44 @@ public class JConfig {
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public String appendPremiseStr(List<String> premises, String extraPM){ public String appendPremiseStr(List<String> premises, String extraPM) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String premiseStr = ""; String premiseStr = "";
for (String premise:premises) for (String premise : premises)
sb.append("," + premise); sb.append("," + premise);
if(sb.length() > 0) if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号 sb.deleteCharAt(0); //删除第一个逗号
if(!extraPM.equals("")){ if (!extraPM.equals("")) {
if(sb.length() == 0) if (sb.length() == 0)
sb.append(extraPM); sb.append(extraPM);
else else
sb.append("," + extraPM); sb.append("," + extraPM);
}else if(sb.length() == 0){ } else if (sb.length() == 0) {
sb.append(" "); sb.append(" ");
} }
premiseStr = sb.toString(); premiseStr = sb.toString();
return premiseStr; return premiseStr;
} }
public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL){ public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr; String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator(); Iterator<String> iit = knowledge.keySet().iterator();
while(iit.hasNext()){ while (iit.hasNext()) {
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);
} }
if(sb.length() > 0) if (sb.length() > 0)
knowledgeStr = "updateKnowledge" + sb.toString(); knowledgeStr = "updateKnowledge" + sb.toString();
else else
knowledgeStr = ""; knowledgeStr = "";
...@@ -128,9 +126,10 @@ public class JConfig { ...@@ -128,9 +126,10 @@ public class JConfig {
} }
public void appendJPremise(JSONArray premiseList, String premise){ public void appendJPremise(JSONArray premiseList, String premise, Map<String, String> conditionDescription) {
//System.out.println(premise);
String pair1[] = premise.split("="); String pair1[] = premise.split("=", 2);
String key = pair1[0]; String key = pair1[0];
String keywords = pair1[1]; String keywords = pair1[1];
String pair2[] = key.split("::"); String pair2[] = key.split("::");
...@@ -138,26 +137,33 @@ public class JConfig { ...@@ -138,26 +137,33 @@ public class JConfig {
String pair3[] = pair2[1].split("-"); String pair3[] = pair2[1].split("-");
String cmpType = pair3[0]; String cmpType = pair3[0];
String operator = ""; String operator = "";
if(pair3.length > 1) if (pair3.length > 1)
operator = pair3[1]; operator = pair3[1];
String question = "";
if (conditionDescription.get(conditionName) != null)
question = conditionDescription.get(conditionName);
JSONObject premiseJ = new JSONObject(); JSONObject premiseJ = new JSONObject();
premiseJ.put("keywords", keywords); premiseJ.put("keywords", keywords);
premiseJ.put("actionName", conditionName); premiseJ.put("actionName", conditionName);
premiseJ.put("cmpType", cmpType); premiseJ.put("cmpType", cmpType);
premiseJ.put("question", "不知"); premiseJ.put("question", question);
premiseJ.put("operator", operator); premiseJ.put("operator", operator);
premiseList.add(premiseJ); premiseList.add(premiseJ);
} }
public void appendJKnowledge(JSONArray knowledgeList, String knowledge){ public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) {
String pair[] = knowledge.split(":"); String pair[] = knowledge.split(":");
if(knowledge.equals("") || pair.length < 2) if (knowledge.equals("") || pair.length < 2)
return; return;
String question = "";
if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]);
JSONObject knowledgeJ = new JSONObject(); JSONObject knowledgeJ = new JSONObject();
knowledgeJ.put("variableName", pair[0]); knowledgeJ.put("variableName", pair[0]);
...@@ -166,35 +172,40 @@ public class JConfig { ...@@ -166,35 +172,40 @@ public class JConfig {
knowledgeList.add(knowledgeJ); knowledgeList.add(knowledgeJ);
} }
public void appendJNextStep(JSONArray nextStepList, String next){ public void appendJNextStep(JSONArray nextStepList, String next, Map<String, String> conditionDescription) {
String pair[] = next.split("-"); String pair[] = next.split("-");
JSONObject nextStepJ = new JSONObject(); JSONObject nextStepJ = new JSONObject();
JSONArray exceptJ = new JSONArray(); JSONArray exceptJ = new JSONArray();
for(int i = 1;i < pair.length;i++) for (int i = 1; i < pair.length; i++)
exceptJ.add(pair[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("nextStep", pair[0]);
nextStepJ.put("except", exceptJ); nextStepJ.put("except", exceptJ);
nextStepJ.put("nextStepText", question);
nextStepList.add(nextStepJ); nextStepList.add(nextStepJ);
} }
public JSONObject toJson(){ public JSONObject toJson(Map<String, String> conditionDescription) {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
JSONArray curPremiseList = new JSONArray(); JSONArray curPremiseList = new JSONArray();
JSONArray hisPremiseList = new JSONArray(); JSONArray hisPremiseList = new JSONArray();
//添加当前对话内容 //添加当前对话内容
for(String premise:curPremise.split(",")){ for (String premise : curPremise.split(",")) {
if(!premise.equals("") && !premise.equals(" ")) if (!premise.equals("") && !premise.equals(" "))
appendJPremise(curPremiseList, premise); appendJPremise(curPremiseList, premise, conditionDescription);
} }
data.put("currentPremiseList", curPremiseList); data.put("currentPremiseList", curPremiseList);
//添加已知信息的内容 //添加已知信息的内容
for(String premise:hisPremise.split(",")){ for (String premise : hisPremise.split(",")) {
if(!premise.equals("") && !premise.equals(" ")) if (!premise.equals("") && !premise.equals(" "))
appendJPremise(hisPremiseList, premise); appendJPremise(hisPremiseList, premise, conditionDescription);
} }
data.put("historyPremiseList", hisPremiseList); data.put("historyPremiseList", hisPremiseList);
...@@ -207,10 +218,22 @@ public class JConfig { ...@@ -207,10 +218,22 @@ public class JConfig {
//添加config状态 //添加config状态
data.put("configStatus", 0); data.put("configStatus", 0);
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参数 //添加post参数
data.put("doPost", false); data.put("doPost", doPost);
data.put("postURL", ""); data.put("postURL", postURL);
data.put("postType", "all"); data.put("postType", postType);
//添加回答 //添加回答
data.put("reply", reply); data.put("reply", reply);
...@@ -223,17 +246,17 @@ public class JConfig { ...@@ -223,17 +246,17 @@ public class JConfig {
//添加更新答案处的信息 //添加更新答案处的信息
JSONArray knowledgeList = new JSONArray(); JSONArray knowledgeList = new JSONArray();
if(!updateKnowledge.equals("")) { if (!updateKnowledge.equals("")) {
for (String knowledge : updateKnowledge.split("-<-")) { for (String knowledge : updateKnowledge.split("-<-")) {
appendJKnowledge(knowledgeList, knowledge); appendJKnowledge(knowledgeList, knowledge, conditionDescription);
} }
data.put("updateKnowledge", knowledgeList);
} }
data.put("updateKnowledge", knowledgeList);
//添加下一步 //添加下一步
JSONArray nextStepList = new JSONArray(); JSONArray nextStepList = new JSONArray();
for(String next: nextStep.split(",")){ for (String next : nextStep.split(",")) {
appendJNextStep(nextStepList, next); appendJNextStep(nextStepList, next, conditionDescription);
} }
data.put("nextStepList", nextStepList); data.put("nextStepList", nextStepList);
...@@ -241,7 +264,7 @@ public class JConfig { ...@@ -241,7 +264,7 @@ public class JConfig {
} }
public String toString(){ public String toString() {
String text = curPremise + "|" + String text = curPremise + "|" +
hisPremise + "|" + hisPremise + "|" +
......
package entity; package entity;
/** /**
* 暂时没用 * 暂时没用
*/ */
......
...@@ -18,7 +18,6 @@ public class Solution { ...@@ -18,7 +18,6 @@ public class Solution {
} }
public void setAnswer(String answer) { public void setAnswer(String answer) {
this.answer = answer; this.answer = answer;
} }
...@@ -35,10 +34,12 @@ public class Solution { ...@@ -35,10 +34,12 @@ public class Solution {
this.next = next; this.next = next;
} }
public Solution(int status, String answers, String next){ public Solution(int status, String answers, String next) {
this.answer = answers; this.answer = answers;
this.next = next; this.next = next;
this.status = status; this.status = status;
} }
public Solution(){}
public Solution() {
}
} }
...@@ -7,13 +7,13 @@ import java.util.List; ...@@ -7,13 +7,13 @@ import java.util.List;
* 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里
*/ */
public class UserInfo { public class UserInfo {
public UserInfo(String userName){ public UserInfo(String userName) {
this.conditionTable = new HashMap<String, List<Condition>>(); this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = ""; this.configStr = "";
this.userName = userName; 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>(); this.id2config = new HashMap<Integer, String>();
...@@ -21,15 +21,14 @@ public class UserInfo { ...@@ -21,15 +21,14 @@ public class UserInfo {
this.varInitialMap = new HashMap<String, String>(); this.varInitialMap = new HashMap<String, String>();
} }
public HashMap<String,List<Condition>> conditionTable; public HashMap<String, List<Condition>> conditionTable;
public String configStr; public String configStr;
public String userName; public String userName;
public HashMap<String,String> extraInfo; public HashMap<String, String> extraInfo;
public HashMap<Integer, String> id2config; public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition; public HashMap<Integer, Condition> id2condition;
//存储需要初始化的变量 //存储需要初始化的变量
public HashMap<String, String> varInitialMap; public HashMap<String, String> varInitialMap;
} }
...@@ -8,7 +8,7 @@ import entity.UserInfo; ...@@ -8,7 +8,7 @@ import entity.UserInfo;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; 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) {
super(); super();
...@@ -16,13 +16,13 @@ public class CharacterConstructor extends ElementConstructor{ ...@@ -16,13 +16,13 @@ public class CharacterConstructor extends ElementConstructor{
this.botId = botId; this.botId = botId;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo){ public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue; String category, name, description, attrName, attrValue;
JSONArray allNPC = jsonObject.getJSONArray("npc"); JSONArray allNPC = jsonObject.getJSONArray("npc");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
for(JSONObject npc:allNPC.toJavaList(JSONObject.class)) { for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) {
category = (String) npc.get("category"); category = (String) npc.get("category");
JSONArray characters = npc.getJSONArray("characters"); JSONArray characters = npc.getJSONArray("characters");
for (JSONObject character : characters.toJavaList(JSONObject.class)) { for (JSONObject character : characters.toJavaList(JSONObject.class)) {
...@@ -33,7 +33,7 @@ public class CharacterConstructor extends ElementConstructor{ ...@@ -33,7 +33,7 @@ public class CharacterConstructor extends ElementConstructor{
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); 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; ...@@ -13,38 +13,66 @@ import java.util.Map;
public class ElementConstructor { public class ElementConstructor {
int botId = 0; int botId = 0;
SqlHelper helper = null; SqlHelper helper = null;
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 userName; String CHITCHAT_URL = "http:192.168.1.178:1111/test", userName;
StringBuffer configText = new StringBuffer(); StringBuffer configText = new StringBuffer();
JConfig jConfig = null; JConfig jConfig = null;
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 void construct(JSONObject jsonObject, UserInfo userinfo){}
public List<JConfig> getjConfigList() { return jConfigList; } public Map<String, String> getVarInitialMap() {
public List<JSONObject> getConfigDataList() { return configDataList; } return varInitialMap;
public void ElementConstructor(String userName){ this.userName = userName; } }
public String getConfigText() { return configText.toString(); }
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(); int id, length = idList.size();
String varValue;
JConfig jConfig = null; JConfig jConfig = null;
for(int i = 0; i< length;i++){ for (int i = 0; i < length; i++) {
jConfig = jConfigList.get(i); jConfig = jConfigList.get(i);
id = idList.get(i); id = idList.get(i);
configText.append(jConfig.toString() + id + "\n"); configText.append(jConfig.toString() + id + "\n");
} }
for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue + "\n");
}
} }
/** /**
* 构造参数配置文件的json版 * 构造参数配置文件的json版
*/ */
public void buildJconfig(){ public void buildJconfig() {
} }
......
...@@ -6,17 +6,21 @@ package gameDesign; ...@@ -6,17 +6,21 @@ package gameDesign;
public class Floyd { public class Floyd {
/**
/** 表示正无穷 */ * 表示正无穷
*/
int MAX_WEIGHT = Integer.MAX_VALUE; int MAX_WEIGHT = Integer.MAX_VALUE;
/**路径矩阵*/ /**
* 路径矩阵
*/
int[][] pathMatirx; int[][] pathMatirx;
/**前驱表*/ /**
* 前驱表
*/
int[][] preTable; int[][] preTable;
public void findShortestPath(int[][] matrix, int length) {
public void findShortestPath(int[][] matrix, int length){
//路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。 //路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。
pathMatirx = new int[length][length]; pathMatirx = new int[length][length];
//前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值 //前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值
...@@ -50,7 +54,7 @@ public class Floyd { ...@@ -50,7 +54,7 @@ public class Floyd {
int mn = pathMatirx[m][n]; int mn = pathMatirx[m][n];
int mk = pathMatirx[m][k]; int mk = pathMatirx[m][k];
int kn = pathMatirx[k][n]; 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) { if (mn > addedPath) {
//如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个 //如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个
...@@ -80,7 +84,6 @@ public class Floyd { ...@@ -80,7 +84,6 @@ public class Floyd {
public void printPath(int[][] matrix, int length) { public void printPath(int[][] matrix, int length) {
for (int m = 0; m < length; m++) { for (int m = 0; m < length; m++) {
for (int n = m + 1; n < length; n++) { for (int n = m + 1; n < length; n++) {
......
...@@ -8,7 +8,7 @@ import entity.UserInfo; ...@@ -8,7 +8,7 @@ import entity.UserInfo;
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) {
super(); super();
...@@ -16,20 +16,20 @@ public class GlobalVariableConstructor extends ElementConstructor{ ...@@ -16,20 +16,20 @@ public class GlobalVariableConstructor extends ElementConstructor{
this.botId = botId; this.botId = botId;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo){ public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue; String category, name, description, attrName, attrValue;
JSONArray globalVariable = jsonObject.getJSONArray("globalVariable"); JSONArray globalVariable = jsonObject.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 = JSONObject.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();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
configText.append("-varInitial-|" + category + "_" + attrName + "|" + attrValue + "\n"); varInitialMap.put(category + "_" + attrName, attrValue);
} }
} }
} }
......
...@@ -8,7 +8,7 @@ import entity.UserInfo; ...@@ -8,7 +8,7 @@ import entity.UserInfo;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; 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) {
...@@ -18,13 +18,13 @@ public class ItemConstructor extends ElementConstructor{ ...@@ -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; String category, name, description, attrName, attrValue;
JSONArray goods = jsonObject.getJSONArray("goods"); JSONArray goods = jsonObject.getJSONArray("goods");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
for(JSONObject good:goods.toJavaList(JSONObject.class)) { for (JSONObject good : goods.toJavaList(JSONObject.class)) {
category = (String) good.get("category"); category = (String) good.get("category");
JSONArray items = good.getJSONArray("items"); JSONArray items = good.getJSONArray("items");
...@@ -36,7 +36,7 @@ public class ItemConstructor extends ElementConstructor{ ...@@ -36,7 +36,7 @@ public class ItemConstructor extends ElementConstructor{
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); 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; ...@@ -10,7 +10,7 @@ import java.io.BufferedReader;
import java.io.StringReader; import java.io.StringReader;
import java.util.*; import java.util.*;
public class MapConstructor extends ElementConstructor{ public class MapConstructor extends ElementConstructor {
int[][] matrix; int[][] matrix;
int locationNum; int locationNum;
...@@ -60,11 +60,11 @@ public class MapConstructor extends ElementConstructor{ ...@@ -60,11 +60,11 @@ public class MapConstructor extends ElementConstructor{
} }
} }
public void construct(JSONObject jsonObject, UserInfo userinfo){ public void construct(JSONObject jsonObject, UserInfo userinfo) {
conditionDescription.put("site","当前地点"); conditionDescription.put("site", "当前地点");
varInitialMap.put("site", "");
JSONObject map = jsonObject.getJSONObject("map"); JSONObject map = jsonObject.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");
...@@ -87,62 +87,61 @@ public class MapConstructor extends ElementConstructor{ ...@@ -87,62 +87,61 @@ public class MapConstructor extends ElementConstructor{
/** /**
* 生成‘我在哪里’所需要的配置文件 * 生成‘我在哪里’所需要的配置文件
*/ */
public void generateWhereIam(JSONObject jsonObject){ public void generateWhereIam(JSONObject jsonObject) {
String zainaKeywords = question2keyword.get("zaina"); String zainaKeywords = question2keyword.get("zaina");
jConfig = new JConfig( jConfig = new JConfig(
"zaina::match-Keyword=" + zainaKeywords, " ", "zaina::match-Keyword=" + zainaKeywords, " ",
"match", "你在{site-2}", "yaobuyao","" "match", "你在{site-2}", "yaobuyao", ""
); );
jConfigList.add(jConfig); 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 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 i = 0; i < locationNum; i++) {
for(int j = 0;j < locationNum;j++){ for (int j = 0; j < locationNum; j++) {
placeA = (String)locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name"); placeB = (String) locations.getJSONObject(j).get("name");
placeKeywords = zenmequKeywords.replace("地点", placeB); placeKeywords = zenmequKeywords.replace("地点", placeB);
if(i == j){ if (i == j) {
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao","" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
continue; continue;
}; }
if(pathMatirx[i][j] == 1){ ;
if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", placeB + "就在附近哦", "yaobuyao", "" "match", placeB + "就在附近哦", "yaobuyao", ""
); );
jConfigList.add(jConfig); 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]; int k = preTable[i][j];
pathNode = ""; pathNode = "";
while (k != j) { while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name"); pathNode += (String) locations.getJSONObject(k).get("name");
k = preTable[k][j]; k = preTable[k][j];
} }
jConfig = new JConfig( jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "zenmequ::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao","" "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
...@@ -154,16 +153,16 @@ public class MapConstructor extends ElementConstructor{ ...@@ -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 nengqunaKeywords = question2keyword.get("nengquna");
String placeA, placeB, pathNode; String placeA, placeB, pathNode;
for(int i = 0;i < locationNum;i++){ for (int i = 0; i < locationNum; i++) {
placeA = (String)locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
pathNode = ""; pathNode = "";
for(int j = 0;j < locationNum;j++){ for (int j = 0; j < locationNum; j++) {
if(pathMatirx[i][j] == 1) { if (pathMatirx[i][j] == 1) {
placeB = (String) locations.getJSONObject(j).get("name"); placeB = (String) locations.getJSONObject(j).get("name");
pathNode += "、" + placeB; pathNode += "、" + placeB;
} }
...@@ -176,7 +175,6 @@ public class MapConstructor extends ElementConstructor{ ...@@ -176,7 +175,6 @@ public class MapConstructor extends ElementConstructor{
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
...@@ -186,32 +184,31 @@ public class MapConstructor extends ElementConstructor{ ...@@ -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 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 i = 0;i < locationNum;i++){ for (int j = 0; j < locationNum; j++) {
for(int j = 0;j < locationNum;j++){ placeA = (String) locations.getJSONObject(i).get("name");
placeA = (String)locations.getJSONObject(i).get("name"); 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 = qunaKeywords.replace("地点", placeB); placeKeywords = qunaKeywords.replace("地点", placeB);
if (i == j) {
if(i == j){
jConfig = new JConfig( jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", "" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
continue; continue;
}; }
;
//如果两点相邻 //如果两点相邻
if(pathMatirx[i][j] == 1){ if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, "quna::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA,
"match", "" + descriptionB, "yaobuyao", "site:" + placeB "match", "" + descriptionB, "yaobuyao", "site:" + placeB
...@@ -219,12 +216,12 @@ public class MapConstructor extends ElementConstructor{ ...@@ -219,12 +216,12 @@ public class MapConstructor extends ElementConstructor{
jConfigList.add(jConfig); 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]; int k = preTable[i][j];
pathNode = ""; pathNode = "";
while (k != j) { while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name"); pathNode += (String) locations.getJSONObject(k).get("name");
k = preTable[k][j]; k = preTable[k][j];
} }
jConfig = new JConfig( jConfig = new JConfig(
......
...@@ -9,56 +9,64 @@ import entity.UserInfo; ...@@ -9,56 +9,64 @@ import entity.UserInfo;
import java.util.*; import java.util.*;
public class PlotConstructor extends ElementConstructor{ public class PlotConstructor extends ElementConstructor {
JSONArray plots = null; JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String ,ArrayList<String>>(); HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String ,ArrayList<String>>(); HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>(); HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>(); HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public PlotConstructor(SqlHelper helper, int botId) {
public PlotConstructor(SqlHelper helper, int botId){
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
} }
public void construct(JSONObject jsonObject, UserInfo userinfo){ public void construct(JSONObject jsonObject, UserInfo userinfo) {
JSONArray plots = jsonObject.getJSONArray("plots"); JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String)jsonObject.get("start"); String start = (String) jsonObject.get("start");
userinfo.varInitialMap.put(start, "1");
userinfo.varInitialMap.put("unknownText", "你说啥?");
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
BFSGenerate2(id2j.get(start)); String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度";
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, start);
varInitialMap.put("unknownText", "你说啥?");
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
BFSGenerate3(id2j.get(start), userinfo);
varInitialMap.put(start, "0");
} }
//根据id构造邻接表 //根据id构造邻接表
public void constructAdjList(JSONArray plots){ public void constructAdjList(JSONArray plots) {
int length = plots.size(), branchSize; int length = plots.size(), branchSize;
String id = "", nextPlotId = ""; String id = "", nextPlotId = "";
JSONObject plot = null; JSONObject plot = null;
JSONArray branch = null; JSONArray branch = null;
for(int i = 0;i < length;i++){ for (int i = 0; i < length; i++) {
plot = plots.getJSONObject(i); plot = plots.getJSONObject(i);
id = (String)plot.get("id"); id = (String) plot.get("id");
plot.put("index", i); plot.put("index", i);
if(adjList.get(id) == null){ if (adjList.get(id) == null) {
adjList.put(id, new ArrayList<>()); adjList.put(id, new ArrayList<>());
} }
//添加branch中的下一个plot //添加branch中的下一个plot
branch = plot.getJSONArray("branch"); branch = plot.getJSONArray("branch");
branchSize = branch.size(); branchSize = branch.size();
for(int j =0;j < branchSize;j++) { for (int j = 0; j < branchSize; j++) {
nextPlotId = (String)branch.getJSONObject(j).get("nextPlotId"); nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId");
if(revAdjList.get(nextPlotId) == null){ if (revAdjList.get(nextPlotId) == null) {
revAdjList.put(nextPlotId, new ArrayList<>()); revAdjList.put(nextPlotId, new ArrayList<>());
} }
adjList.get(id).add(nextPlotId); adjList.get(id).add(nextPlotId);
...@@ -69,9 +77,9 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -69,9 +77,9 @@ public class PlotConstructor extends ElementConstructor{
} }
} }
public void BFSGenerate(JSONObject root){ public void BFSGenerate(JSONObject root, UserInfo userinfo) {
String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName, keywordOptions, conditionName, String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
unknownReply1, unknownReply2, nextCondition; nextUnknownText, curUnknownText, nextCondition;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null; JSONArray branch = null;
...@@ -82,73 +90,79 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -82,73 +90,79 @@ public class PlotConstructor extends ElementConstructor{
root.put("priority", 0); root.put("priority", 0);
root.put("taskName", id); root.put("taskName", id);
root.put("taskStep", 0); root.put("taskStep", 0);
root.put("nextUnknownText", varInitialMap.get("unknownText"));
;
Queue<JSONObject> queue = new LinkedList<JSONObject>(); Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root); queue.add(root);
while(!queue.isEmpty()){ while (!queue.isEmpty()) {
node = queue.remove(); node = queue.remove();
id = (String)node.get("id"); id = (String) node.get("id");
conditionDescription.put(id, "剧情" + id + "进度");
varInitialMap.put(id, "");
taskName = (String)node.get("taskName"); taskName = (String) node.get("taskName");
priority = (Integer)node.get("priority"); priority = (Integer) node.get("priority");
taskStep = (Integer)node.get("taskStep"); taskStep = (Integer) node.get("taskStep");
conditionName = (String)node.get("conditionName"); conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
//初始化 //初始化
newBranch = false; newBranch = false;
manyParent = false; manyParent = false;
adjNodeList = adjList.get(id); adjNodeList = adjList.get(id);
visited.put(id ,true); visited.put(id, true);
//查看是否存在多个子结点,如果有就是一个分支 //查看是否存在多个子结点,如果有就是一个分支
if(adjNodeList.size() > 1) if (adjNodeList.size() > 1)
newBranch = true; newBranch = true;
//查看是否存在多个父节点 //查看是否存在多个父节点
if(revAdjList.get(id) != null) if (revAdjList.get(id) != null)
manyParent = revAdjList.get(id).size() > 1; manyParent = revAdjList.get(id).size() > 1;
if(newBranch){ if (newBranch) {
//多个分支时nextTaskName为子结点的id名,不在这里设 //多个分支时nextTaskName为子结点的id名,不在这里设
nextTaskStep = 1; nextTaskStep = 1;
} } else {
else{ if (manyParent) {
if(manyParent){
nextTaskName = id; nextTaskName = id;
nextTaskStep = 1; nextTaskStep = 1;
priority++; priority++;
} } else {
else{
nextTaskName = taskName; nextTaskName = taskName;
nextTaskStep = taskStep + 1; nextTaskStep = taskStep + 1;
} }
} }
branch = node.getJSONArray("branch"); branch = node.getJSONArray("branch");
branchSize = branch.size(); branchSize = branch.size();
//当两次出现unknown时给用户一下候选项 //当两次出现unknown时给用户一下候选项
keywordOptions = ""; keywordOptions = "";
extraHP = taskName + "::match-Keyword=" + taskStep;
for(int i =0;i < branchSize;i++) { for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
nextId = (String)branchNode.get("nextPlotId"); nextId = (String) branchNode.get("nextPlotId");
if(id2j.get(nextId) != null) Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
nextCondition = (String)id2j.get(nextId).get("conditionName"); nextUnknownText = updateKnowledge.get("unknownText");
if (id2j.get(nextId) != null)
nextCondition = (String) id2j.get(nextId).get("conditionName");
else else
nextCondition = " "; nextCondition = " ";
//unknown计数器更新为0, 当前任务状态+1 //unknown计数器更新为0, 当前任务状态+1
if(newBranch) if (newBranch)
extraUK = taskName + ":" + taskStep; extraUK = taskName + ":" + taskStep;
//多余步骤,以后要处理掉 //多余步骤,以后要处理掉
...@@ -156,54 +170,66 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -156,54 +170,66 @@ public class PlotConstructor extends ElementConstructor{
extraUK = taskName + ":" + (taskStep + 1); extraUK = taskName + ":" + (taskStep + 1);
if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) extraHP = taskName + "::match-Keyword=" + taskStep;
extraUK += "-<-" + nextId + ":" + 1; if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1))
extraHP += "," + nextId + "::match-Keyword=null";
extraUK += "-<-" + nextId + ":" + 1;
jConfig = new JConfig( jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class), updateKnowledge,
"", extraHP, extraUK, "", extraHP, extraUK,
"match", (String) branchNode.get("reply"), (String) nextCondition, String.valueOf(priority) "match", (String) branchNode.get("reply"), (String) nextCondition, String.valueOf(priority)
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
try{
try {
keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者";
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if(branchNode.get("nextPlotId") != null){ if (branchNode.get("nextPlotId") != null) {
adjId = (String)branchNode.get("nextPlotId"); adjId = (String) branchNode.get("nextPlotId");
if(visited.get(adjId) == null && id2j.get(adjId) != null) { if (visited.get(adjId) == null) {
adjNode = id2j.get(adjId); if (id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
adjNode.put("taskStep", nextTaskStep); adjNode.put("nextUnknownText", nextUnknownText);
if(newBranch){ adjNode.put("taskStep", nextTaskStep);
adjNode.put("priority", priority+1); if (newBranch) {
adjNode.put("taskName", adjId); adjNode.put("priority", priority + 1);
}else{ adjNode.put("taskName", adjId);
adjNode.put("priority", priority); } else {
adjNode.put("taskName", taskName); adjNode.put("priority", priority);
adjNode.put("taskName", taskName);
}
queue.add(adjNode);
} else {
conditionDescription.put(adjId, "剧情" + adjId + "进度");
varInitialMap.put(adjId, "");
} }
queue.add(adjNode);
} }
} }
} }
/*
//对于unknown的特殊处理 //对于unknown的特殊处理
jConfig = new JConfig( if (curUnknownText.equals("")) {
conditionName + "::match-Keyword=unknown", jConfig = new JConfig(
extraHP + ",unknown_counter::number-SmallOrEqual=0,unknownReply::match-Keyword=null", conditionName + "::match-Keyword=unknown",
"match", extraHP = taskName + "::match-Keyword=" + taskStep,
"{lastReply-2}", "match,return-0,post::all(" + CHITCHAT_URL + ")",
" ", " ",
"unknown_counter:+1" " ",
); ""
);
jConfigList.add(jConfig);
}
/*
jConfig.setNextStepStatus("return-0"); jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig); jConfigList.add(jConfig);
jConfig = new JConfig( jConfig = new JConfig(
...@@ -230,8 +256,6 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -230,8 +256,6 @@ public class PlotConstructor extends ElementConstructor{
*/ */
} }
//unknown时的处理 //unknown时的处理
jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", "");
...@@ -239,13 +263,12 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -239,13 +263,12 @@ public class PlotConstructor extends ElementConstructor{
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
public void BFSGenerate2(JSONObject root){ //每个结点分为0、1、2三种状态
String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName, keywordOptions, conditionName, public void BFSGenerate2(JSONObject root) {
String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
unknownReply1, unknownReply2, nextCondition; unknownReply1, unknownReply2, nextCondition;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
...@@ -263,9 +286,9 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -263,9 +286,9 @@ public class PlotConstructor extends ElementConstructor{
queue.add(root); queue.add(root);
while(!queue.isEmpty()){ while (!queue.isEmpty()) {
node = queue.remove(); node = queue.remove();
id = (String)node.get("id"); id = (String) node.get("id");
//初始化 //初始化
...@@ -273,7 +296,7 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -273,7 +296,7 @@ public class PlotConstructor extends ElementConstructor{
manyParent = false; manyParent = false;
adjNodeList = adjList.get(id); adjNodeList = adjList.get(id);
visited.put(id ,true); visited.put(id, true);
/* /*
//查看是否存在多个子结点,如果有就是一个分支 //查看是否存在多个子结点,如果有就是一个分支
...@@ -302,7 +325,6 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -302,7 +325,6 @@ public class PlotConstructor extends ElementConstructor{
*/ */
branch = node.getJSONArray("branch"); branch = node.getJSONArray("branch");
branchSize = branch.size(); branchSize = branch.size();
//当两次出现unknown时给用户一下候选项 //当两次出现unknown时给用户一下候选项
...@@ -310,12 +332,12 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -310,12 +332,12 @@ public class PlotConstructor extends ElementConstructor{
extraHP = id + "::match-Keyword=" + 1; extraHP = id + "::match-Keyword=" + 1;
for(int i =0;i < branchSize;i++) { for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
nextId = (String)branchNode.get("nextPlotId"); nextId = (String) branchNode.get("nextPlotId");
if(id2j.get(nextId) != null) if (id2j.get(nextId) != null)
nextCondition = (String)id2j.get(nextId).get("conditionName"); nextCondition = (String) id2j.get(nextId).get("conditionName");
else else
nextCondition = " "; nextCondition = " ";
...@@ -335,16 +357,16 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -335,16 +357,16 @@ public class PlotConstructor extends ElementConstructor{
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
try{ try {
keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者";
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if(branchNode.get("nextPlotId") != null){ if (branchNode.get("nextPlotId") != null) {
adjId = (String)branchNode.get("nextPlotId"); adjId = (String) branchNode.get("nextPlotId");
if(visited.get(adjId) == null && id2j.get(adjId) != null) { if (visited.get(adjId) == null && id2j.get(adjId) != null) {
adjNode = id2j.get(adjId); adjNode = id2j.get(adjId);
queue.add(adjNode); queue.add(adjNode);
...@@ -353,7 +375,6 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -353,7 +375,6 @@ public class PlotConstructor extends ElementConstructor{
} }
} }
//unknown时的处理 //unknown时的处理
jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", "");
...@@ -361,6 +382,163 @@ public class PlotConstructor extends ElementConstructor{ ...@@ -361,6 +382,163 @@ public class PlotConstructor extends ElementConstructor{
jConfigList.add(jConfig); jConfigList.add(jConfig);
}
public void BFSGenerate3(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName,
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName;
boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null;
List<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, branchSize;
root.put("nextUnknownText", varInitialMap.get("unknownText"));
root.put("parentId", "null");
Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root);
while (!queue.isEmpty()) {
node = queue.remove();
id = (String) node.get("id");
parentId = (String) node.get("parentId");
location = (String) node.get("place");
conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度";
if (!varInitialMap.containsKey(taskLineName)) {
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, "");
}
//初始化
newBranch = false;
manyParent = false;
adjNodeList = adjList.get(id);
visited.put(id, true);
branch = node.getJSONArray("branch");
branchSize = branch.size();
//当两次出现unknown时给用户一下候选项
keywordOptions = "";
for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i);
nextId = (String) branchNode.get("nextPlotId");
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
nextUnknownText = updateKnowledge.get("unknownText");
if (id2j.get(nextId) != null) {
nextCondition = (String) id2j.get(nextId).get("conditionName");
nextLocation = (String) id2j.get(nextId).get("place");
nTaskLineName = "任务线_" + nextLocation + "进度";
} else {
nextCondition = " ";
nTaskLineName = taskLineName;
}
extraHP = taskLineName + "::match-Keyword=" + id;
extraUK = nTaskLineName + ":" + nextId;
jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
updateKnowledge,
"", extraHP, extraUK,
"match", (String) branchNode.get("reply"), (String) nextCondition, "0"
);
jConfigList.add(jConfig);
jConfig = new JConfig(
"yaobuyao::match-Keyword=" + location,
extraHP,
"match", (String) branchNode.get("reply"), (String) nextCondition, "0"
);
jConfigList.add(jConfig);
try {
keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者";
} catch (Exception e) {
e.printStackTrace();
}
if (branchNode.get("nextPlotId") != null) {
adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null) {
if (id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
adjNode.put("parentId", id);
adjNode.put("nextUnknownText", nextUnknownText);
queue.add(adjNode);
} else {
conditionDescription.put(adjId, "剧情" + adjId + "进度");
varInitialMap.put(adjId, "");
}
}
}
}
//对于unknown的特殊处理
if (curUnknownText.equals("")) {
jConfig = new JConfig(
conditionName + "::match-Keyword=unknown",
extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId,
"match,return-0,post::all(" + CHITCHAT_URL + ")",
" ",
" ",
""
);
jConfigList.add(jConfig);
}
/*
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
jConfig = new JConfig(
conditionName + "::match-Keyword=unknown",
extraHP + ",unknown_counter::number-SmallOrEqual=0",
"match",
"{unknownReply-2}",
" ",
"unknown_counter:+1"
);
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
jConfig = new JConfig(
conditionName + "::match-Keyword=unknown",
extraHP + ",unknown_counter::number-BiggerOrEqual=1",
"match",
"你可以说" + keywordOptions,
" ",
"unknown_counter:+1"
);
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
*/
}
//unknown时的处理
jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", "");
jConfig.setNextStepStatus("return-0");
jConfigList.add(jConfig);
} }
......
### 设置###
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 { ...@@ -11,24 +11,25 @@ public class ChatCacheController {
/** /**
* 通过chat_key获得后台保存的历史信息点 * 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点) * chatCache:存储了chatKye相对应的对话记录(历史信息点)
*
* @return 历史信息点,对话过程中引擎提取的用户信息 * @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, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = 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>>(); chatCache = new HashMap<String, Map<String, String>>();
context.setAttribute("chatCache", chatCache); context.setAttribute("chatCache", chatCache);
} else{ } else {
chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
} }
String chatkey; String chatkey;
try{ try {
historyInfoPoint = chatCache.get(chatKey); historyInfoPoint = chatCache.get(chatKey);
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName); //historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
}catch(Exception e){ } catch (Exception e) {
//可整合 //可整合
historyInfoPoint = null; historyInfoPoint = null;
...@@ -42,10 +43,10 @@ public class ChatCacheController { ...@@ -42,10 +43,10 @@ public class ChatCacheController {
/** /**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/ */
public static synchronized void updateChatCache4Delete(ServletContext context){ public static synchronized void updateChatCache4Delete(ServletContext context) {
String chatKey; String chatKey;
long lastChatTime,now; long lastChatTime, now;
Map<String,String> history = new HashMap<String,String>(); Map<String, String> history = new HashMap<String, String>();
Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
...@@ -65,15 +66,15 @@ public class ChatCacheController { ...@@ -65,15 +66,15 @@ public class ChatCacheController {
/** /**
* 根据chatKey更新chatCache的数据,并修改最后更新时间 * 根据chatKey更新chatCache的数据,并修改最后更新时间
*/ */
public static synchronized void updateChatCache4Insert(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,ServletContext context){ public static synchronized void updateChatCache4Insert(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis())); historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String,Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint); keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint);
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 userName, HashMap<String, String> infoPoints) throws IOException {
String fileDir = System.getProperty("user.dir")+"/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
String key; String key;
boolean saveFlag = true; boolean saveFlag = true;
try { try {
...@@ -91,25 +92,25 @@ public class ChatCacheController { ...@@ -91,25 +92,25 @@ public class ChatCacheController {
} }
fw.close(); fw.close();
}catch (Exception e){ } catch (Exception e) {
saveFlag = false; saveFlag = false;
} }
return saveFlag; return saveFlag;
} }
public static boolean loadChatCache(String userName, ServletContext context){ public static boolean loadChatCache(String userName, ServletContext context) {
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"); File file = new File(fileDir + "/" + userName + ".txt");
if(!file.exists()) { if (!file.exists()) {
return false; return false;
}else { } else {
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){ while ((line = br.readLine()) != null) {
pair = line.trim().split("-----"); pair = line.trim().split("-----");
infoPoints.put(pair[0], pair[1]); infoPoints.put(pair[0], pair[1]);
} }
......
...@@ -17,13 +17,12 @@ public class ConditionTableController { ...@@ -17,13 +17,12 @@ public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId); int id = Integer.parseInt(configId);
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList //data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(","); String conditionNameList[] = data.split(",");
String conditionName = ""; String conditionName = "";
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context); userInfoController.userConfigInit(userName, context);
} }
UserInfo userInfo = (UserInfo) context.getAttribute(userName); UserInfo userInfo = (UserInfo) context.getAttribute(userName);
...@@ -34,15 +33,10 @@ public class ConditionTableController { ...@@ -34,15 +33,10 @@ public class ConditionTableController {
try { try {
Condition oldCondition = userInfo.id2condition.get(id); Condition oldCondition = userInfo.id2condition.get(id);
conditionName = oldCondition.indexName; conditionName = oldCondition.indexName;
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
//-------------------
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(id));
//String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) { if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName); List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
...@@ -57,7 +51,7 @@ public class ConditionTableController { ...@@ -57,7 +51,7 @@ public class ConditionTableController {
userInfo.id2config.remove(id); userInfo.id2config.remove(id);
userInfo.id2condition.remove(id); userInfo.id2condition.remove(id);
} else{ } else {
System.out.println("未找到要删除的configId"); System.out.println("未找到要删除的configId");
} }
...@@ -66,23 +60,17 @@ public class ConditionTableController { ...@@ -66,23 +60,17 @@ public class ConditionTableController {
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException { public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String conditionName = ""; String conditionName = "";
for(int configId:idGroup) { for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) { if (userInfo.id2config.containsKey(configId)) {
try { try {
Condition oldCondition = userInfo.id2condition.get(configId); Condition oldCondition = userInfo.id2condition.get(configId);
conditionName = oldCondition.indexName; conditionName = oldCondition.indexName;
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId));
//String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) { if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName); List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
...@@ -107,10 +95,8 @@ public class ConditionTableController { ...@@ -107,10 +95,8 @@ public class ConditionTableController {
} }
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList //data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---"); String dataPair[] = data.split("---");
String configLine = dataPair[0]; String configLine = dataPair[0];
...@@ -120,12 +106,12 @@ public class ConditionTableController { ...@@ -120,12 +106,12 @@ public class ConditionTableController {
condition = userInfoController.buildCondition(condition, configLine); condition = userInfoController.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context); userInfoController.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); 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>(); List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(condition.indexName, conditionList); userinfo.conditionTable.put(condition.indexName, conditionList);
} }
...@@ -139,41 +125,37 @@ public class ConditionTableController { ...@@ -139,41 +125,37 @@ public class ConditionTableController {
public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList //data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---", -1); String dataPair[] = data.split("---", -1);
String name = dataPair[0],value = dataPair[1]; String name = dataPair[0], value = dataPair[1];
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context); userInfoController.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.put(name, value); userinfo.varInitialMap.put(name, value);
return true; return true;
} }
public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { 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 //data=configLine+"---"+conditionNameList
String name = data; String name = data;
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context); userInfoController.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.remove(name); userinfo.varInitialMap.remove(name);
return true; return true;
} }
...@@ -183,13 +165,13 @@ public class ConditionTableController { ...@@ -183,13 +165,13 @@ public class ConditionTableController {
UserInfoController userInfoController = new UserInfoController(); UserInfoController userInfoController = new UserInfoController();
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context); userInfoController.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|"); String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]); userinfo.extraInfo.put(extraElements[1], extraElements[2]);
return true; return true;
} }
...@@ -199,15 +181,15 @@ public class ConditionTableController { ...@@ -199,15 +181,15 @@ public class ConditionTableController {
System.out.println("p"); System.out.println("p");
System.out.println(userName); 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"; String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path); 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"; String returnMessage = "success";
if(!dir.exists()) if (!dir.exists())
dir.mkdir(); dir.mkdir();
if(!file.exists()){ if (!file.exists()) {
file.createNewFile(); file.createNewFile();
} }
...@@ -217,7 +199,7 @@ public class ConditionTableController { ...@@ -217,7 +199,7 @@ public class ConditionTableController {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator(); Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) { while (keyIter.hasNext()) {
String info = keyIter.next(); 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"); bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
} }
...@@ -233,10 +215,10 @@ public class ConditionTableController { ...@@ -233,10 +215,10 @@ public class ConditionTableController {
bw.write(userinfo.id2config.get(id) + "\n"); bw.write(userinfo.id2config.get(id) + "\n");
} }
bw.write("\n"); bw.write("\n");
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
returnMessage = "config file write error"; returnMessage = "config file write error";
}finally { } finally {
bw.close(); bw.close();
fw.close(); fw.close();
} }
......
...@@ -24,24 +24,26 @@ public class MyFunc { ...@@ -24,24 +24,26 @@ public class MyFunc {
jobj.put("process", ans.getNext()); jobj.put("process", ans.getNext());
return jobj.toString(); return jobj.toString();
} }
public static String toJson(String returnStr){
public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
jobj.put("returnString",returnStr); jobj.put("returnString", returnStr);
return jobj.toString(); return jobj.toString();
} }
/** /**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据 * 当请求中的数据是json格式时,该函数用于提取request中的json数据
*
* @param request * @param request
* @return json字符串 * @return json字符串
*/ */
public static String readJSONString(HttpServletRequest request){ public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer(); StringBuffer json = new StringBuffer();
String line = null; String line = null;
try{ try {
BufferedReader reader = request.getReader(); BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){ while ((line = reader.readLine()) != null) {
json.append(line); json.append(line);
} }
} catch (IOException e) { } catch (IOException e) {
...@@ -54,10 +56,10 @@ public class MyFunc { ...@@ -54,10 +56,10 @@ public class MyFunc {
/** /**
* 通过get方法传递参数时需要对参数的编码进行转换 * 通过get方法传递参数时需要对参数的编码进行转换
*/ */
public static String convert2Utf8(String s){ public static String convert2Utf8(String s) {
if(s==null)return null; if (s == null) return null;
try { try {
s=new String(s.getBytes("iso-8859-1"),"utf-8"); s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
...@@ -71,7 +73,7 @@ public class MyFunc { ...@@ -71,7 +73,7 @@ public class MyFunc {
System.out.println(keyword); System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"}; String timeSeries[] = {"时", "分", "秒"};
for(String f : timeSeries){ for (String f : timeSeries) {
if (!keyword.contains(f)) if (!keyword.contains(f))
keyword += "0" + f; keyword += "0" + f;
} }
...@@ -81,6 +83,7 @@ public class MyFunc { ...@@ -81,6 +83,7 @@ public class MyFunc {
return time; return time;
} }
public static String transferToStandardTime(long time) throws ParseException { public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
...@@ -91,6 +94,4 @@ public class MyFunc { ...@@ -91,6 +94,4 @@ public class MyFunc {
} }
} }
package processing;
import entity.Solution;
import entity.Condition;
import entity.UserInfo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletContext;
import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuestionMatcher {
static Map<Integer, Condition> activatedMap = new HashMap<Integer, Condition>();
static String POST_DATA_ERROR = "post数据有误";
static String POST_ERROR = "数据post时出错了";
static String API_ERROR = "api处理过程中出错了";
static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
/*
public void updateDB(QuestionKeyWord qkw) throws SQLException {
SqlHelper helper = new SqlHelper();
String result = helper.queryActionByKey(qkw.getChatKey());
if(result != "empty")
//待添加
//qkw.setActionName(result+"+"+qkw.getActionName());
helper.updateAction(qkw);
else
helper.insertAction(qkw);
helper.destroy();
}
*/
public boolean infoPointPreprocessing(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo) {
String return_str = "", k;
boolean debugFlag = false;
HashSet<String> skipSet = new HashSet<String>() {
{
add("chat_key");
add("action_name");
add("bot_name");
add("emptySet");
add("query_text");
}
};
//输出所有actionName的值
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
//
System.out.print(k + ": ");
if (k.equals("debug_mode"))
debugFlag = true;
String values[] = curInfoPoint.get(k);
for (String v : values) {
System.out.print(v + " ");
}
System.out.println();
if (values[0].equals(":")) {
values[0] = "";
curInfoPoint.put(k, values);
}
}
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator();
boolean unknown_flag = true;
while (iit.hasNext()) {
k = iit.next();
String values[] = curInfoPoint.get(k);
if (skipSet.contains(k))
continue;
if (values != null && !values[0].equals("")) {
unknown_flag = false;
break;
}
}
String currentAction = "";
if (historyInfoPoint.containsKey("currentAction"))
currentAction = historyInfoPoint.get("currentAction");
else if (userinfo.extraInfo.containsKey("activeAction")) {
currentAction = userinfo.extraInfo.get("activeAction");
historyInfoPoint.put("currentAction", currentAction);
} else
currentAction = " ";
curInfoPoint.put("emptySet", new String[]{" ",});
if (historyInfoPoint.get("activeList") == null) {
historyInfoPoint.put("activeList", currentAction);
}
if (unknown_flag && !currentAction.equals("")) {
String i[] = {"unknown",};
curInfoPoint.put(currentAction, i);
}
return debugFlag;
}
/**
* 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch
*
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @param conditionTable 满足什么条件,就回答什么,下一步跳什么
* @return bestMatch 状态表中满足条件最多的一条
*/
public Condition getBestMatch(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, HashMap<String, List<Condition>> conditionTable, ServletContext context) throws IOException {
Integer configId = 0;
List<Condition> conditionList = null;
Condition bestMatch = new Condition(-1), iterCon;
Iterator<String> it = curInfoPoint.keySet().iterator();
Queue<Condition> activatedQueue = new LinkedList<Condition>();
Queue<Condition> activatedCondition = new LinkedList<Condition>();
while (it.hasNext()) {
String conditionName = it.next();
String[] keywords = curInfoPoint.get(conditionName);
String keyword = null;
if (keywords != null && !keywords[0].equals(""))
keyword = keywords[0];
if (keyword != null && conditionTable.get(conditionName) != null) {
conditionList = conditionTable.get(conditionName);
for (Condition condition : conditionList) {
if (condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) {
if (condition.featureMap.get("instantPost") != null) {
}
//Post后还是可以激活
if (condition.featureMap.get("activate") != null) {
bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
} else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority))
bestMatch = condition;
}
}
}
}
bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context);
return bestMatch;
}
public Condition activatedQueueMatching(Condition bestMatch, Queue<Condition> activatedQueue, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
Condition condition;
//待激活配置条目被激活后的匹配
while (!activatedQueue.isEmpty()) {
condition = activatedQueue.remove();
activatedMap.remove(condition.id);
if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) {
if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) {
bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) {
bestMatch = condition;
}
}
}
return bestMatch;
}
/**
* 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。
* currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件
*
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @param condition 配置文件(状态表)的一行
* @return 满足条件就为True, 不满足就为False
*/
public boolean conditionSatisfy(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, Condition condition) {
boolean flag = true;
String actionName, keywords[], keyword, comparePair[], cmpType, premiseStr;
HashSet<String> keywordSet = null;
if (condition.featureMap.containsKey("match")) {
Iterator<String> it = condition.currentPremise.keySet().iterator();
while (flag && it.hasNext()) {
premiseStr = it.next();
comparePair = premiseStr.split("::");
actionName = comparePair[0];
keywords = curInfoPoint.get(actionName);
if (keywords == null) {
flag = false;
break;
}
keyword = keywords[0];
if (comparePair.length == 1)
cmpType = "match";
else
cmpType = comparePair[1];
keywordSet = condition.currentPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false;
}
it = condition.historyPremise.keySet().iterator();
while (flag && it.hasNext()) {
premiseStr = it.next();
comparePair = premiseStr.split("::");
actionName = comparePair[0];
keyword = historyInfoPoint.get(actionName);
if (keyword == null) {
flag = false;
break;
}
if (comparePair.length == 1)
cmpType = "match";
else
cmpType = comparePair[1];
keywordSet = condition.historyPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false;
}
}
return flag;
}
/**
* 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet)
*
* @param keyword
* @param cmpType 比较类型
* @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件
* @return 返回匹配或者不匹配
*/
public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet) {
boolean flag = true;
String operator = "";
try {
String splitPair[] = cmpType.split("-");
if (splitPair.length > 1) {
operator = splitPair[1];
cmpType = splitPair[0];
}
if (cmpType.equals("match")) {
if (!keywordSet.contains(keyword)) {
flag = false;
}
if (flag == false && keyword.contains(":")) {
String ks[] = keyword.split(":");
for (String k : ks) {
if (keywordSet.contains(k))
flag = true;
}
}
} else if (cmpType.equals("number") && !keyword.equals("")) {
int candidateA = 0;
int candidateB = 0;
if (keyword.contains(":")) {
String ks[] = keyword.split(":");
for (String k : ks) {
if(StringUtils.isNumeric(k))
keyword = k;
}
}
if(!StringUtils.isNumeric(keyword)){
return false;
}
candidateA = Integer.parseInt(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
if (operator.equals("Bigger"))
flag = candidateA > candidateB;
else if (operator.equals("BiggerOrEqual"))
flag = candidateA >= candidateB;
else if (operator.equals("Smaller"))
flag = candidateA < candidateB;
else if (operator.equals("SmallerOrEqual"))
flag = candidateA <= candidateB;
} else if (cmpType.equals("time")) {
long candidateA, candidateB = 0;
if (keyword.contains(":")) {
String ks[] = keyword.split(":");
for (String k : ks) {
if(k.startsWith("20") && k.endsWith("日"))
keyword = k;
}
}
candidateA = MyFunc.transferToMillisecond(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = MyFunc.transferToMillisecond(k);
break;
}
}
if (operator.equals("Early"))
flag = candidateA < candidateB;
else if (operator.equals("Later"))
flag = candidateA > candidateB;
}
//--------------------------------------------------------------------
//为兼容旧数据
else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) {
int candidateA = 0;
int candidateB = 0;
candidateA = Integer.parseInt(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
flag = candidateA > candidateB;
} else if (cmpType.equals("numberBiggerOrEqual") && StringUtils.isNumeric(keyword)) {
int candidateA = 0;
int candidateB = 0;
candidateA = Integer.parseInt(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
flag = candidateA >= candidateB;
} else if (cmpType.equals("numberSmaller") && StringUtils.isNumeric(keyword)) {
int candidateA = 0;
int candidateB = 0;
candidateA = Integer.parseInt(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
flag = candidateA < candidateB;
} else if (cmpType.equals("numberSmallerOrEqual") && StringUtils.isNumeric(keyword)) {
int candidateA = 0;
int candidateB = 0;
candidateA = Integer.parseInt(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
flag = candidateA <= candidateB;
} else if (cmpType.equals("timeEarly")) {
long candidateA, candidateB = 0;
candidateA = MyFunc.transferToMillisecond(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = MyFunc.transferToMillisecond(k);
break;
}
}
flag = candidateA < candidateB;
} else if (cmpType.equals("timeLater")) {
long candidateA, candidateB = 0;
candidateA = MyFunc.transferToMillisecond(keyword);
for (String k : keywordSet) {
if (!k.equals("")) {
candidateB = MyFunc.transferToMillisecond(k);
break;
}
}
flag = candidateA > candidateB;
} else if (cmpType.equals("any")) {
if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足
flag = false;
} else {
flag = false;
}
} catch (IndexOutOfBoundsException e) {
System.out.println("配置文件格式有误");
e.printStackTrace();
} catch (Exception e) {
System.out.println("操作符有误");
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。
*
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @return 返回给引擎的数据
*/
public Solution getSolution(Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName, reply, variable;
Solution ans = new Solution(0, "", "");
//如果一条配置文件有多个答案,则随
// 机选择一个答案
int randNum = (int) (Math.random() * ansCondition.answer.length);
ans.setAnswer(ansCondition.answer[randNum]);
//System.out.println(ans.getAnswer());
//post关键字
if (ansCondition.featureMap.containsKey("post")) {
ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint);
//nextNext关键字
} else if (ansCondition.featureMap.containsKey("newNext")) {
ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint);
//上一步
} else if (ansCondition.featureMap.containsKey("return-1")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if (activeList.length == 1)
ans.setNext("nextStep=" + activeList[activeList.length - 1]);
else {
ans.setNext("nextStep=" + activeList[activeList.length - 2]);
}
//停留
} else if (ansCondition.featureMap.containsKey("return-0")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|");
ans.setNext("nextStep=" + activeList[activeList.length - 1]);
//激活
} else if (ansCondition.featureMap.containsKey("activate")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if (activeList.length == 1)
ans.setNext("nextStep=" + activeList[activeList.length - 1]);
else {
ans.setNext("nextStep=" + activeList[activeList.length - 2]);
}
}
//updateKnowledge关键字
if (ansCondition.featureMap.containsKey("updateKnowledge")) {
updateKnowledge(ansCondition, historyInfoPoint);
}
if (ans.getNext().equals("")) {
ans.setNext("nextStep=" + ansCondition.nextStep);
}
try {
/*
it = historyInfoPoint.keySet().iterator();
String keyword1, keyword2;
while (it.hasNext()) {
actionName = it.next();
if(curInfoPoint.get(actionName) != null) {
keyword1 = curInfoPoint.get(actionName)[0];
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里
}
keyword2 = historyInfoPoint.get(actionName);
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2));
}
*/
//用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值
reply = ans.getAnswer();
Matcher m = replacePattern.matcher(reply);
while (m.find()) {
variable = m.group(1).substring(1, m.group(1).length() - 3);
if (m.group(1).endsWith("-1}")) {
if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals(""))
reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]);
} else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals(""))
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
}
}
ans.setAnswer(reply);
} catch (Exception e) {
e.printStackTrace();
}
return ans;
}
public void infoTransfer(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag) {
//将当前信息点更新至历史信息点
Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName, lastReply;
String next = ans.getNext().split("=", 2)[1];
//保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx
historyInfoPoint.put("currentAction", next);
historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next);
if (debugFlag)
lastReply = ans.getAnswer().split(")")[2];
else
lastReply = ans.getAnswer();
historyInfoPoint.put("lastReply", lastReply);
try {
String keyword1, keyword2;
while (it.hasNext()) {
actionName = it.next();
keyword1 = curInfoPoint.get(actionName)[0];
keyword2 = historyInfoPoint.get(actionName);
if (keyword2 == null)
historyInfoPoint.put(actionName, keyword1);
else if (keyword2 != null && !keyword1.equals(""))
historyInfoPoint.put(actionName, keyword1);
}
ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context);
//context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试
*
* @param ans 最终返回的数据
* @param curInfoPoint 当前对话识别到的信息点
* @param historyInfoPoint 在当前对话之前采集到的所有用户信息点
* @param context
*/
public void appendDebugInfo(Solution ans, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
Iterator<String> it = null;
String key, values[], value;
HashSet<String> skipSet = new HashSet<String>() {
{
add("activeList");
add("currentAction");
add("lastUpdateTime");
add("bot_name");
add("action_name");
add("chat_key");
add("lastReply");
}
};
it = curInfoPoint.keySet().iterator();
String debugInfo = "";
debugInfo += "<font color=\"green\">(识别:";
while (it.hasNext()) {
key = it.next();
values = curInfoPoint.get(key);
if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key))
debugInfo += (" " + key + ":\'" + values[0] + "\' ");
}
debugInfo += ")(已知:";
it = historyInfoPoint.keySet().iterator();
while (it.hasNext()) {
key = it.next();
value = historyInfoPoint.get(key);
if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key))
debugInfo += (" " + key + ":\'" + value + "\' ");
}
ans.setAnswer(debugInfo + ")</font>" + ans.getAnswer());
}
/**
* 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换)
*
* @param ans 返回给用户的数据
* @param ansCondition 满足条件最多的condition(配置文件的某一行)
*/
public Solution postToServer(Solution ans, Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) throws IOException {
String url = null, elem[], subElem[], key, postType = "all";
Map<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> k_iter = null;
elem = ansCondition.featureMap.get("post").split("\\|");
url = elem[0];
postType = elem[1];
//提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器
if (postType.equals("all")) {
k_iter = curInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (curInfoPoint.get(key)[0] != "")
//infoMap.put(key + "_cur", curInfoPoint.get(key)[0]);
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)[0]));
}
k_iter = historyInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (historyInfoPoint.get(key) != "")
//infoMap.put(key + "_his", historyInfoPoint.get(key));
if (key.equals("game_step"))
pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key)));
else
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
}
//提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值
} else if (postType.equals("term")) {
k_iter = ansCondition.currentPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key)[0] != "")
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)[0]));
}
k_iter = ansCondition.historyPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (historyInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
//infoMap.put(key + "_his", historyInfoPoint.get(key));
}
}
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
try {
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
JSONObject jobj = JSONObject.fromString(respContent);
Iterator<String> kit = jobj.keys();
while (kit.hasNext()) {
keyName = kit.next();
if (keyName.equals("process")) {
ans.setNext((String) jobj.get(keyName));
historyInfoPoint.put("process", (String) jobj.get(keyName));
} else if (keyName.equals("solution")) {
ans.setAnswer((String) jobj.get(keyName));
} else {
ans.setNext("nextStep=" + ansCondition.nextStep);
historyInfoPoint.put(keyName, jobj.getString(keyName));
}
}
} else {
ans.setAnswer(API_ERROR);
}
} catch (Exception e) {
e.printStackTrace();
ans.setAnswer(POST_ERROR + url);
return ans;
}
return ans;
}
public Solution findNewNext(Solution ans, Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) {
String nextOptions[] = ansCondition.nextStep.split(",");
String conditionName, premises[], cpPair[];
boolean flag = true;
String activeList = historyInfoPoint.get("activeList");
for (String option : nextOptions) {
flag = true;
cpPair = option.split(":");
conditionName = cpPair[0];
if (cpPair.length == 1) {
ans.setNext("nextStep=" + conditionName);
break;
}
premises = cpPair[1].split("-");
for (String premise : premises) {
if (premise.equals("known")) {
//如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别
boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName)[0].equals("") && !curInfoPoint.get(conditionName)[0].equals("unknown");
boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown");
//只有前两者都为假时,conditionExist才为真
boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint);
if (conditionExist)
flag = false;
}
if (premise.equals("active")) {
boolean isActive = activeList.contains(conditionName);
if (isActive)
flag = false;
}
}
if (flag) {
ans.setNext("nextStep=" + conditionName);
break;
}
}
return ans;
}
public void updateKnowledge(Condition condition, Map<String, String> historyInfoPoint) throws ParseException {
String keyword, variableName, updateValue;
Iterator<String> iit = condition.updateKnowledge.keySet().iterator();
while (iit.hasNext()) {
variableName = iit.next();
updateValue = condition.updateKnowledge.get(variableName);
keyword = historyInfoPoint.get(variableName);
try {
//做数字加法
if (updateValue.startsWith("+")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time + (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = String.valueOf(number + offset);
}
//做数字减法
} else if (updateValue.startsWith("-")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time - (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = String.valueOf(number - offset);
}
//做字符串累加
} else if (updateValue.startsWith("str+")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword + updateValue.substring(4);
//做字符串删除
} else if (updateValue.startsWith("str-")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword.replace(updateValue.substring(4), "");
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
historyInfoPoint.put(variableName, updateValue);
}
}
public void activateCondition(Queue<Condition> activatedQueue, String userName, int basePriority, String activateList, ServletContext context) {
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String configStr = "";
Integer configId;
Condition newCondition, originCondition;
for (String configIdStr : activateList.split(",")) {
if (!StringUtils.isNumeric(configIdStr))
continue;
configId = Integer.parseInt(configIdStr);
configStr = userinfo.id2config.get(configId);
if (configStr != null) {
originCondition = userinfo.id2condition.get(configId);
newCondition = new Condition(originCondition, basePriority);
//condition = QuestionMatcher.buildCondition(condition, configStr);
if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) {
activatedMap.get(configId).activePriority = newCondition.activePriority;
} else if (!activatedMap.containsKey(configId)) {
activatedMap.put(configId, newCondition);
activatedQueue.add(newCondition);
}
}
}
}
public Solution postActivate(Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Queue<Condition> activatedQueue = new LinkedList<Condition>();
Solution bestMatch = null;
activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context);
ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context);
bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
return bestMatch;
}
}
...@@ -13,7 +13,7 @@ import java.util.List; ...@@ -13,7 +13,7 @@ import java.util.List;
public class UserInfoController { 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文件有误"; static String FILE_ERROR = ".txt文件有误";
...@@ -25,9 +25,9 @@ public class UserInfoController { ...@@ -25,9 +25,9 @@ public class UserInfoController {
String line; String line;
File dir = new File(CONFIG_DIR); File dir = new File(CONFIG_DIR);
if(!dir.exists()) if (!dir.exists())
dir.mkdir(); dir.mkdir();
for(File configFile: dir.listFiles()) { for (File configFile : dir.listFiles()) {
FileReader reader = new FileReader(configFile); FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
...@@ -36,8 +36,8 @@ public class UserInfoController { ...@@ -36,8 +36,8 @@ public class UserInfoController {
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName, userinfo);
}catch(Exception e){ } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -50,27 +50,27 @@ public class UserInfoController { ...@@ -50,27 +50,27 @@ public class UserInfoController {
public static void userConfigInit(String userName, ServletContext context) throws IOException { public static void userConfigInit(String userName, ServletContext context) throws IOException {
String line; String line;
File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); File userFile = new File(CONFIG_DIR + "/" + userName + ".txt");
if(!userFile.exists()){ if (!userFile.exists()) {
BufferedReader br = new BufferedReader(new StringReader("")); BufferedReader br = new BufferedReader(new StringReader(""));
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(userName);
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName, userinfo);
}catch(Exception e){ } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
}else { } else {
FileReader reader = new FileReader(userFile); FileReader reader = new FileReader(userFile);
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(userName);
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName, userinfo);
}catch(Exception e){ } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.userName + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -81,8 +81,8 @@ public class UserInfoController { ...@@ -81,8 +81,8 @@ public class UserInfoController {
} }
public static Condition buildCondition(Condition condition, String line){ public static Condition buildCondition(Condition condition, String line) {
String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName; String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName;
try { try {
...@@ -122,14 +122,14 @@ public class UserInfoController { ...@@ -122,14 +122,14 @@ public class UserInfoController {
int length = knowledge.length; int length = knowledge.length;
condition.featureMap.put("updateKnowledge", ""); condition.featureMap.put("updateKnowledge", "");
for (int i = 1; i < length; i++) { for (int i = 1; i < length; i++) {
if(knowledge[i].equals("") || knowledge[i].equals(" ")) if (knowledge[i].equals("") || knowledge[i].equals(" "))
continue; continue;
pair = knowledge[i].split(":"); pair = knowledge[i].split(":", 2);
condition.updateKnowledge.put(pair[0], pair[1]); condition.updateKnowledge.put(pair[0], pair[1]);
} }
} else if (feat.startsWith("post")) { } else if (feat.startsWith("post")) {
pair = feature.split("\\(", 2); pair = feat.split("\\(", 2);
url = pair[1]; url = pair[1];
url = url.substring(0, url.length() - 1); url = url.substring(0, url.length() - 1);
pair = pair[0].split("::"); pair = pair[0].split("::");
...@@ -140,10 +140,10 @@ public class UserInfoController { ...@@ -140,10 +140,10 @@ public class UserInfoController {
} }
insertPremise(condition.currentPremise,cur_premises); insertPremise(condition.currentPremise, cur_premises);
insertPremise(condition.historyPremise,history_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; condition.activePriority = condition.priority;
/* /*
for(String premise:cur_premises){ for(String premise:cur_premises){
...@@ -152,12 +152,13 @@ public class UserInfoController { ...@@ -152,12 +152,13 @@ public class UserInfoController {
} }
*/ */
firstCnditionName = cur_premises[0]; firstCnditionName = cur_premises[0];
if(firstCnditionName.equals(" ")) if (firstCnditionName.equals(" "))
condition.indexName = "emptySet"; condition.indexName = "emptySet";
else else
condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; condition.indexName = firstCnditionName.split("=")[0].split("::")[0];
}catch (IndexOutOfBoundsException e){ } catch (IndexOutOfBoundsException e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(line);
System.out.println("文本格式有误"); System.out.println("文本格式有误");
} }
return condition; return condition;
...@@ -165,24 +166,25 @@ public class UserInfoController { ...@@ -165,24 +166,25 @@ public class UserInfoController {
/** /**
*
* @param br * @param br
* @param userinfo * @param userinfo
* @param overRide 覆盖之前的状态表 * @param overRide 覆盖之前的状态表
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) 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; HashMap<String, List<Condition>> conditionTable = null;
//是否覆盖原有的数据 //是否覆盖原有的数据
if(overRide) { if (overRide) {
conditionTable = new HashMap<String, List<Condition>>(); conditionTable = new HashMap<String, List<Condition>>();
userinfo.id2condition.clear(); userinfo.id2condition.clear();
userinfo.id2config.clear(); userinfo.id2config.clear();
userinfo.configStr = ""; userinfo.configStr = "";
}else { userinfo.varInitialMap.clear();
} else {
conditionTable = userinfo.conditionTable; conditionTable = userinfo.conditionTable;
} }
...@@ -215,10 +217,10 @@ public class UserInfoController { ...@@ -215,10 +217,10 @@ public class UserInfoController {
} }
} }
} catch(ArrayIndexOutOfBoundsException e){ } catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数据格式有误"); System.out.println("数据格式有误");
e.printStackTrace(); e.printStackTrace();
} catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
...@@ -230,22 +232,23 @@ public class UserInfoController { ...@@ -230,22 +232,23 @@ public class UserInfoController {
/** /**
* 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) * 通过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[]; String pair[];
HashSet<String> keyWordSet = null; HashSet<String> keyWordSet = null;
for(String premise:premisesString) { for (String premise : premisesString) {
// System.out.println(premise); // System.out.println(premise);
if (premise.equals("") || premise.equals(" ")) if (premise.equals("") || premise.equals(" "))
continue; continue;
pair = premise.split("=", 2); pair = premise.split("=", 2);
keyWordSet = new HashSet<String>(); keyWordSet = new HashSet<String>();
for (String keyword : pair[1].split("\\+")) for (String keyword : pair[1].split("\\+"))
//为了处理条件不满足(为空)时的特殊情况, //为了处理条件不满足(为空)时的特殊情况,
if(keyword.equals("null")) keyWordSet.add(""); if (keyword.equals("null")) keyWordSet.add("");
else if(!keyword.equals("")) keyWordSet.add(keyword); else if (!keyword.equals("")) keyWordSet.add(keyword);
premiseMap.put(pair[0],keyWordSet); premiseMap.put(pair[0], keyWordSet);
} }
} }
...@@ -268,13 +271,13 @@ public class UserInfoController { ...@@ -268,13 +271,13 @@ public class UserInfoController {
*/ */
String userName = bot_name; String userName = bot_name;
UserInfo userinfo = null; UserInfo userinfo = null;
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userConfigInit(userName, context); userConfigInit(userName, context);
} }
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
userinfo = new UserInfo(userName); userinfo = new UserInfo(userName);
userinfo.conditionTable = new HashMap<String, List<Condition>>(); userinfo.conditionTable = new HashMap<String, List<Condition>>();
}else { } else {
userinfo = (UserInfo) context.getAttribute(userName); userinfo = (UserInfo) context.getAttribute(userName);
} }
//helper.destroy(); //helper.destroy();
......
package servlet; package servlet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import gameDesign.*; import gameDesign.*;
import processing.MyFunc; import processing.MyFunc;
import processing.ProcessQuestion;
import processing.ConditionTableController; import processing.ConditionTableController;
import processing.UserInfoController; import processing.UserInfoController;
...@@ -26,7 +23,7 @@ import java.util.ArrayList; ...@@ -26,7 +23,7 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"}) @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer botId, projectId, dataId; Integer botId, projectId, dataId;
...@@ -47,23 +44,22 @@ public class GameDesignServlet extends HttpServlet { ...@@ -47,23 +44,22 @@ public class GameDesignServlet extends HttpServlet {
String jsonStr = MyFunc.readJSONString(request); String jsonStr = MyFunc.readJSONString(request);
if(jsonStr != null && !jsonStr.equals("")){ if (jsonStr != null && !jsonStr.equals("")) {
JSONObject jsonObject = JSONObject.parseObject(jsonStr); JSONObject jsonObject = JSONObject.parseObject(jsonStr);
dataId = (Integer)jsonObject.get("id"); dataId = (Integer) jsonObject.get("id");
JSONObject gameElements = helper.queryGameElementsByBotId(dataId); JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
botId = (Integer)gameElements.get("botId"); botId = (Integer) gameElements.get("botId");
userName = (String)gameElements.get("userName"); userName = (String) gameElements.get("userName");
//假设重新重新建用户信息 //假设重新重新建用户信息
if(context.getAttribute(userName) == null){ if (context.getAttribute(userName) == null) {
UserInfoController.userConfigInit(userName, context); UserInfoController.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
//UserInfo userinfo = new UserInfo(userName); //UserInfo userinfo = new UserInfo(userName);
//清空之前生成的配置条目 //清空之前生成的配置条目
...@@ -77,7 +73,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -77,7 +73,7 @@ public class GameDesignServlet extends HttpServlet {
Iterator<String> moduleIter = gameElements.keySet().iterator(); Iterator<String> moduleIter = gameElements.keySet().iterator();
StringBuffer mergedConfigText = new StringBuffer(); StringBuffer mergedConfigText = new StringBuffer();
while(moduleIter.hasNext()) { while (moduleIter.hasNext()) {
moduleName = moduleIter.next(); moduleName = moduleIter.next();
switch (moduleName) { switch (moduleName) {
case "map": case "map":
...@@ -103,10 +99,10 @@ public class GameDesignServlet extends HttpServlet { ...@@ -103,10 +99,10 @@ public class GameDesignServlet extends HttpServlet {
constructor.construct(gameElements, userinfo); constructor.construct(gameElements, userinfo);
//先清空再插入 //先清空再插入
idList.clear(); idList.clear();
if(moduleName.equals("map") || moduleName.equals("plots")) { helper.batchInsertVariableByBotId(botId, constructor);
helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList); helper.batchInsertConfigByBotId(botId, constructor, idList);
constructor.generateConfigText(idList); constructor.generateConfigText(idList);
}
mergedConfigText.append(constructor.getConfigText()); mergedConfigText.append(constructor.getConfigText());
...@@ -132,8 +128,8 @@ public class GameDesignServlet extends HttpServlet { ...@@ -132,8 +128,8 @@ public class GameDesignServlet extends HttpServlet {
} }
public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { public boolean clearOldConfig(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException {
boolean deleteFlag = helper.deleteConfigByBotId(botId); boolean deleteConfigFlag = helper.deleteConfigByBotId(botId);
boolean deleteVariableFlag = helper.deleteVariableByBotId(botId);
return deleteFlag; return deleteConfigFlag && deleteVariableFlag;
} }
} }
...@@ -5,7 +5,7 @@ import entity.Condition; ...@@ -5,7 +5,7 @@ import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import processing.ChatCacheController; import processing.ChatCacheController;
import processing.MyFunc; import processing.MyFunc;
import processing.ProcessQuestion; import processing.QuestionMatcher;
import processing.UserInfoController; import processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -21,30 +21,29 @@ import java.text.ParseException; ...@@ -21,30 +21,29 @@ import java.text.ParseException;
import java.util.*; import java.util.*;
@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"}) @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/"})
public class GetAnswerServlet extends HttpServlet { public class GetAnswerServlet extends HttpServlet {
/** /**
* GetAnswerServlet就是处理post请求并返回答案的入口 * GetAnswerServlet就是处理post请求并返回答案的入口
*/ */
String NAME_MISSING_ERROR = "没找到bot名?"; String NAME_MISSING_ERROR = "没找到bot名?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); 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; Map<String, String> historyInfoPoint = null;
Solution bestMatch = null; Solution bestMatch = null;
Condition ansCondition = null; Condition ansCondition = null;
String ansJ,return_str="",state = ""; String ansJ, return_str = "", state = "";
String chatKey = curInfoPoint.get("chat_key")[0]; String chatKey = curInfoPoint.get("chat_key")[0];
ProcessQuestion process = new ProcessQuestion(); QuestionMatcher matcher = new QuestionMatcher();
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
boolean debugFlag = false; boolean debugFlag = false;
//获得用户历史信息 //获得用户历史信息
historyInfoPoint = ChatCacheController.getChatCache(chatKey,context); historyInfoPoint = ChatCacheController.getChatCache(chatKey, context);
StringBuffer curInfoRecord = new StringBuffer();
StringBuffer hisInfoRecord = new StringBuffer();
UserInfo userinfo = null; UserInfo userinfo = null;
...@@ -52,46 +51,46 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -52,46 +51,46 @@ public class GetAnswerServlet extends HttpServlet {
try { try {
//userinfo = process.userInfoQuery(chatKey,context); //userinfo = process.userInfoQuery(chatKey,context);
//从servlet根据用户名查询用户信息 //从servlet根据用户名查询用户信息
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"),context); userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context);
} catch (SQLException e) { } catch (SQLException e) {
state = NAME_MISSING_ERROR; state = NAME_MISSING_ERROR;
e.printStackTrace(); e.printStackTrace();
} }
//如果historyInfoPoint不存在,就新建一个 //如果historyInfoPoint不存在,就新建一个
if(historyInfoPoint == null) { if (historyInfoPoint == null) {
String k; String k;
historyInfoPoint = new HashMap<String,String>(); historyInfoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator(); Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()){ while (iit.hasNext()) {
k = iit.next(); k = iit.next();
historyInfoPoint.put(k,""); historyInfoPoint.put(k, "");
} }
//变量初始化 //变量初始化
iit = userinfo.varInitialMap.keySet().iterator(); iit = userinfo.varInitialMap.keySet().iterator();
while(iit.hasNext()){ while (iit.hasNext()) {
k = iit.next(); k = iit.next();
historyInfoPoint.put(k, userinfo.varInitialMap.get(k)); historyInfoPoint.put(k, userinfo.varInitialMap.get(k));
} }
} }
//信息点预处理 //信息点预处理
debugFlag = process.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, curInfoRecord); debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context); //process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试 //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) if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { 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包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = process.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = matcher.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
} }
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -104,16 +103,16 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -104,16 +103,16 @@ public class GetAnswerServlet extends HttpServlet {
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
} }
//bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); //bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
}else{ } else {
bestMatch = new Solution(0," \n" + return_str + "\n " +state,"nextStep=" + historyInfoPoint.get("currentAction")); bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction"));
} }
if(debugFlag) { if (debugFlag) {
process.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context); matcher.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context);
} }
process.infoTransition(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag);
ansJ = MyFunc.toJson(bestMatch); ansJ = MyFunc.toJson(bestMatch);
......
...@@ -7,24 +7,24 @@ import javax.servlet.http.HttpServletRequest; ...@@ -7,24 +7,24 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
@WebServlet(name = "GetConfigServlet",urlPatterns = {"/getConfig"}) @WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"})
public class GetConfigServlet extends HttpServlet { public class GetConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName"); 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); File file = new File(path);
OutputStream out = response.getOutputStream(); 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); BufferedReader br = new BufferedReader(fr);
String line; String line;
while ((line = br.readLine()) != null){ while ((line = br.readLine()) != null) {
line = line + "\n"; line = line + "\n";
out.write(line.getBytes()); out.write(line.getBytes());
} }
...@@ -32,7 +32,7 @@ public class GetConfigServlet extends HttpServlet { ...@@ -32,7 +32,7 @@ public class GetConfigServlet extends HttpServlet {
fr.close(); fr.close();
br.close(); br.close();
} else{ } else {
out.write("查无此bot".getBytes()); out.write("查无此bot".getBytes());
} }
out.flush(); out.flush();
......
package servlet; package servlet;
import entity.UserInfo; import entity.UserInfo;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.UserInfoController; import processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -17,31 +15,31 @@ import java.io.*; ...@@ -17,31 +15,31 @@ import java.io.*;
/** /**
* 发请求从本地文件夹重新加载某用户的配置文件 * 发请求从本地文件夹重新加载某用户的配置文件
*/ */
@WebServlet(name = "ReloadConfigServlet",urlPatterns = {"/reload","/reload/"}) @WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"})
public class ReloadConfigServlet extends HttpServlet { public class ReloadConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName"); String userName = request.getParameter("userName");
boolean flag = true; boolean flag = true;
UserInfo userinfo = new UserInfo(userName); 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()); System.out.println(configFile.getAbsolutePath());
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
if(!configFile.exists()) { if (!configFile.exists()) {
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("文件不存在: "+userName); out.println("文件不存在: " + userName);
}else{ } else {
FileReader reader = new FileReader(configFile); FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
try { try {
userinfo = UserInfoController.buildUserInfo(br, userinfo, true); userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName, userinfo);
}catch(Exception e){ } catch (Exception e) {
flag = false; flag = false;
System.out.println(userinfo.userName + ".txt 有误"); System.out.println(userinfo.userName + ".txt 有误");
e.printStackTrace(); e.printStackTrace();
...@@ -50,18 +48,17 @@ public class ReloadConfigServlet extends HttpServlet { ...@@ -50,18 +48,17 @@ public class ReloadConfigServlet extends HttpServlet {
reader.close(); reader.close();
br.close(); br.close();
if(!flag) { if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>"); //request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
response.setStatus(111); response.setStatus(111);
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("更新失败配置文件有误:" + userName +".txt\\\n"); out.println("更新失败配置文件有误:" + userName + ".txt\\\n");
} } else {
else{
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("重新加载成功"); out.println("重新加载成功");
out.flush(); out.flush();
...@@ -75,7 +72,6 @@ public class ReloadConfigServlet extends HttpServlet { ...@@ -75,7 +72,6 @@ public class ReloadConfigServlet extends HttpServlet {
} }
} }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
......
...@@ -3,7 +3,6 @@ package servlet; ...@@ -3,7 +3,6 @@ package servlet;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import processing.MyFunc; import processing.MyFunc;
import processing.ProcessQuestion;
import processing.UserInfoController; import processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -21,12 +20,12 @@ import java.util.List; ...@@ -21,12 +20,12 @@ import java.util.List;
/** /**
* 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。 * 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。
*/ */
@WebServlet(name = "UpdateServlet",urlPatterns = {"/update"}) @WebServlet(name = "UpdateServlet", urlPatterns = {"/update"})
public class UpdateServlet extends HttpServlet { public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。 //在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String line,extraElements[]; String line, extraElements[];
ArrayList<String> errorList = new ArrayList<String>(); ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
String userName = request.getParameter("userName"); String userName = request.getParameter("userName");
...@@ -42,35 +41,35 @@ public class UpdateServlet extends HttpServlet { ...@@ -42,35 +41,35 @@ public class UpdateServlet extends HttpServlet {
String errorStr = ""; String errorStr = "";
while((line = br.readLine()) != null){ while ((line = br.readLine()) != null) {
System.out.println(line); System.out.println(line);
if(line.trim().equals("")) if (line.trim().equals(""))
continue; continue;
line = line.replace("\n",""); line = line.replace("\n", "");
//在用户信息中添加额外信息,如设为active的action //在用户信息中添加额外信息,如设为active的action
if(line.indexOf("-extraInfo-") != -1){ if (line.indexOf("-extraInfo-") != -1) {
extraElements = line.split("\\|"); extraElements = line.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]); userinfo.extraInfo.put(extraElements[1], extraElements[2]);
userinfo.configStr += line+"\n"; userinfo.configStr += line + "\n";
continue; continue;
} }
//line = MyFunc.convert2Utf8(line.trim()); //line = MyFunc.convert2Utf8(line.trim());
userinfo.configStr += line+"\n"; userinfo.configStr += line + "\n";
Condition condition = new Condition(); Condition condition = new Condition();
try { try {
condition = UserInfoController.buildCondition(condition,line); condition = UserInfoController.buildCondition(condition, line);
conditionList = userinfo.conditionTable.get(condition.indexName); conditionList = userinfo.conditionTable.get(condition.indexName);
if(conditionList == null) if (conditionList == null)
conditionList = new ArrayList<Condition>(); conditionList = new ArrayList<Condition>();
conditionList.add(condition); conditionList.add(condition);
userinfo.conditionTable.put(condition.indexName,conditionList); userinfo.conditionTable.put(condition.indexName, conditionList);
/* /*
for(String name:condition.indexName){ for(String name:condition.indexName){
userinfo.conditionTable.put() userinfo.conditionTable.put()
} }
*/ */
} catch(Exception e ){ } catch (Exception e) {
System.out.println("配置文件有误!"); System.out.println("配置文件有误!");
flag = false; flag = false;
errorList.add(line); errorList.add(line);
...@@ -80,23 +79,22 @@ public class UpdateServlet extends HttpServlet { ...@@ -80,23 +79,22 @@ public class UpdateServlet extends HttpServlet {
} }
br.close(); br.close();
if(!flag) { if (!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>"); //request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr +"\\\n"); String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n");
out.println("更新失败,以下行有误: "); out.println("更新失败,以下行有误: ");
for(String error:errorList) for (String error : errorList)
out.println("---"+error); out.println("---" + error);
out.flush(); out.flush();
out.close(); out.close();
System.out.println("error"); System.out.println("error");
} } else {
else{
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("更新成功+ “ "); out.println("更新成功+ “ ");
out.flush(); out.flush();
...@@ -104,14 +102,14 @@ public class UpdateServlet extends HttpServlet { ...@@ -104,14 +102,14 @@ public class UpdateServlet extends HttpServlet {
System.out.println("success"); System.out.println("success");
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr); //request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
context.setAttribute(userName,userinfo); context.setAttribute(userName, userinfo);
String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt"; String path = System.getProperty("user.dir") + "/config/" + userinfo.userName + ".txt";
File file = new File(path); 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(); dir.mkdir();
if(!file.exists()){ if (!file.exists()) {
file.createNewFile(); file.createNewFile();
} }
FileWriter fw = new FileWriter(file); FileWriter fw = new FileWriter(file);
......
package servlet; package servlet;
import entity.UserInfo; import entity.UserInfo;
import processing.ProcessQuestion;
import processing.ConditionTableController; import processing.ConditionTableController;
import processing.UserInfoController; import processing.UserInfoController;
...@@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletRequest; ...@@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
@WebServlet(name = "UpdateSingleConfigServlet",urlPatterns = {"/update2"}) @WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"})
public class UpdateSingleConfigServlet extends HttpServlet { public class UpdateSingleConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
...@@ -22,9 +21,9 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -22,9 +21,9 @@ public class UpdateSingleConfigServlet extends HttpServlet {
String processType = request.getParameter("type"); String processType = request.getParameter("type");
String configId = request.getParameter("configId"); String configId = request.getParameter("configId");
String data = request.getParameter("configData"); 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) { switch (processType) {
case "insert_config": case "insert_config":
ConditionTableController.insertConfig(userName, configId, data, context); ConditionTableController.insertConfig(userName, configId, data, context);
...@@ -56,17 +55,17 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -56,17 +55,17 @@ public class UpdateSingleConfigServlet extends HttpServlet {
writeConfig(userName, context); writeConfig(userName, context);
response.setStatus(200); response.setStatus(200);
}else if(processType.equals("batch_update")){ } else if (processType.equals("batch_update")) {
batchUpdate(userName, data, context); batchUpdate(userName, data, context);
writeConfig(userName, context); writeConfig(userName, context);
response.setStatus(200); response.setStatus(200);
}else{ } else {
response.setStatus(111); response.setStatus(111);
} }
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.write("success"); out.write("success");
out.flush(); out.flush();
...@@ -93,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -93,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet {
BufferedReader br = new BufferedReader(new StringReader(data)); BufferedReader br = new BufferedReader(new StringReader(data));
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(userName);
userinfo = UserInfoController.buildUserInfo(br, userinfo, true); userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName, userinfo);
System.out.println("batchupdate"); 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