diff --git b/out/commons-dbcp-1.2.jar a/out/commons-dbcp-1.2.jar new file mode 100644 index 0000000..4721271 Binary files /dev/null and a/out/commons-dbcp-1.2.jar differ diff --git b/out/commons-pool-1.6.jar a/out/commons-pool-1.6.jar new file mode 100644 index 0000000..72ca75a Binary files /dev/null and a/out/commons-pool-1.6.jar differ diff --git b/out/production/webapp/db/DB.class a/out/production/webapp/db/DB.class new file mode 100644 index 0000000..96b6a4a Binary files /dev/null and a/out/production/webapp/db/DB.class differ diff --git b/out/production/webapp/db/DBCPUtils.class a/out/production/webapp/db/DBCPUtils.class new file mode 100644 index 0000000..987a5eb Binary files /dev/null and a/out/production/webapp/db/DBCPUtils.class differ diff --git b/out/production/webapp/db/SqlHelper.class a/out/production/webapp/db/SqlHelper.class new file mode 100644 index 0000000..e32cf26 Binary files /dev/null and a/out/production/webapp/db/SqlHelper.class differ diff --git b/out/production/webapp/entity/AnswerNextStep.class a/out/production/webapp/entity/AnswerNextStep.class new file mode 100644 index 0000000..ec21ffd Binary files /dev/null and a/out/production/webapp/entity/AnswerNextStep.class differ diff --git b/out/production/webapp/entity/Condition.class a/out/production/webapp/entity/Condition.class new file mode 100644 index 0000000..4b3fb0a Binary files /dev/null and a/out/production/webapp/entity/Condition.class differ diff --git b/out/production/webapp/entity/QuestionKeyWord.class a/out/production/webapp/entity/QuestionKeyWord.class new file mode 100644 index 0000000..f3b0760 Binary files /dev/null and a/out/production/webapp/entity/QuestionKeyWord.class differ diff --git b/out/production/webapp/entity/UserInfo.class a/out/production/webapp/entity/UserInfo.class new file mode 100644 index 0000000..9c41ee0 Binary files /dev/null and a/out/production/webapp/entity/UserInfo.class differ diff --git b/out/production/webapp/processing/ChatCacheController.class a/out/production/webapp/processing/ChatCacheController.class new file mode 100644 index 0000000..125e874 Binary files /dev/null and a/out/production/webapp/processing/ChatCacheController.class differ diff --git b/out/production/webapp/processing/MyFunc.class a/out/production/webapp/processing/MyFunc.class new file mode 100644 index 0000000..f1601d6 Binary files /dev/null and a/out/production/webapp/processing/MyFunc.class differ diff --git b/out/production/webapp/processing/ProcessQuestion.class a/out/production/webapp/processing/ProcessQuestion.class new file mode 100644 index 0000000..c83a9c2 Binary files /dev/null and a/out/production/webapp/processing/ProcessQuestion.class differ diff --git b/out/production/webapp/servlet/GetAnswerServlet.class a/out/production/webapp/servlet/GetAnswerServlet.class new file mode 100644 index 0000000..d68dc83 Binary files /dev/null and a/out/production/webapp/servlet/GetAnswerServlet.class differ diff --git b/out/production/webapp/servlet/ReloadConfig.class a/out/production/webapp/servlet/ReloadConfig.class new file mode 100644 index 0000000..1e20431 Binary files /dev/null and a/out/production/webapp/servlet/ReloadConfig.class differ diff --git b/out/production/webapp/servlet/UpdateServlet.class a/out/production/webapp/servlet/UpdateServlet.class new file mode 100644 index 0000000..ba12c2a Binary files /dev/null and a/out/production/webapp/servlet/UpdateServlet.class differ diff --git b/src/db/DB.java a/src/db/DB.java new file mode 100644 index 0000000..b01bcbe --- /dev/null +++ a/src/db/DB.java @@ -0,0 +1,24 @@ +package db; + +import java.sql.Connection; +import java.sql.DriverManager; + +public class DB { + private static String driver = "com.mysql.jdbc.Driver"; + private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; + private static String user = "root"; + private static String pwd = "admin"; + + public static Connection getConnection(){ + Connection conn = null; + try{ + Class.forName(driver); + conn = DriverManager.getConnection(url,user,pwd); + + }catch(Exception e){ + e.printStackTrace(); + } + + return conn; + } +} diff --git b/src/db/DBCPUtils.java a/src/db/DBCPUtils.java new file mode 100644 index 0000000..41d167e --- /dev/null +++ a/src/db/DBCPUtils.java @@ -0,0 +1,58 @@ +package db; + + +import org.apache.commons.dbcp.BasicDataSourceFactory; + +import javax.sql.DataSource; +import java.io.File; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + + +public class DBCPUtils { + private static DataSource ds;//定义一个连接池对象 + static{ + try { + Properties pro = new Properties(); + File file = new File("dbcpconfig.properties"); + pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties")); + ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象 + } catch (Exception e) { + e.printStackTrace(); + //throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); + } + } + //从池中获取一个连接 + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + public static void closeAll(ResultSet rs, Statement stmt, Connection conn){ + if(rs!=null){ + try { + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + if(stmt!=null){ + try { + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + if(conn!=null){ + try { + conn.close();//关闭 + } catch (SQLException e) { + e.printStackTrace(); + } + } + } +} \ No newline at end of file diff --git b/src/db/SqlHelper.java a/src/db/SqlHelper.java new file mode 100644 index 0000000..40ce642 --- /dev/null +++ a/src/db/SqlHelper.java @@ -0,0 +1,104 @@ +package db; + +import entity.QuestionKeyWord; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class SqlHelper { + private Connection conn = null; + /* + public SqlHelper(){ + conn = DB.getConnection(); + } + */ + + public SqlHelper() throws SQLException { + conn = DBCPUtils.getConnection(); + } + + + public void destroy(){ + if (conn != null){ + try{ + conn.close(); + }catch(Exception e){ + e.printStackTrace(); + } + + } + } +/* + public boolean insertAction(QuestionKeyWord qkw){ + String sql = "insert into user_info (chat_key,action_name) values(?,?)"; + boolean b = false; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,qkw.getChatKey()); + ps.setString(2,qkw.getActionName()); + b = ps.execute(); + return b; + } catch(Exception e){ + e.printStackTrace(); + } + return b; + } + + public boolean updateAction(QuestionKeyWord qkw){ + String sql = "update user_info set action_name=? where chat_key=?"; + boolean b = false; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,qkw.getActionName()); + ps.setString(2,qkw.getChatKey()); + b = ps.execute(); + return b; + } catch (SQLException e) { + e.printStackTrace(); + } + return b; + + } + public String queryActionByKey(String chat_key){ + String sql = "select * from user_info where chat_key= ?"; + String pre_name = ""; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,chat_key); + ResultSet rs = ps.executeQuery(); + if(rs.next()) + return rs.getString("action_name"); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return "empty"; + } +*/ + + public String queryUsernameByKey(String chat_key){ + String sql = "select * from chats where chat_key = ?"; + String userName = ""; + String result = "empty"; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,chat_key); + ResultSet rs = ps.executeQuery(); + if(rs.next()) + result = rs.getString("bot"); + rs.close(); + ps.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return result; + } + + + +} diff --git b/src/entity/AnswerNextStep.java a/src/entity/AnswerNextStep.java new file mode 100644 index 0000000..39b26fe --- /dev/null +++ a/src/entity/AnswerNextStep.java @@ -0,0 +1,40 @@ +package entity; + +public class AnswerNextStep { + int status = 0; + String answer; + String next; + + public String getAnswer() { + return answer; + } + + public int getStatus() { + return status; + } + + + + public void setAnswer(String answer) { + this.answer = answer; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + public AnswerNextStep(int status, String answers, String next){ + this.answer = answers; + this.next = next; + this.status = status; + } + public AnswerNextStep(){} +} diff --git b/src/entity/Condition.java a/src/entity/Condition.java new file mode 100644 index 0000000..6e118d9 --- /dev/null +++ a/src/entity/Condition.java @@ -0,0 +1,25 @@ +package entity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; + +public class Condition { + public int priority = 1; + public HashSet keywordSet = new HashSet(); + public HashMap> historyPremise = new HashMap>(); + public HashMap> currentPremise = new HashMap>(); + public String Answer; + public String nextStep; + public String feature; + public String indexName; + //public ArrayList indexName = new ArrayList(); + + public Condition(int priority) { + this.priority = priority; + } + + public Condition() { + } + +} diff --git b/src/entity/QuestionKeyWord.java a/src/entity/QuestionKeyWord.java new file mode 100644 index 0000000..a7962b5 --- /dev/null +++ a/src/entity/QuestionKeyWord.java @@ -0,0 +1,31 @@ +package entity; + +public class QuestionKeyWord { + String actionName; + String chatKey; + String keyWord; + + public String getActionName() { + return actionName; + } + + public String getChatKey() { + return chatKey; + } + + public String getKeyWord() { + return keyWord; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public void setChatKey(String chatKey) { + this.chatKey = chatKey; + } + + public void setKeyWord(String keyWord) { + this.keyWord = keyWord; + } +} diff --git b/src/entity/UserInfo.java a/src/entity/UserInfo.java new file mode 100644 index 0000000..06bf0e4 --- /dev/null +++ a/src/entity/UserInfo.java @@ -0,0 +1,17 @@ +package entity; + +import java.util.HashMap; +import java.util.List; + +public class UserInfo { + public UserInfo(String userName){ + this.conditionTable = new HashMap>(); + this.configStr = ""; + this.userName = userName; + } + + public HashMap> conditionTable; + public String configStr; + public String userName; + +} diff --git b/src/processing/ChatCacheController.java a/src/processing/ChatCacheController.java new file mode 100644 index 0000000..cad49f7 --- /dev/null +++ a/src/processing/ChatCacheController.java @@ -0,0 +1,68 @@ +package processing; + +import javax.servlet.ServletContext; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class ChatCacheController { + + public static synchronized Map getChatCache(String chatKey, ServletContext context){ + Map historyInfoPoint = null; + Map> chatCache = null; + if(context.getAttribute("chatCache") == null) { + chatCache = new HashMap>(); + context.setAttribute("chatCache", chatCache); + } else{ + chatCache = (Map>) context.getAttribute("chatCache"); + } + String chatkey; + + /* + Iterator it = chatCache.keySet().iterator(); + while(it.hasNext()){ + chatkey = it.next(); + System.out.println("chatkey:"+chatkey); + } + */ + + try{ + historyInfoPoint = chatCache.get(chatKey); + //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); + }catch(Exception e){ + + //可整合 + historyInfoPoint = null; + + } + + return historyInfoPoint; + } + + public static synchronized void updateChatCache4Delete(ServletContext context){ + String chatKey; + long lastChatTime,now; + Map history = new HashMap(); + Map> chatCache = (Map>) context.getAttribute("chatCache"); + + + Iterator it = chatCache.keySet().iterator(); + while (it.hasNext()) { + chatKey = it.next(); + history = chatCache.get(chatKey); + lastChatTime = Long.valueOf(history.get("lastUpdateTime")); + now = System.currentTimeMillis(); + if (now - lastChatTime > 300000) { + it.remove(); + } + } + context.setAttribute("chatCache", chatCache); + } + public static synchronized void updateChatCache4Insert(Map curInfoPoint,Map historyInfoPoint,ServletContext context){ + historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis())); + Map> keyCache = (Map>) context.getAttribute("chatCache"); + keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint); + context.setAttribute("chatCache",keyCache); + } +} diff --git b/src/processing/MyFunc.java a/src/processing/MyFunc.java new file mode 100644 index 0000000..ba8ed64 --- /dev/null +++ a/src/processing/MyFunc.java @@ -0,0 +1,31 @@ +package processing; + +import entity.AnswerNextStep; +import net.sf.json.JSONObject; + +import java.io.UnsupportedEncodingException; + +public class MyFunc { + public static String toJson(AnswerNextStep ans) { + JSONObject jobj = new JSONObject(); + jobj.put("solution", ans.getAnswer()); + jobj.put("status", ans.getStatus()); + 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(); + } + public static String convert2Utf8(String s){ + if(s==null)return null; + try { + s=new String(s.getBytes("iso-8859-1"),"utf-8"); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return s; + } +} diff --git b/src/processing/ProcessQuestion.java a/src/processing/ProcessQuestion.java new file mode 100644 index 0000000..b4e68ea --- /dev/null +++ a/src/processing/ProcessQuestion.java @@ -0,0 +1,352 @@ +package processing; + +import entity.AnswerNextStep; +import entity.Condition; +import entity.UserInfo; +import net.sf.json.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + + +import javax.servlet.ServletContext; +import java.io.*; +import java.sql.SQLException; +import java.util.*; + + +public class ProcessQuestion { + + static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; + +/* + public void updateDB(QuestionKeyWord qkw) throws SQLException { + SqlHelper helper = new SqlHelper(); + String result = helper.queryActionByKey(qkw.getChatKey()); + if(result != "empty") + //待添加 + //qkw.setActionName(result+"+"+qkw.getActionName()); + helper.updateAction(qkw); + else + helper.insertAction(qkw); + helper.destroy(); + } +*/ + + + /** + * 根据本地配置文件生成状态表 + */ + public static void configInit(ServletContext context) throws IOException { + + String line; + + File dir = new File(CONFIG_DIR); + if(!dir.exists()) + dir.mkdir(); + for(File configFile: dir.listFiles()) { + + FileReader reader = new FileReader(configFile); + BufferedReader br = new BufferedReader(reader); + String fileName = configFile.getName(); + UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); + + try { + userinfo = buildUserInfo(br, userinfo); + context.setAttribute(userinfo.userName,userinfo); + }catch(Exception e){ + System.out.println(userinfo.userName + ".txt 有误"); + e.printStackTrace(); + } + + reader.close(); + br.close(); + } + + } + + + public static Condition buildCondition(Condition condition,String line){ + String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[]; + + element = line.trim().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.nextStep = next[1]; + //第二处 + condition.nextStep = next[1].split("=")[1]; + condition.feature = feature; + + ProcessQuestion.insertPremise(condition.currentPremise,cur_premises); + ProcessQuestion.insertPremise(condition.historyPremise,history_premises); + //满足条件越多,优先级越大 + condition.priority = condition.historyPremise.size()+condition.currentPremise.size(); + /* + for(String premise:cur_premises){ + pair = premise.split("="); + condition.indexName.add(pair[0]); + } + */ + condition.indexName = cur_premises[0].split("=")[0]; + + return condition; + } + + + public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException { + String line; + HashMap> conditionTable = new HashMap>(); + List conditionList = null; + + + while ((line = br.readLine()) != null) { + if (line.trim().equals("")) + continue; + userinfo.configStr += line + '\n'; + Condition condition = new Condition(); + condition = buildCondition(condition, line); + conditionList = conditionTable.get(condition.indexName); + if (conditionList == null) + conditionList = new ArrayList(); + conditionList.add(condition); + conditionTable.put(condition.indexName, conditionList); + + } + userinfo.conditionTable = conditionTable; + + return userinfo; + } + + public static void insertPremise(HashMap> premiseMap,String[] premisesString){ + String pair[]; + HashSet keyWordSet = null; + for(String premise:premisesString) { + if (premise.equals("") || premise.equals(" ")) + continue; + pair = premise.split("="); + keyWordSet = new HashSet(); + for (String keyword : pair[1].split("\\+")) + //为了处理条件不满足(为空)时的特殊情况, + if(keyword.equals("null")) keyWordSet.add(""); + else if(!keyword.equals("")) keyWordSet.add(keyword); + premiseMap.put(pair[0],keyWordSet); + } + + } + + + /** + * 原为通过用户chat_key从数据库中获得用户名 + * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) + * 如果context中没有,就重新加载本地配置文件(即初始化) + * 初始化后还是没有就创建一个userinfo + * ------------- + * 修改后直接通过request获得用户名,并从context获得userinfo + * + * @param bot_name 用户名 + * @return 用户信息 + */ + public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { + /*根据数据库得到userName改为直接得到 + SqlHelper helper = new SqlHelper(); + String userName = helper.queryUsernameByKey(chat_key); + */ + String userName = bot_name; + UserInfo userinfo = null; + if(context.getAttribute(userName) == null){ + ProcessQuestion.configInit(context); + } + if(context.getAttribute(userName) == null){ + userinfo = new UserInfo(userName); + userinfo.conditionTable = new HashMap>(); + }else { + userinfo = (UserInfo) context.getAttribute(userName); + } + //helper.destroy(); + + + return userinfo; + } + + + /** + * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch + * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 + * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 + * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 + * @return bestMatch 状态表中满足条件最多的一条 + */ + public Condition getAnswer(Map curInfoPoint,Map historyInfoPoint,HashMap> conditionTable) throws IOException { + + + List conditionList = null; + Condition bestMatch = new Condition(0); + Iterator it = curInfoPoint.keySet().iterator(); + while (it.hasNext()) { + String conditionName = it.next(); + String[] keywords = curInfoPoint.get(conditionName); + String keyword = null; + + if (keywords != null && !keywords[0].equals("")) + keyword = keywords[0]; + + if (keyword != null) { + conditionList = conditionTable.get(conditionName); + if (conditionList != null) { + for (Condition condition : conditionList) { + if (condition.priority > bestMatch.priority && satisfy(curInfoPoint, historyInfoPoint, condition)) + bestMatch = condition; + } + } + } + + } + + + + return bestMatch; + } + + /** + * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 + * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 + * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 + * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 + * @param condition 配置文件(状态表)的一行 + * @return 满足条件就为True,不满足就为False + */ + public boolean satisfy(Map curInfoPoint,Map historyInfoPoint,Condition condition){ + boolean flag = true; + String actionName,keywords[],keyword; + HashSet keywordSet = null; + + if(condition.feature.indexOf("match")!= -1){ + Iterator it = condition.currentPremise.keySet().iterator(); + while (flag && it.hasNext()) { + actionName = it.next(); + + keywords = curInfoPoint.get(actionName); + + if (keywords == null){ + flag = false; + break; + } + keyword = keywords[0]; + keywordSet = condition.currentPremise.get(actionName); + if (!keywordSet.contains(keyword)) { + flag = false; + } + } + + it = condition.historyPremise.keySet().iterator(); + while (flag && it.hasNext()) { + if (historyInfoPoint == null) { + flag = false; + break; + } + actionName = it.next(); + keyword = historyInfoPoint.get(actionName); + keywordSet = condition.historyPremise.get(actionName); + if (!keywordSet.contains(keyword)) { + flag = false; + } + } + } + + return flag; + + } + + /** + * 替换答案中相应的变量{xxx-1},并将当前信息点更新为历史信息点。 + * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 + * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 + * @return 返回给引擎的数据 + */ + public AnswerNextStep updateInfoGetBestMatch(Condition ansCondition,Map curInfoPoint,Map historyInfoPoint,ServletContext context,UserInfo userinfo){ + + Iterator it = curInfoPoint.keySet().iterator(); + String actionName; + AnswerNextStep ans = new AnswerNextStep(); + ans.setAnswer(ansCondition.Answer); + //System.out.println(ans.getAnswer()); + + if(ansCondition.feature.indexOf("post") != -1){ + //ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); + } + + try { + String keyword1, keyword2; + if (historyInfoPoint == null) + historyInfoPoint = new HashMap(); + 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) { + if (keyword2 == null) + historyInfoPoint.put(actionName, keyword1); + else if (keyword2 != null && !keyword1.equals("")) + historyInfoPoint.put(actionName, keyword1); + ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里 + } + + } + ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); + + //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); + ans.setNext("nextStep=" + ansCondition.nextStep); + + }catch(Exception e){ + e.printStackTrace(); + } + + return ans; + } + + /* + public AnswerNextStep postToServer(AnswerNextStep ans, Condition ansCondition, Map curInfoPoint,Map historyInfoPoint) throws IOException { + String url = null,features[] = ansCondition.feature.trim().split(","),elem[]; + for(String feature:features){ + elem = feature.split(":"); + if(elem[0].equals("post")){ + url = elem[elem.length-1]; + break; + } + } + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + +// json方式 + JSONObject jsonParam = new JSONObject(); + jsonParam.put("curInfoPoint", curInfoPoint); + jsonParam.put("historyInfoPoint", historyInfoPoint); + StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题 + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httpPost.setEntity(entity); + System.out.println(); + + HttpResponse resp = client.execute(httpPost); + if(resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he,"UTF-8"); + } + return respContent; + } + */ + + +} diff --git b/src/servlet/GetAnswerServlet.java a/src/servlet/GetAnswerServlet.java new file mode 100644 index 0000000..3644131 --- /dev/null +++ a/src/servlet/GetAnswerServlet.java @@ -0,0 +1,102 @@ +package servlet; + +import entity.AnswerNextStep; +import entity.Condition; +import entity.UserInfo; +import processing.ChatCacheController; +import processing.MyFunc; +import processing.ProcessQuestion; + +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.IOException; +import java.io.OutputStream; +import java.sql.SQLException; +import java.util.*; + + +@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"}) +public class GetAnswerServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + Map curInfoPoint = request.getParameterMap(); + Map historyInfoPoint = null; + AnswerNextStep bestMatch = null; + Condition ansCondition = null; + String ansJ,return_str=""; + String chatKey = curInfoPoint.get("chat_key")[0]; + ProcessQuestion process = new ProcessQuestion(); + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); + + + UserInfo userinfo = null; + try { + //userinfo = process.userInfoQuery(chatKey,context); + userinfo = process.userInfoQuery(request.getParameter("bot_name"),context); + } catch (SQLException e) { + e.printStackTrace(); + } + historyInfoPoint = ChatCacheController.getChatCache(chatKey,context); + + + + if(historyInfoPoint == null) { + String k; + historyInfoPoint = new HashMap(); + Iterator iit = curInfoPoint.keySet().iterator(); + while (iit.hasNext()){ + k = iit.next(); + historyInfoPoint.put(k,""); + } + } + + + + //输出所有actionName的值 + Iterator 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] + " "; + for(String v:values) { + System.out.print(v + " "); + } + System.out.println(); + } + + + + /*得到答案,清楚超时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()); + } + bestMatch.setAnswer(" \n"+return_str+"\n " + bestMatch.getAnswer()); + ansJ = MyFunc.toJson(bestMatch); + //System.out.println(ansJ); + out.write(ansJ.getBytes()); + out.flush(); + + } + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + System.out.println("do get method"); + } +} diff --git b/src/servlet/ReloadConfig.java a/src/servlet/ReloadConfig.java new file mode 100644 index 0000000..1e2912f --- /dev/null +++ a/src/servlet/ReloadConfig.java @@ -0,0 +1,76 @@ +package servlet; + +import entity.UserInfo; +import processing.MyFunc; +import processing.ProcessQuestion; + +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.*; + +@WebServlet(name = "ReloadConfig") +public class ReloadConfig extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String userName = request.getParameter("userName"); + boolean flag = true; + UserInfo userinfo = new UserInfo(userName); + File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt"); + ServletContext context = this.getServletContext(); + if(!configFile.exists()) { + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + out.println("文件不存在: "+userName); + + }else{ + + FileReader reader = new FileReader(configFile); + BufferedReader br = new BufferedReader(reader); + + try { + userinfo = ProcessQuestion.buildUserInfo(br, userinfo); + context.setAttribute(userinfo.userName,userinfo); + }catch(Exception e){ + flag = false; + System.out.println(userinfo.userName + ".txt 有误"); + e.printStackTrace(); + } + + reader.close(); + br.close(); + + if(!flag) { + //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + out.println("更新失败配置文件有误:" + userName +".txt\\\n"); + + } + else{ + response.setCharacterEncoding("utf-8"); + response.setContentType( "text/plain"); + PrintWriter out = response.getWriter(); + out.println("更新成功+ “ "); + out.flush(); + out.close(); + + //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); + + + } + + } + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git b/src/servlet/UpdateServlet.java a/src/servlet/UpdateServlet.java new file mode 100644 index 0000000..81b341f --- /dev/null +++ a/src/servlet/UpdateServlet.java @@ -0,0 +1,119 @@ +package servlet; + +import entity.Condition; +import entity.UserInfo; +import processing.MyFunc; +import processing.ProcessQuestion; + +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.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + + +@WebServlet(name = "UpdateServlet",urlPatterns = {"/update"}) +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[]; + ArrayList errorList = new ArrayList(); + ServletContext context = this.getServletContext(); + String userName = request.getParameter("userName"); + + UserInfo userinfo = new UserInfo(userName); + userinfo.conditionTable = new HashMap>(); + + List conditionList = null; + HashSet keyWordSet = null; + + BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string"))); + boolean flag = true; + String errorStr = ""; + + + while((line = br.readLine()) != null){ + + if(line.trim().equals("")) + continue; + //line = MyFunc.convert2Utf8(line.trim()); + userinfo.configStr += line+"\n"; + Condition condition = new Condition(); + try { + condition = ProcessQuestion.buildCondition(condition,line); + conditionList = userinfo.conditionTable.get(condition.indexName); + if(conditionList == null) + conditionList = new ArrayList(); + conditionList.add(condition); + userinfo.conditionTable.put(condition.indexName,conditionList); + /* + for(String name:condition.indexName){ + userinfo.conditionTable.put() + } + */ + + + } catch(Exception e ){ + System.out.println("配置文件有误!"); + flag = false; + errorList.add(line); + + + } + + } + br.close(); + if(!flag) { + //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr +"\\\n"); + out.println("更新失败,以下行有误: "); + for(String error:errorList) + out.println("---"+error); + out.flush(); + out.close(); + + } + else{ + response.setCharacterEncoding("utf-8"); + response.setContentType( "text/plain"); + PrintWriter out = response.getWriter(); + out.println("更新成功+ “ "); + out.flush(); + out.close(); + + //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()){ + file.createNewFile(); + } + FileWriter fw = new FileWriter(file); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(userinfo.configStr); + bw.close(); + fw.close(); + + + } + //request.; + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git b/web/WEB-INF/classes/dbcpconfig.properties a/web/WEB-INF/classes/dbcpconfig.properties new file mode 100644 index 0000000..7825838 --- /dev/null +++ a/web/WEB-INF/classes/dbcpconfig.properties @@ -0,0 +1,36 @@ +#连接设置 +driverClassName=com.mysql.jdbc.Driver +url=jdbc:mysql://192.168.1.81:3306/chatCN +username=root +password=admin + +# +initialSize=10 + +#最大连接数量 +maxActive=30 + +# +maxIdle=20 + +# +minIdle=5 + +# +maxWait=60000 + + +#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] +#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。 +connectionProperties=useUnicode=true;characterEncoding=UTF-8 + +#指定由连接池所创建的连接的自动提交(auto-commit)状态。 +defaultAutoCommit=true + +#driver default 指定由连接池所创建的连接的只读(read-only)状态。 +#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix) +defaultReadOnly= + +#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 +#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE +defaultTransactionIsolation=READ_UNCOMMITTED \ No newline at end of file diff --git b/web/WEB-INF/lib/commons-beanutils.jar a/web/WEB-INF/lib/commons-beanutils.jar new file mode 100644 index 0000000..795655a Binary files /dev/null and a/web/WEB-INF/lib/commons-beanutils.jar differ diff --git b/web/WEB-INF/lib/commons-codec-1.9.jar a/web/WEB-INF/lib/commons-codec-1.9.jar new file mode 100644 index 0000000..ef35f1c Binary files /dev/null and a/web/WEB-INF/lib/commons-codec-1.9.jar differ diff --git b/web/WEB-INF/lib/commons-collections-3.0.jar a/web/WEB-INF/lib/commons-collections-3.0.jar new file mode 100644 index 0000000..5cc4f90 Binary files /dev/null and a/web/WEB-INF/lib/commons-collections-3.0.jar differ diff --git b/web/WEB-INF/lib/commons-collections-3.1.jar a/web/WEB-INF/lib/commons-collections-3.1.jar new file mode 100644 index 0000000..41e230f Binary files /dev/null and a/web/WEB-INF/lib/commons-collections-3.1.jar differ diff --git b/web/WEB-INF/lib/commons-dbcp-1.4.jar a/web/WEB-INF/lib/commons-dbcp-1.4.jar new file mode 100644 index 0000000..c4c1c4f Binary files /dev/null and a/web/WEB-INF/lib/commons-dbcp-1.4.jar differ diff --git b/web/WEB-INF/lib/commons-lang-2.1.jar a/web/WEB-INF/lib/commons-lang-2.1.jar new file mode 100644 index 0000000..87b80ab Binary files /dev/null and a/web/WEB-INF/lib/commons-lang-2.1.jar differ diff --git b/web/WEB-INF/lib/commons-logging-1.2.jar a/web/WEB-INF/lib/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and a/web/WEB-INF/lib/commons-logging-1.2.jar differ diff --git b/web/WEB-INF/lib/commons-logging.jar a/web/WEB-INF/lib/commons-logging.jar new file mode 100644 index 0000000..b99c937 Binary files /dev/null and a/web/WEB-INF/lib/commons-logging.jar differ diff --git b/web/WEB-INF/lib/commons-pool-1.5.6.jar a/web/WEB-INF/lib/commons-pool-1.5.6.jar new file mode 100644 index 0000000..ce5ff60 Binary files /dev/null and a/web/WEB-INF/lib/commons-pool-1.5.6.jar differ diff --git b/web/WEB-INF/lib/dbcpconfig.properties a/web/WEB-INF/lib/dbcpconfig.properties new file mode 100644 index 0000000..9ead01a --- /dev/null +++ a/web/WEB-INF/lib/dbcpconfig.properties @@ -0,0 +1,36 @@ +#连接设置 +driverClassName=com.mysql.jdbc.Driver +url=jdbc:mysql://192.168.1.81:3306/chatCN +username=root +password=admin + +# +initialSize=10 + +#最大连接数量 +maxActive=50 + +# +maxIdle=20 + +# +minIdle=5 + +# +maxWait=60000 + + +#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] +#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。 +connectionProperties=useUnicode=true;characterEncoding=UTF-8 + +#指定由连接池所创建的连接的自动提交(auto-commit)状态。 +defaultAutoCommit=true + +#driver default 指定由连接池所创建的连接的只读(read-only)状态。 +#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix) +defaultReadOnly= + +#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 +#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE +defaultTransactionIsolation=READ_UNCOMMITTED \ No newline at end of file diff --git b/web/WEB-INF/lib/ezmorph-1.0.2.jar a/web/WEB-INF/lib/ezmorph-1.0.2.jar new file mode 100644 index 0000000..2223179 Binary files /dev/null and a/web/WEB-INF/lib/ezmorph-1.0.2.jar differ diff --git b/web/WEB-INF/lib/fluent-hc-4.5.jar a/web/WEB-INF/lib/fluent-hc-4.5.jar new file mode 100644 index 0000000..88da03b Binary files /dev/null and a/web/WEB-INF/lib/fluent-hc-4.5.jar differ diff --git b/web/WEB-INF/lib/httpclient-4.5.jar a/web/WEB-INF/lib/httpclient-4.5.jar new file mode 100644 index 0000000..970c989 Binary files /dev/null and a/web/WEB-INF/lib/httpclient-4.5.jar differ diff --git b/web/WEB-INF/lib/httpclient-cache-4.5.jar a/web/WEB-INF/lib/httpclient-cache-4.5.jar new file mode 100644 index 0000000..5540226 Binary files /dev/null and a/web/WEB-INF/lib/httpclient-cache-4.5.jar differ diff --git b/web/WEB-INF/lib/httpclient-win-4.5.jar a/web/WEB-INF/lib/httpclient-win-4.5.jar new file mode 100644 index 0000000..340d154 Binary files /dev/null and a/web/WEB-INF/lib/httpclient-win-4.5.jar differ diff --git b/web/WEB-INF/lib/httpcore-4.4.1.jar a/web/WEB-INF/lib/httpcore-4.4.1.jar new file mode 100644 index 0000000..99715b6 Binary files /dev/null and a/web/WEB-INF/lib/httpcore-4.4.1.jar differ diff --git b/web/WEB-INF/lib/httpmime-4.5.jar a/web/WEB-INF/lib/httpmime-4.5.jar new file mode 100644 index 0000000..b631ceb Binary files /dev/null and a/web/WEB-INF/lib/httpmime-4.5.jar differ diff --git b/web/WEB-INF/lib/jna-4.1.0.jar a/web/WEB-INF/lib/jna-4.1.0.jar new file mode 100644 index 0000000..b1a3922 Binary files /dev/null and a/web/WEB-INF/lib/jna-4.1.0.jar differ diff --git b/web/WEB-INF/lib/jna-platform-4.1.0.jar a/web/WEB-INF/lib/jna-platform-4.1.0.jar new file mode 100644 index 0000000..8d5fe3d Binary files /dev/null and a/web/WEB-INF/lib/jna-platform-4.1.0.jar differ diff --git b/web/WEB-INF/lib/json-lib-1.1-jdk13.jar a/web/WEB-INF/lib/json-lib-1.1-jdk13.jar new file mode 100644 index 0000000..abf3b00 Binary files /dev/null and a/web/WEB-INF/lib/json-lib-1.1-jdk13.jar differ diff --git b/web/WEB-INF/lib/mysql-jdbc.jar a/web/WEB-INF/lib/mysql-jdbc.jar new file mode 100644 index 0000000..412138a Binary files /dev/null and a/web/WEB-INF/lib/mysql-jdbc.jar differ diff --git b/web/WEB-INF/lib/servlet-api.jar a/web/WEB-INF/lib/servlet-api.jar new file mode 100644 index 0000000..d0f912a Binary files /dev/null and a/web/WEB-INF/lib/servlet-api.jar differ diff --git b/web/WEB-INF/lib/xom-1.0d10.jar a/web/WEB-INF/lib/xom-1.0d10.jar new file mode 100644 index 0000000..1452d82 Binary files /dev/null and a/web/WEB-INF/lib/xom-1.0d10.jar differ diff --git b/web/WEB-INF/web.xml a/web/WEB-INF/web.xml new file mode 100644 index 0000000..a0b58fd --- /dev/null +++ a/web/WEB-INF/web.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git b/web/index.jsp a/web/index.jsp new file mode 100644 index 0000000..d440655 --- /dev/null +++ a/web/index.jsp @@ -0,0 +1,16 @@ +<%-- + Created by IntelliJ IDEA. + User: hxw + Date: 18-5-8 + Time: 下午1:47 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + $Title$ + + + $END$ + + diff --git b/web/update.html a/web/update.html new file mode 100644 index 0000000..82abc2e --- /dev/null +++ a/web/update.html @@ -0,0 +1,62 @@ + + + + 配置文件 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+
+ + + +
+
+
+
+ + + + + + + + + + diff --git b/web/update2.html a/web/update2.html new file mode 100644 index 0000000..2bc9f54 --- /dev/null +++ a/web/update2.html @@ -0,0 +1,57 @@ + + + + QA + + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+
+ + + +
+
+
+
+ + + + + + + + + + diff --git b/web/update3.html a/web/update3.html new file mode 100644 index 0000000..c5ac067 --- /dev/null +++ a/web/update3.html @@ -0,0 +1,82 @@ + + + + 配置文件 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

关键词替换:

+

 

+
+ + + +
+
+
+
+ + + + + + + + + + diff --git b/webapp.iml a/webapp.iml new file mode 100644 index 0000000..3943953 --- /dev/null +++ a/webapp.iml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file