Commit 04bd4be9 by 赵国君

殷勤穿过来的表单,你我替换

parent 3e9933cf
package com.qiwu.chatbotbackend.actiongenerate.DB; package com.qiwu.chatbotbackend.actiongenerate.DB;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.qiwu.chatbotbackend.actiongenerate.entity.EngineUnit; import com.qiwu.chatbotbackend.actiongenerate.entity.EngineUnit;
import com.qiwu.chatbotbackend.db.C3p0Utils; import com.qiwu.chatbotbackend.db.C3p0Utils;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class EngineUtils { public class EngineUtils {
private Connection conn = null; private Connection conn = null;
public EngineUtils() throws SQLException { public EngineUtils() throws SQLException {
conn = C3p0Utils.getEngineConnection(); conn = C3p0Utils.getEngineConnection();
} }
public void destroy() { public void destroy() {
if (conn != null) { if (conn != null) {
try { try {
conn.close(); conn.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public String queryKeywordUnitText(int botId){ public String queryKeywordUnitText(int botId){
String sql = "select text from units where user_id = ? and name = 'keywords'"; String sql = "select text from units where user_id = ? and name = 'keywords'";
String keywordText = ""; String keywordText = "";
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,botId); ps.setInt(1,botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()){ if(rs.next()){
keywordText = (rs.getString("text")); keywordText = (rs.getString("text"));
} }
ps.close(); ps.close();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return keywordText; return keywordText;
} }
public Boolean updateKeywordUnitText(int botId, String keywordText){ public Boolean updateKeywordUnitText(int botId, String keywordText){
Boolean b = true; Boolean b = true;
String sql = "update units set text = ? where user_id = ? and name = 'keywords'"; String sql = "update units set text = ? where user_id = ? and name = 'keywords'";
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, keywordText); ps.setString(1, keywordText);
ps.setInt(2,botId); ps.setInt(2,botId);
b = ps.executeUpdate() == 1; b = ps.executeUpdate() == 1;
ps.close(); ps.close();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return b; return b;
} }
public Boolean updateWelcomeText(int botId, String welcome){ public Boolean updateWelcomeText(int botId, String welcome){
boolean b; boolean b;
try { try {
String sql = "update users set welcome = ? where id=?"; String sql = "update users set welcome = ? where id=?";
PreparedStatement ps1 = conn.prepareStatement(sql); PreparedStatement ps1 = conn.prepareStatement(sql);
ps1.setString(1, welcome + "#welcome"); ps1.setString(1, welcome + "#welcome");
ps1.setInt(2, botId); ps1.setInt(2, botId);
b = ps1.executeUpdate() == 1; b = ps1.executeUpdate() == 1;
ps1.close(); ps1.close();
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
} }
public Map<Integer, String> queryConditionPatternText(int botId, List<String> patternRelationList){ public Map<Integer, String> queryConditionPatternText(int botId, List<String> patternRelationList){
String sql = "select user_id, text from `users` join `units` on users.id = units.user_id where users.username in ('" + Joiner.on("','").join(patternRelationList)+ "') and units.name = 'actions'"; String sql = "select user_id, text from `users` join `units` on users.id = units.user_id where users.username in ('" + Joiner.on("','").join(patternRelationList)+ "') and units.name = 'actions'";
String keywordText = ""; String keywordText = "";
Map<Integer, String> patternTextMap = new HashMap<Integer, String>(); Map<Integer, String> patternTextMap = new HashMap<Integer, String>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
//ps.setString(1, Joiner.on(",").join(patternRelationList)); //ps.setString(1, Joiner.on(",").join(patternRelationList));
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
while(rs.next()){ while(rs.next()){
patternTextMap.put(rs.getInt("user_id"), rs.getString("text")); patternTextMap.put(rs.getInt("user_id"), rs.getString("text"));
} }
ps.close(); ps.close();
rs.close(); rs.close();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return patternTextMap; return patternTextMap;
} }
public Map<Integer, EngineUnit> queryUnitsByIdList(List<Integer> idList){ public Map<Integer, EngineUnit> queryUnitsByIdList(List<Integer> idList){
String sql = "select user_id, name, text from units where user_id in (" + Joiner.on(",").join(idList) + ") and name in ('actions','keywords')"; String sql = "select user_id, name, text from units where user_id in (" + Joiner.on(",").join(idList) + ") and name in ('actions','keywords')";
Integer id; Integer id;
Map<Integer, EngineUnit> id2unit= new HashMap<Integer, EngineUnit>(); Map<Integer, EngineUnit> id2unit= new HashMap<Integer, EngineUnit>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
//ps.setArray(1, idList.toArray()); //ps.setArray(1, idList.toArray());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
while(rs.next()){ while(rs.next()){
id = rs.getInt("user_id"); id = rs.getInt("user_id");
if(id2unit.get(id) == null){ if(id2unit.get(id) == null){
id2unit.put(id, new EngineUnit()); id2unit.put(id, new EngineUnit());
} }
switch(rs.getString("name")){ switch(rs.getString("name")){
case "actions": case "actions":
id2unit.get(id).setActions(rs.getString("text")); id2unit.get(id).setActions(rs.getString("text"));
break; break;
case "keywords": case "keywords":
id2unit.get(id).setKeywords(rs.getString("text")); id2unit.get(id).setKeywords(rs.getString("text"));
break; break;
} }
} }
ps.close(); ps.close();
rs.close(); rs.close();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return id2unit; return id2unit;
} }
public String queryBotAccountByBotId(int botId){ public String queryBotAccountByBotId(int botId){
String sql = "select username from users where id= ?"; String sql = "select username from users where id= ?";
String botAccount = ""; String botAccount = "";
try { try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId); ps.setInt(1, botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if (rs.next()) if (rs.next())
botAccount = rs.getString("username"); botAccount = rs.getString("username");
ps.close(); ps.close();
rs.close(); rs.close();
conn.close(); conn.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return botAccount; return botAccount;
} }
public String queryBotNickNameByName(String userName){
String sql = "select nickname from users where username= ?";
String nickname = "";
try {
} PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ResultSet rs = ps.executeQuery();
if (rs.next())
nickname = rs.getString("nickname");
ps.close();
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return nickname;
}
}
...@@ -846,19 +846,19 @@ public class ActionUtils { ...@@ -846,19 +846,19 @@ public class ActionUtils {
conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_head", new HashSet<String>()); conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_head", new HashSet<String>());
conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_tail", new HashSet<String>()); conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_tail", new HashSet<String>());
String condTemple = patternConditionJson.toJSONString(); String condTemple = patternConditionJson.toJSONString();
for(int i = 0;i < 100;i++){ int i = 0;
boolean beEnd = false;
while(true) {
//给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样 //给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样
if(i == 0) if(i == 0)
postfix = ""; postfix = "";
else else
postfix = "_" + String.valueOf(i); postfix = "_" + String.valueOf(i);
activeFlag = "0";
conditionJson = (JSONObject) JSON.parse(condTemple); conditionJson = (JSONObject) JSON.parse(condTemple);
// conditionJson = (JSONObject) patternConditionJson.clone(); String originName = conditionJson.getString("conditionName");
conditionName = conditionJson.getString("conditionName") + postfix; conditionName = originName + postfix;
conditionName2 = conditionName + "_indep"; conditionName2 = conditionName + "_indep";
if(conditionExtraKeywords.containsKey(conditionName + "_tail")) { if(conditionExtraKeywords.containsKey(conditionName + "_tail")) {
...@@ -868,13 +868,20 @@ public class ActionUtils { ...@@ -868,13 +868,20 @@ public class ActionUtils {
conditionJson.put("conditionName", conditionName2); conditionJson.put("conditionName", conditionName2);
conditionAppendKeyword2(conditionName2, conditionJson, conditionExtraKeywords, macroAppendMap); conditionAppendKeyword2(conditionName2, conditionJson, conditionExtraKeywords, macroAppendMap);
conditionName = conditionName2; conditionName = conditionName2;
} else { } else if(i>1 && !conditionExtraKeywords.containsKey(originName + "_tail")) {
conditionName = originName;
beEnd = true;
} else if(i == 0) {
++i;
continue; continue;
} else {
break;
} }
if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition)) if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition))
conditionJson.put("active", false); conditionJson.put("active", false);
activeFlag = "0";
actionText = generateSingleActionText(conditionName, conditionJson); actionText = generateSingleActionText(conditionName, conditionJson);
if(startCondition.equals(conditionName)) { if(startCondition.equals(conditionName)) {
conditionJson.put("active", true); conditionJson.put("active", true);
...@@ -894,6 +901,9 @@ public class ActionUtils { ...@@ -894,6 +901,9 @@ public class ActionUtils {
add(finalRelationName); add(finalRelationName);
} }
}); });
++i;
if(beEnd == true)
break;
} }
} }
parameters.put("conditionData", conditionData); parameters.put("conditionData", conditionData);
......
package com.qiwu.chatbotbackend.processing; package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; 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.Date; import java.util.Date;
import java.util.List; import java.util.List;
public class SimpleUtil { public class SimpleUtil {
/** /**
* 将后台返回的数据转成json格式 * 将后台返回的数据转成json格式
*/ */
public static String toJson(Solution ans) { public static String toJson(Solution ans) {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer()); jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus()); jobj.put("status", ans.getStatus());
jobj.put("process", ans.getNext()); jobj.put("process", ans.getNext());
return jobj.toString(); return jobj.toString();
} }
public static String toJson(String returnStr) { public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
jobj.put("returnString", returnStr); jobj.put("returnString", returnStr);
return jobj.toString(); return jobj.toString();
} }
/** /**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据 * 当请求中的数据是json格式时,该函数用于提取request中的json数据
* *
* @param request * @param request
* @return json字符串 * @return json字符串
*/ */
public static String readJSONString(HttpServletRequest request) { public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer(); StringBuffer json = new StringBuffer();
String line = null; String line = null;
try { try {
BufferedReader reader = request.getReader(); BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
json.append(line); json.append(line);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return json.toString(); return json.toString();
} }
public static JSONObject getMethod(String url, String auth){ public static JSONObject getMethod(String url, String auth){
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse resp = null; CloseableHttpResponse resp = null;
String respContent = null; String respContent = null;
String keyName = null; String keyName = null;
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
if(auth != null){ if(auth != null){
httpGet.setHeader("Authorization", auth); httpGet.setHeader("Authorization", auth);
} }
resp = client.execute(httpGet); resp = client.execute(httpGet);
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent); jobj = JSONObject.parseObject(respContent);
jobj.put("get_status", 1); jobj.put("get_status", 1);
jobj.put("status_code", 200); jobj.put("status_code", 200);
} else { } else {
jobj.put("get_status", 0); jobj.put("get_status", 0);
jobj.put("status_code", resp.getStatusLine().getStatusCode()); jobj.put("status_code", resp.getStatusLine().getStatusCode());
jobj.put("parameter", "接收请求的程序出现异常"); jobj.put("parameter", "接收请求的程序出现异常");
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
jobj.put("status_code", 0); jobj.put("status_code", 0);
jobj.put("get_status", 0); jobj.put("get_status", 0);
}finally { }finally {
try { try {
if (resp != null) { if (resp != null) {
resp.close(); resp.close();
} }
if (client != null) { if (client != null) {
client.close(); client.close();
} }
}catch(IOException e){ }catch(IOException e){
e.printStackTrace(); e.printStackTrace();
} }
} }
return jobj; return jobj;
} }
/** /**
* 通过get方法传递参数时需要对参数的编码进行转换 * 通过get方法传递参数时需要对参数的编码进行转换
*/ */
public static String convert2Utf8(String s) { public static String convert2Utf8(String s) {
if (s == null) return null; if (s == null) return null;
try { try {
s = new String(s.getBytes("iso-8859-1"), "utf-8"); s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return s; return s;
} }
public static long transferToMillisecond(String keyword) throws ParseException { public static long transferToMillisecond(String keyword) throws ParseException {
long time; long time;
System.out.println(keyword); System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"}; String timeSeries[] = {"时", "分", "秒"};
for (String f : timeSeries) { for (String f : timeSeries) {
if (!keyword.contains(f)) if (!keyword.contains(f))
keyword += "0" + f; keyword += "0" + f;
} }
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
time = format.parse(keyword).getTime(); time = format.parse(keyword).getTime();
return time; return time;
} }
public static String transferToStandardTime(long time) throws ParseException { public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
Date date = new Date(time); Date date = new Date(time);
return format.format(date); return format.format(date);
} }
public static boolean isInteger(String str){ public static boolean isInteger(String str){
return true; return true;
} }
public static JSONObject postJSON(String url, JSON data, String auth) throws UnsupportedEncodingException { public static JSONObject postJSON(String url, JSON data, String auth) throws UnsupportedEncodingException {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.createDefault();
String respContent = null; String respContent = null;
String keyName = null; String keyName = null;
StringEntity entity = new StringEntity(data.toJSONString(), "utf-8"); StringEntity entity = new StringEntity(data.toJSONString(), "utf-8");
entity.setContentType("application/json; charset=utf-8"); entity.setContentType("application/json; charset=utf-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
if(auth != null){ if(auth != null){
httpPost.setHeader("Authorization", auth); httpPost.setHeader("Authorization", auth);
} }
try { try {
HttpResponse resp = client.execute(httpPost); HttpResponse resp = client.execute(httpPost);
jobj.put("status_code", resp.getStatusLine().getStatusCode()); jobj.put("status_code", resp.getStatusLine().getStatusCode());
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent); jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1); jobj.put("post_status", 1);
jobj.put("status_code", 200); jobj.put("status_code", 200);
} else { } else {
jobj.put("post_status", 0); jobj.put("post_status", 0);
jobj.put("status_code", resp.getStatusLine().getStatusCode()); jobj.put("status_code", resp.getStatusLine().getStatusCode());
jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase());
} }
} catch (Exception e) { } catch (Exception e) {
jobj.put("status_code", 0); jobj.put("status_code", 0);
jobj.put("post_status", 0); jobj.put("post_status", 0);
e.printStackTrace(); System.out.println("respContent:");
} System.out.println(respContent);
e.printStackTrace();
return jobj; }
} return jobj;
}
public static JSONObject postFORM(String url, List<BasicNameValuePair> pairList) throws UnsupportedEncodingException {
public static JSONObject postFORM(String url, List<BasicNameValuePair> pairList) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null; HttpPost httpPost = new HttpPost(url);
String keyName = null; CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); String keyName = null;
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
JSONObject jobj = new JSONObject(); entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
try { JSONObject jobj = new JSONObject();
System.out.println("url为:" + url);
HttpResponse resp = client.execute(httpPost); try {
if (resp.getStatusLine().getStatusCode() == 200) { System.out.println("url为:" + url);
HttpEntity he = resp.getEntity(); HttpResponse resp = client.execute(httpPost);
respContent = EntityUtils.toString(he, "UTF-8"); if (resp.getStatusLine().getStatusCode() == 200) {
jobj = JSONObject.parseObject(respContent); HttpEntity he = resp.getEntity();
jobj.put("post_status", 1); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
} else { jobj.put("post_status", 1);
jobj.put("post_status", 0);
jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); } else {
} jobj.put("post_status", 0);
} catch (Exception e) { jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode());
jobj.put("error_message", "提交表单时出错:" + e.getMessage()); }
jobj.put("post_status", 0); } catch (Exception e) {
} jobj.put("error_message", "提交表单时出错:" + e.getMessage());
jobj.put("post_status", 0);
return jobj; }
} return jobj;
public static String randStr(String strList[]){ }
String reply;
int randNum = (int) (Math.random() * strList.length); public static String randStr(String strList[]){
reply = strList[randNum]; String reply;
int randNum = (int) (Math.random() * strList.length);
return reply; reply = strList[randNum];
}
return reply;
public static String randStr(List<String> strList){ }
String reply;
public static String randStr(List<String> strList){
int randNum = (int) (Math.random() * strList.size()); String reply;
reply = strList.get(randNum);
int randNum = (int) (Math.random() * strList.size());
return reply; reply = strList.get(randNum);
}
return reply;
}
} }
\ No newline at end of file
...@@ -20,6 +20,8 @@ import java.io.OutputStream; ...@@ -20,6 +20,8 @@ import java.io.OutputStream;
import java.text.ParseException; import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.Config.Config.*;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2; import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2;
...@@ -30,28 +32,37 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -30,28 +32,37 @@ public class GetAnswerServlet extends HttpServlet {
/** /**
* GetAnswerServlet就是处理post请求并返回答案的入口 * GetAnswerServlet就是处理post请求并返回答案的入口
*/ */
//String LOG_PATH = "/home/hxw/source/logs/";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap()); Map<String, String[]> requestParamters = new HashMap<>(request.getParameterMap());
Map<String, String> receiveParamters = new HashMap<>();
Set<Entry<String, String[]>> entrySet = requestParamters.entrySet();
String tmpStr;
for(Map.Entry<String, String[]> entry : entrySet) {
if(entry.getValue().length > 0) {
tmpStr = entry.getValue()[0];
if(tmpStr == null || tmpStr.equals(""))
continue;
tmpStr = tmpStr.replace("qiwu", "我");
//tmpStr = tmpStr.replace("qiwu", "你");
receiveParamters.put(entry.getKey(), tmpStr);
}
}
String botName = receiveParamters.get("bot_name");
Map<String ,String> curInfoPoint = new HashMap<String, String>(); Map<String ,String> curInfoPoint = new HashMap<String, String>();
Solution bestMatch = null; Solution bestMatch = null;
BasicBotUtil botUtil = null; BasicBotUtil botUtil = null;
Action ansAction = null; Action ansAction = null;
boolean debugFlag = false; boolean debugFlag = false;
String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = "";
String botName = receiveParamters.get("bot_name")[0];
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
//如果有client_id,会用@分隔 //如果有client_id,会用@分隔
chatKey = receiveParamters.get("chat_key")[0]; chatKey = receiveParamters.get("chat_key");
String chatKeys[] = receiveParamters.get("chat_key")[0].split(COMBINE_PUNC2); String chatKeys[] = receiveParamters.get("chat_key").split(COMBINE_PUNC2);
if(chatKeys.length == 1){ if(chatKeys.length == 1){
userKey = chatKeys[0]; userKey = chatKeys[0];
randKey = chatKeys[0]; randKey = chatKeys[0];
...@@ -60,23 +71,19 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -60,23 +71,19 @@ public class GetAnswerServlet extends HttpServlet {
randKey = chatKeys[1]; randKey = chatKeys[1];
} }
receiveParamters.put("userKey", new String[]{userKey}); receiveParamters.put("userKey", userKey);
receiveParamters.put("randKey", new String[]{randKey}); receiveParamters.put("randKey", randKey);
try { try {
LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
UserInfo userinfo = null; UserInfo userinfo = null;
UserInfoController uiController = new UserInfoController(); UserInfoController uiController = new UserInfoController();
logWriter.record("query bot config", 0); logWriter.record("query bot config", 0);
userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context);
if (userinfo != null) { if (userinfo != null) {
//获得用户历史信息 //获得用户历史信息
ChatCache chatCache = null; ChatCache chatCache = null;
...@@ -96,16 +103,12 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -96,16 +103,12 @@ public class GetAnswerServlet extends HttpServlet {
if (chatCache == null) { if (chatCache == null) {
throw (new Exception("chatCache初始化失败")); throw (new Exception("chatCache初始化失败"));
} }
/** /**
* 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答)
* 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据
*/ */
//historyInfoPoint = chatCache.getInfoPoint();
switch (botType) { switch (botType) {
case "game": case "game":
WorldController worldController = new WorldController(logWriter, userinfo); WorldController worldController = new WorldController(logWriter, userinfo);
......
...@@ -35,7 +35,7 @@ public class BasicBotUtil { ...@@ -35,7 +35,7 @@ public class BasicBotUtil {
this.chatCache = chatCache; this.chatCache = chatCache;
} }
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String> receiveParameters, ServletContext context) throws IOException {
return infoPointPreprocessing(receiveParameters, context, true); return infoPointPreprocessing(receiveParameters, context, true);
...@@ -51,7 +51,7 @@ public class BasicBotUtil { ...@@ -51,7 +51,7 @@ public class BasicBotUtil {
* @return * @return
* @throws IOException * @throws IOException
*/ */
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context, Boolean setUnknown) throws IOException { public boolean infoPointPreprocessing(Map<String, String> receiveParameters, ServletContext context, Boolean setUnknown) throws IOException {
String return_str = "", k, botType = ""; String return_str = "", k, botType = "";
String receiveParameterStr = ""; String receiveParameterStr = "";
...@@ -75,18 +75,15 @@ public class BasicBotUtil { ...@@ -75,18 +75,15 @@ public class BasicBotUtil {
receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------<br>"; receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------<br>";
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
//
receiveParameterStr += k + ": "; receiveParameterStr += k + ": ";
curInfoPoint.put(k, receiveParameters.get(k)[0]); curInfoPoint.put(k, receiveParameters.get(k));
if (k.equals("debug_mode") || k.equals("debug_rule")) if (k.equals("debug_mode") || k.equals("debug_rule"))
debugFlag = true; debugFlag = true;
String values[] = receiveParameters.get(k); String values = receiveParameters.get(k);
receiveParameterStr += values + " " + "<br>";
receiveParameterStr += values[0] + " " + "<br>"; if (values.equals(":")) {
if (values[0].equals(":")) {
curInfoPoint.put(k, ""); curInfoPoint.put(k, "");
} }
} }
......
...@@ -44,7 +44,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -44,7 +44,7 @@ public class GameBotUtil extends BasicBotUtil{
* @throws IOException * @throws IOException
*/ */
@Override @Override
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String> receiveParameters, ServletContext context) throws IOException {
Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false);
//将要去的地点的别名替换为真名 //将要去的地点的别名替换为真名
......
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