Commit 3d56c4c5 by hxw

添加根据地点存档、离线语音过滤

parent f4b0c0b4
package com.qiwu.chatbotbackend.db; package com.qiwu.chatbotbackend.db;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.entity.QuestionKeyWord;
import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor;
import com.qiwu.chatbotbackend.processing.MyFunc;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class SqlHelper { public class SqlHelper {
private Connection conn = null; private Connection conn = null;
...@@ -473,6 +474,80 @@ public class SqlHelper { ...@@ -473,6 +474,80 @@ public class SqlHelper {
} }
public Boolean insertArchiveInfo(String archiveName, String userKey, String site){
String sql = "insert into game_archive (archive_id, user_key, site, plot) VALUES (?, ?, ?, '')";
int id = 0;
boolean b = true;
int bNum = 0;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(archiveName));
ps.setString(2, String.valueOf(userKey));
ps.setString(3, String.valueOf(site));
System.out.println(ps.toString());
bNum = ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
return bNum == 1;
}
public ArchiveInfo queryUserLastGameArchive(String userKey){
String sql = "select * from game_archive where user_key = ? order by update_time desc";
String result = "{}";
ArchiveInfo archiveInfo = null;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(userKey));
ResultSet rs = ps.executeQuery();
if (rs.next())
archiveInfo = new ArchiveInfo(rs.getString("archive_id"),rs.getString("user_key"),
rs.getString("site"),rs.getString("update_time"),rs.getString("plot"));
ps.close();
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return archiveInfo;
}
public ArchiveInfo queryUserLastGameArchiveBySite(String userKey, String site){
String sql = "select * from game_archive where user_key = ? and site = ? order by update_time desc";
String result = "{}";
ArchiveInfo archiveInfo = null;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userKey);
ps.setString(2, site);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"),
rs.getString("site"), rs.getString("update_time"), rs.getString("plot"));
}
ps.close();
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return archiveInfo;
}
// public boolean insertCategoryByBotId(int botId, String categoryName) { // public boolean insertCategoryByBotId(int botId, String categoryName) {
// String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; // String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
// int id = 0; // int id = 0;
......
package com.qiwu.chatbotbackend.entity;
public class ArchiveInfo {
String archiveId;
String userKey;
String site;
String updateTime;
String plot;
public String getArchiveId() {
return archiveId;
}
public void setArchiveId(String archiveId) {
this.archiveId = archiveId;
}
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getPlot() {
return plot;
}
public void setPlot(String plot) {
this.plot = plot;
}
public ArchiveInfo(String archiveId, String userKey, String site, String updateTime, String plot) {
this.archiveId = archiveId;
this.userKey = userKey;
this.site = site;
this.updateTime = updateTime;
this.plot = plot;
}
}
package com.qiwu.chatbotbackend.entity; package com.qiwu.chatbotbackend.entity;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import org.springframework.beans.factory.DisposableBean;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutionException;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; public class ChatCache implements DisposableBean {
import com.qiwu.chatbotbackend.processing.ChatCacheController;
import org.springframework.beans.factory.DisposableBean;
import javax.annotation.PreDestroy; // private String chatKey = "不知道";
private String userKey = "";
public class ChatCache implements DisposableBean { private String randKey = "";
private String chatKey = "不知道";
private String botAccount = ""; private String botAccount = "";
private Map<String, String> infoPoint = null; private Map<String, String> infoPoint = null;
...@@ -36,16 +33,24 @@ public class ChatCache implements DisposableBean { ...@@ -36,16 +33,24 @@ public class ChatCache implements DisposableBean {
return reloading; return reloading;
} }
public void setReloading(boolean reloading) { public String getUserKey() {
this.reloading = reloading; return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
} }
public String getChatKey() { public String getRandKey() {
return chatKey; return randKey;
} }
public void setChatKey(String chatKey) { public void setRandKey(String randKey) {
this.chatKey = chatKey; this.randKey = randKey;
}
public void setReloading(boolean reloading) {
this.reloading = reloading;
} }
public Map<String, String> getInfoPoint() { public Map<String, String> getInfoPoint() {
...@@ -64,8 +69,9 @@ public class ChatCache implements DisposableBean { ...@@ -64,8 +69,9 @@ public class ChatCache implements DisposableBean {
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
} }
public ChatCache(String chatKey, GameEnv gameEnv, Map<String, String> infoPoint) { public ChatCache(String userKey, String randKey, GameEnv gameEnv, Map<String, String> infoPoint) {
this.chatKey = chatKey; this.userKey = userKey;
this.randKey = randKey;
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
this.infoPoint = infoPoint; this.infoPoint = infoPoint;
} }
...@@ -73,11 +79,9 @@ public class ChatCache implements DisposableBean { ...@@ -73,11 +79,9 @@ public class ChatCache implements DisposableBean {
@Override @Override
public void destroy() throws IOException { public void destroy() throws IOException {
//System.out.println("销毁:" + chatKey);
//ChatCacheController.saveChatCache(chatKey, this);
} }
public ChatCache(UserInfo userInfo) throws Exception { public ChatCache(UserInfo userInfo, String userKey, String randKey) throws Exception {
try { try {
gameEnv = new GameEnv(userInfo.botAccount); gameEnv = new GameEnv(userInfo.botAccount);
} catch (Exception e) { } catch (Exception e) {
...@@ -94,13 +98,10 @@ public class ChatCache implements DisposableBean { ...@@ -94,13 +98,10 @@ public class ChatCache implements DisposableBean {
infoPoint.put(k, userInfo.varInitialMap.get(k)); infoPoint.put(k, userInfo.varInitialMap.get(k));
} }
infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
this.randKey = randKey;
this.userKey = userKey;
} }
@PreDestroy
public void dostory() {
System.out.println("I'm destory method using @PreDestroy.....");
}
} }
package com.qiwu.chatbotbackend.entity;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.processing.ChatCacheController;
import org.springframework.beans.factory.DisposableBean;
import javax.annotation.PreDestroy;
public class ChatCache3 implements DisposableBean {
// private String chatKey = "不知道";
private String chatKey = "";
private String botAccount = "";
private Map<String, String> infoPoint = null;
private GameEnv gameEnv = null;
private boolean reloading = false;
public String getBotAccount() {
return botAccount;
}
public void setBotAccount(String botAccount) {
this.botAccount = botAccount;
}
public boolean isReloading() {
return reloading;
}
public void setReloading(boolean reloading) {
this.reloading = reloading;
}
public Map<String, String> getInfoPoint() {
return infoPoint;
}
public void setInfoPoint(Map<String, String> infoPoint) {
this.infoPoint = infoPoint;
}
public GameEnv getGameEnv() {
return gameEnv;
}
public void setGameEnv(GameEnv gameEnv) {
this.gameEnv = gameEnv;
}
public ChatCache3(String chatKey, GameEnv gameEnv, Map<String, String> infoPoint) {
this.chatKey = chatKey;
this.gameEnv = gameEnv;
this.infoPoint = infoPoint;
}
@Override
public void destroy() throws IOException {
}
public ChatCache3(UserInfo userInfo) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount);
} catch (Exception e) {
System.out.println("游戏平台初始化失败");
e.printStackTrace();
}
String k;
this.botAccount = userInfo.botAccount;
infoPoint = new HashMap<String, String>();
Iterator<String> iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k));
}
infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
}
}
...@@ -21,17 +21,24 @@ public class JConfig implements Cloneable{ ...@@ -21,17 +21,24 @@ public class JConfig implements Cloneable{
private String jNextStep = ""; private String jNextStep = "";
private String jReply = ""; private String jReply = "";
private String jAuxiliaryPriority = "0"; private String jAuxiliaryPriority = "0";
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
private int jStatus = 0; private int jStatus = 0;
private String curPremise = ""; private String curPremise = "";
private String hisPremise = ""; private String hisPremise = "";
private String feature = "";
private String reply = "";
private String nextStep = "";
private String updateKnowledge = "";
private String nextStepStatus = "return";
private String configName = "";
private String auxiliaryPriority = "1";
private String status = "waiting";
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
public String getFeature() { public String getFeature() {
return feature; return feature;
} }
...@@ -40,8 +47,9 @@ public class JConfig implements Cloneable{ ...@@ -40,8 +47,9 @@ public class JConfig implements Cloneable{
this.feature = feature; this.feature = feature;
} }
private String feature = ""; public String getCurPremise() {
private String reply = ""; return curPremise;
}
public String getNextStep() { public String getNextStep() {
return nextStep; return nextStep;
...@@ -50,8 +58,9 @@ public class JConfig implements Cloneable{ ...@@ -50,8 +58,9 @@ public class JConfig implements Cloneable{
public void setNextStep(String nextStep) { public void setNextStep(String nextStep) {
this.nextStep = nextStep; this.nextStep = nextStep;
} }
public String getConfigName() {
private String nextStep = ""; return configName;
}
public void setConfigName(String configName, Boolean append) { public void setConfigName(String configName, Boolean append) {
...@@ -62,21 +71,6 @@ public class JConfig implements Cloneable{ ...@@ -62,21 +71,6 @@ public class JConfig implements Cloneable{
this.configName = configName; this.configName = configName;
} }
} }
public String getConfigName() {
return configName;
}
private String configName = "";
public String getCurPremise() {
return curPremise;
}
private String auxiliaryPriority = "1";
private String status = "waiting";
public int getId() { public int getId() {
return id; return id;
} }
...@@ -85,6 +79,7 @@ public class JConfig implements Cloneable{ ...@@ -85,6 +79,7 @@ public class JConfig implements Cloneable{
this.id = id; this.id = id;
} }
public String getjCurPremise() { public String getjCurPremise() {
return jCurPremise; return jCurPremise;
} }
...@@ -177,8 +172,6 @@ public class JConfig implements Cloneable{ ...@@ -177,8 +172,6 @@ public class JConfig implements Cloneable{
this.updateKnowledge = updateKnowledge; this.updateKnowledge = updateKnowledge;
} }
private String updateKnowledge = "";
private String nextStepStatus = "return";
static Map<String, String> statusMap = new HashMap<String, String>() { static Map<String, String> statusMap = new HashMap<String, String>() {
{ {
...@@ -189,7 +182,6 @@ public class JConfig implements Cloneable{ ...@@ -189,7 +182,6 @@ public class JConfig implements Cloneable{
put("activate:after", "activate:after"); put("activate:after", "activate:after");
} }
}; };
static int querySkipCount = 10;
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
......
...@@ -26,6 +26,8 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -26,6 +26,8 @@ public class CharacterConstructor extends ElementConstructor {
try { try {
String pattern1 = keywordMap.get("npc_location_pattern").toString(); String pattern1 = keywordMap.get("npc_location_pattern").toString();
StringBuffer onlineModeTalkers = new StringBuffer(",");
JSONArray allNPC = gameElements.getJSONArray("npc"); JSONArray allNPC = gameElements.getJSONArray("npc");
...@@ -56,12 +58,19 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -56,12 +58,19 @@ public class CharacterConstructor extends ElementConstructor {
String classPattern = keywordMap.get("npc_class_pattern").toString(); String classPattern = keywordMap.get("npc_class_pattern").toString();
for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { for (JSONObject character : allNPC.toJavaList(JSONObject.class)) {
name = (String) character.get("name"); name = character.getString("name");
//找到所有处于离线模式的npc
if(character.getBoolean("offline")!= null && !character.getBoolean("offline")){
onlineModeTalkers.append(name).append(",");
}
List<String> nameList = new ArrayList<String>(); List<String> nameList = new ArrayList<String>();
nameList.add(name); nameList.add(name);
...@@ -86,6 +95,7 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -86,6 +95,7 @@ public class CharacterConstructor extends ElementConstructor {
} }
//添加类名称 //添加类名称
if (!classSet.contains(className)) { if (!classSet.contains(className)) {
classSet.add(className); classSet.add(className);
...@@ -111,6 +121,8 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -111,6 +121,8 @@ public class CharacterConstructor extends ElementConstructor {
} }
} }
varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString());
conditionDescription.put("onlineModeTalkers", "所有在线npc");
//根据根据NPC的名字查询地点 //根据根据NPC的名字查询地点
for (String conditionName : locationRelateConditions) { for (String conditionName : locationRelateConditions) {
......
...@@ -41,17 +41,18 @@ public class MapConstructor2 extends ElementConstructor { ...@@ -41,17 +41,18 @@ public class MapConstructor2 extends ElementConstructor {
locationNum = locations.size(); locationNum = locations.size();
StringBuffer nameSet = null; StringBuffer nameSet = null;
keywordMap.putIfAbsent("site_list", new StringBuffer());
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
jobj = locations.getJSONObject(i); jobj = locations.getJSONObject(i);
jobj.put("index", i); jobj.put("index", i);
locationName = (String) jobj.get("name"); locationName = (String) jobj.get("name");
keywordMap.get("site_list").append("+").append(locationName);
taskLineName = String.format(PlotConstructor.TASK_LINE, locationName); taskLineName = String.format(PlotConstructor.TASK_LINE, locationName);
if (!varInitialMap.containsKey(taskLineName)) { if (!varInitialMap.containsKey(taskLineName)) {
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, ""); varInitialMap.put(taskLineName, "");
...@@ -219,8 +220,6 @@ public class MapConstructor2 extends ElementConstructor { ...@@ -219,8 +220,6 @@ public class MapConstructor2 extends ElementConstructor {
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
......
...@@ -6,18 +6,20 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -6,18 +6,20 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.io.*;
import java.util.*; import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL;
public class PlotConstructor extends ElementConstructor { public class PlotConstructor extends ElementConstructor {
public static String ASSISTANT = "globalVariable_智能助手"; public static String ASSISTANT = "globalVariable_智能助手";
public static String ASSISTANT_EMOTION = "0"; public static String ASSISTANT_EMOTION = "正常";
public static String TASK_DESCRIPTION = "globalVariable_任务"; public static String TASK_DESCRIPTION = "globalVariable_任务";
public static String TALKER_PATTERN = "【%s】"; public static String TALKER_PATTERN = "【%s@%s】";
String GAME_STEP_FORMAT = "%s_plot_%s"; String GAME_STEP_FORMAT = "%s_plot_%s";
JSONArray plots = null; JSONArray plots = null;
...@@ -27,7 +29,6 @@ public class PlotConstructor extends ElementConstructor { ...@@ -27,7 +29,6 @@ public class PlotConstructor extends ElementConstructor {
HashMap<String, Boolean> visited = new HashMap<String, Boolean>(); HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public static String TASK_LINE = "任务线_%s进度"; public static String TASK_LINE = "任务线_%s进度";
public static String TASK_CONDITION = "任务线%s最后一个condition"; public static String TASK_CONDITION = "任务线%s最后一个condition";
public static String TASK_REPLY = "任务线%s最后的回答"; public static String TASK_REPLY = "任务线%s最后的回答";
...@@ -49,7 +50,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -49,7 +50,7 @@ public class PlotConstructor extends ElementConstructor {
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
try { try {
addGameStartPlot(jsonObject); addGameStartPlot(jsonObject, keywordMap);
JSONArray plots = jsonObject.getJSONArray("plots"); JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String) jsonObject.get("start"), startCondition; String start = (String) jsonObject.get("start"), startCondition;
...@@ -121,6 +122,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -121,6 +122,7 @@ public class PlotConstructor extends ElementConstructor {
if (revAdjList.get(nextPlotId) == null) { if (revAdjList.get(nextPlotId) == null) {
revAdjList.put(nextPlotId, new ArrayList<>()); revAdjList.put(nextPlotId, new ArrayList<>());
} }
varSlotFilt(branch.getJSONObject(j), varInitialMap);
adjList.get(id).add(nextPlotId); adjList.get(id).add(nextPlotId);
revAdjList.get(nextPlotId).add(id); revAdjList.get(nextPlotId).add(id);
...@@ -129,6 +131,28 @@ public class PlotConstructor extends ElementConstructor { ...@@ -129,6 +131,28 @@ public class PlotConstructor extends ElementConstructor {
} }
} }
/**
* 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉
* @param branchNode
*/
public static void varSlotFilt(JSONObject branchNode, Map<String, String> varInitialMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = "";
Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN);
Matcher m = replacePattern.matcher(branchNode.getString("reply"));
while (m.find()) {
npcName = m.group(1);
//onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题
if(!varInitialMap.get("onlineModeTalkers").contains("," + npcName)) {
varSlot = m.group(3);
middleText = m.group(2);
branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText));
}
}
}
/** /**
...@@ -193,13 +217,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -193,13 +217,13 @@ public class PlotConstructor extends ElementConstructor {
taskLineName = String.format(PlotConstructor.TASK_LINE, location); taskLineName = String.format(PlotConstructor.TASK_LINE, location);
conditionDescription.put(id, "剧情" + id + "状态"); conditionDescription.put(id, "剧情" + id + "状态");
varInitialMap.put(id ,""); varInitialMap.put(id ,"");
skipText.setLength(0);
//本任务线的最后一个condition和本任务线的最后一个回答 //本任务线的最后一个condition和本任务线的最后一个回答
visited.put(id, true);
branch = node.getJSONArray("branch"); branch = node.getJSONArray("branch");
...@@ -207,13 +231,18 @@ public class PlotConstructor extends ElementConstructor { ...@@ -207,13 +231,18 @@ public class PlotConstructor extends ElementConstructor {
for (int i = 0; i < branchSize; i++) { for (int i = 0; i < branchSize; i++) {
System.out.println("branch:" + i);
skipText.setLength(0);
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString());
nextUnknownText = updateKnowledge.get("unknownText"); nextUnknownText = updateKnowledge.get("unknownText");
System.out.println(id + "分支内" +nextUnknownText);
nextId = (String)branchNode.get("nextPlotId"); nextId = (String)branchNode.get("nextPlotId");
//skipText.append(); //skipText.append();
...@@ -241,7 +270,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -241,7 +270,9 @@ public class PlotConstructor extends ElementConstructor {
branchNode.put("reply", jumpBranchNode.get("reply")); branchNode.put("reply", jumpBranchNode.get("reply"));
Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge");
autoJumpUpdateKnowledge.putAll(newUpdateKnowledge); autoJumpUpdateKnowledge.putAll(newUpdateKnowledge);
nextUnknownText = (String)newUpdateKnowledge.get("unknownText"); nextUnknownText = (String)newUpdateKnowledge.get("unknownText");
System.out.println("循环内" +nextUnknownText);
//updateKnowledge.putAll(newUpdateKnowledge); //updateKnowledge.putAll(newUpdateKnowledge);
...@@ -298,7 +329,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -298,7 +329,9 @@ public class PlotConstructor extends ElementConstructor {
* 2. 设一个专门的剧情表示剧情的结尾 * 2. 设一个专门的剧情表示剧情的结尾
*/ */
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; //现在暂时放开下一步剧情未发生过的限制条件
//extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null";
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1;
extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply + extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText; "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText;
...@@ -359,11 +392,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -359,11 +392,13 @@ public class PlotConstructor extends ElementConstructor {
*/ */
//如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 //如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同
if(!location.equals(beforeJumpLocatin)){ if(!location.equals(beforeJumpLocatin)){
if(curUnknownText.equals("")) //System.out.println(id + "报异常" + curUnknownText);
if(curUnknownText.equals("")) {
reply = "请到" + beforeJumpLocatin; reply = "请到" + beforeJumpLocatin;
//如果当前地点和下一步剧情地点不同,要提示 //如果当前地点和下一步剧情地点不同,要提示
else }else {
reply = curUnknownText; reply = curUnknownText;
}
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
...@@ -403,11 +438,14 @@ public class PlotConstructor extends ElementConstructor { ...@@ -403,11 +438,14 @@ public class PlotConstructor extends ElementConstructor {
extraFT = "";
//是否将当前识别到的数据加入到已知数据列表 //是否将当前识别到的数据加入到已知数据列表
if((Boolean)branchNode.get("includeCurInfo")){ if((Boolean)branchNode.get("includeCurInfo")){
extraFT = ",includeCurInfo"; extraFT += ",includeCurInfo";
}else{ }
extraFT = "";
if(branchNode.get("extraFeature") != null){
extraFT += "," + branchNode.getString("extraFeature");
} }
jConfig = new JConfig( jConfig = new JConfig(
...@@ -432,9 +470,11 @@ public class PlotConstructor extends ElementConstructor { ...@@ -432,9 +470,11 @@ public class PlotConstructor extends ElementConstructor {
//将子结点加入队列 //将子结点加入队列
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) {
visited.put(adjId, true);
adjNode = id2j.get(adjId); adjNode = id2j.get(adjId);
adjNode.put("parentId", id); adjNode.put("parentId", id);
//System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText);
adjNode.put("nextUnknownText", nextUnknownText); adjNode.put("nextUnknownText", nextUnknownText);
queue.add(adjNode); queue.add(adjNode);
} else { } else {
...@@ -498,11 +538,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -498,11 +538,13 @@ public class PlotConstructor extends ElementConstructor {
*/ */
//处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0
jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + QA_URL+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", "");
jConfig.setNextStepStatus("active"); jConfig.setNextStepStatus("active");
jConfig.setAuxiliaryPriority("0"); jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig); jConfigList.add(jConfig);
System.out.println("qa_URL" + keywordMap.get("QA_URL"));
jConfig = new JConfig( jConfig = new JConfig(
" ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", ""
...@@ -563,10 +605,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -563,10 +605,13 @@ public class PlotConstructor extends ElementConstructor {
/** /**
* ---------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------
* 用于处理开始游戏或者继续游戏 * 用于存档
*
*
*/ */
jConfig = new JConfig(
"save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", ""
);
jConfig.setAuxiliaryPriority("4");
jConfigList.add(jConfig);
} }
...@@ -627,46 +672,100 @@ public class PlotConstructor extends ElementConstructor { ...@@ -627,46 +672,100 @@ public class PlotConstructor extends ElementConstructor {
id2j.put(nextId, endNode); id2j.put(nextId, endNode);
visited.put(nextId, true); visited.put(nextId, true);
} }
void addGameStartPlot(JSONObject gameElements){ void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){
JSONObject startPlot = new JSONObject(); // JSONObject startPlot = new JSONObject();
startPlot.put("id", "start"); // startPlot.put("id", "start");
startPlot.put("conditionName", "start_options"); // startPlot.put("conditionName", "start_options");
startPlot.put("place", "哪呢? 还没开始呢"); // startPlot.put("place", "哪呢? 还没开始呢");
startPlot.put("branch", new JSONArray()); // startPlot.put("branch", new JSONArray());
//
JSONObject branch1 = new JSONObject(); // JSONObject branch1 = new JSONObject();
branch1.put("curPremise", new JSONArray(){ // branch1.put("curPremise", new JSONArray(){
{ // {
add("start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始"); // add("start_options::match-Include=+重新开始");
} // }
}); // });
//
branch1.get("curPremise"); // branch1.put("higherPriority", true);
branch1.put("higherPriority", true); // branch1.put("hisPremise", new JSONArray());
branch1.put("hisPremise", new JSONArray()); // branch1.put("extraFeature", "newGame");
branch1.put("reply", gameElements.get("plotStartText")); // branch1.put("reply", gameElements.get("plotStartText"));
branch1.put("updateKnowledge", new JSONObject(){ // branch1.put("updateKnowledge", new JSONObject(){
{ // {
put("unknownText", gameElements.get("firstUnknownText")); // put("unknownText", gameElements.get("firstUnknownText"));
} // }
}); // });
branch1.put("nextPlotId", gameElements.get("start")); // branch1.put("nextPlotId", gameElements.get("start"));
branch1.put("includeCurInfo", false); // branch1.put("includeCurInfo", false);
if(gameElements.get("startAutoJump") != null) //
branch1.put("autoJump", gameElements.get("startAutoJump")); //
else //
branch1.put("autoJump", false); // startPlot.getJSONArray("branch").add(branch1);
//
startPlot.getJSONArray("branch").add(branch1); //
gameElements.getJSONArray("plots").add(startPlot); // JSONObject branch2 = new JSONObject();
gameElements.put("start", "start"); // branch2.put("curPremise", new JSONArray(){
gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); // {
// add("start_options::match-Include=+开始+开始游戏+继续游戏+继续");
// }
// });
//
// branch2.put("higherPriority", true);
// branch2.put("hisPremise", new JSONArray());
// branch2.put("reply", gameElements.get("plotStartText"));
// branch2.put("updateKnowledge", new JSONObject(){
// {
// put("unknownText", gameElements.get("firstUnknownText"));
// }
// });
// branch2.put("extraFeature", "loadLastArchive");
// branch2.put("nextPlotId", gameElements.get("start"));
// branch2.put("includeCurInfo", false);
// if(gameElements.get("startAutoJump") != null)
// branch2.put("autoJump", gameElements.get("startAutoJump"));
// else
// branch2.put("autoJump", false);
// startPlot.getJSONArray("branch").add(branch2);
//
//
// gameElements.getJSONArray("plots").add(startPlot);
// gameElements.put("start", "start");
// gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
File file = null;
FileReader fr = null;
BufferedReader br = null;
try {
file = new File("gameconfig.txt");
fr = new FileReader(file);
br = new BufferedReader(fr);
String jsonStr = br.readLine();
jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump"));
jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText"));
jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText"));
jsonStr = jsonStr.replace("startId", gameElements.getString("start"));
jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString());
JSONObject config = JSONObject.parseObject(jsonStr);
System.out.println(config.toJSONString());
// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump"));
// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump"));
gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart"));
gameElements.put("start", "start1");
gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }
...@@ -674,7 +773,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -674,7 +773,7 @@ public class PlotConstructor extends ElementConstructor {
//如果是无条件剧情,那么需要跟着一个激活操作 //如果是无条件剧情,那么需要跟着一个激活操作
public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){ public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")");
jConfig.setNextStep("queryskip*,map*,item*,npc*"); jConfig.setNextStep("queryskip*,map*,item*,npc*");
jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
jConfig.setNextStepStatus("active"); jConfig.setNextStepStatus("active");
...@@ -702,7 +801,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -702,7 +801,7 @@ public class PlotConstructor extends ElementConstructor {
public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){
knowledgeStr.append("-<-"); knowledgeStr.append("-<-");
knowledgeStr.append("key"); knowledgeStr.append(key);
knowledgeStr.append(":"); knowledgeStr.append(":");
knowledgeStr.append(value); knowledgeStr.append(value);
......
package com.qiwu.chatbotbackend.processing; package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil;
import com.qiwu.chatbotbackend.GameEnvironment.Util; import com.qiwu.chatbotbackend.entity.ChatCache3;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import org.apache.catalina.User; import com.qiwu.chatbotbackend.task.utils.FileFinder;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class ChatCacheController { public class ChatCacheController {
...@@ -25,11 +19,12 @@ public class ChatCacheController { ...@@ -25,11 +19,12 @@ public class ChatCacheController {
private static String CHAT_CACHE_DIR = "ChatCache"; private static String CHAT_CACHE_DIR = "ChatCache";
private static String ENV_PATH = CHAT_CACHE_DIR + "/%s-env.data"; //private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data";
private static String INFO_PATH = CHAT_CACHE_DIR + "/%s-info.data"; //private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data";
private static String ENV_PATH = CHAT_CACHE_DIR + "%s-env.data";
private static String INFO_PATH = CHAT_CACHE_DIR + "%s-info.data";
public static synchronized boolean saveChatCache(String chatKey, ChatCache3 chatCache) throws IOException {
public static synchronized boolean saveChatCache(String chatKey, ChatCache chatCache) throws IOException {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String nowStr = now .format(format); String nowStr = now .format(format);
...@@ -62,8 +57,8 @@ public class ChatCacheController { ...@@ -62,8 +57,8 @@ public class ChatCacheController {
return saveFlag; return saveFlag;
} }
public static synchronized ChatCache loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception { public static synchronized ChatCache3 loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception {
ChatCache chatCache = null; ChatCache3 chatCache = null;
GameEnv gameEnv = null; GameEnv gameEnv = null;
Map<String ,String> infoPoint = null; Map<String ,String> infoPoint = null;
...@@ -85,7 +80,7 @@ public class ChatCacheController { ...@@ -85,7 +80,7 @@ public class ChatCacheController {
String jsonStr = br.readLine(); String jsonStr = br.readLine();
infoPoint = (Map)JSON.parseObject(jsonStr); infoPoint = (Map)JSON.parseObject(jsonStr);
chatCache = new ChatCache(chatKey, gameEnv, infoPoint); chatCache = new ChatCache3(chatKey, gameEnv, infoPoint);
chatCache.setReloading(true); chatCache.setReloading(true);
br.close(); br.close();
...@@ -97,7 +92,7 @@ public class ChatCacheController { ...@@ -97,7 +92,7 @@ public class ChatCacheController {
} catch (IOException e) { } catch (IOException e) {
System.out.println(e.toString()); System.out.println(e.toString());
chatCache = new ChatCache(userInfo); chatCache = new ChatCache3(userInfo);
loadCacheStatus = false; loadCacheStatus = false;
} }
...@@ -105,6 +100,47 @@ public class ChatCacheController { ...@@ -105,6 +100,47 @@ public class ChatCacheController {
} }
public static synchronized ChatCache3 loadChatCache2(String userKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception {
ChatCache3 chatCache = null;
GameEnv gameEnv = null;
Map<String ,String> infoPoint = null;
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>();
try {
File file = new File(String.format(ENV_PATH, userKey));
if (file.exists()){
gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, userKey));
}else{
throw new IOException("环境存档不存在");
}
file = new File(String.format(INFO_PATH, userKey));
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String jsonStr = br.readLine();
infoPoint = (Map)JSON.parseObject(jsonStr);
chatCache.setReloading(true);
br.close();
fr.close();
loadCacheStatus = true;
} catch (IOException e) {
System.out.println(e.toString());
chatCache = new ChatCache3(userInfo);
loadCacheStatus = false;
}
return chatCache;
}
...@@ -114,16 +150,16 @@ public class ChatCacheController { ...@@ -114,16 +150,16 @@ public class ChatCacheController {
* *
* @return 历史信息点,对话过程中引擎提取的用户信息 * @return 历史信息点,对话过程中引擎提取的用户信息
*/ */
public static synchronized ChatCache getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception { public static synchronized ChatCache3 getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
Map<String, ChatCache> chatCacheMap = null; Map<String, ChatCache3> chatCacheMap = null;
ChatCache chatCache = null; ChatCache3 chatCache = null;
if (context.getAttribute("chatCache") == null) { if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>(); chatCacheMap = new HashMap<String, ChatCache3>();
//chatCacheMap.put(chatKey, new ChatCache(userinfo)); //chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap); context.setAttribute("chatCache", chatCacheMap);
} else { } else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); chatCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache");
} }
String chatkey; String chatkey;
...@@ -159,10 +195,10 @@ public class ChatCacheController { ...@@ -159,10 +195,10 @@ public class ChatCacheController {
chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus); chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus);
//没有继续游戏相关的关键词 //没有继续游戏相关的关键词
}else { }else {
chatCache = new ChatCache(userinfo); chatCache = new ChatCache3(userinfo);
} }
}else { }else {
chatCache = new ChatCache(userinfo); chatCache = new ChatCache3(userinfo);
} }
chatCacheMap.put(chatKey, chatCache); chatCacheMap.put(chatKey, chatCache);
//用户几分钟前还在玩 //用户几分钟前还在玩
...@@ -175,14 +211,14 @@ public class ChatCacheController { ...@@ -175,14 +211,14 @@ public class ChatCacheController {
if(startKeySet.contains(startKeyword)) { if(startKeySet.contains(startKeyword)) {
chatCache.setReloading(true); chatCache.setReloading(true);
}else if(restartKeySet.contains(startKeyword)){ }else if(restartKeySet.contains(startKeyword)){
chatCache = new ChatCache(userinfo); chatCache = new ChatCache3(userinfo);
} }
} }
} }
//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) {
//可整合 //可整合
chatCache = new ChatCache(userinfo); chatCache = new ChatCache3(userinfo);
} }
...@@ -195,10 +231,10 @@ public class ChatCacheController { ...@@ -195,10 +231,10 @@ public class ChatCacheController {
*/ */
public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context, UserInfo userInfo) throws IOException { public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context, UserInfo userInfo) throws IOException {
String chatKey; String chatKey;
ChatCache chatCache = null; ChatCache3 chatCache = null;
long lastChatTime, now; long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>(); Map<String, String> history = new HashMap<String, String>();
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); Map<String, ChatCache3> chatCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache");
Iterator<String> it = chatCacheMap.keySet().iterator(); Iterator<String> it = chatCacheMap.keySet().iterator();
...@@ -226,8 +262,8 @@ public class ChatCacheController { ...@@ -226,8 +262,8 @@ public class ChatCacheController {
*/ */
public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); Map<String, ChatCache3> keyCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); ChatCache3 chatCache = keyCacheMap.get(curInfoPoint.get("chat_key"));
chatCache.setInfoPoint(historyInfoPoint); chatCache.setInfoPoint(historyInfoPoint);
chatCache.setGameEnv(gameEnv); chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap); context.setAttribute("chatCache", keyCacheMap);
...@@ -235,7 +271,7 @@ public class ChatCacheController { ...@@ -235,7 +271,7 @@ public class ChatCacheController {
public static synchronized boolean findChatCache(String chatKey, ServletContext context, String botAccount) throws Exception { public static synchronized boolean findChatCache(String chatKey, ServletContext context, String botAccount) throws Exception {
ChatCache chatCache = null; ChatCache3 chatCache = null;
GameEnv gameEnv = null; GameEnv gameEnv = null;
Map<String ,String> infoPoint = null; Map<String ,String> infoPoint = null;
...@@ -244,7 +280,7 @@ public class ChatCacheController { ...@@ -244,7 +280,7 @@ public class ChatCacheController {
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
if (context.getAttribute("chatCache") != null) { if (context.getAttribute("chatCache") != null) {
if (((HashMap<String, ChatCache>)context.getAttribute("chatCache")).get(chatKey) != null){ if (((HashMap<String, ChatCache3>)context.getAttribute("chatCache")).get(chatKey) != null){
return true; return true;
} }
} }
...@@ -266,7 +302,7 @@ public class ChatCacheController { ...@@ -266,7 +302,7 @@ public class ChatCacheController {
public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception {
try { try {
System.out.println("移除----------------------------"); System.out.println("移除----------------------------");
HashMap<String, ChatCache> chatCacheHashMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache"); HashMap<String, ChatCache3> chatCacheHashMap = (HashMap<String, ChatCache3>)context.getAttribute("chatCache");
chatCacheHashMap.remove(chatKey); chatCacheHashMap.remove(chatKey);
} catch(Exception e){ } catch(Exception e){
...@@ -277,6 +313,35 @@ public class ChatCacheController { ...@@ -277,6 +313,35 @@ public class ChatCacheController {
return true; return true;
} }
public static synchronized List<File> queryChatCacheBySite(String key, String site) {
String findPattern = String.format(ENV_PATH, key, site, ".*?");
List<File> fileList = FileFinder.findFiles(CHAT_CACHE_DIR, findPattern);
Comparator<File> FILES_BY_MODEFIED_DATE = new Comparator<File>() {
@Override
public int compare(File object1, File object2) {
long d1 = object1.lastModified();
long d2 = object2.lastModified();
if (d1 == d2) {
return 0;
} else {
return d1 < d2 ? 1 : -1;
}
}
};
fileList.sort(FILES_BY_MODEFIED_DATE);
return fileList;
}
......
package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ChatCacheController2 {
public static long TIME_OUT = 300000;
private static String CHAT_CACHE_DIR = "ChatCache/";
private static String ARCHIVE_NAME = "%s-%s-%s";
private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data";
private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data";
private static String ENV_POSTFIX = "-env.data";
private static String INFO_POSTFIX = "-info.data";
public static String COMBINE_PUNC1 = "@@@";
public static String COMBINE_PUNC2 = "@@@@";
/**
* 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点)
*
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>();
//chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
}
try {
chatCache = chatCacheMap.get(userKey);
//如果用户之前没有玩过或者有一段时间没有玩
if(chatCache == null){
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
//用户几分钟前还在玩
} else {
if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话
saveChatCache(chatCache, null);
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
}
}
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) {
//可整合
e.printStackTrace();
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
}
return chatCache;
}
public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String nowTime = now .format(format);
Boolean opFlag;
String userKey = chatCache.getUserKey();
String site = chatCache.getInfoPoint().get("site");
String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime);
try {
if(helper == null){
helper = new SqlHelper();
}
File dir = new File(CHAT_CACHE_DIR);
if (!dir.exists())
dir.mkdir();
ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime));
File file = new File(String.format(INFO_PATH, userKey, site, nowTime));
FileWriter fw = new FileWriter(file);
String jsonString = JSON.toJSONString(chatCache.getInfoPoint());
fw.write(jsonString);
fw.close();
opFlag = helper.insertArchiveInfo(archiveName, userKey, site);
} catch (Exception e) {
System.out.println("游戏存档时发生异常");
e.printStackTrace();
opFlag = false;
}
return opFlag;
}
public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception {
ChatCache chatCache = null;
GameEnv gameEnv = null;
Map<String ,String> infoPoint = null;
String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1);
keys[1] = keys[1].split("-")[0];
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>();
try {
File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX);
if (file.exists()){
gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX);
}else{
throw new IOException("环境存档不存在");
}
file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String jsonStr = br.readLine();
infoPoint = (Map)JSON.parseObject(jsonStr);
chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint);
chatCache.setReloading(true);
br.close();
fr.close();
} catch (IOException e) {
System.out.println(e.toString());
}
return chatCache;
}
/**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/
public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException {
String sessionKey;
ChatCache chatCache = null;
SqlHelper helper = null;
long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>();
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
try {
Iterator<String> it = chatCacheMap.keySet().iterator();
while (it.hasNext()) {
sessionKey = it.next();
if (sessionKey.equals(userKey)) {
saveChatCache(chatCacheMap.get(sessionKey),null);
continue;
}
history = chatCacheMap.get(sessionKey).getInfoPoint();
lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis();
if (now - lastChatTime > ChatCacheController2.TIME_OUT) {
chatCache = chatCacheMap.get(sessionKey);
if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) {
saveChatCache(chatCache, null);
}
System.out.println("移除" + sessionKey);
it.remove();
}
}
}catch (Exception e){
e.printStackTrace();
}
context.setAttribute("chatCache", chatCacheMap);
}
/**
* 根据chatKey更新chatCache的数据,并修改最后更新时间
*/
public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey"));
chatCache.setInfoPoint(historyInfoPoint);
chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap);
}
public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception {
ChatCache chatCache = null;
GameEnv gameEnv = null;
ArchiveInfo archiveInfo = null;
Map<String ,String> infoPoint = null;
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[];
SqlHelper helper;
Map<String, String> infoPoints = new HashMap<String, String>();
try {
helper = new SqlHelper();
archiveInfo = helper.queryUserLastGameArchive(userKey);
} catch(Exception e){
e.printStackTrace();
return false;
}
return archiveInfo != null;
}
public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception {
try {
System.out.println("移除----------------------------");
HashMap<String, ChatCache> chatCacheHashMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache");
chatCacheHashMap.remove(chatKey);
} catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
}
...@@ -8,6 +8,7 @@ import com.qiwu.chatbotbackend.entity.Condition; ...@@ -8,6 +8,7 @@ import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.*; import java.util.*;
...@@ -17,8 +18,17 @@ import java.util.regex.Pattern; ...@@ -17,8 +18,17 @@ import java.util.regex.Pattern;
public class FormsPoster { public class FormsPoster {
LogWriter logWriter = null; LogWriter logWriter;
public static String QA_URL = "http://qcloud-gz1.chewrobot.com:58000/game";
static String TALKER = "【(.*?)@.*?】";
@Value("${qa.url}")
public String QA_URL;
public void setQaUrl(String qaUrl) {
QA_URL = qaUrl;
}
public FormsPoster(LogWriter logWriter) { public FormsPoster(LogWriter logWriter) {
this.logWriter = logWriter; this.logWriter = logWriter;
...@@ -33,7 +43,7 @@ public class FormsPoster { ...@@ -33,7 +43,7 @@ public class FormsPoster {
} }
}; };
static String TALKER = "【(.*?)@.*?】";
/** /**
* 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器
......
...@@ -6,11 +6,32 @@ import java.time.format.DateTimeFormatter; ...@@ -6,11 +6,32 @@ import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class LogWriter { public class LogWriter {
private PrintWriter recorder = null; private PrintWriter recorder = null;
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"); DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss");
LocalDateTime ldt = null; LocalDateTime ldt = null;
String filePath;
String fileName;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
String PRINT_PATTERN = "<font color=\"%s\">[%s] %s" + String PRINT_PATTERN = "<font color=\"%s\">[%s] %s" +
"----------------------------------------------------------------------------<br></font>"; "----------------------------------------------------------------------------<br></font>";
Map<Integer, String> colorMap = new HashMap<Integer, String>(){ Map<Integer, String> colorMap = new HashMap<Integer, String>(){
......
...@@ -19,10 +19,8 @@ import java.io.IOException; ...@@ -19,10 +19,8 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.Date;
import java.util.List;
import static com.qiwu.chatbotbackend.processing.QuestionMatcher.API_ERROR;
import static com.qiwu.chatbotbackend.processing.QuestionMatcher.POST_ERROR;
public class MyFunc { public class MyFunc {
...@@ -173,6 +171,7 @@ public class MyFunc { ...@@ -173,6 +171,7 @@ public class MyFunc {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
try { try {
System.out.println("url为:" + url);
HttpResponse resp = client.execute(httpPost); HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
......
package com.qiwu.chatbotbackend.processing; package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.Condition; import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; import com.qiwu.chatbotbackend.task.utils.BasicBotUtil;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuestionMatcher { public class QuestionMatcher {
...@@ -24,8 +22,8 @@ public class QuestionMatcher { ...@@ -24,8 +22,8 @@ public class QuestionMatcher {
static String POST_DATA_ERROR = "post数据有误"; static String POST_DATA_ERROR = "post数据有误";
static String POST_ERROR = "数据post时出错了"; static String POST_ERROR = "数据post时出错了";
static String API_ERROR = "api处理过程中出错了"; static String API_ERROR = "api处理过程中出错了";
static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
public LogWriter logWriter = null; public LogWriter logWriter = null;
...@@ -147,11 +145,9 @@ public class QuestionMatcher { ...@@ -147,11 +145,9 @@ public class QuestionMatcher {
activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context);
} }
if((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) { bestMatch = condition;
bestMatch = condition; logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2);
logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln();
logWriter.writeln();
}
} }
...@@ -287,7 +283,7 @@ public class QuestionMatcher { ...@@ -287,7 +283,7 @@ public class QuestionMatcher {
String ks[] = keyword.split(":", 2); String ks[] = keyword.split(":", 2);
if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1]))
flag = false; flag = false;
}else { }else {
if (keywordSet.contains(keyword)) { if (keywordSet.contains(keyword)) {
flag = false; flag = false;
} }
...@@ -585,46 +581,27 @@ public class QuestionMatcher { ...@@ -585,46 +581,27 @@ public class QuestionMatcher {
} }
} }
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
if (ans.getNext().equals("")) {
ans.setNext("nextStep=" + ansCondition.nextStep);
}
try { try {
reply = MyFunc.randStr(ansCondition.answer); reply = MyFunc.randStr(ansCondition.answer);
//用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 reply = botUtil.varSlotReplace(reply);
String keyword;
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).equals("")) {
keyword = curInfoPoint.get(variable);
if(keyword.contains(":"))
keyword = keyword.split(":")[1];
reply = reply.replace("{" + variable + "-1}", keyword);
}
} else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null)
if(historyInfoPoint.get(variable).equals("do_reset")){
reply = reply.replace("{" + variable + "-2}", "");
}else
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
}
}
reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter); reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter);
ans.setAnswer(reply);
botUtil.extraOperation(ansCondition, ans);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ans.setAnswer(reply);
if (ans.getNext().equals("")) {
ans.setNext("nextStep=" + ansCondition.nextStep);
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -681,7 +658,7 @@ public class QuestionMatcher { ...@@ -681,7 +658,7 @@ public class QuestionMatcher {
historyInfoPoint.put(actionName, keyword1); historyInfoPoint.put(actionName, keyword1);
}else if (historyInfoPoint.get(actionName).equals("do_reset")){ }else if (historyInfoPoint.get(actionName).equals("do_reset")){
historyInfoPoint.put(actionName, ""); historyInfoPoint.put(actionName, "");
}else if (keyword2 != null && !keyword1.equals("")) }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals(""))
historyInfoPoint.put(actionName, keyword1); historyInfoPoint.put(actionName, keyword1);
} }
historyInfoPoint.put("临时变量reply", ""); historyInfoPoint.put("临时变量reply", "");
...@@ -720,6 +697,8 @@ public class QuestionMatcher { ...@@ -720,6 +697,8 @@ public class QuestionMatcher {
add("unknownTextList"); add("unknownTextList");
add("finalUnknownText"); add("finalUnknownText");
add("unknownText"); add("unknownText");
add("randKey");
add("userKey");
} }
}; };
...@@ -930,6 +909,8 @@ public class QuestionMatcher { ...@@ -930,6 +909,8 @@ public class QuestionMatcher {
keyword = ""; keyword = "";
updateValue = keyword.replace(updateValue.substring(5), ""); updateValue = keyword.replace(updateValue.substring(5), "");
//变量提取
} else if (updateValue.startsWith("var=")) { } else if (updateValue.startsWith("var=")) {
String conditionName = updateValue.substring(5, updateValue.length() - 3); String conditionName = updateValue.substring(5, updateValue.length() - 3);
...@@ -945,11 +926,15 @@ public class QuestionMatcher { ...@@ -945,11 +926,15 @@ public class QuestionMatcher {
} else { } else {
updateValue = ""; updateValue = "";
} }
//提取配置条目的下一步
} else if (updateValue.endsWith("nextStep-3}")) { } else if (updateValue.endsWith("nextStep-3}")) {
updateValue = condition.nextStep; updateValue = condition.nextStep;
//提取配置条目的回答
} else if (updateValue.endsWith("reply-3}")) { } else if (updateValue.endsWith("reply-3}")) {
updateValue = MyFunc.randStr(condition.answer); updateValue = MyFunc.randStr(condition.answer);
} }
//如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue
if (variableName.startsWith("process-nextStep")) { if (variableName.startsWith("process-nextStep")) {
condition.nextStep = updateValue; condition.nextStep = updateValue;
updateValue = ""; updateValue = "";
...@@ -957,6 +942,7 @@ public class QuestionMatcher { ...@@ -957,6 +942,7 @@ public class QuestionMatcher {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
continue; continue;
...@@ -965,7 +951,7 @@ public class QuestionMatcher { ...@@ -965,7 +951,7 @@ public class QuestionMatcher {
if(updateValue.equals("")) { if(updateValue.equals("")) {
curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点转移时这个变量的已知信息依然不是空的。 curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。
// 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。
curInfoPoint.put(variableName, ""); curInfoPoint.put(variableName, "");
} }
......
...@@ -11,6 +11,7 @@ import java.util.Map; ...@@ -11,6 +11,7 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN;
import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER;
public class ResponseFilter { public class ResponseFilter {
...@@ -38,7 +39,7 @@ public class ResponseFilter { ...@@ -38,7 +39,7 @@ public class ResponseFilter {
return reply; return reply;
} }
if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT) + "@" + PlotConstructor.ASSISTANT_EMOTION + "】") ){ if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){
return reply; return reply;
}else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){
return reply; return reply;
...@@ -61,11 +62,17 @@ public class ResponseFilter { ...@@ -61,11 +62,17 @@ public class ResponseFilter {
List<String> unknownList = new ArrayList<String>(); List<String> unknownList = new ArrayList<String>();
String lastTalker = ""; String lastTalker = "";
//如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是剧情中的人 //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人
if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){
Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)));
while(m.find()) { while(m.find()) {
lastTalker = m.group(1); //回答unknown文本的npc必须处于在线模式
npc = m.group(1);
if(historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",")) {
lastTalker = npc;
}else{
System.out.println(npc + "是离线模式");
}
} }
for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) {
...@@ -151,6 +158,9 @@ public class ResponseFilter { ...@@ -151,6 +158,9 @@ public class ResponseFilter {
* @param logWriter * @param logWriter
* @return * @return
*/ */
static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){
String npc, location; String npc, location;
......
...@@ -10,6 +10,8 @@ import java.util.List; ...@@ -10,6 +10,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION;
public class WorldController { public class WorldController {
public LogWriter logWriter = null; public LogWriter logWriter = null;
public UserInfo userInfo = null; public UserInfo userInfo = null;
...@@ -200,7 +202,7 @@ public class WorldController { ...@@ -200,7 +202,7 @@ public class WorldController {
lastTalker = m.group(1); lastTalker = m.group(1);
} }
returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker);
break; break;
......
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController2;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -19,12 +19,12 @@ public class FindCacheServlet extends HttpServlet { ...@@ -19,12 +19,12 @@ public class FindCacheServlet extends HttpServlet {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String chatKey = request.getParameter("client_id"); String userKey = request.getParameter("client_id");
String botAccount = request.getParameter("aipioneer_username"); String botAccount = request.getParameter("aipioneer_username");
Boolean exist = false; Boolean exist = false;
try { try {
exist = ChatCacheController.findChatCache(chatKey+ "-" + botAccount, context, botAccount); exist = ChatCacheController2.findChatCache(userKey, context, botAccount);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -32,6 +32,7 @@ public class FindCacheServlet extends HttpServlet { ...@@ -32,6 +32,7 @@ public class FindCacheServlet extends HttpServlet {
JSONObject responseJSONObject = new JSONObject(); JSONObject responseJSONObject = new JSONObject();
responseJSONObject.put("exist", exist); responseJSONObject.put("exist", exist);
responseJSONObject.put("aipioneer_username", botAccount); responseJSONObject.put("aipioneer_username", botAccount);
responseJSONObject.put("client_id", userKey);
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8"); response.setContentType("application/json; charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Origin", "*");
......
...@@ -267,8 +267,6 @@ public class GameDesignServlet extends HttpServlet { ...@@ -267,8 +267,6 @@ public class GameDesignServlet extends HttpServlet {
boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap);
return deleteConfigFlag && deleteVariableFlag; return deleteConfigFlag && deleteVariableFlag;
} }
......
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.*; import com.qiwu.chatbotbackend.processing.*;
import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; import com.qiwu.chatbotbackend.task.utils.BasicBotUtil;
import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import com.qiwu.chatbotbackend.task.utils.GameBotUtil;
...@@ -12,10 +14,12 @@ import javax.servlet.annotation.WebServlet; ...@@ -12,10 +14,12 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.HashMap;
import java.util.Map;
@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"})
...@@ -37,18 +41,30 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -37,18 +41,30 @@ public class GetAnswerServlet extends HttpServlet {
BasicBotUtil botUtil = null; BasicBotUtil botUtil = null;
Condition ansCondition = null; Condition ansCondition = null;
boolean debugFlag = false; boolean debugFlag = false;
String ansJ = "", return_str = "", state = "", chatKey = "", botType = ""; String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = "";
String botName = receiveParamters.get("bot_name")[0]; String botName = receiveParamters.get("bot_name")[0];
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
//如果有client_id,会用@分隔 //如果有client_id,会用@分隔
if(!receiveParamters.get("chat_key")[0].startsWith("@")) chatKey = receiveParamters.get("chat_key")[0];
chatKey = receiveParamters.get("chat_key")[0].split("@")[0]; String chatKeys[] = receiveParamters.get("chat_key")[0].split("@@@@");
else if(chatKeys.length == 1){
chatKey = receiveParamters.get("chat_key")[0]; userKey = chatKeys[0];
receiveParamters.get("chat_key")[0] = chatKey; randKey = chatKeys[0];
}else{
userKey = chatKeys[0];
randKey = chatKeys[1];
}
receiveParamters.put("userKey", new String[]{userKey});
receiveParamters.put("randKey", new String[]{randKey});
// if(!receiveParamters.get("chat_key")[0].startsWith("@"))
// chatKey = receiveParamters.get("chat_key")[0].split("@")[0];
// else
// chatKey = receiveParamters.get("chat_key")[0];
// receiveParamters.get("chat_key")[0] = chatKey;
LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
...@@ -74,7 +90,8 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -74,7 +90,8 @@ public class GetAnswerServlet extends HttpServlet {
ChatCache chatCache = null; ChatCache chatCache = null;
Boolean loadCacheStatus = Boolean.valueOf(false); Boolean loadCacheStatus = Boolean.valueOf(false);
try { try {
chatCache = ChatCacheController.getChatCache(chatKey, context, userinfo, receiveParamters, loadCacheStatus); //chatCache = ChatCacheController.getChatCache2(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus);
chatCache = ChatCacheController2.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
...@@ -86,86 +103,73 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -86,86 +103,73 @@ public class GetAnswerServlet extends HttpServlet {
* 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据
*/ */
if(!chatCache.isReloading()) { historyInfoPoint = chatCache.getInfoPoint();
historyInfoPoint = chatCache.getInfoPoint();
if(userinfo.varInitialMap.get("botType") != null) if(userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType"); botType = userinfo.varInitialMap.get("botType");
switch(botType){ switch(botType){
case "game": case "game":
WorldController worldController = new WorldController(logWriter,userinfo); WorldController worldController = new WorldController(logWriter,userinfo);
botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv()); botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv(), chatCache);
break; break;
default: default:
botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter);
break; break;
} }
//针对不同游戏类型对信息点做预处理 //针对不同游戏类型对信息点做预处理
debugFlag = botUtil.preprocessing(receiveParamters, context); debugFlag = botUtil.preprocessing(receiveParamters, context);
//信息点预处理 //信息点预处理
QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context); //process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试 //System.out.println(userinfo.conditionTable); //测试
ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansCondition.priority == -1) if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { try {
bestMatch = matcher.getSolution(ansCondition, context, userinfo); bestMatch = matcher.getSolution(ansCondition, context, userinfo);
if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) { if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansCondition, context, userinfo); bestMatch = matcher.postActivate(ansCondition, context, userinfo);
}
} catch (ParseException e) {
e.printStackTrace();
} }
} else { } catch (ParseException e) {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); e.printStackTrace();
} }
} else {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction"));
}
if (debugFlag) { if (debugFlag) {
matcher.appendDebugInfo(bestMatch, context); matcher.appendDebugInfo(bestMatch, context);
} }
//if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after"))
matcher.infoTransfer(bestMatch, context, debugFlag);
ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, chatCache.getGameEnv(), context, userinfo);
//清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) {
ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
}
//针对不同游戏类型做后处理
botUtil.postprocessing(chatKey, context, bestMatch);
//if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after"))
matcher.infoTransfer(bestMatch, context, debugFlag);
} else { ChatCacheController2.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo);
//清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController2.TIME_OUT) {
ChatCacheController2.updateChatCache4Delete(chatKey, context, userinfo);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
}
System.out.println("----------读档中------------"); //针对不同游戏类型做后处理
String site = chatCache.getInfoPoint().get("site"); botUtil.postprocessing(chatKey, context, bestMatch);
String nextStep = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site));
String reply = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site));
bestMatch = new Solution(1, "--读取存档--" + reply, "nextStep=" + nextStep);
}
ansJ = MyFunc.toJson(bestMatch); ansJ = MyFunc.toJson(bestMatch);
} else { } else {
ansJ = "找不到配置文件"; ansJ = "找不到配置文件";
......
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController2;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
...@@ -23,6 +24,7 @@ public class MyListener implements ServletContextListener { ...@@ -23,6 +24,7 @@ public class MyListener implements ServletContextListener {
ServletContext servletContext = sce.getServletContext(); ServletContext servletContext = sce.getServletContext();
Object obj = servletContext.getAttribute("chatCache"); Object obj = servletContext.getAttribute("chatCache");
ChatCache cache = null; ChatCache cache = null;
SqlHelper helper = null;
if(obj != null){ if(obj != null){
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj; Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj;
...@@ -34,8 +36,9 @@ public class MyListener implements ServletContextListener { ...@@ -34,8 +36,9 @@ public class MyListener implements ServletContextListener {
chatKey = cacheIter.next(); chatKey = cacheIter.next();
cache = chatCacheMap.get(chatKey); cache = chatCacheMap.get(chatKey);
try { try {
helper = new SqlHelper();
System.out.println(String.format("saving %s", chatKey)); System.out.println(String.format("saving %s", chatKey));
ChatCacheController.saveChatCache(chatKey, cache); ChatCacheController2.saveChatCache(cache, helper);
}catch (Exception e){ }catch (Exception e){
System.out.println(String.format("保存%s时出现异常", chatKey)); System.out.println(String.format("保存%s时出现异常", chatKey));
} }
......
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController2;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -12,7 +11,6 @@ import javax.servlet.http.HttpServlet; ...@@ -12,7 +11,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Map; import java.util.Map;
...@@ -22,20 +20,19 @@ public class SaveChatCacheServlet extends HttpServlet { ...@@ -22,20 +20,19 @@ public class SaveChatCacheServlet extends HttpServlet {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String chatKey = request.getParameter("chatKey"), message = ""; String chatKey = request.getParameter("chatKey"), message = "";
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
chatKey = chatKey.split("@")[0]; chatKey = chatKey.split("@@@@")[0];
Boolean flag = false; Boolean flag = false;
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)context.getAttribute("chatCache"); Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)context.getAttribute("chatCache");
ChatCache chatCache = chatCacheMap.get(chatKey); ChatCache chatCache = chatCacheMap.get(chatKey);
if(chatCache != null) { if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) {
flag = ChatCacheController.saveChatCache(chatKey, chatCache); flag = ChatCacheController2.saveChatCache(chatCache, null);
chatCacheMap.remove(chatKey); chatCacheMap.remove(chatKey);
} }
System.out.println("调用接口删除" + chatKey); System.out.println("调用接口删除" + chatKey);
//out.write(message.getBytes());
......
package com.qiwu.chatbotbackend.task.utils; package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
...@@ -9,6 +10,8 @@ import java.io.IOException; ...@@ -9,6 +10,8 @@ import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BasicBotUtil { public class BasicBotUtil {
Map<String, String> curInfoPoint = null; Map<String, String> curInfoPoint = null;
...@@ -17,6 +20,8 @@ public class BasicBotUtil { ...@@ -17,6 +20,8 @@ public class BasicBotUtil {
LogWriter logWriter = null; LogWriter logWriter = null;
public BasicBotUtil(){}; public BasicBotUtil(){};
public BasicBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter){ public BasicBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter){
this.curInfoPoint = curInfoPoint; this.curInfoPoint = curInfoPoint;
...@@ -29,10 +34,10 @@ public class BasicBotUtil { ...@@ -29,10 +34,10 @@ public class BasicBotUtil {
return infoPointPreprocessing(receiveParameters, context); return infoPointPreprocessing(receiveParameters, context);
} }
//在接收到请求后对数据做处理,转化为系统可以处理的数据
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
String return_str = "", k, botType = ""; String return_str = "", k, botType = "";
...@@ -42,6 +47,8 @@ public class BasicBotUtil { ...@@ -42,6 +47,8 @@ public class BasicBotUtil {
HashSet<String> skipSet = new HashSet<String>() { HashSet<String> skipSet = new HashSet<String>() {
{ {
add("chat_key"); add("chat_key");
add("randKey");
add("userKey");
add("action_name"); add("action_name");
add("bot_name"); add("bot_name");
add("emptySet"); add("emptySet");
...@@ -123,6 +130,14 @@ public class BasicBotUtil { ...@@ -123,6 +130,14 @@ public class BasicBotUtil {
} }
/**
* 从当前信息点或者已知信息点中提取关键词
* @param infoPoint
* @param infoPoint2
* @param chooseLater
* @param actionName
* @return
*/
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){ public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = ""; String keyword = "";
String nameSeries[] = actionName.split("_"); String nameSeries[] = actionName.split("_");
...@@ -141,6 +156,11 @@ public class BasicBotUtil { ...@@ -141,6 +156,11 @@ public class BasicBotUtil {
return keyword; return keyword;
}; };
/**
* 更新历史信息点中的某一个键值对
* @param variableName
* @param updateValue
*/
public void putKeyword(String variableName, String updateValue){ public void putKeyword(String variableName, String updateValue){
historyInfoPoint.put(variableName, updateValue); historyInfoPoint.put(variableName, updateValue);
} }
...@@ -149,4 +169,44 @@ public class BasicBotUtil { ...@@ -149,4 +169,44 @@ public class BasicBotUtil {
return updateValue; return updateValue;
} }
/**
* 额外的更新操作
*/
public void extraOperation(Condition ansCondition, Solution solution) throws IOException {
}
//将文本中存在的变量槽位{npc_xxx}替换成变量值
public String varSlotReplace(String text){
String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
//用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值
String keyword, variable,reply = text;
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).equals("")) {
keyword = curInfoPoint.get(variable);
if(keyword.contains(":"))
keyword = keyword.split(":")[1];
reply = reply.replace("{" + variable + "-1}", keyword);
}
} else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null)
if(historyInfoPoint.get(variable).equals("do_reset")){
reply = reply.replace("{" + variable + "-2}", "");
}else
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
}
}
return reply;
}
} }
package com.qiwu.chatbotbackend.task.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 实现一个支持通配符的基于广度优先算法的文件查找器
*/
public class FileFinder {
/**
* 查找文件。
* @param baseDirName 待查找的目录
* @param targetFileName 目标文件名,支持通配符形式
* @param count 期望结果数目,如果畏0,则表示查找全部。
* @return 满足查询条件的文件名列表
*/
public static List findFiles(String baseDirName, String targetFileName) {
String tempName;
List fileList = new ArrayList();
//判断目录是否存在
File baseDir = new File(baseDirName);
if (!baseDir.exists() || !baseDir.isDirectory()){
System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
return fileList;
}
File[] files = baseDir.listFiles();
for (int i = 0; i < files.length; i++) {
//如果是目录则放进队列
if (files[i].isDirectory()) {
continue;
} else {
//如果是文件则根据文件名与目标文件名进行匹配
tempName = files[i].getName();
if (FileFinder.wildcardMatch(targetFileName, tempName)) {
//匹配成功,将文件名添加到结果集
fileList.add(files[i]);
}
}
}
return fileList;
}
/**
* 通配符匹配
* @param pattern 通配符模式
* @param str 待匹配的字符串
* @return 匹配成功则返回true,否则返回false
*/
private static boolean wildcardMatch(String pattern, String str) {
int patternLength = pattern.length();
int strLength = str.length();
int strIndex = 0;
char ch;
for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
ch = pattern.charAt(patternIndex);
if (ch == '*') {
//通配符星号*表示可以匹配任意多个字符
while (strIndex < strLength) {
if (wildcardMatch(pattern.substring(patternIndex + 1),
str.substring(strIndex))) {
return true;
}
strIndex++;
}
} else if (ch == '?') {
//通配符问号?表示匹配任意一个字符
strIndex++;
if (strIndex > strLength) {
//表示str中已经没有字符匹配?了。
return false;
}
} else {
if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
return false;
}
strIndex++;
}
}
return (strIndex == strLength);
}
}
package com.qiwu.chatbotbackend.task.utils; package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.ChatCacheController2;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
import com.qiwu.chatbotbackend.processing.WorldController; import com.qiwu.chatbotbackend.processing.WorldController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN;
public class GameBotUtil extends BasicBotUtil{ public class GameBotUtil extends BasicBotUtil{
WorldController worldController = null; WorldController worldController = null;
GameEnv gameEnv = null; GameEnv gameEnv = null;
ChatCache chatCache = null;
public static String LOAD_BY_SITE_CONDITION = "load_game_by_site";
public static String LOAD_BY_LAST = "load_last";
public GameBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv){ public GameBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv, ChatCache chatCache){
this.curInfoPoint = curInfoPoint; this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint; this.historyInfoPoint = historyInfoPoint;
this.userinfo = userinfo; this.userinfo = userinfo;
this.logWriter = logWriter; this.logWriter = logWriter;
this.worldController = worldController; this.worldController = worldController;
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
this.chatCache = chatCache;
} }
...@@ -39,10 +51,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -39,10 +51,14 @@ public class GameBotUtil extends BasicBotUtil{
for(String conditionName: conditionList) { for(String conditionName: conditionList) {
if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) {
String info = curInfoPoint.get(conditionName); String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName);
String destination = info.split(":")[1]; String destination = info.split(":")[1];
String site = historyInfoPoint.get("site"); String site = historyInfoPoint.get("site");
String newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); try {
newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site));
}catch(Exception e){
e.printStackTrace();
}
logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1);
curInfoPoint.put(conditionName, newInfo); curInfoPoint.put(conditionName, newInfo);
...@@ -88,9 +104,6 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -88,9 +104,6 @@ public class GameBotUtil extends BasicBotUtil{
} }
return true; return true;
} }
...@@ -185,4 +198,137 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -185,4 +198,137 @@ public class GameBotUtil extends BasicBotUtil{
return returnValue; return returnValue;
} }
@Override
public void extraOperation(Condition ansCondition, Solution solution) throws IOException {
Boolean flag = true;
String userKey = curInfoPoint.get("userKey");
String randKey = curInfoPoint.get("randKey");
String keyword = "", site;
SqlHelper helper = null;
ChatCache chatCache = null;
try {
helper = new SqlHelper();
if(ansCondition.featureMap.containsKey("newGame")) {
System.out.println("newGame");
this.chatCache.setReloading(true);
}else if (ansCondition.featureMap.containsKey("gameBackup")) {
System.out.println("gameBackup");
if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档
chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint);
flag = ChatCacheController2.saveChatCache(chatCache, null);
if(flag)
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功");
else
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败");
}else{
solution.setAnswer("体验作品时无法存档哦,请下载我们的app体验更多功能");
solution.setNext(""); //可能存在问题,估计要一个空格
}
} else if (ansCondition.featureMap.containsKey("loadLastArchive")) {
System.out.println("loadLastArchive");
ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey);
loading(archiveInfo, solution);
} else if (ansCondition.featureMap.containsKey("loadArchiveBySite")) {
System.out.println("loadArchiveBySite");
if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) {
site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1];
System.out.println("要读取的存档的地点是:" + site);
ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site);
loading(archiveInfo, solution);
}else{
System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION);
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally{
helper.destroy();
}
}
private void loading(ArchiveInfo archiveInfo, Solution solution){
String keyword = "", site;
ChatCache loadCache = null;
if (archiveInfo != null) {
try {
loadCache = ChatCacheController2.loadChatCache(archiveInfo);
} catch (Exception e) {
System.out.println("从本地加载存档失败");
solution.setAnswer("从本地加载存档失败");
e.printStackTrace();
}
this.chatCache.setInfoPoint(loadCache.getInfoPoint());
this.chatCache.setGameEnv(loadCache.getGameEnv());
// this.historyInfoPoint = chatCache.getInfoPoint();
// this.gameEnv = chatCache.getGameEnv();
System.out.println("----------读档中------------");
site = loadCache.getInfoPoint().get("site");
String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site));
String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site));
solution.setAnswer(reply);
solution.setNext("nextStep=" + nextStep);
}else{
System.out.println("没有找到该存档");
}
}
//将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版
//@Override
public String varSlotReplace2(String text){
String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
String varElements[] = {}, result = "";
String keyword, variable, variableSlot, reply = text;
Matcher m = replacePattern.matcher(reply);
while (m.find()) {
variable = m.group(1);
varElements = variable.split("_");
variableSlot = "${" + variable + "}";
switch (varElements[0]){
//如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。
case "globalVariable":
reply = reply.replace(variableSlot, historyInfoPoint.get(variable));
case "npc":
result = gameEnv.queryNpcAttrByNpcName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result);
case "goods":
result = gameEnv.queryGoodsAttrByGoodsName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result);
case "map":
System.out.println("地图替换还没写");
default:
if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){
reply = reply.replace(variableSlot, curInfoPoint.get(variable));
}else if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")){
reply = reply.replace(variableSlot, historyInfoPoint.get(variable));
}
}
}
return reply;
}
} }
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