diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000..3fd3a09 --- /dev/null +++ b/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: com.qiwu.chatbotbackend.ChatbotBackendApplication + diff --git a/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java new file mode 100644 index 0000000..d31e972 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java @@ -0,0 +1,14 @@ +package com.qiwu.chatbotbackend; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; + +@SpringBootApplication +@ServletComponentScan +public class ChatbotBackendApplication { + + public static void main(String[] args) { + SpringApplication.run(ChatbotBackendApplication.class, args); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java new file mode 100644 index 0000000..40031c7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java @@ -0,0 +1,40 @@ +package com.qiwu.chatbotbackend.GameEnvironment; + +import com.qiwu.chatbotbackend.db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class DBUtil { + + public static String queryEnvJsonByBotName(String botName) throws Exception{ + Connection conn = C3p0Utils.getConnection(); + String sql = "select * from generate_json_tb where bot_name = ?"; + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + return result; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java new file mode 100644 index 0000000..272b5e5 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java @@ -0,0 +1,498 @@ +package com.qiwu.chatbotbackend.GameEnvironment; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; + +import com.qiwu.chatbotbackend.GameEnvironment.bean.Attr; +import com.qiwu.chatbotbackend.GameEnvironment.bean.GoodsInstance; +import com.qiwu.chatbotbackend.GameEnvironment.bean.SuperClass; +import com.qiwu.chatbotbackend.GameEnvironment.bean.NpcInstance; +import com.qiwu.chatbotbackend.GameEnvironment.bean.Place; + +public class GameEnv implements Serializable{ + private static final long serialVersionUID = 1L; + public Map npcClassIndex; + public Map npcInstanceIndex; + public Map goodsClassIndex; + public Map goodsInstanceIndex; + public Map placeIndex; + + public GameEnv(String botName) throws Exception { + // 通过文件来初始化游戏环境 +// String fullName = "E:\\projects\\env\\"+projectId+".json"; +// +// String jsonString = Util.getJsonString(fullName); + String jsonString = DBUtil.queryEnvJsonByBotName(botName); + Map gameProjectMap = JSON.parseObject(jsonString); +// System.out.println(gameProjectMap); + if(!gameProjectMap.isEmpty()) { + // 地图 + Map map = (Map)gameProjectMap.get("map"); + this.placeIndex = new HashMap(); + Map placeMapTmp = new HashMap(); + if(!map.isEmpty()) { + for(String key:map.keySet()) { + Map one = (Map)map.get(key); + placeMapTmp.put(key, (String)one.get("name")); + Place place = new Place(); + place.setIntro((String)one.get("intro")); + place.setName((String)one.get("name")); + placeIndex.put((String)one.get("name"), place); + } + for(String tmp:placeMapTmp.keySet()) { + List ableGos = new ArrayList(); + List ableGoLongs = (List)((Map)map.get(tmp)).get("canGo"); + for(int j=0; j npcClasses = (Map)gameProjectMap.get("npc"); + Map npcNames = new HashMap(); + this.npcClassIndex = new HashMap(); + this.npcInstanceIndex = new HashMap(); + if(!npcClasses.isEmpty()) { + for(String classKey:npcClasses.keySet()) { + Map one = (Map)npcClasses.get(classKey); + // class + Map oneClass = (Map)one.get("class"); + SuperClass npcClass = new SuperClass(); + npcClass.setName(classKey); + npcClass.setIntro((String)oneClass.get("intro")); + + List attrs = new ArrayList(); + for(String attrKey:oneClass.keySet()) { + if(!attrKey.equals("intro") && !attrKey.equals("class") && !attrKey.equals("")) { + Attr attr = new Attr(); + attr.setName(attrKey); + attr.setValue((String)oneClass.get(attrKey)); + attrs.add(attr); + } + } + npcClass.setAttrs(attrs); + // instance + Map instances = (Map)one.get("instance"); + for(String instanceKey:instances.keySet()) { + Map instance = new HashMap(); + NpcInstance npcInstance = new NpcInstance(); + Map instanceAttrMap = (Map)instances.get(instanceKey); + npcNames.put(instanceKey, (String)instanceAttrMap.get("name")); + npcInstance.setName((String)instanceAttrMap.get("name")); + npcInstance.setIntro((String)instanceAttrMap.get("intro")); + List npcInstanceAttrs = new ArrayList(); + for(String instanceAttrKey:instanceAttrMap.keySet()) { + if(!instanceAttrKey.equals("name")&&!instanceAttrKey.equals("intro")&&!instanceAttrKey.equals("placeId")&&!instanceAttrKey.equals("placeName")&&!instanceAttrKey.equals("class")) { + Attr attr = new Attr(); + attr.setName(instanceAttrKey); + attr.setValue((String)instanceAttrMap.get(instanceAttrKey)); + npcInstanceAttrs.add(attr); + } + } + npcInstance.setAttrs(npcInstanceAttrs); + Place place = placeIndex.get(((Map)map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name")); + + List npcInstances = place.getNpcInstances(); + if(npcInstances == null) { + npcInstances = new ArrayList(); + } + npcInstances.add(npcInstance); + place.setNpcInstances(npcInstances); + List npcInstanceClass = npcClass.getNpcInstances(); + if(npcInstanceClass == null) { + npcInstanceClass = new ArrayList(); + } + npcInstanceClass.add(npcInstance); + npcClass.setNpcInstances(npcInstanceClass); + npcInstance.setPlace(place); + this.npcInstanceIndex.put((String)instanceAttrMap.get("name"), npcInstance); + } + this.npcClassIndex.put(classKey, npcClass); + } + } + // goods + Map goodsClasses = (Map)gameProjectMap.get("goods"); + this.goodsClassIndex = new HashMap(); + this.goodsInstanceIndex = new HashMap(); + if(!goodsClasses.isEmpty()) { + for(String classKey:goodsClasses.keySet()) { + Map one = (Map)goodsClasses.get(classKey); + // class + Map oneClass = (Map)one.get("class"); + SuperClass goodsClass = new SuperClass(); + goodsClass.setName(classKey); + goodsClass.setIntro((String)oneClass.get("intro")); + + List attrs = new ArrayList(); + for(String attrKey:oneClass.keySet()) { + if(!attrKey.equals("intro")&&!attrKey.equals("placeId")&&!attrKey.equals("npcName")&&!attrKey.equals("class")&&!attrKey.equals("placeName")) { + Attr attr = new Attr(); + attr.setName(attrKey); + attr.setValue((String)oneClass.get(attrKey)); + attrs.add(attr); + } + } + goodsClass.setAttrs(attrs); + + // instance + Map instances = (Map)one.get("instance"); + + for(String instanceKey:instances.keySet()) { + Map instance = new HashMap(); + GoodsInstance goodsInstance = new GoodsInstance(); + Map instanceAttrMap = (Map)instances.get(instanceKey); + goodsInstance.setName((String)instanceAttrMap.get("name")); + goodsInstance.setIntro((String)instanceAttrMap.get("intro")); + List goodsInstanceAttrs = new ArrayList(); + for(String instanceAttrKey:instanceAttrMap.keySet()) { + if(instanceAttrKey!="placeId"&&instanceAttrKey!="npcId"&&instanceAttrKey!="name"&&instanceAttrKey!="intro") { + Attr attr = new Attr(); + attr.setName(instanceAttrKey); + attr.setValue((String)instanceAttrMap.get(instanceAttrKey)); + goodsInstanceAttrs.add(attr); + } + } + goodsInstance.setAttrs(goodsInstanceAttrs); + Place place = placeIndex.get(((Map)map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name")); + goodsInstance.setPlace(place); + List placeGoodsInstances= place.getGoodsInstances(); + if(placeGoodsInstances == null) { + placeGoodsInstances = new ArrayList(); + } + placeGoodsInstances.add(goodsInstance); + place.setGoodsInstances(placeGoodsInstances); + + if(instanceAttrMap.get("npcId")!=null){ + NpcInstance npc = this.npcInstanceIndex.get(npcNames.get(String.valueOf(instanceAttrMap.get("npcId")))); + goodsInstance.setNpc(npc); + List npcGoodsInstances = npc.getGoodsInstances(); + if(npcGoodsInstances == null) { + npcGoodsInstances = new ArrayList(); + } + npcGoodsInstances.add(goodsInstance); + npc.setGoodsInstances(npcGoodsInstances); + } + + List goodsInstancesClass = goodsClass.getGoodsInstances(); + if(goodsInstancesClass == null) { + goodsInstancesClass = new ArrayList(); + } + goodsInstancesClass.add(goodsInstance); + goodsClass.setGoodsInstances(goodsInstancesClass); + this.goodsInstanceIndex.put((String)instanceAttrMap.get("name"), goodsInstance); + } + this.goodsClassIndex.put(classKey, goodsClass); + } + } + } + } + + /********************************************地点******************************************/ + // 周围有什么 + public List queryAroundAllBySite(String site){ + List queryGoods = this.queryAroundGoodsBySite(site); + List queryNpc = this.queryAroundNpcBySite(site); + queryGoods.addAll(queryNpc); + return queryGoods; + } + // 周围有什么人 + public List queryAroundNpcBySite(String site){ + Place place = this.placeIndex.get(site); + List queryNpc = new ArrayList(); + if(place !=null) { + List npcInstances = place.getNpcInstances(); + if(npcInstances!=null) { + for(int i=0; i queryAroundGoodsBySite(String site){ + Place place = this.placeIndex.get(site); + List queryGoods = new ArrayList(); + if(place !=null) { + List goodsInstances = place.getGoodsInstances(); + if(goodsInstances!=null) { + for(int i=0; i queryCanGoBySite(String site){ + List ableGoString = new ArrayList(); + Place place = this.placeIndex.get(site); + List ableGos = place.getAbleGo(); + for(int i=0; i queryPathBySite(String start, String destination){ + return null; + } + + /**************************************物品***************************/ + // 通过类和地点查询所有物品名称 + public List queryGoodsByClassAndSite(String className, String site){ + List goodsNames = new ArrayList(); + List placeGoodsInstances = null; + List goodsInstances = null; + if(this.placeIndex.get(site)!=null && this.goodsClassIndex.get(className)!=null) { + placeGoodsInstances = this.placeIndex.get(site).getGoodsInstances(); + goodsInstances = this.goodsClassIndex.get(className).getGoodsInstances(); + for(int i=0; i attrs = goodsInstance.getAttrs(); + if(attrName.equals("location")) { + if(goodsInstance.getPlace()!=null) { + return goodsInstance.getPlace().getName(); + } + } + if(attrName.equals("owner")) { + if(goodsInstance.getNpc()!=null) { + return goodsInstance.getNpc().getName(); + } + } + for(int i=0; i queryGoodsAllAttrByGoodsName(String name){ + List attrnames = new ArrayList(); + GoodsInstance goodsInstance = queryGoodsByGoodsName(name); + if(goodsInstance != null) { + List attrs = goodsInstance.getAttrs(); + for(int i=0; i queryNpcByClassAndSite(String className, String site){ + List npcNames = new ArrayList(); + List placeNpcInstances = this.placeIndex.get(site).getNpcInstances(); + List npcInstances = this.goodsClassIndex.get(className).getNpcInstances(); + NpcInstance npcInstance = new NpcInstance(); + for(int i=0; i attrs = npcInstance.getAttrs(); + for(int i=0; i queryNpcAttrsByNpcName(String name){ + List attrNames = new ArrayList(); + NpcInstance npcInstance = queryNpcByNpcName(name); + if(npcInstance != null) { + List attrs = npcInstance.getAttrs(); + for(int i=0; i goodsClassAttrs = goodsClass.getAttrs(); + GoodsInstance goodsInstance = new GoodsInstance(); + List goodsInstanceAttr = new ArrayList(); + goodsInstance.setName(names[2]); + goodsInstance.setIntro(goodsClass.getIntro()); + for(int i=0; i npcClassAttrs = npcClass.getAttrs(); + NpcInstance npcInstance = new NpcInstance(); + List npcInstanceAttr = new ArrayList(); + npcInstance.setName(names[2]); + npcInstance.setIntro(npcClass.getIntro()); + for(int i=0; i goodsInstancesByClass = this.goodsClassIndex.get(names[1]).getGoodsInstances(); + boolean goodsInstanceBoolean = false; + GoodsInstance goodsInstance = this.goodsInstanceIndex.get(names[2]); + for(int i=0; i attrs = goodsInstance.getAttrs(); + for(int j=0; j npcInstancesByClass = this.npcClassIndex.get(names[1]).getNpcInstances(); + boolean npcInstanceBoolean = false; + NpcInstance npcInstance = this.npcInstanceIndex.get(names[2]); + for(int i=0; i attrs = npcInstance.getAttrs(); + for(int j=0; j goodsInstances; + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + @Override + public String toString() { + String placeName = ""; + if(place != null) { + placeName = place.getName(); + } + int goodsInstancesSize = 0; + if(goodsInstances!=null) { + goodsInstancesSize = goodsInstances.size(); + } + return super.toString()+"NpcInstance [placeName=" + placeName + ", goodsInstancesSize=" + goodsInstancesSize + "]"; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java new file mode 100644 index 0000000..bdd28f9 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java @@ -0,0 +1,61 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.List; + +public class Place implements Serializable{ + private static final long serialVersionUID = 1L; + private String name; + private String intro; + private List ableGo; + private List npcInstances; + private List goodsInstances; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAbleGo() { + return ableGo; + } + public void setAbleGo(List ableGo) { + this.ableGo = ableGo; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + @Override + public String toString() { + int ableGoSize = 0; + int npcInstancesSize = 0; + int goodsInstancesSize = 0; + if(ableGo != null) { + ableGoSize = ableGo.size(); + } + if(npcInstances != null) { + npcInstancesSize = npcInstances.size(); + } + if(goodsInstances != null) { + goodsInstancesSize = goodsInstances.size(); + } + return "Place [name=" + name + ", intro=" + intro + ", ableGo=" + ableGoSize + ", npcInstances=" + npcInstancesSize + + ", goodsInstances=" + goodsInstancesSize + "]"; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java new file mode 100644 index 0000000..03b7bc1 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java @@ -0,0 +1,53 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.List; + +public class SuperClass implements Serializable{ + private static final long serialVersionUID = 1L; + private String name; + private String intro; + private List attrs; + private List goodsInstances; + private List npcInstances; + + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAttrs() { + return attrs; + } + public void setAttrs(List attrs) { + this.attrs = attrs; + } + @Override + public String toString() { + int goodsInstanceSize = 0; + if(goodsInstances!=null) { + goodsInstanceSize = goodsInstances.size(); + } + return "SuperClass [name=" + name + ", intro=" + intro + "goodsInstancesSize="+goodsInstanceSize+", attrs=" + attrs + "]"; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java new file mode 100644 index 0000000..6d3cdbe --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java @@ -0,0 +1,57 @@ +package com.qiwu.chatbotbackend.db; + + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import org.apache.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class C3p0Utils { + static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); + + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); + + //从连接池中取用一个连接 + public static Connection getConnection() throws SQLException { + try { + return dataSource.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //释放连接回连接池 + public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + if (pst != null) { + try { + pst.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/DB.java b/src/main/java/com/qiwu/chatbotbackend/db/DB.java new file mode 100644 index 0000000..2a0a658 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/DB.java @@ -0,0 +1,24 @@ +package com.qiwu.chatbotbackend.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 a/src/main/java/com/qiwu/chatbotbackend/db/DBCPUtils.java b/src/main/java/com/qiwu/chatbotbackend/db/DBCPUtils.java new file mode 100644 index 0000000..4746731 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/DBCPUtils.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.db; + + +import org.apache.tomcat.dbcp.dbcp2.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 a/src/main/java/com/qiwu/chatbotbackend/db/DBUtils.java b/src/main/java/com/qiwu/chatbotbackend/db/DBUtils.java new file mode 100644 index 0000000..5dc4aaa --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/DBUtils.java @@ -0,0 +1,4 @@ +package com.qiwu.chatbotbackend.db; + +public class DBUtils { +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java new file mode 100644 index 0000000..915e678 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java @@ -0,0 +1,511 @@ +package com.qiwu.chatbotbackend.db; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.QuestionKeyWord; +import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; +import com.qiwu.chatbotbackend.processing.MyFunc; + +import java.sql.*; +import java.util.*; + +public class SqlHelper { + private Connection conn = null; + /* + public SqlHelper(){ + conn = DB.getConnection(); + } + */ + + public SqlHelper() throws SQLException { + conn = C3p0Utils.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"; + } +*/ + + private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException { + C3p0Utils.close(_conn, _st, _rs); + } + + 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"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + public boolean deleteConfigByIdGroup(int botId, List idGroup) throws SQLException { + + StringBuilder inClause = new StringBuilder(); + boolean firstValue = true; + int batchSize = idGroup.size(); + + for (int i = 0; i < batchSize; i++) { + inClause.append('?'); + if (firstValue) { + firstValue = false; + } else { + inClause.append(','); + } + } + + String sql = "delete from chatbot_config where botId = ? and configId in (" + inClause.toString() + ')'; + String userName = ""; + boolean b = true; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.execute(); + + ps.close(); + + return b; + } catch (Exception e) { + e.printStackTrace(); + } + return b; + } + + public boolean deleteConfigByBotId(int botId) { + boolean b; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); + ps1.setString(1, String.valueOf(botId)); + b = ps1.execute(); + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除旧数据config失败"); + e.printStackTrace(); + return false; + } + } + + public boolean deleteVariableByBotId(int botId) { + String sql = "delete from chatbot_variable where botId= ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.execute(); + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除旧数据variable失败"); + e.printStackTrace(); + return false; + } + } + + + public boolean deleteCategoryByBotId(int botId) { + String sql = "delete from config_categories where botId= ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.execute(); + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除旧数据category失败"); + e.printStackTrace(); + return false; + } + } + + public boolean batchInsertVariableByBotId(int botId, ElementConstructor constructor) { + + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; + PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + Iterator iit = constructor.getVarInitialMap().keySet().iterator(); + while (iit.hasNext()) { + varName = iit.next(); + varValue = constructor.getVarInitialMap().get(varName); + if (constructor.getConditionDescription().get(varName) == null) + description = ""; + else + description = constructor.getConditionDescription().get(varName); + + ps2.setString(1, String.valueOf(botId)); + ps2.setString(2, varName); + ps2.setString(3, description); + ps2.setString(4, varValue); + ps2.addBatch(); + } + + count = ps2.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + ps2.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + public boolean batchInsertConfigByBotId(int botId, List jsonList, List idList, int categoryId) { + int count[]; + boolean insertFlag = true; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for (JSONObject json : jsonList) { + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, json.toJSONString()); + ps.setString(4, (String)json.get("configName")); + ps.addBatch(); + } + + count = ps.executeBatch(); + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + + ResultSet rs = ps.getGeneratedKeys(); + while (rs.next()) + idList.add(rs.getInt(1)); + + + ps.close(); + rs.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + } + + + public boolean batchInsertCategoryByBotId(int botId, Map categoryMap) { + + int count[], iterNum = 0, id; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + ArrayList nameList = new ArrayList(); + + + try { + conn.setAutoCommit(false); + + + sql = "insert into config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, -1, ?, 'avaliable')"; + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + Iterator iit = categoryMap.keySet().iterator(); + while (iit.hasNext()) { + varName = iit.next(); + + nameList.add(varName); + ps.setString(1, String.valueOf(botId)); + ps.setString(2, varName); + ps.addBatch(); + } + + count = ps.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + + + ResultSet rs = ps.getGeneratedKeys(); + while (rs.next()){ + id = rs.getInt(1); + categoryMap.put(nameList.get(iterNum), id); + iterNum++; + + } + + + ps.close(); + rs.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + + public JSONObject queryGameElementsByBotId(int id) { + String sql = "select * from generate_json_tb where project_id = ?"; + String userName = ""; + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("json_text"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return JSONObject.parseObject(result); + + } + + public static String queryEnvJsonByBotName(String botName) throws SQLException { + String sql = "select * from generate_json_tb where bot_name = ?"; + Connection conn = C3p0Utils.getConnection(); + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) { + String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + boolean b = true; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ps.setString(2, variableName); + ps.setString(3, description); + ps.setString(4, defaultValue); + b = ps.execute(); + + ps.close(); + conn.commit(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + + public boolean insertConfigByBotId(int botId, JSONObject json, List idList, int categoryId) { + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + int id = 0; + boolean b = true; + int bNum = 0; + try { + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, json.toJSONString()); + ps.setString(4, (String)json.get("configName")); + + System.out.println(ps.toString()); + + bNum = ps.executeUpdate(); + ResultSet rs = ps.getGeneratedKeys(); + if(rs.next()){ + id = rs.getInt(1); + idList.add(id); + } + ps.close(); + rs.close(); + conn.commit(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + +// public boolean insertCategoryByBotId(int botId, String categoryName) { +// String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; +// int id = 0; +// boolean b = true; +// int bNum = 0; +// try { +// PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); +// ps.setString(1, String.valueOf(botId)); +// ps.setString(2, "0"); +// ps.setString(4, jConfig.getConfigName()); +// +// System.out.println(ps.toString()); +// +// bNum = ps.executeUpdate(); +// ResultSet rs = ps.getGeneratedKeys(); +// if(rs.next()){ +// id = rs.getInt(1); +// idList.add(id); +// } +// ps.close(); +// rs.close(); +// conn.commit(); +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// +// return b; +// +// } + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java b/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java new file mode 100644 index 0000000..e7830e8 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java @@ -0,0 +1,47 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; + + +public class ChatCache { + private Map infoPoint = null; + private GameEnv gameEnv = null; + + public Map getInfoPoint() { + return infoPoint; + } + + public void setInfoPoint(Map infoPoint) { + this.infoPoint = infoPoint; + } + + public GameEnv getGameEnv() { + return gameEnv; + } + + public void setGameEnv(GameEnv gameEnv) { + this.gameEnv = gameEnv; + } + + public ChatCache(UserInfo userInfo) throws Exception { + try { + gameEnv = new GameEnv(userInfo.botAccount); + }catch (Exception e){ + System.out.println("游戏平台初始化失败"); + } + + String k; + infoPoint = new HashMap(); + Iterator iit = userInfo.varInitialMap.keySet().iterator(); + while (iit.hasNext()) { + k = iit.next(); + infoPoint.put(k, userInfo.varInitialMap.get(k)); + } + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Condition.java b/src/main/java/com/qiwu/chatbotbackend/entity/Condition.java new file mode 100644 index 0000000..3ebce66 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Condition.java @@ -0,0 +1,51 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.HashSet; + + +/** + * 保存配置文件每一行(单行)解析后的信息的实体类。 + * 独立于引擎的另一种condition + */ +public class Condition { + public int priority = -1; + public int activePriority = 0; //如果本condition被其他condition激活 + public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 + public HashSet keywordSet = new HashSet(); + public HashMap> historyPremise = new HashMap>(); + public HashMap> currentPremise = new HashMap>(); + public HashMap updateKnowledge = new HashMap(); + public String[] answer = {"",}; + public String nextStep = ""; + public HashMap featureMap = new HashMap(); + public String indexName = ""; + public int id = 0; + public String status = "waiting"; + //public ArrayList indexName = new ArrayList(); + + public Condition(int priority) { + this.priority = priority; + this.activePriority = priority; + } + + public Condition(Condition originCondition, int basePriority, int baseAuxiliaryPriority) { + this.priority = originCondition.priority; + this.keywordSet = originCondition.keywordSet; + this.historyPremise = originCondition.historyPremise; + this.currentPremise = originCondition.currentPremise; + this.answer = originCondition.answer; + this.nextStep = originCondition.nextStep; + this.featureMap = originCondition.featureMap; + this.updateKnowledge = originCondition.updateKnowledge; + this.indexName = originCondition.indexName; + this.id = originCondition.id; + this.status = originCondition.status; + this.activePriority = originCondition.activePriority + basePriority; + this.auxiliaryPriority = originCondition.auxiliaryPriority + baseAuxiliaryPriority; + } + + public Condition() { + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/JConfig.java b/src/main/java/com/qiwu/chatbotbackend/entity/JConfig.java new file mode 100644 index 0000000..e5ecb29 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/JConfig.java @@ -0,0 +1,296 @@ +package com.qiwu.chatbotbackend.entity; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class JConfig { + + private int id = 0; + private String jCurPremise = ""; + private String jHisPremise = ""; + private String jFeature = ""; + + + private String jNextStep = ""; + private String jReply = ""; + private String jAuxiliaryPriority = "0"; + + public void setjStatus(int jStatus) { + this.jStatus = jStatus; + } + + private int jStatus = 0; + + private String curPremise = ""; + private String hisPremise = ""; + + + private String feature = ""; + private String reply = ""; + private String nextStep = ""; + + public void setConfigName(String configName) { + this.configName = configName; + } + + public String getConfigName() { + return configName; + } + + private String configName = ""; + + public String getCurPremise() { + return curPremise; + } + + private String auxiliaryPriority = "0"; + private String status = "waiting"; + + + private String updateKnowledge = ""; + private String nextStepStatus = "return"; + + Map statusMap = new HashMap() { + { + put("return", "return"); + put("return-1", "back"); + put("return-0", "stay"); + put("active", "activate"); + } + }; + + public void setStatus(String status) { + this.status = status; + } + public void setAuxiliaryPriority(String auxiliaryPriority) { + this.auxiliaryPriority = auxiliaryPriority; + } + + public void setNextStepStatus(String nextStepStatus) { + this.nextStepStatus = nextStepStatus; + } + + public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { + this.curPremise = curPremise; + this.hisPremise = hisPremise; + this.feature = feature; + if (!updateKnowledge.equals("")) + this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; + + this.reply = reply; + this.nextStep = nextStep; + } + + + public JConfig(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { + this.curPremise = appendPremiseStr(curPremise, extraCP); + this.hisPremise = appendPremiseStr(hisPremise, extraHP); + this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); + this.feature = feature; + this.reply = reply; + this.nextStep = nextStep; + this.auxiliaryPriority = auxiliaryPriority; + } + + public String appendPremiseStr(List premises, String extraPM) { + StringBuffer sb = new StringBuffer(); + String premiseStr = ""; + + for (String premise : premises) + sb.append("," + premise); + if (sb.length() > 0) + sb.deleteCharAt(0); //删除第一个逗号 + + + if (!extraPM.equals("")) { + if (sb.length() == 0) + sb.append(extraPM); + else + sb.append("," + extraPM); + } else if (sb.length() == 0) { + sb.append(" "); + } + premiseStr = sb.toString(); + + return premiseStr; + } + + public String appendKnowledgeStr(Map knowledge, String extraKL) { + StringBuffer sb = new StringBuffer(); + String varName = "", varValue = "", knowledgeStr; + Iterator iit = knowledge.keySet().iterator(); + + while (iit.hasNext()) { + varName = iit.next(); + varValue = knowledge.get(varName); + sb.append("-<-" + varName + ":" + varValue); + } + if (!extraKL.equals("")) { + sb.append("-<-" + extraKL); + } + + if (sb.length() > 0) + knowledgeStr = "updateKnowledge" + sb.toString(); + else + knowledgeStr = ""; + + return knowledgeStr; + } + + + public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { + //System.out.println(premise); + + String pair1[] = premise.split("=", 2); + String key = pair1[0]; + String keywords = pair1[1]; + String pair2[] = key.split("::"); + String conditionName = pair2[0]; + String pair3[] = pair2[1].split("-"); + String cmpType = pair3[0]; + String operator = ""; + if (pair3.length > 1) + operator = pair3[1]; + + String question = ""; + if (conditionDescription.get(conditionName) != null) + question = conditionDescription.get(conditionName); + + JSONObject premiseJ = new JSONObject(); + premiseJ.put("keywords", keywords); + premiseJ.put("actionName", conditionName); + premiseJ.put("cmpType", cmpType); + premiseJ.put("question", question); + premiseJ.put("operator", operator); + + premiseList.add(premiseJ); + + } + + public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { + String pair[] = knowledge.split(":", 2); + + if (knowledge.equals("") || pair.length < 2) + return; + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + JSONObject knowledgeJ = new JSONObject(); + knowledgeJ.put("variableName", pair[0]); + knowledgeJ.put("keyword", pair[1]); + + knowledgeList.add(knowledgeJ); + } + + public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { + String pair[] = next.split("-"); + JSONObject nextStepJ = new JSONObject(); + JSONArray exceptJ = new JSONArray(); + + for (int i = 1; i < pair.length; i++) + exceptJ.add(pair[i]); + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + nextStepJ.put("nextStep", pair[0]); + nextStepJ.put("except", exceptJ); + nextStepJ.put("nextStepText", question); + nextStepList.add(nextStepJ); + } + + public JSONObject toJson(Map conditionDescription) { + JSONObject data = new JSONObject(); + JSONArray curPremiseList = new JSONArray(); + JSONArray hisPremiseList = new JSONArray(); + + //添加当前对话内容 + for (String premise : curPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(curPremiseList, premise, conditionDescription); + } + data.put("currentPremiseList", curPremiseList); + + //添加已知信息的内容 + for (String premise : hisPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(hisPremiseList, premise, conditionDescription); + } + data.put("historyPremiseList", hisPremiseList); + + //添加下一步状态 + data.put("nextStepStatus", statusMap.get(nextStepStatus)); + + //添加configName + data.put("configName", configName); + + //添加config状态 + data.put("configStatus", jStatus); + + + boolean doPost = false; + String postURL = "", postType = "all", pair[]; + + for (String feat : feature.split(",")) { + if (feat.startsWith("post")) { + doPost = true; + pair = feat.substring(0, feat.length() - 1).split("\\(", 2); + postURL = pair[1]; + postType = pair[0].split("::")[1]; + } + } + //添加post参数 + data.put("doPost", doPost); + data.put("postURL", postURL); + data.put("postType", postType); + + //添加回答 + data.put("reply", reply); + + //添加config类别id + data.put("categoryId", 0); + + //添加辅助优先级 + data.put("auxiliaryPriority", auxiliaryPriority); + + //添加更新答案处的信息 + JSONArray knowledgeList = new JSONArray(); + if (!updateKnowledge.equals("")) { + for (String knowledge : updateKnowledge.split("-<-")) { + appendJKnowledge(knowledgeList, knowledge, conditionDescription); + } + } + data.put("updateKnowledge", knowledgeList); + + //添加下一步 + JSONArray nextStepList = new JSONArray(); + for (String next : nextStep.split(",")) { + appendJNextStep(nextStepList, next, conditionDescription); + } + data.put("nextStepList", nextStepList); + + return data; + } + + public String toString() { + + String text = curPremise + "|" + + hisPremise + "|" + + feature + "," + updateKnowledge + "," + nextStepStatus + "|" + + "auxiliaryPriority=" + auxiliaryPriority + "|=>|" + + reply + "|" + + "nextStep=" + nextStep + "|" + + "status=" + status + "|" + + "configId="; + + return text; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/QuestionKeyWord.java b/src/main/java/com/qiwu/chatbotbackend/entity/QuestionKeyWord.java new file mode 100644 index 0000000..c1b9ca6 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/QuestionKeyWord.java @@ -0,0 +1,35 @@ +package com.qiwu.chatbotbackend.entity; + + +/** + * 暂时没用 + */ +public class QuestionKeyWord { + private String actionName; + private String chatKey; + private 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 a/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java b/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java new file mode 100644 index 0000000..3435ea3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java @@ -0,0 +1,45 @@ +package com.qiwu.chatbotbackend.entity; + + +/** + * 包含后台返回数据的实体类。 + */ +public class Solution { + private int status = 0; + private String answer; + private 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 Solution(int status, String answers, String next) { + this.answer = answers; + this.next = next; + this.status = status; + } + + public Solution() { + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java b/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java new file mode 100644 index 0000000..0e88ab0 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java @@ -0,0 +1,34 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.List; + +/** + * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 + */ +public class UserInfo { + public UserInfo(String botAccount) { + this.conditionTable = new HashMap>(); + this.configStr = ""; + this.botAccount = botAccount; + this.extraInfo = new HashMap() { + { + put("activeAction", " "); + } + }; + this.id2config = new HashMap(); + this.id2condition = new HashMap(); + this.varInitialMap = new HashMap(); + } + + public HashMap> conditionTable; + public String configStr; + public String botAccount; + public HashMap extraInfo; + public HashMap id2config; + public HashMap id2condition; + //存储需要初始化的变量 + public HashMap varInitialMap; + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java new file mode 100644 index 0000000..37940fe --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java @@ -0,0 +1,96 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class CharacterConstructor extends ElementConstructor { + + public CharacterConstructor(SqlHelper helper, int botId, HashSet exceptRelation) { + super(); + this.helper = helper; + this.botId = botId; + this.exceptRelation = exceptRelation; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { + String category, name, className, description, attrName, attrValue; + + try { + JSONArray allNPC = gameElements.getJSONArray("npc"); + Map attribute = null; + Iterator attrIter = null; + HashSet classSet = new HashSet(); + + //与npc属性相关的所有condition + ArrayList relateConditions = new ArrayList() { + { + add("wenzainali"); + add("shishenme"); + } + }; + //与npc类相关的所有condition + ArrayList classRelateConditions = new ArrayList() { + { + add("know_exist_what"); + } + }; + + + //在condition的三元组中添加与NPC相关的关键词 + + String conditionValue = "哪里:人称", repValue; + StringBuffer keywords = new StringBuffer(); + StringBuffer classKeywords = new StringBuffer(); + + for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { + + name = (String) character.get("name"); + className = (String) character.get("class"); + + if (!classSet.contains(className)) { + classSet.add(className); + classKeywords.append("+周围:" + className + "+附近:" + className); + } + + + attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); + attrIter = attribute.keySet().iterator(); + repValue = conditionValue.replace("人称", name); + keywords.append("+" + repValue); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + + } + + System.out.println(name); + + } + //根据根据NPC名字和属性查询属性值 + for (String conditionName : relateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywords, " ", + "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName + ); + jConfigList.add(jConfig); + } + //根据根据NPC类别和地点属性查询所有NPC实例 + for (String conditionName : relateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + classKeywords, " ", + "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAroundNpcByClassName:" + conditionName + ); + jConfigList.add(jConfig); + } + }catch (Exception e){ + operationStatus = 0; + message = "NPC接口处理出现异常"; + return; + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java new file mode 100644 index 0000000..4a8eb60 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java @@ -0,0 +1,132 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class ElementConstructor { + + + int botId = 0; + + + + int operationStatus = 1; + SqlHelper helper = null; + HashSet exceptRelation = null; + JConfig jConfig = null; + String CHITCHAT_URL = "http:192.168.1.178:1111/test"; + String userName; + + + + String message = ""; + + + List configDataList = new ArrayList(); + List jConfigList = new ArrayList(); + StringBuffer configText = new StringBuffer(); + Map varInitialMap = new HashMap(); + Map conditionDescription = new HashMap(); + + + public String getMessage() { return message; } + + public int getOperationStatus() { return operationStatus; } + + public Map getVarInitialMap() { + return varInitialMap; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { } + + public List getjConfigList() { + return jConfigList; + } + + public Map getConditionDescription() { + return conditionDescription; + } + + public List getConfigDataList() { + return configDataList; + } + + public void ElementConstructor(String userName) { + this.userName = userName; + } + + public String getConfigText() { + return configText.toString(); + } + + public void generateConfigText(List idList) { + int id, length = idList.size(); + String varValue; + JConfig jConfig = null; + for (int i = 0; i < length; i++) { + jConfig = jConfigList.get(i); + id = idList.get(i); + + configText.append(jConfig.toString() + id + "\n"); + } + for (String varName : varInitialMap.keySet()) { + varValue = varInitialMap.get(varName); + configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); + } + + } + + public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation){ + String conditionName, pair[]; + for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ + conditionName = (String) premise.get("actionName"); + + + + if(!exceptRelation.contains(conditionName)) { + + if(!relationKeywords.containsKey(conditionName + "_head")) { + relationKeywords.put(conditionName + "_head", new HashSet()); + relationKeywords.put(conditionName + "_tail", new HashSet()); + } + + for (String keyword : ((String) premise.get("keywords")).split("\\+")) { + + if(keyword.equals("")){ + continue; + + } else if(keyword.contains(":")){ + pair = keyword.split(":"); + + relationKeywords.get(conditionName + "_head").add(pair[0]); + relationKeywords.get(conditionName + "_tail").add(pair[1]); + + } else { + relationKeywords.get(conditionName + "_tail").add(keyword); + } + + } + } + + } + } + + /** + * 根据插入的数据做后处理 + * @param idList + */ + public void postProcessing(List idList, int categoryId){} + + /** + * 构造参数配置文件的json版 + */ + public void buildJconfig() { + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java new file mode 100644 index 0000000..b28d28d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java @@ -0,0 +1,106 @@ +package com.qiwu.chatbotbackend.gameDesign; + +/** + * 弗洛伊德算法,用于构造地图时求最短路径 + */ +public class Floyd { + + + /** + * 表示正无穷 + */ + int MAX_WEIGHT = Integer.MAX_VALUE; + /** + * 路径矩阵 + */ + int[][] pathMatirx; + /** + * 前驱表 + */ + int[][] preTable; + + + public void findShortestPath(int[][] matrix, int length) { + //路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。 + pathMatirx = new int[length][length]; + //前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值 + preTable = new int[length][length]; + + /* + System.out.println("matrix"); + for (int i = 0; i < length; i++){ + for(int j = 0; j < length; j++){ + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + */ + + //初始化D,P + for (int i = 0; i < length; i++) { + for (int j = 0; j < length; j++) { + pathMatirx[i][j] = matrix[i][j]; + preTable[i][j] = j; + } + } + + //循环 中间经过顶点 + for (int k = 0; k < length; k++) { + //循环所有路径 + for (int m = 0; m < length; m++) { + + for (int n = 0; n < length; n++) { + + int mn = pathMatirx[m][n]; + int mk = pathMatirx[m][k]; + int kn = pathMatirx[k][n]; + int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn; + + if (mn > addedPath) { + //如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个 + pathMatirx[m][n] = addedPath; + //前驱设置为经过下标为k的顶点 + preTable[m][n] = preTable[m][k]; + } + + } + } + } + + /* + System.out.println("pathMatrix"); + for (int i = 0; i < length; i++){ + for(int j = 0; j < length; j++){ + System.out.print(pathMatirx[i][j] + " "); + } + System.out.println(); + } + */ + } + + /** + * 打印 所有最短路径 + */ + public void printPath(int[][] matrix, int length) { + + + for (int m = 0; m < length; m++) { + for (int n = m + 1; n < length; n++) { + + int k = preTable[m][n]; + System.out.print("(" + m + "," + n + ")" + pathMatirx[m][n] + ": "); + System.out.print(m); + while (k != n) { + System.out.print("->" + k); + k = preTable[k][n]; + } + + System.out.println("->" + n); + } + System.out.println(); + } + + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java new file mode 100644 index 0000000..cb5233a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java @@ -0,0 +1,46 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +public class GlobalVariableConstructor extends ElementConstructor { + + public GlobalVariableConstructor(SqlHelper helper, int botId, HashSet exceptRelation) { + super(); + this.helper = helper; + this.botId = botId; + this.exceptRelation = exceptRelation; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { + + try { + String category, name, description, attrName, attrValue; + JSONArray globalVariable = gameElements.getJSONArray("globalVariable"); + Map attribute = null; + Iterator attrIter = null; + + for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) { + category = (String) variableList.get("category"); + attribute = gameElements.toJavaObject(variableList.getJSONObject("variables"), Map.class); + attrIter = attribute.keySet().iterator(); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + varInitialMap.put(category + "_" + attrName, attrValue); + } + } + }catch (Exception e){ + operationStatus = 0; + message = "全局变量处理出现异常"; + return; + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java new file mode 100644 index 0000000..00f74a6 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java @@ -0,0 +1,99 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class ItemConstructor extends ElementConstructor { + + + public ItemConstructor(SqlHelper helper, int botId, HashSet exceptRelation) { + super(); + this.helper = helper; + this.botId = botId; + this.exceptRelation = exceptRelation; + } + + + public void construct(JSONObject gameElements, UserInfo userinfo) { + try { + String category, name, className, description, attrName, attrValue; + JSONArray goods = gameElements.getJSONArray("goods"); + Map attribute = null; + Iterator attrIter = null; + HashSet classSet = new HashSet(); + + //与物品属性查询相关的所有condition + ArrayList attrRelateConditions = new ArrayList() { + { + add("nums"); + add("shishenme"); + } + }; + //与物品类查询相关的所有condition + ArrayList classRelateConditions = new ArrayList() { + { + add("know_exist_what"); + } + }; + + StringBuffer keywords = new StringBuffer(); + StringBuffer classKeywords = new StringBuffer(); + + for (JSONObject good : goods.toJavaList(JSONObject.class)) { + name = (String) good.get("name"); + className = (String) good.get("class"); + + if (!classSet.contains(className)) { + classSet.add(className); + //添加周围有什么士兵等关于类别的关键词 + classKeywords.append("+周围:" + className + "+附近:" + className); + } + + attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); + attrIter = attribute.keySet().iterator(); + while (attrIter.hasNext()) { + attrName = attrIter.next(); + attrValue = attribute.get(attrName); + keywords.append("+" + name + ":" + attrName); + + } + + + } + + //根据根据物品名字和属性查询属性值 + for (String conditionName : attrRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywords, " ", + "match,return-0", + "{goods_query-2}", + " ", + "goods_query:queryAttrByGoodsName:" + conditionName + ); + jConfigList.add(jConfig); + } + + //根据类名和地点查询所有实例 + for (String conditionName : attrRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + classKeywords, " ", + "match,return-0", + "{goods_query-2}", + " ", + "goods_query:queryAroundGoodsByClassName:" + conditionName + ); + jConfigList.add(jConfig); + } + } catch(Exception e){ + operationStatus = 0; + message = "物品处理出现异常"; + return; + } + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java new file mode 100644 index 0000000..cd014c5 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java @@ -0,0 +1,310 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class MapConstructor extends ElementConstructor { + + int[][] matrix; + int locationNum; + HashMap id2j = new HashMap(); + Map question2keyword = new HashMap(); + JSONArray locations = null; + + public MapConstructor(SqlHelper helper, int botId, HashSet exceptRelation) { + super(); + this.helper = helper; + this.botId = botId; + this.exceptRelation = exceptRelation; + } + + + public void constructGreph(JSONArray locations) { + + JSONObject jobj = null; + int locationId, index; + + //ArrayList> matrix= new ArrayList>(); + //ArrayList vec1d = new ArrayList(); + locationNum = locations.size(); + + for (int i = 0; i < locationNum; i++) { + jobj = locations.getJSONObject(i); + jobj.put("index", i); + locationId = (Integer) jobj.get("id"); + id2j.put(locationId, jobj); + } + + //邻接矩阵初始化 + matrix = new int[locationNum][locationNum]; + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { + matrix[i][j] = Integer.MAX_VALUE; + } + } + + for (int i = 0; i < locationNum; i++) { + List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); + for (int neighbourId : neighbours) { + JSONObject neighbourObject = id2j.get(neighbourId); + System.out.println(neighbourObject); + index = (Integer) neighbourObject.get("index"); + matrix[i][index] = 1; + matrix[index][i] = 1; + } + } + } + + + public void construct(JSONObject gameElements, UserInfo userinfo) { + + try { + conditionDescription.put("site", "当前地点"); + varInitialMap.put("site", "海边"); + JSONObject map = gameElements.getJSONObject("map"); + Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); + JSONArray locations = map.getJSONArray("locations"); + String userName = (String) gameElements.get("userName"); + this.locations = locations; + this.question2keyword = question2keyword; + //通过邻接表构造邻接矩阵 + constructGreph(locations); + + //用弗洛伊德算法求最短路径 + Floyd floyd = new Floyd(); + floyd.findShortestPath(matrix, locationNum); + floyd.printPath(matrix, locationNum); + generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements); + generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements); + generateWhereIam(gameElements, userName); + generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements); + generateSurroundingItem(); + generateSurroundingPeople(); + generateSurroundThings(); + + } catch(Exception e){ + operationStatus = 0; + message = "地图处理出现异常"; + return; + } + + } + + /** + * 生成‘我在哪里’所需要的配置文件 + */ + public void generateWhereIam(JSONObject gameElements, String botName) { + String conditionName = "rencheng"; + String conditionKeywords = "qiwu:哪里+qiwu:哪+现在:哪里+现在:哪"; + String zainaliKeywords = conditionKeywords.replace("botName", botName); + jConfig = new JConfig( + conditionName + "::match-Include=" + zainaliKeywords, " ", + "match", "你在{site-2}", "yaobuyao", "" + ); + jConfigList.add(jConfig); + + } + + + + + + /** + * 生成‘怎么去哪里’所需要的配置文件 + */ + public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String conditionName = "want_know_zenmezuo"; + String conditionKeywords = "去:地点"; + + String placeA, placeB, descriptionB, placeKeywords, text, pathNode; + + + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { + + + placeA = (String) locations.getJSONObject(i).get("name"); + placeB = (String) locations.getJSONObject(j).get("name"); + placeKeywords = conditionKeywords.replace("地点", placeB); + + if (i == j) { + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, + "match", "你已经在" + placeB + "了", "yaobuyao", "" + ); + jConfigList.add(jConfig); + continue; + } + ; + if (pathMatirx[i][j] == 1) { + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, + "match", placeB + "就在附近哦", "yaobuyao", "" + ); + jConfigList.add(jConfig); + + } else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) { + int k = preTable[i][j]; + pathNode = ""; + while (k != j) { + pathNode += (String) locations.getJSONObject(k).get("name"); + k = preTable[k][j]; + } + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, + "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", "" + ); + jConfigList.add(jConfig); + } + } + } + } + + + /** + * 生成‘我能去哪里’所需要的配置文件 + */ + public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String conditionKeywords = "去:哪里+能去:哪+能去:哪里+能去:哪儿"; + String conditionName = "choose_gowhere"; + String placeA, placeB, pathNode; + + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); + pathNode = ""; + + for (int j = 0; j < locationNum; j++) { + if (pathMatirx[i][j] == 1) { + placeB = (String) locations.getJSONObject(j).get("name"); + pathNode += "、" + placeB; + } + } + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, "site::match-Include=" + placeA, + "match", "你可以去" + pathNode, "yaobuyao", "" + ); + jConfigList.add(jConfig); + } + } + + + /** + * 生成‘我要去那里’所需要的配置文件 + */ + public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String placeA, placeB, descriptionB, placeKeywords, text, pathNode, lastTaskCondition, lastTaskReply; + String conditionName = "yaobuyao"; + String conditionKeywords = "地点"; + String start = (String)gameElements.get("start"); + + + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); + + /** + * 添加初始化变量 + */ + if(!varInitialMap.containsKey("任务线" + placeA + "最后一个condition")) { + varInitialMap.put("任务线" + placeA + "最后一个condition", "yaobuyao"); + varInitialMap.put("任务线" + placeA + "最后的回答", "你来到了" + placeA + ",现在什么都没有, 请继续之前的剧情,接着往下玩吧!"); + conditionDescription.put("任务线" + placeA + "最后一个condition", "任务线" + placeA + "最后一个condition"); + conditionDescription.put("任务线" + placeA + "最后的回答", "任务线" + placeA + "最后的回答"); + } + + + for (int j = 0; j < locationNum; j++) { + placeB = (String) locations.getJSONObject(j).get("name"); + descriptionB = (String) locations.getJSONObject(j).get("description"); + placeKeywords = conditionKeywords.replace("地点", placeB); + lastTaskCondition = "任务线" + placeB + "最后一个condition"; + lastTaskReply = "任务线" + placeB + "最后的回答"; + + + if (i == j) { + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, + "match", "你已经在" + placeB + "了", "yaobuyao", "" + ); + jConfigList.add(jConfig); + continue; + } + ; + + //如果两点相邻 + if (pathMatirx[i][j] == 1) { + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, + "site::match-Include=" + placeA + "," + lastTaskCondition + "::match-Include=null" + "," + lastTaskReply + "::match-Include=null", + "match, reutrn-0", "地点尚未激活", "yaobuyao", "" + ); + jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA, + "match", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeB + "-<-process-nextStep:var={" + lastTaskCondition +"-2}" + ); + jConfigList.add(jConfig); + + + //如果两点不是相邻点 + } else if (pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE) { + + + int k = preTable[i][j]; + pathNode = ""; + while (k != j) { + pathNode += (String) locations.getJSONObject(k).get("name"); + k = preTable[k][j]; + } + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords, + "site::match-Include=" + placeA, + "match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", "" + ); + jConfigList.add(jConfig); + } + } + } + } + + public void generateSurroundingPeople(){ + String conditionName = "know_exist_what"; + String conditionKeywords = "周围:人+附近:人"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:" + ); + jConfigList.add(jConfig); + } + + public void generateSurroundingItem(){ + String conditionName = "know_exist_what"; + String conditionKeywords = "周围:物品+周围:东西+附近:物品+附近:东西"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:" + ); + jConfigList.add(jConfig); + } + + public void generateSurroundThings(){ + String conditionName = "know_exist_what_mohu"; + String conditionKeywords = "有什么:周围+有什么:附近"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "周围{map_query-2}。", "yaobuyao", "map_query:queryAroundAllBySite:" + ); + jConfigList.add(jConfig); + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor.java new file mode 100644 index 0000000..9b20363 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor.java @@ -0,0 +1,805 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; +import org.apache.http.message.BasicNameValuePair; +import com.qiwu.chatbotbackend.processing.MyFunc; + +import java.io.UnsupportedEncodingException; +import java.util.*; + + +public class PlotConstructor extends ElementConstructor { + + String botName = ""; + + JSONArray plots = null; + HashMap> adjList = new HashMap>(); + HashMap> revAdjList = new HashMap>(); + private HashMap id2j = new HashMap(); + HashMap visited = new HashMap(); + + public HashMap getId2j() { + return id2j; + } + + public PlotConstructor(SqlHelper helper, int botId, HashSet exceptRelation) { + super(); + this.helper = helper; + this.botId = botId; + this.exceptRelation = exceptRelation; + } + + public void construct(JSONObject jsonObject, UserInfo userinfo) { + + try { + JSONArray plots = jsonObject.getJSONArray("plots"); + String start = (String) jsonObject.get("start"), startCondition; + JSONObject returnMessage = null; + + this.plots = plots; + constructAdjList(plots); + + if (id2j.containsKey(start)) { + String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, start); + varInitialMap.put("unknownText", "你说啥?"); + varInitialMap.put("game_step", (String) id2j.get(start).get("id")); + conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); + conditionDescription.put("game_step", "QA问答游戏进度"); + + + BFSGenerate4(id2j.get(start), userinfo, jsonObject); + + varInitialMap.put(start, "1"); + + + } else { + System.out.println("start剧情不存在"); + operationStatus = 0; + message = "start剧情不存在"; + return; + } + } catch(Exception e){ + operationStatus = 0; + message = "地图接口处理出现异常"; + return; + } + } + + //根据id构造邻接表 + public void constructAdjList(JSONArray plots) { + int length = plots.size(), branchSize; + String id = "", nextPlotId = ""; + JSONObject plot = null; + JSONArray branch = null; + + for (int i = 0; i < length; i++) { + plot = plots.getJSONObject(i); + id = (String) plot.get("id"); + plot.put("index", i); + + if (adjList.get(id) == null) { + adjList.put(id, new ArrayList<>()); + } + + //添加branch中的下一个plot + branch = plot.getJSONArray("branch"); + branchSize = branch.size(); + for (int j = 0; j < branchSize; j++) { + nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); + if (revAdjList.get(nextPlotId) == null) { + revAdjList.put(nextPlotId, new ArrayList<>()); + } + adjList.get(id).add(nextPlotId); + revAdjList.get(nextPlotId).add(id); + + } + id2j.put(id, plot); + } + } + + + /** + * 根据每个剧情点的进度设置计数器 + * @param root + * @param userinfo + */ + public void BFSGenerate(JSONObject root, UserInfo userinfo) { + String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + nextUnknownText, curUnknownText, nextCondition; + boolean newBranch, manyParent; + JSONObject node = null, branchNode = null, adjNode = null; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("priority", 0); + root.put("taskName", id); + root.put("taskStep", 0); + root.put("nextUnknownText", varInitialMap.get("unknownText")); + ; + + + Queue queue = new LinkedList(); + + queue.add(root); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + conditionDescription.put(id, "剧情" + id + "进度"); + varInitialMap.put(id, ""); + + + taskName = (String) node.get("taskName"); + priority = (Integer) node.get("priority"); + taskStep = (Integer) node.get("taskStep"); + conditionName = (String) node.get("conditionName"); + curUnknownText = (String) node.get("nextUnknownText"); + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id, true); + + //查看是否存在多个子结点,如果有就是一个分支 + if (adjNodeList.size() > 1) + newBranch = true; + + //查看是否存在多个父节点 + if (revAdjList.get(id) != null) + manyParent = revAdjList.get(id).size() > 1; + + if (newBranch) { + //多个分支时nextTaskName为子结点的id名,不在这里设 + nextTaskStep = 1; + } else { + if (manyParent) { + nextTaskName = id; + nextTaskStep = 1; + priority++; + } else { + nextTaskName = taskName; + nextTaskStep = taskStep + 1; + } + } + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + + + for (int i = 0; i < branchSize; i++) { + + branchNode = branch.getJSONObject(i); + nextId = (String) branchNode.get("nextPlotId"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + nextUnknownText = updateKnowledge.get("unknownText"); + + + if (id2j.get(nextId) != null) + nextCondition = (String) id2j.get(nextId).get("conditionName"); + else + nextCondition = " "; + + + //unknown计数器更新为0, 当前任务状态+1 + if (newBranch) + extraUK = taskName + ":" + taskStep; + //多余步骤,以后要处理掉 + + else + extraUK = taskName + ":" + (taskStep + 1); + + + extraHP = taskName + "::match-Include=" + taskStep; + if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) + extraHP += "," + nextId + "::match-Include=null"; + extraUK += "-<-" + nextId + ":" + 1; + + jConfig = new JConfig( + JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), + JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), + updateKnowledge, + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, String.valueOf(priority) + ); + jConfigList.add(jConfig); + + + try { + keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null) { + if (id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + adjNode.put("nextUnknownText", nextUnknownText); + adjNode.put("taskStep", nextTaskStep); + if (newBranch) { + adjNode.put("priority", priority + 1); + adjNode.put("taskName", adjId); + } else { + adjNode.put("priority", priority); + adjNode.put("taskName", taskName); + } + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); + } + } + } + } + + + //对于unknown的特殊处理 + if (curUnknownText.equals("")) { + jConfig = new JConfig( + conditionName + "::match-Include=unknown", + extraHP = taskName + "::match-Include=" + taskStep, + "match,return-0,post::all(" + CHITCHAT_URL + ")", + " ", + " ", + "" + ); + jConfigList.add(jConfig); + } + /* + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP + ",unknown_counter::number-SmallOrEqual=0", + "match", + "{unknownReply-2}", + " ", + "unknown_counter:+1" + ); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Keyword=unknown", + extraHP + ",unknown_counter::number-BiggerOrEqual=1", + "match", + "你可以说" + keywordOptions, + " ", + "unknown_counter:+1" + ); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + + */ + + + } + //unknown时的处理 + jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + + + } + + + //每个结点分为0、1、2三种状态 + public void BFSGenerate2(JSONObject root) { + String id = (String) root.get("id"), adjId, nextId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + unknownReply1, unknownReply2, nextCondition; + boolean newBranch, manyParent; + JSONObject node = null, branchNode = null, adjNode = null; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("priority", 0); + root.put("taskName", id); + root.put("taskStep", 0); + + + Queue queue = new LinkedList(); + + queue.add(root); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id, true); + + /* + //查看是否存在多个子结点,如果有就是一个分支 + if(adjNodeList.size() > 1) + newBranch = true; + + //查看是否存在多个父节点 + if(revAdjList.get(id) != null) + manyParent = revAdjList.get(id).size() > 1; + + if(newBranch){ + //多个分支时nextTaskName为子结点的id名,不在这里设 + nextTaskStep = 1; + } + else{ + if(manyParent){ + nextTaskName = id; + nextTaskStep = 1; + priority++; + } + else{ + nextTaskName = taskName; + nextTaskStep = taskStep + 1; + } + } + */ + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + extraHP = id + "::match-Include=" + 1; + + + for (int i = 0; i < branchSize; i++) { + + branchNode = branch.getJSONObject(i); + nextId = (String) branchNode.get("nextPlotId"); + if (id2j.get(nextId) != null) + nextCondition = (String) id2j.get(nextId).get("conditionName"); + else + nextCondition = " "; + + + extraUK = id + ":" + "+1-<-" + nextId + ":" + "+1"; + + + //if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) + // extraUK += "-<-" + nextId + ":" + 1; + + jConfig = new JConfig( + JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), + JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), + JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class), + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, "0" + ); + jConfigList.add(jConfig); + + try { + keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null && id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + queue.add(adjNode); + } + } + } + + + } + //unknown时的处理 + jConfig = new JConfig(" ", " ", "", "{unknownText-2}", " ", ""); + jConfig.setNextStepStatus("return-0"); + jConfigList.add(jConfig); + + + } + + + /** + * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 + * @param root + * @param userinfo + */ + public void BFSGenerate3(JSONObject root, UserInfo userinfo) { + String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition; + boolean newBranch, manyParent; + JSONObject node = null, branchNode = null, adjNode = null; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("nextUnknownText", varInitialMap.get("unknownText")); + root.put("parentId", "null"); + + + Queue queue = new LinkedList(); + System.out.println("rootId"); + + queue.add(root); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + parentId = (String) node.get("parentId"); + location = (String) node.get("place"); + conditionName = (String) node.get("conditionName"); + curUnknownText = (String) node.get("nextUnknownText"); + taskLineName = "任务线_" + location + "进度"; + //本任务线的最后一个condition和本任务线的最后一个回答 + + + + if (!varInitialMap.containsKey(taskLineName)) { + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, ""); + } + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id, true); + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + + + for (int i = 0; i < branchSize; i++) { + + branchNode = branch.getJSONObject(i); + + nextId = (String) branchNode.get("nextPlotId"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + nextUnknownText = updateKnowledge.get("unknownText"); + + + //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 + if (id2j.get(nextId) != null) { + nextCondition = (String) id2j.get(nextId).get("conditionName"); + nextLocation = (String) id2j.get(nextId).get("place"); + nTaskLineName = "任务线_" + nextLocation + "进度"; + } else { + //如果不存在下一剧情,就将condition设为空,任务线进度不变 + nextCondition = " "; + nTaskLineName = taskLineName; + nextLocation = location; + } + + lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; + lastTaskReply = "任务线" + nextLocation + "最后的回答"; + + + //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location; + + + + //测试用 + System.out.println(id); + + extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}"; + + + + jConfig = new JConfig( + JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), + JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), + updateKnowledge, + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, "0" + ); + jConfigList.add(jConfig); + + + +// try { +// keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; +// } catch (Exception e) { +// e.printStackTrace(); +// } + + + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null) { + if (id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + adjNode.put("parentId", id); + adjNode.put("nextUnknownText", nextUnknownText); + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); + } + } + } + } + + + + + //对于unknown的特殊处理 + if (curUnknownText.equals("")) { + jConfig = new JConfig( + conditionName + "::match-Include=unknown", + extraHP = "任务线_" + location + "进度::match-Include=" + parentId, + "match,return-0,post::all(" + CHITCHAT_URL + ")", + " ", + " ", + "" + ); + jConfigList.add(jConfig); + } + + } + + jConfig = new JConfig( + " ", " ", "", " ", " ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("unknown"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + jConfig = new JConfig( + " ", "", "", " " ," ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("common_answer"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + + + } + + + /** + * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 + * 加上剧情计数器, 每一步分为三个状态 + * @param root + * @param userinfo + */ + public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { + String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition; + boolean newBranch, manyParent; + JSONObject node = null, branchNode = null, adjNode = null; + JSONArray branch = null; + + List adjNodeList = null; + int priority, taskStep, nextPriority, nextTaskStep, branchSize; + + root.put("nextUnknownText", varInitialMap.get("unknownText")); + root.put("parentId", "null"); + + + String startPlace = (String)root.get("place"); + varInitialMap.put("任务线" + startPlace + "最后一个condition", (String)root.get("conditionName")); + varInitialMap.put("任务线" + startPlace + "最后的回答", (String)jsonObject.get("plotStartText")); + conditionDescription.put("任务线" + startPlace + "最后一个condition","任务线" + startPlace + "最后一个condition"); + conditionDescription.put("任务线" + startPlace + "最后的回答", "任务线" + startPlace + "最后的回答"); + + + Queue queue = new LinkedList(); + + queue.add(root); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + parentId = (String) node.get("parentId"); + location = (String) node.get("place"); + conditionName = (String) node.get("conditionName"); + curUnknownText = (String) node.get("nextUnknownText"); + taskLineName = "任务线_" + location + "进度"; + conditionDescription.put(id, "剧情" + id + "状态"); + varInitialMap.put(id ,""); + nextUnknownText = ""; + //本任务线的最后一个condition和本任务线的最后一个回答 + + + + if (!varInitialMap.containsKey(taskLineName)) { + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, ""); + } + + //初始化 + newBranch = false; + manyParent = false; + + adjNodeList = adjList.get(id); + visited.put(id, true); + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + //当两次出现unknown时给用户一下候选项 + keywordOptions = ""; + + + for (int i = 0; i < branchSize; i++) { + + branchNode = branch.getJSONObject(i); + + nextId = (String) branchNode.get("nextPlotId"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + if(updateKnowledge.containsKey("unkonwnText")) + nextUnknownText = updateKnowledge.get("unknownText"); + else + nextUnknownText = "unknown"; + + + //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 + if (id2j.get(nextId) != null) { + nextCondition = (String) id2j.get(nextId).get("conditionName"); + nextLocation = (String) id2j.get(nextId).get("place"); + nTaskLineName = "任务线_" + nextLocation + "进度"; + } else { + //如果不存在下一剧情,就将condition设为空,任务线进度不变 + nextCondition = " "; + nTaskLineName = taskLineName; + nextLocation = location; + } + + lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; + lastTaskReply = "任务线" + nextLocation + "最后的回答"; + + + //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + + extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}" + + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-game_step:" + botName + "_plot_" + nextId; + + jConfig = new JConfig( + JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), + JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), + updateKnowledge, + "", extraHP, extraUK, + "match", (String) branchNode.get("reply"), (String) nextCondition, "0" + ); + jConfigList.add(jConfig); + + + +// try { +// keywordOptions += jConfig.getCurPremise().split(",")[0].split("=")[1].split("\\+")[0] + " 或者"; +// } catch (Exception e) { +// e.printStackTrace(); +// } + + + if (branchNode.get("nextPlotId") != null) { + adjId = (String) branchNode.get("nextPlotId"); + if (visited.get(adjId) == null) { + if (id2j.get(adjId) != null) { + adjNode = id2j.get(adjId); + + adjNode.put("parentId", id); + adjNode.put("nextUnknownText", nextUnknownText); + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); + } + } + } + } + + + + + //对于unknown的特殊处理 + //对于unknown的特殊处理 + if (curUnknownText.equals("")) { + jConfig = new JConfig( + conditionName + "::match-Include=unknown", + extraHP = "任务线_" + location + "进度::match-Include=" + parentId, + "match,return-0,post::all(" + CHITCHAT_URL + ")", + " ", + " ", + "" + ); + jConfigList.add(jConfig); + } + + } + + + /** + * ---------------------------------------------------------------------------------------------------- + * 待激活列表,用于qa问答 + */ + + jConfig = new JConfig( + " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("unknown1"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + jConfig = new JConfig( + " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", + "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", + " ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("unknown2"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + + + jConfig = new JConfig( + " ", "qa_status::match-Include=ok,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", + "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", + " ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("unknown3"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + + + jConfig = new JConfig( + " ", "qa_status::match-Include=ok,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("unknown4"); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + + + jConfig = new JConfig( + " ", "qa_status::match-Include=ok,qa_score::number-BiggerOrEqual=90", "match,return-0", "{common_answer-2}" ," ", "" + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("common_answer"); + jConfigList.add(jConfig); + //--------------------------------------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------------------------------------- + + } + + @Override + public void postProcessing(List idList, int categoryId){ + if (idList.size() != 0) { + jConfig = new JConfig(" ", " ", "activate,post::all(http://simqa.sz.chewrobot.com:28081/game)", "", idList.get(idList.size() - 5) + "," + idList.get(idList.size() - 4) + "," + idList.get(idList.size() - 3) + "," + idList.get(idList.size() - 2) + "," + idList.get(idList.size() - 1), ""); + jConfig.setNextStepStatus("active"); + JSONObject json = jConfig.toJson(this.getConditionDescription()); + helper.insertConfigByBotId(botId, json, idList, categoryId); + jConfigList.add(jConfig); + } + } + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java new file mode 100644 index 0000000..7391641 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java @@ -0,0 +1,233 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.alibaba.fastjson.JSON; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.*; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class ChatCacheController { + /** + * 通过chat_key获得后台保存的历史信息点 + * chatCache:存储了chatKye相对应的对话记录(历史信息点) + * + * @return 历史信息点,对话过程中引擎提取的用户信息 + */ +// public static synchronized Map getChatCache(String chatKey, ServletContext context) { +// +// GameEnv gameEnv = new GameEnv(chatKey); +// 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; +// +// +// try { +// historyInfoPoint = chatCache.get(chatKey); +// //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); +// } catch (Exception e) { +// +// //可整合 +// historyInfoPoint = null; +// +// } +// +// return historyInfoPoint; +// } + + + /** + * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 + */ +// 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); +// } + + /** + * 根据chatKey更新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); +// } + + public static boolean saveChatCache(String userName, HashMap infoPoints) throws IOException { + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String key; + boolean saveFlag = true; + try { + File dir = new File(fileDir); + if (!dir.exists()) + dir.mkdir(); + + File file = new File(fileDir + "/" + userName + ".txt"); + FileWriter fw = new FileWriter(file); + + Iterator infoIter = infoPoints.keySet().iterator(); + while (infoIter.hasNext()) { + key = infoIter.next(); + fw.write(key + "-----" + infoPoints.get(key) + "\n"); + } + fw.close(); + + } catch (Exception e) { + saveFlag = false; + } + + return saveFlag; + } + + public static boolean loadChatCache(String userName, ServletContext context) { + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + Map infoPoints = new HashMap(); + try { + File file = new File(fileDir + "/" + userName + ".txt"); + if (!file.exists()) { + return false; + } else { + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + while ((line = br.readLine()) != null) { + pair = line.trim().split("-----"); + infoPoints.put(pair[0], pair[1]); + } + // context.setAttribute(userName, ); + + fr.close(); + + } + + } catch (IOException e) { + e.printStackTrace(); + } + + return true; + } + + + + + + + public static synchronized ChatCache getChatCache(String chatKey, ServletContext context, UserInfo userinfo) throws Exception { + Map chatCacheMap = null; + ChatCache chatCache = null; + if (context.getAttribute("chatCache") == null) { + chatCacheMap = new HashMap(); + chatCacheMap.put(chatKey, new ChatCache(userinfo)); + context.setAttribute("chatCache", chatCacheMap); + } else { + chatCacheMap = (Map) context.getAttribute("chatCache"); + } + String chatkey; + + + try { + chatCache = chatCacheMap.get(chatKey); + if(chatCache == null){ + chatCache = new ChatCache(userinfo); + chatCacheMap.put(chatKey, chatCache); + } + //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); + } catch (Exception e) { + //可整合 + chatCache = new ChatCache(userinfo); + + } + + return chatCache; + } + + + /** + * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 + */ + public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context) { + String chatKey; + ChatCache chatCache = null; + long lastChatTime, now; + Map history = new HashMap(); + Map chatCacheMap = (Map) context.getAttribute("chatCache"); + + + Iterator it = chatCacheMap.keySet().iterator(); + while (it.hasNext()) { + chatKey = it.next(); + if(curChatKey.equals(chatKey)) + continue; + history = chatCacheMap.get(chatKey).getInfoPoint(); + lastChatTime = Long.valueOf(history.get("lastUpdateTime")); + now = System.currentTimeMillis(); + if (now - lastChatTime > 300000) { + chatCache = chatCacheMap.get(chatKey); + saveChatCache(chatKey, chatCache); + it.remove(); + } + } + context.setAttribute("chatCache", chatCacheMap); + } + + /** + * 根据chatKey更新chatCache的数据,并修改最后更新时间 + */ + public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context) { + historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + Map keyCacheMap = (Map) context.getAttribute("chatCache"); + ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); + chatCache.setInfoPoint(historyInfoPoint); + chatCache.setGameEnv(gameEnv); + context.setAttribute("chatCache", keyCacheMap); + } + + public static synchronized String saveChatCache(String chatKey, ChatCache chatCache){ + + if(chatCache == null){ + return "chat_key不存在或者已失效"; + }else { + String jChatCache = JSON.toJSONString(chatCache); + System.out.println(jChatCache); + + + + chatCache = JSON.parseObject(jChatCache,ChatCache.class); + System.out.println(chatCache.getInfoPoint().size()); + + return "成功"; + } + + + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/ConditionTableController.java b/src/main/java/com/qiwu/chatbotbackend/processing/ConditionTableController.java new file mode 100644 index 0000000..377260a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ConditionTableController.java @@ -0,0 +1,228 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class ConditionTableController { + + public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { + int id = Integer.parseInt(configId); + Condition condition = new Condition(); + UserInfoController userInfoController = new UserInfoController(); + //data=configLine+"---"+conditionNameList + + String conditionNameList[] = data.split(","); + String conditionName = ""; + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userInfo = (UserInfo) context.getAttribute(userName); + + if (userInfo.id2config.containsKey(id)) { + + //------------------- + try { + Condition oldCondition = userInfo.id2condition.get(id); + conditionName = oldCondition.indexName; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (userInfo.conditionTable.get(conditionName) != null) { + List conditionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Condition c = condIter.next(); + if (c.id == id) { + condIter.remove(); + } + } + } + + userInfo.id2config.remove(id); + userInfo.id2condition.remove(id); + } else { + System.out.println("未找到要删除的configId"); + } + + return true; + } + + public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { + Condition condition = new Condition(); + String conditionName = ""; + + for (int configId : idGroup) { + if (userInfo.id2config.containsKey(configId)) { + try { + Condition oldCondition = userInfo.id2condition.get(configId); + conditionName = oldCondition.indexName; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (userInfo.conditionTable.get(conditionName) != null) { + List conditionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Condition c = condIter.next(); + if (c.id == configId) { + condIter.remove(); + } + } + } + + userInfo.id2config.remove(configId); + userInfo.id2condition.remove(configId); + } else { + System.out.println("未找到要删除的configId:" + configId); + } + } + + + return true; + } + + + public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { + Condition condition = new Condition(); + //data=configLine+"---"+conditionNameList + String dataPair[] = data.split("---"); + String configLine = dataPair[0]; + String conditionNameList[]; + UserInfoController userInfoController = new UserInfoController(); + int id = Integer.parseInt(configId); + + condition = userInfoController.buildCondition(condition, configLine); + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + if (userinfo.conditionTable.get(condition.indexName) == null) { + List conditionList = new ArrayList(); + userinfo.conditionTable.put(condition.indexName, conditionList); + } + userinfo.conditionTable.get(condition.indexName).add(condition); + userinfo.id2config.put(id, configLine); + userinfo.id2condition.put(id, condition); + + return true; + + } + + public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { + Condition condition = new Condition(); + //data=configLine+"---"+conditionNameList + String dataPair[] = data.split("---", -1); + String name = dataPair[0], value = dataPair[1]; + + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.put(name, value); + + + return true; + + } + + public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { + //data=configLine+"---"+conditionNameList + String name = data; + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.remove(name); + + + return true; + + } + + + public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + String extraElements[] = data.split("\\|"); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + + return true; + } + + + public static String writeConfigText(String userName, UserInfo userinfo) throws IOException { + + System.out.println("p"); + System.out.println(userName); + String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText; + String path = CONFIG_DIR + "/" + userName + ".txt"; + File file = new File(path); + File dir = new File(System.getProperty("user.dir") + "/config"); + String returnMessage = "success"; + + if (!dir.exists()) + dir.mkdir(); + if (!file.exists()) { + file.createNewFile(); + } + + FileWriter fw = new FileWriter(file); + BufferedWriter bw = new BufferedWriter(fw); + try { + Iterator keyIter = userinfo.extraInfo.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + if (!userinfo.extraInfo.get(info).equals("")) + bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); + } + + keyIter = userinfo.varInitialMap.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); + } + + Iterator idIter = userinfo.id2config.keySet().iterator(); + while (idIter.hasNext()) { + int id = idIter.next(); + bw.write(userinfo.id2config.get(id) + "\n"); + } + bw.write("\n"); + } catch (Exception e) { + e.printStackTrace(); + returnMessage = "config file write error"; + } finally { + bw.close(); + fw.close(); + } + + return returnMessage; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java b/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java new file mode 100644 index 0000000..5e49529 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.processing; + +import java.io.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; + +public class LogWriter { + private PrintWriter recorder = null; + DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"); + LocalDateTime ldt = null; + + String PRINT_PATTERN = "[%s] %s" + + "----------------------------------------------------------------------------
"; + Map colerMap = new HashMap(){ + { + put(0, "black"); + put(1, "gray"); + put(2, "green"); + put(3, "yellow"); + put(4, "green"); + put(5, "red"); + } + }; + public LogWriter(String filePath, String fileName) throws IOException { + File file = new File(filePath + "/" + fileName + ".html"); + + System.out.println(file.getAbsolutePath()); + + if (!file.exists()) { + file.createNewFile(); + } + file.setReadable(true,false); + + FileWriter fw = new FileWriter(file, true); + + + BufferedWriter bw = new BufferedWriter(fw); + recorder = new PrintWriter(bw); + recorder.println("\n" + + "\n" + + "\n" + + " \n" + + " log\n" + + ""); + } + + public void record(String text, int level){ + ldt = LocalDateTime.now(); + recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), ldt.format(dtf), text)); + } + public void writeln(){ + recorder.println("
"); + } + + public void close(){ + recorder.close(); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/MyFunc.java b/src/main/java/com/qiwu/chatbotbackend/processing/MyFunc.java new file mode 100644 index 0000000..2963822 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/MyFunc.java @@ -0,0 +1,147 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.entity.Solution; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.entity.UrlEncodedFormEntity; +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.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + + +public class MyFunc { + + /** + * 将后台返回的数据转成json格式 + */ + public static String toJson(Solution 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(); + } + + /** + * 当请求中的数据是json格式时,该函数用于提取request中的json数据 + * + * @param request + * @return json字符串 + */ + public static String readJSONString(HttpServletRequest request) { + StringBuffer json = new StringBuffer(); + String line = null; + + try { + BufferedReader reader = request.getReader(); + while ((line = reader.readLine()) != null) { + json.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + + return json.toString(); + } + + /** + * 通过get方法传递参数时需要对参数的编码进行转换 + */ + public static String convert2Utf8(String s) { + 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; + } + + public static long transferToMillisecond(String keyword) throws ParseException { + long time; + + System.out.println(keyword); + + String timeSeries[] = {"时", "分", "秒"}; + for (String f : timeSeries) { + if (!keyword.contains(f)) + keyword += "0" + f; + } + + SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); + time = format.parse(keyword).getTime(); + + return time; + } + + public static String transferToStandardTime(long time) throws ParseException { + + SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); + + Date date = new Date(time); + return format.format(date); + + } + + public static boolean isInteger(String str){ + return true; + } + + public static JSONObject postJSON(String url, JSONObject data) throws UnsupportedEncodingException { + + JSONObject jobj = new JSONObject(); + + + + + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + String keyName = null; + + + StringEntity entity = new StringEntity(data.toJSONString(), "utf-8"); + + entity.setContentType("application/json; charset=utf-8"); + httpPost.setEntity(entity); + + try { + HttpResponse resp = client.execute(httpPost); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + + } else { + jobj.put("status", 0); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return jobj; + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/QuestionMatcher.java b/src/main/java/com/qiwu/chatbotbackend/processing/QuestionMatcher.java new file mode 100644 index 0000000..7524197 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/QuestionMatcher.java @@ -0,0 +1,1251 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.UserInfo; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.servlet.ServletContext; +import java.io.*; +import java.text.ParseException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class QuestionMatcher { + + Map activatedMap = new HashMap(); + + + static String POST_DATA_ERROR = "post数据有误"; + static String POST_ERROR = "数据post时出错了"; + static String API_ERROR = "api处理过程中出错了"; + static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + + public LogWriter logWriter = null; + public UserInfo userinfo = null; + public ServletContext context = null; + public GameEnv gameEnv = null; + public Map curInfoPoint = null; + public Map historyInfoPoint = null; + public WorldController worldController = null; + + public QuestionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv) { + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; + this.logWriter = logWriter; + this.userinfo = userinfo; + this.context = context; + this.gameEnv = gameEnv; + this.worldController = new WorldController(logWriter); + } + + /** + 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 boolean infoPointPreprocessing(Map receiveParameters, Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { + + String return_str = "", k; + String receiveParameterStr = ""; + boolean debugFlag = false; + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + + //输出所有actionName的值 + Iterator iit = receiveParameters.keySet().iterator(); + receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; + while (iit.hasNext()) { + k = iit.next(); + // + receiveParameterStr += k + ": "; + curInfoPoint.put(k, receiveParameters.get(k)[0]); + + if (k.equals("debug_mode")) + debugFlag = true; + + String values[] = receiveParameters.get(k); + + for (String v : values) { + receiveParameterStr += v + " "; + } + receiveParameterStr += "
"; + if (values[0].equals(":")) { + curInfoPoint.put(k, ""); + } + if(! historyInfoPoint.containsKey(k)) + historyInfoPoint.put(k, ""); + } + logWriter.record(receiveParameterStr, 0); + + //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown + iit = curInfoPoint.keySet().iterator(); + boolean unknown_flag = true; + while (iit.hasNext()) { + k = iit.next(); + String values = curInfoPoint.get(k); + if (skipSet.contains(k)) + continue; + if (!values.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"); + historyInfoPoint.put("currentAction", currentAction); + } else + currentAction = " "; + + + curInfoPoint.put("emptySet", " "); + if (historyInfoPoint.get("activeList") == null) { + historyInfoPoint.put("activeList", currentAction); + } + + if (unknown_flag && !currentAction.equals("")) { + String i = "unknown"; + curInfoPoint.put(currentAction, i); + } + + return debugFlag; + } + + + /** + * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch + * + * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 + * @return bestMatch 状态表中满足条件最多的一条 + */ + public Condition getBestMatch( HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { + + Integer configId = 0; + List conditionList = null; + Condition bestMatch = new Condition(-1), iterCon; + Iterator it = curInfoPoint.keySet().iterator(); + Queue activatedQueue = new LinkedList(); + Queue activatedCondition = new LinkedList(); + + + + while (it.hasNext()) { + String conditionName = it.next(); + String keywords = curInfoPoint.get(conditionName); + String keyword = null; + + if (keywords != null && !keywords.equals("")) + keyword = keywords; + + + if (keyword != null && conditionTable.get(conditionName) != null) { + conditionList = conditionTable.get(conditionName); + + + for (Condition condition : conditionList) { + + if (condition.status.equals("waiting") && conditionSatisfy(condition)) { + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); + + if (condition.featureMap.get("instantPost") != null) { + + + } + //Post后还是可以激活 + + if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { + //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 + bestMatch = condition; + + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + //} else if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) + } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)) + bestMatch = condition; + } + } + } + + } + logWriter.record("----------------------匹配结束", 2); + + bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); + + + return bestMatch; + } + + /** + * 在激活列表中选择满足匹配且优先级最高的一条配置条目 + * @param bestMatch + * @param activatedQueue + * @param context + * @return + * @throws IOException + */ + public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, ServletContext context) throws IOException { + Condition condition; + //待激活配置条目被激活后的匹配 + while (!activatedQueue.isEmpty()) { + condition = activatedQueue.remove(); + activatedMap.remove(condition.id); + + if (conditionSatisfy(condition)) { + if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); + bestMatch = condition; + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + //} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) { + } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) { + bestMatch = condition; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); + + } + } + + } + + return bestMatch; + + } + + /** + * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 + * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 + * + * @param condition 配置文件(状态表)的一行 + * @return 满足条件就为True, 不满足就为False + */ + public boolean conditionSatisfy(Condition condition) { + boolean flag = true; + String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; + HashSet keywordSet = null; + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(condition.id), 1); + + if (condition.featureMap.containsKey("match")) { + Iterator it = condition.currentPremise.keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + actionName = comparePair[0]; + cmpType = comparePair[1]; + keyword = getKeyword(curInfoPoint, actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + keywordSet = condition.currentPremise.get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + + it = condition.historyPremise.keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + cmpType = comparePair[1]; + actionName = comparePair[0]; + keyword = getKeyword(historyInfoPoint, actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + + + keywordSet = condition.historyPremise.get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + } + + + return flag; + + } + + public String getKeyword(Map infoPoint, String actionName){ + String keyword = ""; + String nameSeries[] = actionName.split("_"); + if(actionName.startsWith("npc_")){ + if(nameSeries.length == 4){ + String keywrod = gameEnv.queryNpcAttrByNpcName(nameSeries[3], nameSeries[4]); + } + + }else if (actionName.startsWith("goods_")){ + if(nameSeries.length == 4){ + keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]); + System.out.println("return" + keyword); + } + }else { + keyword = infoPoint.get(actionName); + + } + + + return keyword; + }; + + + /** + * 单个条件的匹配,判断是否满足条件 + * 比较类型分为 match、number、time、variable, + * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 + * + * @param keyword + * @param cmpType 比较类型 + * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 + * @return 返回匹配或者不匹配 + */ + public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { + boolean flag = true; + String operator = ""; + + try { + String splitPair[] = cmpType.split("-"); + if (splitPair.length > 1) { + operator = splitPair[1]; + cmpType = splitPair[0]; + } + + + if (cmpType.equals("match")) { + if(operator.equals("Keyword") || operator.equals("Include")) { + if (!keywordSet.contains(keyword)) { + flag = false; + } + if (flag == false && keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if (keywordSet.contains(k)) + flag = true; + } + } + } else if(operator.equals("Exclude")) { + if (keywordSet.contains(keyword)) { + flag = false; + } + }else { + flag = false; + } + + + } else if (cmpType.equals("number") && !keyword.equals("")) { + int candidateA = 0; + int candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(StringUtils.isNumeric(k)) + keyword = k; + + } + } + + if(!StringUtils.isNumeric(keyword)){ + return false; + + } + + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if (cmpType.equals("time")) { + + long candidateA, candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(k.contains("年") && k.contains("月") && k.contains("日")) + keyword = k; + + } + } + + candidateA = MyFunc.transferToMillisecond(keyword); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = MyFunc.transferToMillisecond(k); + break; + } + } + if (operator.equals("Early")) + flag = candidateA < candidateB; + else if (operator.equals("Later")) + flag = candidateA > candidateB; + + + } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { + String conditionName2 = "", conditionValue2 = ""; + for (String k : keywordSet) { + if (!k.equals("")) { + conditionName2 = k; + break; + } + } + + if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { + conditionValue2 = getKeyword(curInfoPoint, conditionName2); + }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ + conditionValue2 = getKeyword(historyInfoPoint, conditionName2); + }else { + flag = false; + } + + + if(flag ){ + /** + * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true + */ + flag = false; + if(operator.equals("Equal")){ + flag = keyword.equals(conditionValue2); + + }else if(keyword.contains(":") && conditionValue2.contains(":")){ + String relPair1[] = keyword.split(":", 2), keyword1 = ""; + String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; + boolean similar = false; + + if(relPair1[0].equals(relPair2[0])){ + similar = true; + keyword1 = relPair1[1]; + keyword2 = relPair2[1]; + }else if (relPair1[1].equals(relPair2[1])){ + similar = true; + keyword1 = relPair1[0]; + keyword2 = relPair2[0]; + } + + if(similar){ + if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ + int candidateA = Integer.parseInt(keyword1); + int candidateB = Integer.parseInt(keyword2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") + && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ + long candidateA = MyFunc.transferToMillisecond(keyword1); + long candidateB = MyFunc.transferToMillisecond(keyword2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ + if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ + int candidateA = Integer.parseInt(keyword); + int candidateB = Integer.parseInt(conditionValue2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") + && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ + long candidateA = MyFunc.transferToMillisecond(keyword); + long candidateB = MyFunc.transferToMillisecond(conditionValue2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + + + } + + + + } + //-------------------------------------------------------------------- + //为兼容旧数据 + else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) { + int candidateA = 0; + int candidateB = 0; + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + flag = candidateA > candidateB; + + } else if (cmpType.equals("numberBiggerOrEqual") && StringUtils.isNumeric(keyword)) { + int candidateA = 0; + int candidateB = 0; + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + flag = candidateA >= candidateB; + + } else if (cmpType.equals("numberSmaller") && StringUtils.isNumeric(keyword)) { + int candidateA = 0; + int candidateB = 0; + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + flag = candidateA < candidateB; + + } else if (cmpType.equals("numberSmallerOrEqual") && StringUtils.isNumeric(keyword)) { + int candidateA = 0; + int candidateB = 0; + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + flag = candidateA <= candidateB; + + } else if (cmpType.equals("timeEarly")) { + long candidateA, candidateB = 0; + candidateA = MyFunc.transferToMillisecond(keyword); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = MyFunc.transferToMillisecond(k); + break; + } + } + flag = candidateA < candidateB; + + } else if (cmpType.equals("timeLater")) { + long candidateA, candidateB = 0; + candidateA = MyFunc.transferToMillisecond(keyword); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = MyFunc.transferToMillisecond(k); + break; + } + } + flag = candidateA > candidateB; + + } else if (cmpType.equals("any")) { + if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + flag = false; + + } else { + flag = false; + } + } catch (IndexOutOfBoundsException e) { + System.out.println("配置文件格式有误"); + flag = false; + e.printStackTrace(); + } catch (ParseException e) { + System.out.println("时间解析错误"); + e.printStackTrace(); + flag = false; + } catch (Exception e) { + System.out.println("操作符有误"); + e.printStackTrace(); + flag = false; + } + + return flag; + } + + /** + * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 + * + * @return 返回给引擎的数据 + */ + public Solution getSolution(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, reply, variable; + Solution ans = new Solution(0, "", ""); + + + //如果一条配置文件有多个答案,则随 + // 机选择一个答案 + int randNum = (int) (Math.random() * ansCondition.answer.length); + ans.setAnswer(ansCondition.answer[randNum]); + //System.out.println(ans.getAnswer()); + + //post关键字 + if (ansCondition.featureMap.containsKey("post")) { + logWriter.record("---------------------进入表单结束",1); + ans = postToServer(ans, ansCondition); + logWriter.record("---------------------提交表单结束",1); + + //nextNext关键字 + } + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + //updateKnowledge关键字 + if (ansCondition.featureMap.containsKey("updateKnowledge")) { + logWriter.record("---------------------进入更新答案【略】",1); + updateKnowledge(ansCondition); + logWriter.record("---------------------更新答案结束",1); + } + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ansCondition.featureMap.containsKey("newNext")) { + logWriter.record("---------------------进入判断下一步【略】",1); + ans = findNewNext(ans, ansCondition); + logWriter.record("---------------------判断下一步结束",1); + //上一步 + } else if (ansCondition.featureMap.containsKey("return-1")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + //停留 + } else if (ansCondition.featureMap.containsKey("return-0")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + //激活 + } else if (ansCondition.featureMap.containsKey("activate")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + } + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ans.getNext().equals("")) { + ans.setNext("nextStep=" + ansCondition.nextStep); + } + + + try { + + + //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 + reply = ans.getAnswer(); + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1).substring(1, m.group(1).length() - 3); + if (m.group(1).endsWith("-1}")) { + if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) + reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)); + } else if (m.group(1).endsWith("-2}")) { + if (historyInfoPoint.get(variable) != null) + if(historyInfoPoint.get(variable).equals("do_reset")){ + reply = reply.replace("{" + variable + "-2}", ""); + }else + reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); + } + } + ans.setAnswer(reply); + + } catch (Exception e) { + e.printStackTrace(); + } + + return ans; + } + + /** + * 请求处理结束后台将当前信息的信息点转移到已知信息 + * @param ans + * @param context + * @param debugFlag + */ + public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { + //将当前信息点更新至历史信息点 + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, lastReply; + String next = ans.getNext().split("=", 2)[1]; + + //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx + historyInfoPoint.put("currentAction", next); + historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + if (debugFlag) + lastReply = ans.getAnswer().split(")")[2]; + else + lastReply = ans.getAnswer(); + historyInfoPoint.put("lastReply", lastReply); + + try { + String keyword1, keyword2; + while (it.hasNext()) { + actionName = it.next(); + + if(skipSet.contains(actionName)) + continue; + + keyword1 = curInfoPoint.get(actionName); + keyword2 = historyInfoPoint.get(actionName); + if (keyword2 == null) { + historyInfoPoint.put(actionName, keyword1); + }else if (historyInfoPoint.get(actionName).equals("do_reset")){ + historyInfoPoint.put(actionName, ""); + }else if (keyword2 != null && !keyword1.equals("")) + historyInfoPoint.put(actionName, keyword1); + } + + + ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, gameEnv, context); + //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 + * + * @param ans 最终返回的数据 + * @param context + */ + public void appendDebugInfo(Solution ans, ServletContext context) { + Iterator it = null; + String key, values, value; + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("bot_name"); + add("action_name"); + add("lastReply"); + } + }; + + it = curInfoPoint.keySet().iterator(); + String debugInfo = ""; + debugInfo += "(识别:"; + + while (it.hasNext()) { + key = it.next(); + values = curInfoPoint.get(key); + if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { + if (key.endsWith("_backup")) { + key = key.substring(0, key.length() - 7); + } + debugInfo += (" " + key + ":\'" + values + "\' "); + } + } + + debugInfo += ")(已知:"; + it = historyInfoPoint.keySet().iterator(); + while (it.hasNext()) { + + key = it.next(); + value = historyInfoPoint.get(key); + if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition")) + debugInfo += (" " + key + ":\'" + value + "\' "); + + } + ans.setAnswer(debugInfo + ")" + ans.getAnswer()); + } + + + /** + * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) + * + * @param ans 返回给用户的数据 + * @param ansCondition 满足条件最多的condition(配置文件的某一行) + */ + public Solution postToServer(Solution ans, Condition ansCondition) throws IOException { + String url = null, elem[], subElem[], key,keys, postType = "all"; + Map infoMap = new HashMap(); + List pairList = new ArrayList(); + Iterator k_iter = null; + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("lastReply"); + } + }; + + elem = ansCondition.featureMap.get("post").split("\\|"); + url = elem[0]; + postType = elem[1]; + + //提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 + if (postType.equals("all")) { + k_iter = curInfoPoint.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next(); + if (curInfoPoint.get(key) != "") + //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); + } + + k_iter = historyInfoPoint.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next(); + if (historyInfoPoint.get(key) != "") + //infoMap.put(key + "_his", historyInfoPoint.get(key)); + if (key.equals("game_step")) + pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); + else if(skipSet.contains(key)){} + else + pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); + } + + //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 + } else if (postType.equals("term")) { + pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); + pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); + pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); + k_iter = ansCondition.currentPremise.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next().split("::")[0]; + if (curInfoPoint.get(key) != "") + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); + } + + k_iter = ansCondition.historyPremise.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next().split("::")[0]; + if (historyInfoPoint.get(key) != "") + pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); + //infoMap.put(key + "_his", historyInfoPoint.get(key)); + } + } + + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); + + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + String keyName = null; + + + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); + entity.setContentType("application/x-www-form-urlencoded"); + httpPost.setEntity(entity); + + try { + HttpResponse resp = client.execute(httpPost); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + logWriter.record("提交表单接收到的数据:
" + respContent, 2); + JSONObject jobj = JSONObject.parseObject(respContent); + Iterator kit = jobj.keySet().iterator(); + + while (kit.hasNext()) { + keyName = kit.next(); + if (keyName.equals("process")) { + ans.setNext((String) jobj.get(keyName)); + historyInfoPoint.put("process", (String) jobj.get(keyName)); + } else if (keyName.equals("solution")) { + ans.setAnswer((String) jobj.get(keyName)); + } else if (keyName.equals("status")){ + continue; + } else{ + historyInfoPoint.put(keyName, jobj.getString(keyName)); + } + } + } else { + ans.setAnswer(API_ERROR); + } + } catch (Exception e) { + e.printStackTrace(); + + ans.setAnswer(POST_ERROR + url); + return ans; + } + + return ans; + + } + + public Solution findNewNext(Solution ans, Condition ansCondition) { + String nextOptions[] = ansCondition.nextStep.split(","); + String conditionName, premises[], cpPair[]; + boolean flag = true; + + String activeList = historyInfoPoint.get("activeList"); + + for (String option : nextOptions) { + flag = true; + cpPair = option.split(":"); + conditionName = cpPair[0]; + if (cpPair.length == 1) { + ans.setNext("nextStep=" + conditionName); + break; + } + premises = cpPair[1].split("-"); + for (String premise : premises) { + if (premise.equals("known")) { + //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 + boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); + boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); + + //只有前两者都为假时,conditionExist才为真 + boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); + + if (conditionExist) + flag = false; + } + + if (premise.equals("active")) { + boolean isActive = activeList.contains(conditionName); + if (isActive) + flag = false; + } + } + + if (flag) { + ans.setNext("nextStep=" + conditionName); + break; + } + + } + return ans; + + } + + public void updateKnowledge(Condition condition) throws ParseException { + String keyword, variableName, updateValue, returnStr = "1"; + + + + Iterator iit = condition.updateKnowledge.keySet().iterator(); + while (iit.hasNext()) { + + variableName = iit.next(); + updateValue = condition.updateKnowledge.get(variableName); + keyword = historyInfoPoint.get(variableName); + + //如果变量名开头为NPC或者item,就专门交给world处理 + if(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_")){ + try { + returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); + updateValue = returnStr; + }catch (Exception e){ + e.printStackTrace(); + updateValue = "游戏模块处理出错"; + } + }else { + + try { + //做数字加法 + if (updateValue.startsWith("+")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("-")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(4); + //做字符串删除 + } else if (updateValue.startsWith("str-")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(4), ""); + + } else if (updateValue.startsWith("int+=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("int-=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(5); + //做字符串删除 + } else if (updateValue.startsWith("str-=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(5), ""); + + } else if (updateValue.startsWith("var=")) { + String conditionName = updateValue.substring(5, updateValue.length() - 3); + + if (updateValue.endsWith("-1}")) { + if (curInfoPoint.get(conditionName) != null) { + updateValue = curInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("-2}")) { + if (historyInfoPoint.get(conditionName) != null) { + updateValue = historyInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("nextStep-3}")) { + updateValue = condition.nextStep; + } else if (updateValue.endsWith("reply-3}")) { + updateValue = condition.answer[0]; + } + if (variableName.startsWith("process-nextStep")) { + condition.nextStep = updateValue; + updateValue = ""; + } + + } + } catch (Exception e) { + e.printStackTrace(); + continue; + } + } + + + if(updateValue.equals("")) { + curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点转移时这个变量的已知信息依然不是空的。 + // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 + curInfoPoint.put(variableName, ""); + } + + historyInfoPoint.put(variableName, updateValue); + + } + + + } + + + public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + String configStr = ""; + Integer configId; + Condition newCondition, originCondition; + + for (String configIdStr : activateList.split(",")) { + if (!StringUtils.isNumeric(configIdStr)) + continue; + configId = Integer.parseInt(configIdStr); + + configStr = userinfo.id2config.get(configId); + if (configStr != null) { + originCondition = userinfo.id2condition.get(configId); + newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); + //condition = QuestionMatcher.buildCondition(condition, configStr); + + logWriter.record("------激活-------" + userinfo.id2config.get(configId) + "-------
", 0); + + if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { + activatedMap.get(configId).activePriority = newCondition.activePriority; + } else if (!activatedMap.containsKey(configId)) { + activatedMap.put(configId, newCondition); + activatedQueue.add(newCondition); + } + } + } + + + } + + /** + * 一个提交表单后在激活的操作 + * @param ansCondition + * @param context + * @param userinfo + * @return + * @throws IOException + * @throws ParseException + */ + public Solution postActivate(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + Queue activatedQueue = new LinkedList(); + Solution bestMatch = null; + activateCondition(activatedQueue, userinfo.botAccount, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); + ansCondition = activatedQueueMatching(ansCondition, activatedQueue, context); + + bestMatch = getSolution(ansCondition, context, userinfo); + + return bestMatch; + + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java new file mode 100644 index 0000000..b63261b --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java @@ -0,0 +1,294 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.*; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +public class UserInfoController { + + static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; + static String FILE_ERROR = ".txt文件有误"; + + + /** + * 根据本地配置文件生成用户信息 + */ + public static void configInit(ServletContext context) throws IOException { + + String line; + + System.out.println("configDir"+ CONFIG_DIR); + + 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, true); + context.setAttribute(userinfo.botAccount, userinfo); + } catch (Exception e) { + System.out.println(userinfo.botAccount + FILE_ERROR); + e.printStackTrace(); + } + + reader.close(); + br.close(); + } + + } + + public static void userConfigInit(String botAccount, ServletContext context) throws IOException { + String line; + File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt"); + + System.out.println(userFile.getAbsolutePath()); + if (!userFile.exists()) { + BufferedReader br = new BufferedReader(new StringReader("")); + UserInfo userinfo = new UserInfo(botAccount); + try { + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + } catch (Exception e) { + System.out.println(userinfo.botAccount + FILE_ERROR); + e.printStackTrace(); + } + + } else { + FileReader reader = new FileReader(userFile); + BufferedReader br = new BufferedReader(reader); + UserInfo userinfo = new UserInfo(botAccount); + + try { + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + } catch (Exception e) { + System.out.println(userinfo.botAccount + FILE_ERROR); + e.printStackTrace(); + } + + reader.close(); + br.close(); + } + } + + + public static Condition buildCondition(Condition condition, String line) { + String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName; + + + try { + line = line.split("---")[0]; + + element = line.replace("\n", "").split("\\|=\\>\\|"); + premises = element[0].split("\\|"); + //System.out.println("element[0]:" + element[0]); + feature = premises[2]; + cur_premises = premises[0].split(","); + history_premises = premises[1].split(","); + + if (premises.length < 4) + condition.auxiliaryPriority = 0; + else + condition.auxiliaryPriority = Integer.parseInt(premises[3].split("=")[1]); + + + next = element[1].split("\\|"); + if (next.length < 4) + return condition; + condition.answer = next[0].split("~"); + //condition.nextStep = next[1]; + //第二处 + condition.nextStep = next[1].split("=", 2)[1]; + condition.id = Integer.parseInt(next[3].split("=")[1]); + condition.status = next[2].split("=")[1]; + + + //featureMap的构建 + features = feature.split(","); + for (String feat : features) { + if (feat.equals("") || feat.equals(" ")) { + continue; + } else if (feat.startsWith("updateKnowledge")) { + String[] knowledge = feat.split("-<-"); + int length = knowledge.length; + condition.featureMap.put("updateKnowledge", ""); + for (int i = 1; i < length; i++) { + if (knowledge[i].equals("") || knowledge[i].equals(" ")) + continue; + + pair = knowledge[i].split(":", 2); + condition.updateKnowledge.put(pair[0], pair[1]); + } + } else if (feat.startsWith("post")) { + pair = feat.split("\\(", 2); + url = pair[1]; + url = url.substring(0, url.length() - 1); + pair = pair[0].split("::"); + condition.featureMap.put("post", url + "|" + pair[1]); + } else { + condition.featureMap.put(feat, ""); + } + } + + + insertPremise(condition.currentPremise, cur_premises); + insertPremise(condition.historyPremise, history_premises); + //满足条件越多,优先级越大 + condition.priority = condition.historyPremise.size() + condition.currentPremise.size(); + condition.activePriority = condition.priority; + /* + for(String premise:cur_premises){ + pair = premise.split("="); + condition.indexName.add(pair[0]); + } + */ + firstCnditionName = cur_premises[0]; + if (firstCnditionName.equals(" ")) + condition.indexName = "emptySet"; + else + condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; + } catch (IndexOutOfBoundsException e) { + e.printStackTrace(); + System.out.println(line); + System.out.println("文本格式有误"); + } + return condition; + } + + + /** + * @param br + * @param userinfo + * @param overRide 覆盖之前的状态表 + * @return + * @throws IOException + */ + public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { + String line, infoName, extraElements[]; + HashMap> conditionTable = null; + + //是否覆盖原有的数据 + if (overRide) { + conditionTable = new HashMap>(); + userinfo.id2condition.clear(); + userinfo.id2config.clear(); + userinfo.configStr = ""; + userinfo.varInitialMap.clear(); + + } else { + conditionTable = userinfo.conditionTable; + } + + List conditionList = null; + + + while ((line = br.readLine()) != null) { + try { + if (line.trim().equals("")) + continue; + line = line.replace("\n", ""); + //在用户信息中添加额外信息,如设为active的action + if (line.contains("extraInfo")) { + extraElements = line.split("\\|", -1); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + } else if (line.contains("varInitial")) { + extraElements = line.split("\\|", -1); + userinfo.varInitialMap.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(); + conditionList.add(condition); + conditionTable.put(condition.indexName, conditionList); + if (condition.id != 0) { + userinfo.id2config.put(condition.id, line); + userinfo.id2condition.put(condition.id, condition); + } + + } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("数据格式有误"); + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + userinfo.conditionTable = conditionTable; + + return userinfo; + } + + /** + * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) + * + * @param premiseMap 前提条件哈希表 + */ + public static void insertPremise(HashMap> premiseMap, String[] premisesString) { + String pair[]; + HashSet keyWordSet = null; + for (String premise : premisesString) { + // System.out.println(premise); + if (premise.equals("") || premise.equals(" ")) + continue; + pair = premise.split("=", 2); + 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 { + /*根据数据库得到botAccount改为直接得到 + SqlHelper helper = new SqlHelper(); + String botAccount = helper.querybotAccountByKey(chat_key); + */ + String botAccount = bot_name; + UserInfo userinfo = null; + if (context.getAttribute(botAccount) == null) { + userConfigInit(botAccount, context); + } + if (context.getAttribute(botAccount) == null) { + + return null; + //userinfo = new UserInfo(botAccount); + //userinfo.conditionTable = new HashMap>(); + } else { + userinfo = (UserInfo) context.getAttribute(botAccount); + } + //helper.destroy(); + + + return userinfo; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java b/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java new file mode 100644 index 0000000..1690e42 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java @@ -0,0 +1,127 @@ +package com.qiwu.chatbotbackend.processing; + + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class WorldController { + public LogWriter logWriter = null; + + public WorldController(LogWriter logWriter) { + this.logWriter = logWriter; + } + + public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ + String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr=""; + String namePair[] = varName.split("_"); + boolean operationFlag = true; + List textList = null; + String subValuePair[] = null; + + logWriter.record(String.format("---------------------key:%s, value:%s", varName, varValue), 0); + + + if(valuePair[0].startsWith("query")){ //查询专用 + + if(varName.startsWith("goods_")) { + switch (valuePair[0]) { + case "queryGoodsIntro": + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]); + if(returnStr == null ) + returnStr = "无"; + break; + + case "queryAttrByGoodsName": + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + subValuePair[0] = subValuePair[0].replace("哪里", "location"); + returnStr = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + break; + case "queryAllAttrByGoodsName": + textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); + if(textList == null || textList.size() == 0) + returnStr = "无"; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + case "queryAroundGoodsByClassName": + textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); + if(textList == null || textList.size() == 0) + returnStr = "无"; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + default: + } + }else if(varName.startsWith("NPC_")) { + switch(valuePair[0]){ + case "queryNpcIntro": + //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + + break; + case "queryAttrByNPCName": + + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + subValuePair[0] = subValuePair[0].replace("哪里", "location"); + returnStr = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); + if(returnStr == null) + returnStr = "无"; + break; + default: + } + }else if (varName.startsWith("map_")) { + List sites = new ArrayList<>(); + switch (valuePair[0]) { + case "queryAroundAllBySite": + sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); + break; + case "queryAroundNpcBySite": + sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + break; + case "queryAroundGoodsBySite": + sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); + break; + case "queryCanGoBySite": + sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); + break; + case "queryPathBySite": + sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]); + break; + } + if(sites == null || sites.size() == 0) + returnStr = "啥都没有"; + else { + returnStr = "有"; + if(sites.size() > 0) { + for (String site : sites) + returnStr += "、" + site; + }else{ + returnStr = "啥都没有"; + } + } + } + }else { //增删改统一使用 + gameEnv.CUD(varName, valuePair[0], valuePair[1]); + } + + + logWriter.record("---------------------return:" + returnStr, 0); + return returnStr; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java new file mode 100644 index 0000000..c132c71 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java @@ -0,0 +1,263 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.gameDesign.*; +import com.qiwu.chatbotbackend.processing.MyFunc; +import com.qiwu.chatbotbackend.processing.ConditionTableController; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +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.sql.SQLException; +import java.util.*; + +import static java.lang.System.out; + +@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) +public class GameDesignServlet extends HttpServlet { + + String POST_URL = "http://localhost:1111/conditionProcess"; + //分组及其相应的id,id初始化为0, 新建分组成功后id会更新。 + HashMap categoryMap = new HashMap(){ + { + put("地图", 0); + put("剧情", 0); + put("物品", 0); + put("NPC", 0); + put("全局变量", 0); + } + }; + + //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等 + HashMap> relationKeywords = new HashMap>(); + + //特定的relation的三元组不会被添加到relationKeywords + HashSet exceptRelation = new HashSet(); + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + Integer botId, projectId, dataId, returnStatus = 1; + String botAccount = null, moduleName, userName, moduleName2, returnMessage = "Success"; + ServletContext context = this.getServletContext(); + JSONObject json = null, root = null; + Boolean flag; + SqlHelper helper = null; + List idList = new ArrayList<>(); + ElementConstructor constructor = new ElementConstructor(); + + try { + helper = new SqlHelper(); + } catch (SQLException e) { + e.printStackTrace(); + } + + //读取并解析json数据 + String jsonStr = MyFunc.readJSONString(request); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); + dataId = (Integer) receiveParaneters.get("id"); + + JSONObject gameElements = helper.queryGameElementsByBotId(dataId); + + out.println(gameElements.toJSONString()); + botId = (Integer)gameElements.get("botId"); + botAccount = (String) gameElements.get("botAccount"); + userName = (String)gameElements.get("userName"); + + + + out.println("botId:" + botId + ",botAccount:" + botAccount); + + //假设重建用户信息 + if (context.getAttribute(botAccount) == null) { + UserInfoController.userConfigInit(botAccount, context); + } + + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + + + //UserInfo userinfo = new UserInfo(botAccount); + + //清空之前生成的配置条目 + try { + flag = botInit(botId, userinfo, helper); + } catch (SQLException e) { + out.println("清空旧数据失败"); + e.printStackTrace(); + } + + + Iterator moduleIter = gameElements.keySet().iterator(); + StringBuffer mergedConfigText = new StringBuffer(); + while (moduleIter.hasNext()) { + + moduleName = moduleIter.next(); + switch (moduleName) { + case "map": + moduleName2 = "地图"; + constructor = new MapConstructor(helper, botId, exceptRelation); + constructor.construct(gameElements, userinfo); + break; + case "plots": + moduleName2 = "剧情"; + constructor = new PlotConstructor(helper, botId, exceptRelation); + constructor.construct(gameElements, userinfo); + + root = ((PlotConstructor) constructor).getId2j().get((String) gameElements.get("start")); + break; + case "goods": + moduleName2 = "物品"; + constructor = new ItemConstructor(helper, botId, exceptRelation); + constructor.construct(gameElements, userinfo); + break; + case "globalVarialbe": + moduleName2 = "全局变量"; + constructor = new GlobalVariableConstructor(helper, botId, exceptRelation); + constructor.construct(gameElements, userinfo); + break; + case "npc": + moduleName2 = "NPC"; + constructor = new CharacterConstructor(helper, botId, exceptRelation); + constructor.construct(gameElements, userinfo); + break; + default: + continue; + + } + if (constructor.getOperationStatus() == 1) { + + out.println(moduleName); + //先清空再插入 + idList.clear(); + helper.batchInsertVariableByBotId(botId, constructor); + + List jsonList = new ArrayList(); + for(JConfig jConfig: constructor.getjConfigList()){ + json = jConfig.toJson(constructor.getConditionDescription()); + constructor.parseKeyword(json, relationKeywords, exceptRelation); + jsonList.add(json); + } + + + helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); + constructor.postProcessing(idList, categoryMap.get(moduleName2)); + constructor.generateConfigText(idList); + + mergedConfigText.append(constructor.getConfigText()); + }else { + returnStatus = 0; + returnMessage = constructor.getMessage(); + break; + } + + } + + if(returnStatus == 1) { + StringReader sr = new StringReader(mergedConfigText.toString()); + BufferedReader br = new BufferedReader(sr); + UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(botAccount, userinfo); + ConditionTableController.writeConfigText(botAccount, userinfo); + Boolean postResult = actionRegenerate(root, gameElements, userinfo); + } + + helper.destroy(); + + + + + }else { + returnStatus = 0; + returnMessage = "请求解析失败"; + } + + + JSONObject responseJSONObject = new JSONObject(); + responseJSONObject.put("status", returnStatus); + responseJSONObject.put("message", returnMessage); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + + + + + try { + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (out != null) { + out.close(); + + } + } + } + + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + OutputStream out = response.getOutputStream(); + out.write("ssss".getBytes()); + out.flush(); + } + + public boolean botInit(int botId, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { + boolean deleteConfigFlag = helper.deleteConfigByBotId(botId); + boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); + boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); + boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); + + + + + return deleteConfigFlag && deleteVariableFlag; + } + + public boolean actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo){ + String startCondition; + String botName = (String)gameElements.get("botName"); + JSONObject returnMessage = null; + + JSONObject actionPostData = new JSONObject(); + out.println("root"+ root.toJSONString()); + startCondition = (String)root.get("conditionName"); + actionPostData.put("startCondition", startCondition); + actionPostData.put("botName_yhm", (String)gameElements.get("botName")); + actionPostData.put("botName", botName); + actionPostData.put("botId", (Integer)gameElements.get("botId")); + actionPostData.put("type", "game_plot_init"); + actionPostData.put("welcome", (String)gameElements.get("plotStartText")); + actionPostData.put("relationKeywords", relationKeywords); + + out.println(actionPostData.toJSONString()); + + userInfo.extraInfo.put("activeAction", startCondition); + try { + returnMessage = MyFunc.postJSON(POST_URL, actionPostData); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + if((Integer)returnMessage.get("status") == 1) { + return true; + }else { + out.println(returnMessage.get("parameter")); + out.println("剧情初始化失败"); + + return false; + } + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java new file mode 100644 index 0000000..0c5d184 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java @@ -0,0 +1,137 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.entity.*; +import com.qiwu.chatbotbackend.processing.*; + +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.sql.SQLException; +import java.text.ParseException; +import java.util.*; + + +@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) +public class GetAnswerServlet extends HttpServlet { + /** + * GetAnswerServlet就是处理post请求并返回答案的入口 + */ + + String NAME_MISSING_ERROR = "没找到bot名?"; + String LOG_PATH = "/var/www/html/logs/"; + + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + Map receiveParamters = new HashMap<>(request.getParameterMap()); + Map curInfoPoint = new HashMap(); + Map historyInfoPoint = null; + Solution bestMatch = null; + Condition ansCondition = null; + String ansJ = "", return_str = "", state = ""; + String chatKey = receiveParamters.get("chat_key")[0]; + String botName = receiveParamters.get("bot_name")[0]; + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); + boolean debugFlag = false; + + + LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); + + + + + UserInfo userinfo = null; + UserInfoController uiController = new UserInfoController(); + try { + //userinfo = process.userInfoQuery(chatKey,context); + //从servlet根据用户名查询用户信息 + userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); + } catch (SQLException e) { + state = NAME_MISSING_ERROR; + e.printStackTrace(); + } + + + if(userinfo != null) { + //获得用户历史信息 + ChatCache chatCache = null; + try { + chatCache = ChatCacheController.getChatCache(chatKey, context, userinfo); + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + historyInfoPoint = chatCache.getInfoPoint(); + + + //信息点预处理 + QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv()); + debugFlag = matcher.infoPointPreprocessing(receiveParamters, curInfoPoint, historyInfoPoint, userinfo, context); + + + /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ + //process.removeTimeoutChatkey(context); + //System.out.println(userinfo.conditionTable); //测试 + ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); + if (state.equals("") && ansCondition.priority == -1) + state = "我不理解,"; + if (state.equals("")) { + try { + bestMatch = matcher.getSolution(ansCondition, context, userinfo); + + if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + bestMatch = matcher.postActivate(ansCondition, context, userinfo); + } + } catch (ParseException e) { + e.printStackTrace(); + } + //清理超时的用户数据 + if (context.getAttribute("cacheUpdateTime") == null) + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > 300000) { + ChatCacheController.updateChatCache4Delete(chatKey, context); + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + } + //bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); + } else { + bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); + } + + + if (debugFlag) { + matcher.appendDebugInfo(bestMatch, context); + } + + matcher.infoTransfer(bestMatch, context, debugFlag); + ansJ = MyFunc.toJson(bestMatch); + } else { + ansJ = "找不到配置文件"; + } + + + + logWriter.writeln(); + logWriter.writeln(); + logWriter.record("-----------------------------------------对话处理结束", 0); + logWriter.writeln(); + logWriter.writeln(); + logWriter.close(); + + 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 a/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java new file mode 100644 index 0000000..72639e3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java @@ -0,0 +1,44 @@ +package com.qiwu.chatbotbackend.servlet; + +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 = "GetConfigServlet", urlPatterns = {"/getConfig"}) +public class GetConfigServlet extends HttpServlet { + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String userName = request.getParameter("userName"); + + String path = "config/" + userName + ".txt"; + File file = new File(path); + OutputStream out = response.getOutputStream(); + + + if (file.exists()) { + + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String line; + while ((line = br.readLine()) != null) { + line = line + "\n"; + out.write(line.getBytes()); + } + + + fr.close(); + br.close(); + } else { + out.write("查无此bot".getBytes()); + } + out.flush(); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadChatCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadChatCacheServlet.java new file mode 100644 index 0000000..20af7a3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadChatCacheServlet.java @@ -0,0 +1,19 @@ +package com.qiwu.chatbotbackend.servlet; + +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; + +@WebServlet(name = "ReloadChatCacheServlet", urlPatterns = {"/reloadChatCache"}) +public class ReloadChatCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadConfigServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadConfigServlet.java new file mode 100644 index 0000000..7d6c8cb --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/ReloadConfigServlet.java @@ -0,0 +1,80 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +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 = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"}) +public class ReloadConfigServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String botAccount = request.getParameter("botAccount"); + boolean flag = true; + UserInfo userinfo = new UserInfo(botAccount); + File configFile = new File(System.getProperty("user.dir") + "/config/" + botAccount + ".txt"); + System.out.println(configFile.getAbsolutePath()); + ServletContext context = this.getServletContext(); + if (!configFile.exists()) { + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + out.println("文件不存在: " + botAccount); + + } else { + + FileReader reader = new FileReader(configFile); + BufferedReader br = new BufferedReader(reader); + + try { + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + } catch (Exception e) { + flag = false; + System.out.println(userinfo.botAccount + ".txt 有误"); + e.printStackTrace(); + } + + reader.close(); + br.close(); + + if (!flag) { + //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + response.setStatus(111); + PrintWriter out = response.getWriter(); + out.println("更新失败配置文件有误:" + botAccount + ".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 a/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java new file mode 100644 index 0000000..aa41226 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java @@ -0,0 +1,40 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +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.util.Map; + +@WebServlet(name = "SaveChatCacheServlet", urlPatterns = {"/saveChatCache"}) +public class SaveChatCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String chatKey = request.getParameter("chat_key"), message = ""; + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); + + Map chatCacheMap = (Map)context.getAttribute("chatCache"); + ChatCache chatCache = chatCacheMap.get(chatKey); + + //message = ChatCacheController.saveChatCache(chatKey, context); + //out.write(message.getBytes()); + out.flush(); + } + +} + + diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateServlet.java new file mode 100644 index 0000000..b22881c --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateServlet.java @@ -0,0 +1,130 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.MyFunc; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +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; + +/** + * 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。 + */ +@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"}) +public class UpdateServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。 + request.setCharacterEncoding("UTF-8"); + String line, extraElements[]; + ArrayList errorList = new ArrayList(); + ServletContext context = this.getServletContext(); + String botAccount = request.getParameter("botAccount"); + + UserInfo userinfo = new UserInfo(botAccount); + 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) { + 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(); + try { + condition = UserInfoController.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(); + System.out.println("error"); + + } else { + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + out.println("更新成功+ “ "); + out.flush(); + out.close(); + System.out.println("success"); + + //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); + context.setAttribute(botAccount, userinfo); + String path = System.getProperty("user.dir") + "/config/" + userinfo.botAccount + ".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(); + + + } + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateSingleConfigServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateSingleConfigServlet.java new file mode 100644 index 0000000..04e5b9a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/UpdateSingleConfigServlet.java @@ -0,0 +1,98 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.ConditionTableController; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +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 = "UpdateSingleConfigServlet", urlPatterns = {"/update2"}) +public class UpdateSingleConfigServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + ServletContext context = this.getServletContext(); + String userName = request.getParameter("userName"); + String processType = request.getParameter("type"); + String configId = request.getParameter("configId"); + String data = request.getParameter("configData"); + System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); + + if (context.getAttribute(userName) != null) { + switch (processType) { + case "insert_config": + ConditionTableController.insertConfig(userName, configId, data, context); + break; + case "update_config": + ConditionTableController.deleteConfig(userName, configId, data, context); + ConditionTableController.insertConfig(userName, configId, data, context); + break; + case "delete_config": + ConditionTableController.deleteConfig(userName, configId, data, context); + break; + case "insert_variable": + ConditionTableController.updateVariable(userName, configId, data, context); + break; + case "delete_variable": + ConditionTableController.deleteVariable(userName, configId, data, context); + break; + case "update_variable": + ConditionTableController.updateVariable(userName, configId, data, context); + break; + case "extra_info": + ConditionTableController.updateExtraInfo(userName, data, context); + break; + + case "batch_update": + batchUpdate(userName, data, context); + + } + writeConfig(userName, context); + response.setStatus(200); + + } else if (processType.equals("batch_update")) { + batchUpdate(userName, data, context); + writeConfig(userName, context); + response.setStatus(200); + } else { + response.setStatus(111); + } + + + response.setCharacterEncoding("utf-8"); + response.setContentType("text/plain"); + PrintWriter out = response.getWriter(); + out.write("success"); + out.flush(); + out.close(); + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + + public String writeConfig(String userName, ServletContext context) throws IOException { + String returnMessage = ""; + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + returnMessage = ConditionTableController.writeConfigText(userName, userinfo); + + return returnMessage; + } + + + public void batchUpdate(String userName, String data, ServletContext context) throws IOException { + BufferedReader br = new BufferedReader(new StringReader(data)); + UserInfo userinfo = new UserInfo(userName); + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + System.out.println("batchupdate"); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..75a19a9 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +server.servlet.context-path=/bot +endpoints.shutdown.enabled=true \ No newline at end of file diff --git a/src/main/resources/dev/c3p0-config.xml b/src/main/resources/dev/c3p0-config.xml new file mode 100644 index 0000000..4287ee0 --- /dev/null +++ b/src/main/resources/dev/c3p0-config.xml @@ -0,0 +1,33 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + admin + 10 + 30 + 50 + 10 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/dev/log4j.properties b/src/main/resources/dev/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/dev/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/resources/pro/c3p0-config.xml b/src/main/resources/pro/c3p0-config.xml new file mode 100644 index 0000000..d25f3a1 --- /dev/null +++ b/src/main/resources/pro/c3p0-config.xml @@ -0,0 +1,33 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/pro/log4j.properties b/src/main/resources/pro/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/pro/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/resources/static/js/jquery-3.3.1.min.js b/src/main/resources/static/js/jquery-3.3.1.min.js new file mode 100644 index 0000000..4d9b3a2 --- /dev/null +++ b/src/main/resources/static/js/jquery-3.3.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w(" + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

+
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/templates/index.jsp b/src/main/resources/templates/index.jsp new file mode 100644 index 0000000..330092e --- /dev/null +++ b/src/main/resources/templates/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 a/src/main/resources/templates/update.html b/src/main/resources/templates/update.html new file mode 100644 index 0000000..e102286 --- /dev/null +++ b/src/main/resources/templates/update.html @@ -0,0 +1,97 @@ + + + + 配置文件 v2.2.4 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

+
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/templates/update3.html b/src/main/resources/templates/update3.html new file mode 100644 index 0000000..3165695 --- /dev/null +++ b/src/main/resources/templates/update3.html @@ -0,0 +1,85 @@ + + + + 配置文件 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

关键词替换:

+

 

+ +
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/test/java/com/qiwu/chatbotbackend/ChatbotBackendApplicationTests.java b/src/test/java/com/qiwu/chatbotbackend/ChatbotBackendApplicationTests.java new file mode 100644 index 0000000..16ae171 --- /dev/null +++ b/src/test/java/com/qiwu/chatbotbackend/ChatbotBackendApplicationTests.java @@ -0,0 +1,16 @@ +package com.qiwu.chatbotbackend; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ChatbotBackendApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/src/test/java/com/qiwu/chatbotbackend/WorldTests.java b/src/test/java/com/qiwu/chatbotbackend/WorldTests.java new file mode 100644 index 0000000..0e904f5 --- /dev/null +++ b/src/test/java/com/qiwu/chatbotbackend/WorldTests.java @@ -0,0 +1,69 @@ +package com.qiwu.chatbotbackend; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.WorldController; +import org.junit.Assert; +import org.junit.Test; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class WorldTests { + + @Test + public void testQuery() throws Exception { + + String result = ""; + Map curInfoPoint = new HashMap(){ + { + put("testCondition", "cc:瑞娜"); + put("testCondition2", "数量:蓝色药水"); + put("testCondition3", "瑞娜:友好度"); + put("testCondition4", "瑞娜:友好度"); + put("testCondition5", " :瑞娜"); + } + }; + + Map hisInfoPoint = new HashMap(){ + { + put("site", "海边"); + } + }; + + LogWriter logWriter = new LogWriter("config", "text"); + +// GameEnv gameEnv = new GameEnv("3474861621"); +// WorldController controller = new WorldController(logWriter); +// +// result = controller.worldOperation(gameEnv, "goods_query", "queryAttrByGoodsName:testCondition2", curInfoPoint, hisInfoPoint); +// System.out.println(result); +// assertEquals("2", result); +// +// result = controller.worldOperation(gameEnv, "map_query", "queryCanGoBySite:2", curInfoPoint, hisInfoPoint); +// System.out.println(result); +// assertEquals("有、山洞、沙滩、营地", result); +// +// result = controller.worldOperation(gameEnv, "NPC_query", "queryAttrByNPCName:testCondition3", curInfoPoint, hisInfoPoint); +// System.out.println(result); +// assertEquals("100", result); +// +// /** +// * 方法暂不存在 +// * +// result = controller.worldOperation(gameEnv, "goods_query", "queryAroundGoodsByClassName:testCondition4", curInfoPoint, hisInfoPoint); +// System.out.println(result); +// assertEquals("100", result); +// */ +// +// result = controller.worldOperation(gameEnv, "NPC_query", "queryNpcIntro:testCondition5", curInfoPoint, hisInfoPoint); +// System.out.println(result); +// assertEquals("至始至终的帮手", result); + + + + } +}