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 {
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
......
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.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