Commit 1214cb0d by hxw

添加游戏设计代码

parent c9c78abf
......@@ -6,6 +6,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class SqlHelper {
private Connection conn = null;
......@@ -99,6 +100,37 @@ public class SqlHelper {
return result;
}
public boolean deleteConfigByIdGroup(int botId, List<Integer> idGroup) throws SQLException {
StringBuilder inClause = new StringBuilder();
boolean firstValue = true;
int batchSize = idGroup.size();
for (int i=0; i < batchSize; i++) {
inClause.append('?');
if ( firstValue ) {
firstValue = false;
} else {
inClause.append(',');
}
}
String sql = "delete from chatbot_config where botId = ? and configId in (" + inClause.toString() + ')';
String userName = "";
boolean b = true;
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(botId));
b = ps.execute();
ps.close();
return b;
}catch(Exception e){
e.printStackTrace();
}
return b;
}
}
......@@ -12,6 +12,7 @@ import java.util.HashSet;
public class Condition {
public int priority = -1;
public int activePriority = 0; //如果本condition被其他condition激活
public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级
public HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String,HashSet<String>> historyPremise = new HashMap<String,HashSet<String>>();
public HashMap<String,HashSet<String>> currentPremise = new HashMap<String,HashSet<String>>();
......
package entity;
public class ConfigurationItem {
}
package gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ElementConstructor {
List<JSONObject> configDataList = new ArrayList<JSONObject>();
String userName;
String configText = "";
public void construct(){}
public List<JSONObject> getConfigDataList() {
return configDataList;
}
public void ElementConstructor(String userName){
this.userName = userName;
}
public String getConfigText() {
return configText;
}
/**
* 构造参数配置文件的json版
*/
public void buildJconfig(){
}
}
package gameDesign;
/**
* 弗洛伊德算法,用于构造地图时求最短路径
*/
public class Floyd {
/** 表示正无穷 */
int MAX_WEIGHT = Integer.MAX_VALUE;
/**路径矩阵*/
int[][] pathMatirx;
/**前驱表*/
int[][] preTable;
public void findShortestPath(int[][] matrix, int length){
//路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。
pathMatirx = new int[length][length];
//前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值
preTable = new int[length][length];
/*
System.out.println("matrix");
for (int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
*/
//初始化D,P
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
pathMatirx[i][j] = matrix[i][j];
preTable[i][j] = j;
}
}
//循环 中间经过顶点
for (int k = 0; k < length; k++) {
//循环所有路径
for (int m = 0; m < length; m++) {
for (int n = 0; n < length; n++) {
int mn = pathMatirx[m][n];
int mk = pathMatirx[m][k];
int kn = pathMatirx[k][n];
int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT)? MAX_WEIGHT : mk + kn;
if (mn > addedPath) {
//如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个
pathMatirx[m][n] = addedPath;
//前驱设置为经过下标为k的顶点
preTable[m][n] = preTable[m][k];
}
}
}
}
/*
System.out.println("pathMatrix");
for (int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
System.out.print(pathMatirx[i][j] + " ");
}
System.out.println();
}
*/
}
/**
* 打印 所有最短路径
*/
public void printPath(int[][] matrix, int length) {
for (int m = 0; m < length; m++) {
for (int n = m + 1; n < length; n++) {
int k = preTable[m][n];
System.out.print("(" + m + "," + n + ")" + pathMatirx[m][n] + ": ");
System.out.print(m);
while (k != n) {
System.out.print("->" + k);
k = preTable[k][n];
}
System.out.println("->" + n);
}
System.out.println();
}
}
}
package gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import db.SqlHelper;
import entity.UserInfo;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class MapConstructor extends ElementConstructor{
int counter = 1;
int[][] matrix;
int locationNum;
HashMap<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>();
JSONArray locations = null;
SqlHelper helper = null;
public MapConstructor(SqlHelper helper) {
super();
this.helper = helper;
}
public void constructGreph(JSONArray locations) {
JSONObject jobj = null;
int locationId, index;
//ArrayList<ArrayList<Integer>> matrix= new ArrayList<ArrayList<Integer>>();
//ArrayList<Integer> vec1d = new ArrayList<Integer>();
locationNum = locations.size();
for (int i = 0; i < locationNum; i++) {
jobj = locations.getJSONObject(i);
jobj.put("index", i);
locationId = (Integer) jobj.get("id");
id2j.put(locationId, jobj);
}
//邻接矩阵初始化
matrix = new int[locationNum][locationNum];
for (int i = 0; i < locationNum; i++) {
for (int j = 0; j < locationNum; j++) {
matrix[i][j] = Integer.MAX_VALUE;
}
}
for (int i = 0; i < locationNum; i++) {
List<Integer> neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class);
for (int neighbourId : neighbours) {
JSONObject neighbourObject = id2j.get(neighbourId);
index = (Integer) neighbourObject.get("index");
matrix[i][index] = 1;
matrix[index][i] = 1;
}
}
}
public void construct(JSONObject jsonObject){
JSONArray locations = jsonObject.getJSONArray("locations");
this.locations = locations;
//通过邻接表构造邻接矩阵
constructGreph(locations);
//用弗洛伊德算法求最短路径
Floyd floyd = new Floyd();
floyd.findShortestPath(matrix, locationNum);
floyd.printPath(matrix, locationNum);
generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereIam(jsonObject);
generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
//
}
/**
* 生成‘我在哪里’所需要的配置文件
*/
public void generateWhereIam(JSONObject jsonObject){
String zainaKeywords = (String)jsonObject.get("zaina");
configText += "zaina=" + zainaKeywords + "| "
+ "|match|=>|你在{site-2}|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
}
/**
* 生成‘怎么去哪里’所需要的配置文件
*/
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String zenmequKeywords = (String)jsonObject.get("zenmequ");
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
placeA = (String)locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name");
placeKeywords = zenmequKeywords.replace("地点", placeB);
if(i == j){
configText += "zenmequ=" + placeKeywords + "|site=" + placeA
+ "|match|=>|" + "你已经在" + placeB + "了|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
continue;
};
if(pathMatirx[i][j] == 1){
configText += "zenmequ=" + placeKeywords + "|site=" + placeA
+ "|match|=>|" + placeB + "就在附近哦|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
int k = preTable[i][j];
pathNode = "";
while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name");
k = preTable[k][j];
}
configText += "zenmequ=" + placeKeywords + "|site=" + placeA + "|match|=>|经过" + pathNode
+ "就可以到达" + placeB + "|nextStep=yaozuo|status=waiting|configId=" + counter + "\n";
counter++;
}
}
}
}
/**
* 生成‘我能去哪里’所需要的配置文件
*/
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
String nengqunaKeywords = (String)jsonObject.get("nengquna");
String placeA, placeB, pathNode;
for(int i = 0;i < locationNum;i++){
placeA = (String)locations.getJSONObject(i).get("name");
pathNode = "";
for(int j = 0;j < locationNum;j++){
if(pathMatirx[i][j] == 1) {
placeB = (String) locations.getJSONObject(j).get("name");
pathNode += "、" + placeB;
}
}
configText += "nengquna=" + nengqunaKeywords + "|site=" + placeA
+ "|match|=>|你可以去" + pathNode + "|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
}
}
/**
* 生成‘我要去那里’所需要的配置文件
*/
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject jsonObject){
String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String qunaKeywords = (String)jsonObject.get("quna");
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
placeA = (String)locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name");
descriptionB = (String)locations.getJSONObject(j).get("description");
placeKeywords = qunaKeywords.replace("地点", placeB);
if(i == j){
configText += "quna=" + placeKeywords + "|site=" + placeA
+ "|match|=>|" + "你已经在" + placeB + "了|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
continue;
};
if(pathMatirx[i][j] == 1){
configText += "quna=" + placeKeywords + "|site=" + placeA
+ "|match,updateKnowledge-<-site:" + placeB + "|=>|" + descriptionB + "|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
int k = preTable[i][j];
pathNode = "";
while (k != j) {
pathNode += (String)locations.getJSONObject(k).get("name");
k = preTable[k][j];
}
configText += "quna=" + placeKeywords + "|site=" + placeA + "|match|=>|从"
+ placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode
+ "才能到达" + placeB + "|nextStep=yaozuo|status=waiting|configId=" + counter + "\n";
counter++;
}
}
}
}
}
package gameDesign;
public class SceneConstructor {
}
......@@ -11,7 +11,7 @@ public class ChatCacheController {
/**
* 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点)
* @return 历史信息点,引擎在上一轮(多轮)识别的关键字
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context){
Map<String, String> historyInfoPoint = null;
......
package processing;
import entity.Condition;
import entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.containsKey(Integer.parseInt(configId))) {
Condition oldCondition = new Condition();
oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(Integer.parseInt(configId)));
String conditionName = oldCondition.indexName;
if (userinfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userinfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userinfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == Integer.parseInt(configId)) {
condIter.remove();
}
}
}
userinfo.id2config.remove(Integer.parseInt(configId));
} else{
System.out.println("未找到要删除的configId");
}
return true;
}
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
for(int configId:idGroup) {
if (userInfo.id2config.containsKey(configId)) {
Condition oldCondition = new Condition();
oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId));
String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == configId) {
condIter.remove();
}
}
}
userInfo.id2config.remove(configId);
} else {
System.out.println("未找到要删除的configId:" + configId);
}
}
return true;
}
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[];
if(dataPair.length > 1)
conditionNameList = dataPair[1].split(",");
else
conditionNameList = new String[]{"emptySet",};
condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(userinfo.conditionTable.get(conditionNameList[0]) == null){
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(conditionNameList[0], conditionList);
}
userinfo.conditionTable.get(conditionNameList[0]).add(condition);
userinfo.id2config.put(Integer.parseInt(configId), configLine);
return true;
}
public static boolean updateConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[] = dataPair[1].split(",");
condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.get(condition.id) == null){
}else {
for (String conditionName : conditionNameList) {
if (userinfo.conditionTable.get(conditionName) == null) {
continue;
}
List<Condition> conditionList = userinfo.conditionTable.get(conditionName);
int condLength = conditionList.size();
for (int i = 0; i < condLength; i++) {
if (conditionList.get(i).id == Integer.parseInt(configId)) {
conditionList.set(i, condition);
}
}
}
userinfo.id2config.put(Integer.parseInt(configId), configLine);
}
return true;
}
public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
ProcessQuestion process = new ProcessQuestion();
if(context.getAttribute(userName) == null){
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
return true;
}
public static String writeConfigText(String userName, UserInfo userinfo) throws IOException {
System.out.println("p");
System.out.println(userName);
String CONFIG_DIR = System.getProperty("user.dir")+"/config", configText;
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
String returnMessage = "success";
if(!dir.exists())
dir.mkdir();
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if(!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
Iterator<Integer> idIter = userinfo.id2config.keySet().iterator();
while (idIter.hasNext()) {
int id = idIter.next();
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
}catch(Exception e){
e.printStackTrace();
returnMessage = "config file write error";
}finally {
bw.close();
fw.close();
}
return returnMessage;
}
}
......@@ -3,7 +3,11 @@ package processing;
import entity.AnswerNextStep;
import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
......@@ -30,6 +34,27 @@ public class MyFunc {
}
/**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据
* @param request
* @return json字符串
*/
public static String readJSONString(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try{
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
json.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 通过get方法传递参数时需要对参数的编码进行转换
*/
public static String convert2Utf8(String s){
......
......@@ -61,7 +61,7 @@ public class ProcessQuestion {
UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]);
try {
userinfo = buildUserInfo(br, userinfo);
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
System.out.println(userinfo.userName + ".txt 有误");
......@@ -81,7 +81,7 @@ public class ProcessQuestion {
BufferedReader br = new BufferedReader(new StringReader(""));
UserInfo userinfo = new UserInfo(userName);
try {
userinfo = buildUserInfo(br, userinfo);
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
System.out.println(userinfo.userName + "-post数据有误");
......@@ -94,7 +94,7 @@ public class ProcessQuestion {
UserInfo userinfo = new UserInfo(userName);
try {
userinfo = buildUserInfo(br, userinfo);
userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
System.out.println(userinfo.userName + ".txt 有误");
......@@ -119,6 +119,12 @@ public class ProcessQuestion {
cur_premises = premises[0].split(",");
history_premises = premises[1].split(",");
if(premises.length < 4)
condition.auxiliaryPriority = 0;
else
condition.auxiliaryPriority = Integer.parseInt(premises[3].split("=")[1]);
next = element[1].split("\\|");
if(next.length < 4)
return condition;
......@@ -149,12 +155,26 @@ public class ProcessQuestion {
return condition;
}
/**
* 逐行读取用户配置文件,并保存在userinfo.conditionTable中
*
* @param br
* @param userinfo
* @param overRide 覆盖之前的状态表
* @return
* @throws IOException
*/
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException {
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException {
String line,infoName,extraElements[];
HashMap<String, List<Condition>> conditionTable = new HashMap<String, List<Condition>>();
HashMap<String, List<Condition>> conditionTable = null;
if(overRide)
conditionTable = new HashMap<String, List<Condition>>();
else {
conditionTable = userinfo.conditionTable;
}
List<Condition> conditionList = null;
......@@ -335,7 +355,7 @@ public class ProcessQuestion {
if(condition.feature.contains("activate")){
activateConfig(extraActivatedConfig, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
} else if(condition.priority > bestMatch.priority)
} else if((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority))
bestMatch = condition;
}
}
......@@ -569,20 +589,6 @@ public class ProcessQuestion {
try {
/*
String keyword1, keyword2;
while (it.hasNext()) {
actionName = it.next();
keyword1 = curInfoPoint.get(actionName)[0];
keyword2 = historyInfoPoint.get(actionName);
if (keyword2 != null && !keyword2.equals(" ") && !keyword2.equals("")) {
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2));
}
if (keyword1 != null) {
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里
}
}
*/
it = historyInfoPoint.keySet().iterator();
String keyword1, keyword2;
......@@ -635,23 +641,6 @@ public class ProcessQuestion {
}
/*
// 根据hisInfoPoint中的key来更新历史信息,前提是在关键词单元不加simple_post
it = historyInfoPoint.keySet().iterator();
String keyword1, keyword2;
while (it.hasNext()) {
actionName = it.next();
if(curInfoPoint.get(actionName) != null){
keyword1 = curInfoPoint.get(actionName)[0];
keyword2 = historyInfoPoint.get(actionName);
if(! keyword2.equals("")){
historyInfoPoint.put(actionName, keyword1);
}
}
}
*/
ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context);
//context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint);
......@@ -686,7 +675,7 @@ public class ProcessQuestion {
key = it.next();
values = curInfoPoint.get(key);
if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key))
debugInfo += (" " + key + ":\'" + values[0] + "\' ");
debugInfo += (" " + key + ":\'" + values[0] + "\' ");
}
debugInfo += ")(已知:";
it = historyInfoPoint.keySet().iterator();
......@@ -695,10 +684,10 @@ public class ProcessQuestion {
key = it.next();
value = historyInfoPoint.get(key);
if(value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key))
debugInfo += (" " + key + ":\'" + value + "\' ");
debugInfo += (" " + key + ":\'" + value + "\' ");
}
ans.setAnswer( debugInfo + ") </font>" + ans.getAnswer());
ans.setAnswer( debugInfo + ")</font>" + ans.getAnswer());
}
......@@ -867,6 +856,7 @@ public class ProcessQuestion {
if(pair.length > 1) {
try {
//做数字加法
if (pair[1].startsWith("+")) {
if(keyword == null || keyword.equals(""))
keyword = "0";
......@@ -879,7 +869,7 @@ public class ProcessQuestion {
int offset = Integer.parseInt(pair[1].substring(1));
pair[1] = String.valueOf(number + offset);
}
//做数字减法
} else if (pair[1].startsWith("-")) {
if(keyword == null || keyword.equals(""))
keyword = "0";
......@@ -892,10 +882,12 @@ public class ProcessQuestion {
int offset = Integer.parseInt(pair[1].substring(1));
pair[1] = String.valueOf(number - offset);
}
//做字符串累加
} else if (pair[1].startsWith("str+")) {
if(keyword == null || keyword.equals(""))
keyword = "";
pair[1] = keyword + pair[1].substring(4);
//做字符串删除
} else if (pair[1].startsWith("str-")) {
if(keyword == null || keyword.equals(""))
keyword = "";
......@@ -938,4 +930,6 @@ public class ProcessQuestion {
}
}
package servlet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import db.SqlHelper;
import entity.Condition;
import entity.UserInfo;
import gameDesign.MapConstructor;
import processing.MyFunc;
import processing.ProcessQuestion;
import processing.ConditionTableController;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.List;
@WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer botId;
String userName = null;
ServletContext context = this.getServletContext();
boolean flag;
SqlHelper helper = null;
try {
helper = new SqlHelper();
} catch (SQLException e) {
e.printStackTrace();
}
//读取并解析json数据
String jsonStr = MyFunc.readJSONString(request);
if(context.getAttribute(userName) == null){
ProcessQuestion.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(jsonStr != null && !jsonStr.equals("")){
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
botId = (Integer)jsonObject.get("botId");
userName = (String)jsonObject.get("userName");
List<Integer> idGroup = JSONArray.parseArray(jsonObject.getJSONArray("configIdGroup").toJSONString(), Integer.class);
//清空之前生成的配置条目
if(idGroup.size() > 0) {
try {
flag = clearOldConfig(botId, idGroup, userinfo, helper);
} catch (SQLException e) {
e.printStackTrace();
}
}
MapConstructor mapConst = new MapConstructor(helper);
mapConst.construct(jsonObject);
StringReader sr = new StringReader(mapConst.getConfigText());
BufferedReader br = new BufferedReader(sr);
ProcessQuestion.buildUserInfo(br, userinfo, false);
ConditionTableController.writeConfigText(userName, userinfo);
}
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(111);
PrintWriter out = response.getWriter();
out.println("完成\\\n");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public boolean clearOldConfig(int botId, List<Integer> idGroup, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException {
boolean deleteFlag = helper.deleteConfigByIdGroup(botId, idGroup);
boolean deleteFlag2 = ConditionTableController.batchDeleteConfig(userInfo.userName, idGroup, userInfo);
return deleteFlag && deleteFlag2;
}
}
package servlet;
import entity.Condition;
import entity.UserInfo;
import processing.ProcessQuestion;
import processing.ConditionTableController;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
......@@ -11,10 +11,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@WebServlet(name = "UpdateSingleConfigServlet",urlPatterns = {"/update2"})
public class UpdateSingleConfigServlet extends HttpServlet {
......@@ -31,17 +27,17 @@ public class UpdateSingleConfigServlet extends HttpServlet {
System.out.println("11");
switch (processType) {
case "insert_config":
insertConfig(userName, configId, data, context);
ConditionTableController.insertConfig(userName, configId, data, context);
break;
case "update_config":
deleteConfig(userName, configId, data, context);
insertConfig(userName, configId, data, context);
ConditionTableController.deleteConfig(userName, configId, data, context);
ConditionTableController.insertConfig(userName, configId, data, context);
break;
case "delete_config":
deleteConfig(userName, configId, data, context);
ConditionTableController.deleteConfig(userName, configId, data, context);
break;
case "extra_info":
updateExtraInfo(userName, data, context);
ConditionTableController.updateExtraInfo(userName, data, context);
break;
case "batch_update":
batchUpdate(userName, data, context);
......@@ -74,157 +70,12 @@ public class UpdateSingleConfigServlet extends HttpServlet {
}
public boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[];
if(dataPair.length > 1)
conditionNameList = dataPair[1].split(",");
else
conditionNameList = new String[]{"emptySet",};
condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(userinfo.conditionTable.get(conditionNameList[0]) == null){
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(conditionNameList[0], conditionList);
}
userinfo.conditionTable.get(conditionNameList[0]).add(condition);
userinfo.id2config.put(Integer.parseInt(configId), configLine);
return true;
}
public boolean updateConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[] = dataPair[1].split(",");
condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.get(condition.id) == null){
}else {
for (String conditionName : conditionNameList) {
if (userinfo.conditionTable.get(conditionName) == null) {
continue;
}
List<Condition> conditionList = userinfo.conditionTable.get(conditionName);
int condLength = conditionList.size();
for (int i = 0; i < condLength; i++) {
if (conditionList.get(i).id == Integer.parseInt(configId)) {
conditionList.set(i, condition);
}
}
}
userinfo.id2config.put(Integer.parseInt(configId), configLine);
}
return true;
}
public boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.containsKey(Integer.parseInt(configId))) {
Condition oldCondition = new Condition();
oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(Integer.parseInt(configId)));
String conditionName = oldCondition.indexName;
if (userinfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userinfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userinfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == Integer.parseInt(configId)) {
condIter.remove();
}
}
}
userinfo.id2config.remove(Integer.parseInt(configId));
} else{
System.out.println("未找到要删除的configId");
}
return true;
}
public boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
ProcessQuestion process = new ProcessQuestion();
if(context.getAttribute(userName) == null){
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
return true;
}
public String writeConfig(String userName, ServletContext context) throws IOException {
String returnMessage = "";
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String CONFIG_DIR = System.getProperty("user.dir")+"/config", configText;
context.setAttribute(userName,userinfo);
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
String returnMessage = "success";
if(!dir.exists())
dir.mkdir();
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if(!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
Iterator<Integer> idIter = userinfo.id2config.keySet().iterator();
while (idIter.hasNext()) {
int id = idIter.next();
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
}catch(Exception e){
e.printStackTrace();
returnMessage = "config file write error";
}finally {
bw.close();
fw.close();
}
returnMessage = ConditionTableController.writeConfigText(userName, userinfo);
return returnMessage;
}
......@@ -233,7 +84,7 @@ public class UpdateSingleConfigServlet extends HttpServlet {
public void batchUpdate(String userName, String data, ServletContext context) throws IOException {
BufferedReader br = new BufferedReader(new StringReader(data));
UserInfo userinfo = new UserInfo(userName);
userinfo = ProcessQuestion.buildUserInfo(br, userinfo);
userinfo = ProcessQuestion.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo);
System.out.println("batchupdate");
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment