Commit 078b5540 by hxw

修复bug、添加automatchURL等字段

parent 32c5a920
......@@ -3,6 +3,7 @@ import requests
import json
from Action import *
import sys;
import os
reload(sys);
sys.setdefaultencoding('utf8');
......@@ -22,12 +23,12 @@ class BackgroundConfig():
for line in config:
if line.strip() == "":
continue
name,value = line.split("=")
name,value = line.split("|")
self.CONFIG_DIC[name] = value.strip()
def reload_background_config(self,userName,botName):
try:
userFile = open(userName+"-"+botName+'-config.data','r')
userFile = open("data/"+userName+"-"+botName+'-config.data','r')
'''
actionList = []
action = {}
......@@ -45,50 +46,120 @@ class BackgroundConfig():
except IOError:
data = []
return {"configList":data}
'''
保存配置文件
'''
def save_background_config(self,parameters):
flag = 1
try:
userName = parameters["userName"].strip()
configList = parameters["configList"]
botName = parameters["botName"].strip()
self.config_string += self.load_extra_user_info(userName,botName)
for config in configList:
currentPremiseList = config["currentPremiseList"]
reply = config["reply"].strip() if config["reply"] != "" else " "
nextStep = config["nextStep"].strip()
nextStep = config["nextStep"].strip() if config["nextStep"] != "" else " "
feature = "match,post("+config["postURL"].strip()+")" if config["doPost"] else "match"
historyPremiseList = config["historyPremiseList"]
if nextStep == "" :
flag = 2
break
if len(currentPremiseList) == 1 and currentPremiseList[0]["keywords"] == "":
flag = 3
break
curPreStr = ','.join([currentPremise["actionName"]+"="+currentPremise["keywords"] for currentPremise in currentPremiseList])
curPreStr = ','.join([currentPremise["actionName"]+"=+"+currentPremise["keywords"].lstrip("+").split("-")[0] for currentPremise in currentPremiseList])
if historyPremiseList != [] and historyPremiseList[0]["keywords"] != "":
hisPreStr = ','.join([historyPremise["actionName"]+"="+historyPremise["keywords"] for historyPremise in historyPremiseList])
hisPreStr = ','.join([historyPremise["actionName"]+"=+"+historyPremise["keywords"].lstrip("+").split("-")[0] for historyPremise in historyPremiseList])
else:
hisPreStr = ""
if hisPreStr == "":
config_line = curPreStr + "| |"+"match|=>|"+reply+"|nextStep="+nextStep+'\n'
config_line = curPreStr + "| |"+feature+"|=>|"+reply+"|nextStep="+nextStep+'\n'
else:
config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n'
config_line = curPreStr + "|"+hisPreStr+"|"+feature+"|=>|"+reply+"|nextStep="+nextStep+'\n'
self.config_string += config_line
print self.config_string
print self.config_string,flag
if flag == 1:
userData = open(userName+"-"+botName+'-config.data','w')
userData = open("data/"+userName+"-"+botName+'-config.data','w')
pickle.dump(parameters,userData)
userData.close()
except KeyError:
except KeyError as e:
print repr(e)
flag = 2
return flag
def post_bg_config(self,userName):
url= self.CONFIG_DIC["config_post_url"]
payload= {'userName':userName,'config_string':self.config_string}
'''
从用户之前创建的action中获取额外信息,如设为active的action
'''
def load_extra_user_info(self,userName,botName):
extra_info = ""
data_file = "data/"+userName+"-"+botName+'-action.data'
if os.path.isfile(data_file):
user_data = {}
with open(data_file,'r') as f:
user_data = pickle.load(f)
conditionList = user_data["conditionList"]
for condition in conditionList:
if condition["active"]:
extra_info += "-extraInfo-|activeAction|"+condition["conditionName"]+"\n"
return extra_info
def change_bg_config(self,userName,botName,conditionList):
data_file = "data/"+userName+"-"+botName+'-config.data'
print "data_file:",data_file
if os.path.isfile(data_file):
user_data = {}
with open(data_file,'r') as f:
user_data = pickle.load(f)
condition_name_list = [condition["conditionName"] for condition in conditionList]
config_list = user_data["configList"]
config_list_new = []
for config in config_list:
currentPremiseList_new = []
config["nextStep"] = config["nextStep"] if config["nextStep"] in condition_name_list else ""
currentPremiseList = config["currentPremiseList"]
currentPremiseList = [{"actionName":premise["actionName"],"keywords":premise["keywords"],"question":premise["question"]}
if premise["actionName"] in condition_name_list
else {"actionName":"","keywords":"","question":premise["question"]}
for premise in currentPremiseList]
empty_indicator = [1 if premise["actionName"] == "" else 0 for premise in currentPremiseList]
if sum(empty_indicator) == len(currentPremiseList):
continue
historyPremiseList = config["historyPremiseList"]
historyPremiseList = [{"actionName":premise["actionName"],"keywords":premise["keywords"],"question":premise["question"]}
if premise["actionName"] in condition_name_list
else {"actionName":"","keywords":"","question":premise["question"]}
for premise in historyPremiseList]
config["currentPremiseList"] = currentPremiseList
config["historyPremiseList"] = historyPremiseList
config_list_new.append(config)
user_data["configList"] = config_list_new
with open(data_file,'w') as f:
pickle.dump(user_data,f)
return 1
else:
return 1
def post_bg_config(self,botName):
url= self.CONFIG_DIC["config_update_url"]
payload= {'userName':botName,'config_string':self.config_string}
ret= requests.post(url,data=payload)
if(ret.status_code == 200):
......
......@@ -3,6 +3,7 @@ import pymysql
class SQLHelper:
def __init__(self):
self.conn_dict = dict(host="192.168.1.81",port=3306,user="root",passwd="admin",db="chatCN",charset="utf8")
#self.conn_dict = dict(host="http://qcloud-sh1.chewrobot.com",port=3306,user="root",passwd="3g9^pWQs#ft7",db="chatCN",charset="utf8")
def query_userid_by_username(self,username):
try:
conn = pymysql.connect(**self.conn_dict)
......@@ -18,11 +19,64 @@ class SQLHelper:
else :
return -1
except Exception as e:
raise e
print repe(e)
finally:
cur.close()
conn.close()
def query_username_by_userid(self,userid):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "select username from users where id=%d"%int(userid)
print "xx"
cur = conn.cursor()
cur.execute(sql)
results = cur.fetchall()
conn.commit()
if len(results):
return results[0][0]
else:
return "error"
except Exception as e:
print repr(e)
finally:
cur.close()
conn.close()
def query_keyword_unit_by_userid(self,userid):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "select text from units where user_id=%d and name='keywords'"%int(userid)
cur = conn.cursor()
cur.execute(sql)
results = cur.fetchall()
conn.commit()
if len(results):
return results[0][0]
else:
return "error"
except Exception as e:
print repr(e)
finally:
cur.close()
conn.close()
def update_keyword_unit_by_userid(self,userid,keyword_str):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "update units set text = '%s' where name='keywords' and user_id=%d"%(keyword_str,userid)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
effect_row = cur.execute(sql)
conn.commit()
return effect_row
except Exception as e:
print repr(e)
finally:
cur.close()
conn.close()
def update_action_text_by_userid(self,userid,action_str):
try:
......@@ -33,11 +87,26 @@ class SQLHelper:
conn.commit()
return effect_row
except Exception as e:
raise e
print repr(e)
finally:
cur.close()
conn.close()
def update_url(self,bot_id,url):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "update users set url = '%s' where id= %d"%(url,bot_id)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
effect_row = cur.execute(sql)
conn.commit()
return effect_row
except Exception as e:
print repr(e)
finally:
cur.close()
conn.close()
'''
def create_new_bot(self,userName,botName)
try:
......
......@@ -25,10 +25,13 @@ def save_action():
action = Action()
dc = json.loads(request.get_data().decode("utf8"))
flag = action.generate_action(dc)
print dc
if flag == 1:
auth = request.headers['Authorization']
action.save_action(dc,auth)
if(dc["botId"] != ""):
bg_config = BackgroundConfig()
bg_config.change_bg_config(dc["userName"],dc["botName"],dc["conditionList"])
print flag
if flag == 1:
return "success"
......@@ -60,10 +63,11 @@ def save_background_config():
if request.method == 'POST':
bg_config = BackgroundConfig()
parameters = json.loads(request.get_data().decode("utf8"))
print parameters
flag = bg_config.save_background_config(parameters)
if flag == 1:
flag = bg_config.post_bg_config(parameters["userName"])
flag = bg_config.post_bg_config(parameters["botName"])
print flag
if flag == 1:
......
def min_ed(sent1,sent2):
l1 = len(sent1)
l2 = len(sent2)
matrix = [[0 for j in range(l2)] for i in range(l1)]
matrix[0][0] = 0
for i in range(1,l1):
matrix[i][0] = i
for j in range(1,l2):
matrix[0][j] = j
for i in range(1,l1):
for j in range(1,l2):
d = 1 if sent1[i] != sent2[j] else 0
matrix[i][j] = min(matrix[i][j-1]+1,matrix[i-1][j]+1,matrix[i-1][j-1]+d)
for i in range(l1):
for j in range(l2):
print matrix[i][j],
print ""
if __name__ == "__main__":
min_ed("#abc","#dcb")
action=select
strategythreshold=
automatchthreshold=
automatchurl=
serviceurl=
pattern=
conflict=
importance=
style=
backend_url=http://192.168.1.178:8081/bot/update
engine_url=http://192.168.1.81:6636/api/post/actions
action|select
strategythreshold|
automatchthreshold|0.5
pattern|
conflict|
importance|
style|
config_update_url|http://192.168.1.178:8081/bot/update
serviceURL|http://192.168.1.178:8081/bot/test
engine_url|http://192.168.1.81:6636/api/post/actions
options|disable_knowledge_qa,fast_understanding,no_parser
AutoMatchURL|http://dev01.centaurstech.com:5700/mermaid/?model=auto-train
......@@ -25,5 +25,10 @@ def login():
if __name__ == '__main__':
app.run(host="0.0.0.0",
port=8888,)
{u'userName': u'aaa', u'cdt_name_ls': [[250, u'rule0find0daikuan'], [251, u'rule0find0zhuangxiu'], [252, u'rule0find0dianti']], u'botName_yhm': u'xx', u'cate': [14], u'botId': u'275', u'conditionList': [{u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u8d2d\u4e70\u8d37\u6b3e', u'repeatKeywords': u'\u8d37\u6b3e-\u4e0d\u8d37\u6b3e'}], u'relationName': u'rule-find-daikuan', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u8d37\u6b3e\u653f\u7b56\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'daikuan', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}, {u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u623f\u5b50\u88c5\u4fee', u'repeatKeywords': u'\u6bdb\u576f\u623f+\u7cbe\u88c5+\u88c5\u4fee'}], u'relationName': u'rule-find-zhuangxiu', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u623f\u5b50\u88c5\u4fee\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'zhuangxiu', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}, {u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u623f\u5b50\u7535\u68af', u'repeatKeywords': u'\u7535\u68af'}], u'relationName': u'rule-find-dianti', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u7535\u68af\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'dianti', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}], u'botName': u'4183891231'}
......@@ -13,10 +13,10 @@ public class Condition {
public HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String,HashSet<String>> historyPremise = new HashMap<String,HashSet<String>>();
public HashMap<String,HashSet<String>> currentPremise = new HashMap<String,HashSet<String>>();
public String Answer;
public String nextStep;
public String feature;
public String indexName;
public String[] answer = {"",};
public String nextStep = "";
public String feature = "";
public String indexName = "";
//public ArrayList<String> indexName = new ArrayList<String>();
public Condition(int priority) {
......
......@@ -11,10 +11,16 @@ public class UserInfo {
this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = "";
this.userName = userName;
this.extraInfo = new HashMap<String,String>(){
{
put("activeAction","");
}
};
}
public HashMap<String,List<Condition>> conditionTable;
public String configStr;
public String userName;
public HashMap<String,String> extraInfo;
}
......@@ -7,6 +7,7 @@ import java.io.UnsupportedEncodingException;
public class MyFunc {
/**
* 将后台返回的数据转成json格式
*/
......@@ -17,6 +18,11 @@ public class MyFunc {
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr){
JSONObject jobj = new JSONObject();
jobj.put("returnString",returnStr);
return jobj.toString();
}
/**
* 通过get方法传递参数时需要对参数的编码进行转换
......
......@@ -73,13 +73,13 @@ public class ProcessQuestion {
public static Condition buildCondition(Condition condition,String line){
String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[];
element = line.trim().split("\\|=\\>\\|");
element = line.replace("\n","").split("\\|=\\>\\|");
premises = element[0].split("\\|");
feature = premises[2];
cur_premises = premises[0].split(",");
history_premises = premises[1].split(",");
next = element[1].split("\\|");
condition.Answer = next[0];
condition.answer = next[0].split("~");
//condition.nextStep = next[1];
//第二处
condition.nextStep = next[1].split("=")[1];
......@@ -104,7 +104,7 @@ public class ProcessQuestion {
* 逐行读取用户配置文件,并保存在userinfo.conditionTable中
*/
public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException {
String line;
String line,infoName,extraElements[];
HashMap<String, List<Condition>> conditionTable = new HashMap<String, List<Condition>>();
List<Condition> conditionList = null;
......@@ -112,15 +112,21 @@ public class ProcessQuestion {
while ((line = br.readLine()) != null) {
if (line.trim().equals(""))
continue;
line = line.replace("\n","");
//在用户信息中添加额外信息,如设为active的action
if(line.indexOf("-extraInfo-") != -1){
extraElements = line.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
}else {
Condition condition = new Condition();
condition = buildCondition(condition, line);
conditionList = conditionTable.get(condition.indexName);
if (conditionList == null)
conditionList = new ArrayList<Condition>();
conditionList.add(condition);
conditionTable.put(condition.indexName, conditionList);
}
userinfo.configStr += line + '\n';
Condition condition = new Condition();
condition = buildCondition(condition, line);
conditionList = conditionTable.get(condition.indexName);
if (conditionList == null)
conditionList = new ArrayList<Condition>();
conditionList.add(condition);
conditionTable.put(condition.indexName, conditionList);
}
userinfo.conditionTable = conditionTable;
......@@ -282,11 +288,14 @@ public class ProcessQuestion {
Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName;
AnswerNextStep ans = new AnswerNextStep();
ans.setAnswer(ansCondition.Answer);
//如果一条配置文件有多个答案,则随机选择一个答案
int randNum = (int) (Math.random() * ansCondition.answer.length);
ans.setAnswer(ansCondition.answer[randNum]);
//System.out.println(ans.getAnswer());
System.out.println("feature="+ansCondition.feature);
if(ansCondition.feature.indexOf("post") != -1){
postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint);
ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint);
}
try {
......@@ -310,6 +319,9 @@ public class ProcessQuestion {
}
}
//保存即将跳转的action名以供下一轮使用
historyInfoPoint.put("currentAction",ansCondition.nextStep);
ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context);
//context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint);
......@@ -362,7 +374,10 @@ public class ProcessQuestion {
keyName = kit.next();
if(keyName.equals("process")){
ans.setNext("nextStep="+jobj.get(keyName));
}else{
}else if(keyName.equals("solution")) {
ans.setAnswer((String) jobj.get(keyName));
}
else{
ans.setAnswer(ans.getAnswer().replace("{"+keyName+"}",jobj.getString(keyName)));
}
}
......
......@@ -18,22 +18,25 @@ import java.io.OutputStream;
import java.sql.SQLException;
import java.util.*;
/**
* GetAnswerServlet就是处理post请求并返回答案的入口
*/
@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"})
public class GetAnswerServlet extends HttpServlet {
/**
* GetAnswerServlet就是处理post请求并返回答案的入口
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String,String[]> curInfoPoint = request.getParameterMap();
Map<String,String[]> curInfoPoint = new HashMap<>(request.getParameterMap());
Map<String, String> historyInfoPoint = null;
AnswerNextStep bestMatch = null;
Condition ansCondition = null;
String ansJ,return_str="";
String ansJ,return_str="",state = "";
String chatKey = curInfoPoint.get("chat_key")[0];
ProcessQuestion process = new ProcessQuestion();
OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext();
//获得用户历史信息
historyInfoPoint = ChatCacheController.getChatCache(chatKey,context);
UserInfo userinfo = null;
......@@ -42,13 +45,12 @@ public class GetAnswerServlet extends HttpServlet {
//从servlet根据用户名查询用户信息
userinfo = process.userInfoQuery(request.getParameter("bot_name"),context);
} catch (SQLException e) {
state = "没找到bot名?";
e.printStackTrace();
}
//获得用户历史信息
historyInfoPoint = ChatCacheController.getChatCache(chatKey,context);
//如果historyInfoPoint不存在,就新建一个
if(historyInfoPoint == null) {
String k;
historyInfoPoint = new HashMap<String,String>();
......@@ -65,35 +67,67 @@ public class GetAnswerServlet extends HttpServlet {
Iterator<String> iit = curInfoPoint.keySet().iterator();
while(iit.hasNext()){
String k = iit.next();
//
System.out.print(k+": ");
String values[] = curInfoPoint.get(k);
if(values != null && !values[0].equals(" ") && !values[0].equals("") && !k.equals("chat_key") && !k.equals("action_name") && !k.equals("bot_name"))
return_str = return_str + " " + k + ":" + values[0] + " ";
//return_str = return_str + " " + k + ":" + values[0] + " ";
for(String v:values) {
System.out.print(v + " ");
}
System.out.println();
}
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator();
boolean unknown_flag = true;
while(iit.hasNext()){
String k = iit.next();
String values[] = curInfoPoint.get(k);
if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name"))
continue;
if(values != null && !values[0].equals("")) {
unknown_flag = false;
break;
}
}
String currentAction = "";
if(historyInfoPoint.containsKey("currentAction"))
currentAction = historyInfoPoint.get("currentAction");
else if(userinfo.extraInfo.containsKey("activeAction"))
currentAction = userinfo.extraInfo.get("activeAction");
else
currentAction = "";
if(unknown_flag && currentAction != ""){
String i[] = {"unknown",};
curInfoPoint.put(currentAction,i);
}
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试
ansCondition = process.getAnswer(curInfoPoint,historyInfoPoint,userinfo.conditionTable);
bestMatch = process.updateInfoGetBestMatch(ansCondition,curInfoPoint,historyInfoPoint,context,userinfo);
//process.updateDB(kw);
//System.out.println("Current time:" + System.currentTimeMillis());
if(context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime",System.currentTimeMillis());
if(System.currentTimeMillis() - (long)context.getAttribute("cacheUpdateTime") > 300000) {
ChatCacheController.updateChatCache4Delete(context);
context.setAttribute("cacheUpdateTime",System.currentTimeMillis());
if (state == "" && ansCondition.priority == 0)
state = "你好像哪里写错了";
if (state == "") {
bestMatch = process.updateInfoGetBestMatch(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
//process.updateDB(kw);
//System.out.println("Current time:" + System.currentTimeMillis());
if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > 300000) {
ChatCacheController.updateChatCache4Delete(context);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
}
bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
}else{
bestMatch = new AnswerNextStep(0,state,"nextStep=error");
}
bestMatch.setAnswer(" \n"+return_str+"\n " + bestMatch.getAnswer());
ansJ = MyFunc.toJson(bestMatch);
//System.out.println(ansJ);
System.out.println(ansJ);
out.write(ansJ.getBytes());
out.flush();
......
......@@ -12,13 +12,19 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* 发请求从本地文件夹重新加载某用户的配置文件
*/
@WebServlet(name = "ReloadConfigServlet",urlPatterns = {"/reload","/reload/"})
public class ReloadConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
boolean flag = true;
UserInfo userinfo = new UserInfo(userName);
File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt");
System.out.println(configFile.getAbsolutePath());
ServletContext context = this.getServletContext();
if(!configFile.exists()) {
response.setCharacterEncoding("utf-8");
......@@ -47,6 +53,7 @@ public class ReloadConfigServlet extends HttpServlet {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(111);
PrintWriter out = response.getWriter();
out.println("更新失败配置文件有误:" + userName +".txt\\\n");
......@@ -55,7 +62,7 @@ public class ReloadConfigServlet extends HttpServlet {
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
PrintWriter out = response.getWriter();
out.println("更新成功+ “ ");
out.println("重新加载成功");
out.flush();
out.close();
......
......@@ -24,7 +24,8 @@ import java.util.List;
public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。
String actionName,feature,line,element[],pair[],next[],cur_premises[],history_premises[],premises[];
request.setCharacterEncoding("UTF-8");
String line,extraElements[];
ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext();
String userName = request.getParameter("userName");
......@@ -41,9 +42,18 @@ public class UpdateServlet extends HttpServlet {
while((line = br.readLine()) != null){
System.out.println(line);
if(line.trim().equals(""))
continue;
line = line.replace("\n","");
//在用户信息中添加额外信息,如设为active的action
if(line.indexOf("-extraInfo-") != -1){
extraElements = line.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]);
userinfo.configStr += line+"\n";
continue;
}
//line = MyFunc.convert2Utf8(line.trim());
userinfo.configStr += line+"\n";
Condition condition = new Condition();
......@@ -59,8 +69,6 @@ public class UpdateServlet extends HttpServlet {
userinfo.conditionTable.put()
}
*/
} catch(Exception e ){
System.out.println("配置文件有误!");
flag = false;
......@@ -82,6 +90,7 @@ public class UpdateServlet extends HttpServlet {
out.println("---"+error);
out.flush();
out.close();
System.out.println("error");
}
else{
......@@ -91,12 +100,13 @@ public class UpdateServlet extends HttpServlet {
out.println("更新成功+ “ ");
out.flush();
out.close();
System.out.println("success");
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
context.setAttribute(userName,userinfo);
String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
if(!dir.exists())
dir.mkdir();
if(!file.exists()){
......@@ -110,7 +120,6 @@ public class UpdateServlet extends HttpServlet {
}
//request.;
}
......
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