Commit 3fa80652 by hxw

routine

parent db12838b
package GameEnvironment;
import 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;
}
}
package GameEnvironment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import GameEnvironment.bean.Attr;
import GameEnvironment.bean.GoodsInstance;
import GameEnvironment.bean.SuperClass;
import GameEnvironment.bean.NpcInstance;
import GameEnvironment.bean.Place;
public class GameEnv {
public Map<String, SuperClass> npcClassIndex = null;
public Map<String, NpcInstance> npcInstanceIndex = null;
public Map<String, SuperClass> goodsClassIndex = null;
public Map<String, GoodsInstance> goodsInstanceIndex = null;
public Map<String, Place> placeIndex = null;
public GameEnv(String botName) throws Exception {
// 通过文件来初始化游戏环境
// String fullName = "E:\\projects\\env\\"+projectId+".json";
//
// String jsonString = Util.getJsonString(fullName);
try {
String jsonString = "";//DBUtil.queryEnvJsonByBotName(botName);
Map<String, Object> gameProjectMap = JSON.parseObject(jsonString);
Map<String, Object> map = (Map<String, Object>) gameProjectMap.get("map");
this.placeIndex = new HashMap<String, Place>();
Map<String, Object> placeMapTmp = new HashMap();
for (String key : map.keySet()) {
Map<String, Object> one = (Map<String, Object>) 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<Place> ableGos = new ArrayList<Place>();
List<Long> ableGoLongs = (List<Long>) ((Map<String, Object>) map.get(tmp)).get("canGo");
for (int j = 0; j < ableGoLongs.size(); j++) {
String idName = String.valueOf(ableGoLongs.get(j));
ableGos.add(placeIndex.get(placeMapTmp.get(idName)));
}
placeIndex.get(placeMapTmp.get(tmp)).setAbleGo(ableGos);
}
// npc
// npc class
Map<String, Object> npcClasses = (Map<String, Object>) gameProjectMap.get("npc");
Map<String, Object> npcNames = new HashMap<String, Object>();
this.npcClassIndex = new HashMap<String, SuperClass>();
this.npcInstanceIndex = new HashMap<String, NpcInstance>();
for (String classKey : npcClasses.keySet()) {
Map<String, Object> one = (Map<String, Object>) npcClasses.get(classKey);
// class
Map<String, Object> oneClass = (Map<String, Object>) one.get("class");
SuperClass npcClass = new SuperClass();
npcClass.setName(classKey);
npcClass.setIntro((String) oneClass.get("intro"));
List<Attr> attrs = new ArrayList<Attr>();
for (String attrKey : oneClass.keySet()) {
if (attrKey != "intro") {
Attr attr = new Attr();
attr.setName(attrKey);
attr.setValue((String) oneClass.get(attrKey));
attrs.add(attr);
}
}
npcClass.setAttrs(attrs);
// instance
Map<String, Object> instances = (Map<String, Object>) one.get("instance");
for (String instanceKey : instances.keySet()) {
Map<String, Object> instance = new HashMap<String, Object>();
NpcInstance npcInstance = new NpcInstance();
Map<String, Object> instanceAttrMap = (Map<String, Object>) instances.get(instanceKey);
npcNames.put(instanceKey, (String) instanceAttrMap.get("name"));
npcInstance.setName((String) instanceAttrMap.get("name"));
npcInstance.setIntro((String) instanceAttrMap.get("intro"));
List<Attr> npcInstanceAttrs = new ArrayList<Attr>();
for (String instanceAttrKey : instanceAttrMap.keySet()) {
if (instanceAttrKey != "name" && instanceAttrKey != "intro" && instanceAttrKey != "placeId") {
Attr attr = new Attr();
attr.setName(instanceAttrKey);
attr.setValue((String) instanceAttrMap.get(instanceAttrKey));
npcInstanceAttrs.add(attr);
}
}
npcInstance.setAttrs(npcInstanceAttrs);
Place place = placeIndex.get(((Map<String, Object>) map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name"));
List<NpcInstance> npcInstances = place.getNpcInstances();
if (npcInstances == null) {
npcInstances = new ArrayList<NpcInstance>();
}
npcInstances.add(npcInstance);
place.setNpcInstances(npcInstances);
List<NpcInstance> npcInstanceClass = npcClass.getNpcInstances();
if (npcInstanceClass == null) {
npcInstanceClass = new ArrayList<NpcInstance>();
}
npcInstanceClass.add(npcInstance);
npcClass.setNpcInstances(npcInstanceClass);
npcInstance.setPlace(place);
this.npcInstanceIndex.put((String) instanceAttrMap.get("name"), npcInstance);
}
this.npcClassIndex.put(classKey, npcClass);
}
// goods
Map<String, Object> goodsClasses = (Map<String, Object>) gameProjectMap.get("goods");
this.goodsClassIndex = new HashMap<String, SuperClass>();
this.goodsInstanceIndex = new HashMap<String, GoodsInstance>();
for (String classKey : goodsClasses.keySet()) {
Map<String, Object> one = (Map<String, Object>) goodsClasses.get(classKey);
// class
Map<String, Object> oneClass = (Map<String, Object>) one.get("class");
SuperClass goodsClass = new SuperClass();
goodsClass.setName(classKey);
goodsClass.setIntro((String) oneClass.get("intro"));
List<Attr> attrs = new ArrayList<Attr>();
for (String attrKey : oneClass.keySet()) {
if (attrKey != "intro") {
Attr attr = new Attr();
attr.setName(attrKey);
attr.setValue((String) oneClass.get(attrKey));
attrs.add(attr);
}
}
goodsClass.setAttrs(attrs);
// instance
Map<String, Object> instances = (Map<String, Object>) one.get("instance");
for (String instanceKey : instances.keySet()) {
Map<String, Object> instance = new HashMap<String, Object>();
GoodsInstance goodsInstance = new GoodsInstance();
Map<String, Object> instanceAttrMap = (Map<String, Object>) instances.get(instanceKey);
goodsInstance.setName((String) instanceAttrMap.get("name"));
goodsInstance.setIntro((String) instanceAttrMap.get("intro"));
List<Attr> goodsInstanceAttrs = new ArrayList<Attr>();
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<String, Object>) map.get(String.valueOf(instanceAttrMap.get("placeId")))).get("name"));
goodsInstance.setPlace(place);
List<GoodsInstance> placeGoodsInstances = place.getGoodsInstances();
if (placeGoodsInstances == null) {
placeGoodsInstances = new ArrayList<GoodsInstance>();
}
placeGoodsInstances.add(goodsInstance);
place.setGoodsInstances(placeGoodsInstances);
NpcInstance npc = this.npcInstanceIndex.get(npcNames.get(String.valueOf(instanceAttrMap.get("npcId"))));
goodsInstance.setNpc(npc);
List<GoodsInstance> npcGoodsInstances = npc.getGoodsInstances();
if (npcGoodsInstances == null) {
npcGoodsInstances = new ArrayList<GoodsInstance>();
}
npcGoodsInstances.add(goodsInstance);
npc.setGoodsInstances(npcGoodsInstances);
List<GoodsInstance> goodsInstancesClass = goodsClass.getGoodsInstances();
if (goodsInstancesClass == null) {
goodsInstancesClass = new ArrayList<GoodsInstance>();
}
goodsInstancesClass.add(goodsInstance);
goodsClass.setGoodsInstances(goodsInstancesClass);
this.goodsInstanceIndex.put((String) instanceAttrMap.get("name"), goodsInstance);
}
this.goodsClassIndex.put(classKey, goodsClass);
}
}catch(Exception e){
System.out.println("处理有误");
}
}
/********************************************地点******************************************/
// 周围有什么
public List<String> queryAroundAllBySite(String site){
List<String> queryGoods = this.queryAroundGoodsBySite(site);
List<String> queryNpc = this.queryAroundNpcBySite(site);
queryGoods.addAll(queryNpc);
return queryGoods;
}
// 周围有什么人
public List<String> queryAroundNpcBySite(String site){
Place place = this.placeIndex.get(site);
List<String> queryNpc = new ArrayList<String>();
List<NpcInstance> npcInstances = place.getNpcInstances();
if(npcInstances!=null) {
for(int i=0; i<npcInstances.size(); i++) {
queryNpc.add(npcInstances.get(i).getName());
}
}
return queryNpc;
}
// 周围有什么物品
public List<String> queryAroundGoodsBySite(String site){
Place place = this.placeIndex.get(site);
List<String> queryGoods = new ArrayList<String>();
List<GoodsInstance> goodsInstances = place.getGoodsInstances();
if(goodsInstances!=null) {
for(int i=0; i<goodsInstances.size(); i++) {
queryGoods.add(goodsInstances.get(i).getName());
}
}
return queryGoods;
}
// 我现在能去哪
public List<String> queryCanGoBySite(String site){
List<String> ableGoString = new ArrayList<String>();
Place place = this.placeIndex.get(site);
List<Place> ableGos = place.getAbleGo();
for(int i=0; i<ableGos.size(); i++) {
ableGoString.add(ableGos.get(i).getName());
}
return ableGoString;
}
// 两点之间的路径
public List<String> queryPathBySite(String start, String destination){
return null;
}
/**************************************物品***************************/
// 通过类和地点查询所有物品名称
public List<String> queryGoodsByClassAndSite(String className, String site){
List<String> goodsNames = new ArrayList<String>();
List<GoodsInstance> placeGoodsInstances = this.placeIndex.get(site).getGoodsInstances();
List<GoodsInstance> goodsInstances = this.goodsClassIndex.get(className).getGoodsInstances();
GoodsInstance goodsInstance = new GoodsInstance();
for(int i=0; i<placeGoodsInstances.size(); i++) {
for(int j=0; j<goodsInstances.size(); j++) {
if(placeGoodsInstances.get(i) == goodsInstances.get(j)) {
goodsNames.add(placeGoodsInstances.get(i).getName());
}
}
}
return goodsNames;
}
// 查询指定物品
public GoodsInstance queryGoodsByGoodsName(String name){
GoodsInstance goodsInstance = this.goodsInstanceIndex.get(name);
return goodsInstance;
}
// 查询指定物品的简介
public String queryGoodsIntroByGoodsName(String name){
GoodsInstance goodsInstance = this.queryGoodsByGoodsName(name);
return goodsInstance.getIntro();
}
// 查询指定物品的属性值
public String queryGoodsAttrByGoodsName(String name, String attrName){
GoodsInstance goodsInstance = queryGoodsByGoodsName(name);
if(goodsInstance == null) {
goodsInstance = queryGoodsByGoodsName(attrName);
attrName = name;
}
if(goodsInstance != null) {
List<Attr> attrs = goodsInstance.getAttrs();
for(int i=0; i<attrs.size(); i++) {
if(attrs.get(i).getName().equals(attrName)) {
return attrs.get(i).getValue();
}
}
return null;
}else {
return null;
}
}
// 查询指定物品的所有属性
public List<String> queryGoodsAllAttrByGoodsName(String name){
List<String> attrnames = new ArrayList<String>();
GoodsInstance goodsInstance = queryGoodsByGoodsName(name);
if(goodsInstance != null) {
List<Attr> attrs = goodsInstance.getAttrs();
for(int i=0; i<attrs.size(); i++) {
attrnames.add(attrs.get(i).getName());
}
return attrnames;
}else {
return null;
}
}
/**************************************npc*****************************************/
// 通过地点和类查询所有的npc名陈
public List<String> queryNpcByClassAndSite(String className, String site){
List<String> npcNames = new ArrayList<String>();
List<NpcInstance> placeNpcInstances = this.placeIndex.get(site).getNpcInstances();
List<NpcInstance> npcInstances = this.goodsClassIndex.get(className).getNpcInstances();
NpcInstance npcInstance = new NpcInstance();
for(int i=0; i<placeNpcInstances.size(); i++) {
for(int j=0; j<npcInstances.size(); j++) {
if(placeNpcInstances.get(i) == npcInstances.get(j)) {
npcNames.add(placeNpcInstances.get(i).getName());
}
}
}
return npcNames;
}
// 查询指定的npc
public NpcInstance queryNpcByNpcName(String npcName){
NpcInstance npcInstance = this.npcInstanceIndex.get(npcName);
return npcInstance;
}
// 查询指定NPC简介
public String queryNpcIntroByNpcName(String name){
NpcInstance npcInstance = queryNpcByNpcName(name);
if(npcInstance != null) {
return npcInstance.getIntro();
}else {
return null;
}
}
// 查询指定npc的属性值
public String queryNpcAttrByNpcName(String name, String attrName){
NpcInstance npcInstance = queryNpcByNpcName(name);
if(npcInstance == null) {
npcInstance = queryNpcByNpcName(attrName);
attrName = name;
}
if(npcInstance != null) {
List<Attr> attrs = npcInstance.getAttrs();
for(int i=0; i<attrs.size(); i++) {
if(attrs.get(i).getName().equals(attrName)) {
return attrs.get(i).getValue();
}
}
return null;
}else {
return null;
}
}
// 查询指定npc的所有属性
public List<String> queryNpcAttrsByNpcName(String name){
List<String> attrNames = new ArrayList<String>();
NpcInstance npcInstance = queryNpcByNpcName(name);
if(npcInstance != null) {
List<Attr> attrs = npcInstance.getAttrs();
for(int i=0; i<attrs.size(); i++) {
attrNames.add(attrs.get(i).getName());
}
return attrNames;
}else {
return null;
}
}
// 增加
public boolean insert(String name){
String[] names = name.split("_");
if(names.length == 3){
if(names[0].equals("goods")){
SuperClass goodsClass= this.goodsClassIndex.get(names[1]);
List<Attr> goodsClassAttrs = goodsClass.getAttrs();
GoodsInstance goodsInstance = new GoodsInstance();
List<Attr> goodsInstanceAttr = new ArrayList<Attr>();
goodsInstance.setName(names[2]);
goodsInstance.setIntro(goodsClass.getIntro());
for(int i=0; i<goodsClassAttrs.size(); i++){
Attr attr = new Attr();
attr.setName(goodsClassAttrs.get(i).getName());
attr.setValue(goodsClassAttrs.get(i).getValue());
goodsInstanceAttr.add(attr);
}
goodsInstance.setAttrs(goodsInstanceAttr);
this.goodsInstanceIndex.put(names[2], goodsInstance);
return true;
}else if(names[0].equals("npc")) {
SuperClass npcClass= this.npcClassIndex.get(names[1]);
List<Attr> npcClassAttrs = npcClass.getAttrs();
NpcInstance npcInstance = new NpcInstance();
List<Attr> npcInstanceAttr = new ArrayList<Attr>();
npcInstance.setName(names[2]);
npcInstance.setIntro(npcClass.getIntro());
for(int i=0; i<npcClassAttrs.size(); i++){
Attr attr = new Attr();
attr.setName(npcClassAttrs.get(i).getName());
attr.setValue(npcClassAttrs.get(i).getValue());
npcInstanceAttr.add(attr);
}
npcInstance.setAttrs(npcInstanceAttr);
this.npcInstanceIndex.put(names[2], npcInstance);
return true;
}else {
return false;
}
}else{
return false;
}
}
// 改变
public boolean update(String name, String value) {
String[] names = name.split("_");
if(names.length == 4){
if(names[0].equals("goods")){
List<GoodsInstance> goodsInstancesByClass = this.goodsClassIndex.get(names[1]).getGoodsInstances();
boolean goodsInstanceBoolean = false;
GoodsInstance goodsInstance = this.goodsInstanceIndex.get(names[2]);
for(int i=0; i<goodsInstancesByClass.size(); i++) {
if(goodsInstance == goodsInstancesByClass.get(i)) {
goodsInstanceBoolean = true;
}
}
if(goodsInstanceBoolean) {
List<Attr> attrs = goodsInstance.getAttrs();
for(int j=0; j<attrs.size(); j++) {
if(names[3].equals(attrs.get(j).getName())) {
attrs.get(j).setValue(value);
return true;
}
}
return true;
}else {
return false;
}
}else if(names[0].equals("npc")) {
List<NpcInstance> npcInstancesByClass = this.npcClassIndex.get(names[1]).getNpcInstances();
boolean npcInstanceBoolean = false;
NpcInstance npcInstance = this.npcInstanceIndex.get(names[2]);
for(int i=0; i<npcInstancesByClass.size(); i++) {
if(npcInstance == npcInstancesByClass.get(i)) {
npcInstanceBoolean = true;
}
}
if(npcInstanceBoolean) {
List<Attr> attrs = npcInstance.getAttrs();
for(int j=0; j<attrs.size(); j++) {
if(names[3].equals(attrs.get(j).getName())) {
attrs.get(j).setValue(value);
return true;
}
}
return true;
}else {
return false;
}
}
}
return false;
}
// 增删改通用
public boolean CUD(String name, String operator, String value){
if(operator.equals("insert")) {
return this.insert(name);
}else if(operator.equals("update")) {
return this.update(name, value);
}else if(operator.equals("delete")) {
return false;
}else {
return false;
}
}
}
package GameEnvironment;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Util {
public static String getJsonString(String fullName) {
Reader reader = null;
String jsonString = "";
try {
// System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[256];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fullName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
// System.out.println(tempchars);
jsonString = jsonString + String.valueOf(tempchars);
// System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
jsonString = jsonString+tempchars[i];
// System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return jsonString;
}
}
package GameEnvironment.bean;
public class Attr {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Attr [name=" + name + ", value=" + value + "]";
}
}
package GameEnvironment.bean;
public class GoodsInstance extends SuperClass{
private Place place;
private NpcInstance npc;
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public NpcInstance getNpc() {
return npc;
}
public void setNpc(NpcInstance npc) {
this.npc = npc;
}
@Override
public String toString() {
String placeName = "";
if(place != null) {
placeName = place.getName();
}
String npcName = "";
if(npc != null) {
npcName = npc.getName();
}
return super.toString()+"GoodsInstance [placeName=" + placeName + ", npcName=" + npcName + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class NpcInstance extends SuperClass{
private Place place;
private List<GoodsInstance> goodsInstances;
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> 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 + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class Place {
private String name;
private String intro;
private List<Place> ableGo;
private List<NpcInstance> npcInstances;
private List<GoodsInstance> 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<Place> getAbleGo() {
return ableGo;
}
public void setAbleGo(List<Place> ableGo) {
this.ableGo = ableGo;
}
public List<NpcInstance> getNpcInstances() {
return npcInstances;
}
public void setNpcInstances(List<NpcInstance> npcInstances) {
this.npcInstances = npcInstances;
}
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> 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 + "]";
}
}
package GameEnvironment.bean;
import java.util.List;
public class SuperClass {
private String name;
private String intro;
private List<Attr> attrs;
private List<GoodsInstance> goodsInstances;
private List<NpcInstance> npcInstances;
public List<GoodsInstance> getGoodsInstances() {
return goodsInstances;
}
public void setGoodsInstances(List<GoodsInstance> goodsInstances) {
this.goodsInstances = goodsInstances;
}
public List<NpcInstance> getNpcInstances() {
return npcInstances;
}
public void setNpcInstances(List<NpcInstance> 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<Attr> getAttrs() {
return attrs;
}
public void setAttrs(List<Attr> 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 + "]";
}
}
...@@ -292,7 +292,7 @@ public class SqlHelper { ...@@ -292,7 +292,7 @@ public class SqlHelper {
public JSONObject queryGameElementsByBotId(int id) { public JSONObject queryGameElementsByBotId(int id) {
String sql = "select * from generate_json_tb where project_id = ?"; String sql = "select * from generate_json_tb where project_id = ?";
String userName = ""; String userName = "";
String result = "empty"; String result = "{}";
try { try {
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, String.valueOf(id)); ps.setString(1, String.valueOf(id));
...@@ -311,6 +311,28 @@ public class SqlHelper { ...@@ -311,6 +311,28 @@ public class SqlHelper {
} }
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) { public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) {
String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)";
String userName = ""; String userName = "";
...@@ -365,4 +387,6 @@ public class SqlHelper { ...@@ -365,4 +387,6 @@ public class SqlHelper {
} }
} }
package entity; package entity;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import GameEnvironment.GameEnv;
public class ChatCache { public class ChatCache {
private Map<String, String> infoPoint = null; private Map<String, String> infoPoint = null;
private World world = null; private GameEnv gameEnv = null;
public Map<String, String> getInfoPoint() { public Map<String, String> getInfoPoint() {
return infoPoint; return infoPoint;
...@@ -16,26 +19,20 @@ public class ChatCache { ...@@ -16,26 +19,20 @@ public class ChatCache {
this.infoPoint = infoPoint; this.infoPoint = infoPoint;
} }
public World getWorld() { public GameEnv getGameEnv() {
return world; return gameEnv;
} }
public void setWorld(World world) { public void setGameEnv(GameEnv gameEnv) {
this.world = world; this.gameEnv = gameEnv;
} }
public ChatCache(Map<String, String[]> curInfoPoint, UserInfo userInfo) { public ChatCache(UserInfo userInfo) throws Exception {
world = new World(); gameEnv = new GameEnv(userInfo.botAccount);
String k; String k;
infoPoint = new HashMap<String, String>(); infoPoint = new HashMap<String, String>();
Iterator<String> iit = curInfoPoint.keySet().iterator(); Iterator<String> iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) {
k = iit.next();
infoPoint.put(k, "");
}
//变量初始化
iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k)); infoPoint.put(k, userInfo.varInitialMap.get(k));
......
...@@ -124,29 +124,8 @@ public class JConfig { ...@@ -124,29 +124,8 @@ public class JConfig {
while (iit.hasNext()) { while (iit.hasNext()) {
varName = iit.next(); varName = iit.next();
varValue = knowledge.get(varName); varValue = knowledge.get(varName);
if(varName.startsWith("NPC")) {
//当名字前为NPC或者items时,需要更新World的状态,所以要在更新信息前加上操作符
if(varValue.startsWith("update:")){
sb.append("-<-" + varName + ":" + "updateAttrByNPCName:" + varValue.substring(5));
} else if(varValue.startsWith("insert:")){
sb.append("-<-" + varName + ":" + "addNpc:" + varValue.substring(5));
} else if(varValue.startsWith("delete")){
sb.append("-<-" + varName + ":" + "deleteNpc:" + varValue.substring(5));
}
}else if(varName.startsWith("item_")){
sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue);
if(varValue.startsWith("update:")){
sb.append("-<-" + varName + ":" + "updateAttrByGoodsName:" + varValue.substring(5));
} else if(varValue.startsWith("insert:")){
sb.append("-<-" + varName + ":" + "addGoodsBase:" + varValue.substring(5));
} else if(varValue.startsWith("delete")){
sb.append("-<-" + varName + ":" + "deleteGoods:" + varValue.substring(5));
}
}else {
sb.append("-<-" + varName + ":" + varValue); sb.append("-<-" + varName + ":" + varValue);
}
} }
if (!extraKL.equals("")) { if (!extraKL.equals("")) {
sb.append("-<-" + extraKL); sb.append("-<-" + extraKL);
......
...@@ -7,10 +7,10 @@ import java.util.List; ...@@ -7,10 +7,10 @@ import java.util.List;
* 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里
*/ */
public class UserInfo { public class UserInfo {
public UserInfo(String userName) { public UserInfo(String botAccount) {
this.conditionTable = new HashMap<String, List<Condition>>(); this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = ""; this.configStr = "";
this.userName = userName; this.botAccount = botAccount;
this.extraInfo = new HashMap<String, String>() { this.extraInfo = new HashMap<String, String>() {
{ {
put("activeAction", " "); put("activeAction", " ");
...@@ -23,7 +23,7 @@ public class UserInfo { ...@@ -23,7 +23,7 @@ public class UserInfo {
public HashMap<String, List<Condition>> conditionTable; public HashMap<String, List<Condition>> conditionTable;
public String configStr; public String configStr;
public String userName; public String botAccount;
public HashMap<String, String> extraInfo; public HashMap<String, String> extraInfo;
public HashMap<Integer, String> id2config; public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition; public HashMap<Integer, Condition> id2condition;
......
...@@ -6,6 +6,8 @@ import db.SqlHelper; ...@@ -6,6 +6,8 @@ import db.SqlHelper;
import entity.JConfig; import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -18,34 +20,68 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -18,34 +20,68 @@ public class CharacterConstructor extends ElementConstructor {
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue; String category, name, className, description, attrName, attrValue;
JSONArray allNPC = jsonObject.getJSONArray("npc"); JSONArray allNPC = jsonObject.getJSONArray("npc");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
String conditionName1 = "wenzainali"; HashSet<String> classSet = new HashSet<String>();
//与npc属性相关的所有condition
ArrayList<String> relateConditions = new ArrayList<String>(){
{
add("wenzainali");
add("shishenme");
}
};
//与npc类相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){
{
add("know_exist_what");
}
};
String conditionValue = "哪里:人称", repValue; String conditionValue = "哪里:人称", repValue;
StringBuffer keywords = new StringBuffer();
StringBuffer classKeywords = new StringBuffer();
for (JSONObject character : allNPC.toJavaList(JSONObject.class)) {
for (JSONObject npc : allNPC.toJavaList(JSONObject.class)) {
category = (String) npc.get("category");
JSONArray characters = npc.getJSONArray("characters");
for (JSONObject character : characters.toJavaList(JSONObject.class)) {
name = (String) character.get("name"); name = (String) character.get("name");
description = (String) character.get("intro"); className = (String)character.get("class");
if(!classSet.contains(className)) {
classSet.add(className);
classKeywords.append("+周围:" + className + "+附近" + className);
}
attribute = JSONObject.toJavaObject(character.getJSONObject("attr"), Map.class); attribute = JSONObject.toJavaObject(character.getJSONObject("attr"), Map.class);
attrIter = attribute.keySet().iterator(); attrIter = attribute.keySet().iterator();
repValue = conditionValue.replace("人称", name);
keywords.append("+" + repValue);
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue);
repValue = conditionValue.replace("人称", name); }
System.out.println(name);
}
//根据根据NPC名字和属性查询属性值
for(String conditionName: relateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName1 + "::match-Keyword=" + repValue, " ", conditionName + "::match-Include=" + keywords, " ",
"match,return-0", "{NPC_reply-2}", "yaobuyao", "NPC_reply:queryAttrByNPCName:" + conditionName1 "match,return-0", "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName
); );
jConfigList.add(jConfig); 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);
} }
} }
} }
...@@ -6,6 +6,8 @@ import db.SqlHelper; ...@@ -6,6 +6,8 @@ import db.SqlHelper;
import entity.JConfig; import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -20,38 +22,74 @@ public class ItemConstructor extends ElementConstructor { ...@@ -20,38 +22,74 @@ public class ItemConstructor extends ElementConstructor {
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
String category, name, description, attrName, attrValue; String category, name, className, description, attrName, attrValue;
JSONArray goods = jsonObject.getJSONArray("goods"); JSONArray goods = jsonObject.getJSONArray("goods");
Map<String, String> attribute = null; Map<String, String> attribute = null;
Iterator<String> attrIter = null; Iterator<String> attrIter = null;
String conditionName1 = "nums"; HashSet<String> classSet = new HashSet<String>();
String keywords1 = "";
//与物品属性查询相关的所有condition
ArrayList<String> attrRelateConditions = new ArrayList<String>(){
{
add("nums");
add("shishenme");
}
};
//与物品类查询相关的所有condition
ArrayList<String> classRelateConditions = new ArrayList<String>(){
{
add("know_exist_what");
}
};
StringBuffer keywords = new StringBuffer();
StringBuffer classKeywords = new StringBuffer();
for (JSONObject good : goods.toJavaList(JSONObject.class)) { for (JSONObject good : goods.toJavaList(JSONObject.class)) {
name = (String) good.get("name");
className = (String)good.get("class");
category = (String) good.get("category"); if(!classSet.contains(className)) {
JSONArray items = good.getJSONArray("items"); classSet.add(className);
for (JSONObject item : items.toJavaList(JSONObject.class)) { //添加周围有什么士兵等关于类别的关键词
name = (String) item.get("name"); classKeywords.append("+周围:" + className + "+附近" + className);
description = (String) item.get("intro"); }
attribute = JSONObject.toJavaObject(item.getJSONObject("attr"), Map.class);
attribute = JSONObject.toJavaObject(good.getJSONObject("attr"), Map.class);
attrIter = attribute.keySet().iterator(); attrIter = attribute.keySet().iterator();
while (attrIter.hasNext()) { while (attrIter.hasNext()) {
attrName = attrIter.next(); attrName = attrIter.next();
attrValue = attribute.get(attrName); attrValue = attribute.get(attrName);
varInitialMap.put(category + "_" + name + "_" + attrName, attrValue); keywords.append( "+" + name + ":" + attrName) ;
keywords1 += "+" + name + ":" + attrName ;
} }
} }
//根据根据物品名字和属性查询属性值
for(String conditionName : attrRelateConditions) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName1 + "::match-Keyword=" + keywords1, " ", conditionName + "::match-Include=" + keywords, " ",
"match,return-0", "match,return-0",
"{items_reply-2}", "{goods_query-2}",
" ", " ",
"items_reply:queryAttrByGoodsName:" + conditionName1 "goods_query:queryAttrByGoodsName:" + conditionName
); );
jConfigList.add(jConfig); 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);
}
} }
} }
...@@ -6,8 +6,6 @@ import db.SqlHelper; ...@@ -6,8 +6,6 @@ import db.SqlHelper;
import entity.JConfig; import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.*; import java.util.*;
public class MapConstructor extends ElementConstructor { public class MapConstructor extends ElementConstructor {
...@@ -66,7 +64,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -66,7 +64,7 @@ public class MapConstructor extends ElementConstructor {
JSONObject map = jsonObject.getJSONObject("map"); JSONObject map = jsonObject.getJSONObject("map");
Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class);
JSONArray locations = map.getJSONArray("locations"); JSONArray locations = map.getJSONArray("locations");
String botName = (String)jsonObject.get("botName"); String userName = (String)jsonObject.get("userName");
this.locations = locations; this.locations = locations;
this.question2keyword = question2keyword; this.question2keyword = question2keyword;
//通过邻接表构造邻接矩阵 //通过邻接表构造邻接矩阵
...@@ -78,8 +76,10 @@ public class MapConstructor extends ElementConstructor { ...@@ -78,8 +76,10 @@ public class MapConstructor extends ElementConstructor {
floyd.printPath(matrix, locationNum); floyd.printPath(matrix, locationNum);
generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateWantToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject); generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, jsonObject);
generateWhereIam(jsonObject, botName); generateWhereIam(jsonObject, userName);
generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
generateSurroundingItem();
generateSurroundingPeople();
} }
...@@ -91,7 +91,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -91,7 +91,7 @@ public class MapConstructor extends ElementConstructor {
String conditionKeywords = "botName:哪里+botName:哪"; String conditionKeywords = "botName:哪里+botName:哪";
String zainaliKeywords = conditionKeywords.replace("botName", botName); String zainaliKeywords = conditionKeywords.replace("botName", botName);
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + zainaliKeywords, " ", conditionName + "::match-Include=" + zainaliKeywords, " ",
"match", "你在{site-2}", "yaobuyao", "" "match", "你在{site-2}", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -110,7 +110,6 @@ public class MapConstructor extends ElementConstructor { ...@@ -110,7 +110,6 @@ public class MapConstructor extends ElementConstructor {
String conditionKeywords = "去:地点"; String conditionKeywords = "去:地点";
String placeA, placeB, descriptionB, placeKeywords, text, pathNode; String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String want_know_zenmezuoKeywords = question2keyword.get("want_know_zenmezuo");
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
...@@ -123,7 +122,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -123,7 +122,7 @@ public class MapConstructor extends ElementConstructor {
if (i == j) { if (i == j) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", "" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -132,7 +131,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -132,7 +131,7 @@ public class MapConstructor extends ElementConstructor {
; ;
if (pathMatirx[i][j] == 1) { if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA,
"match", placeB + "就在附近哦", "yaobuyao", "" "match", placeB + "就在附近哦", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -146,7 +145,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -146,7 +145,7 @@ public class MapConstructor extends ElementConstructor {
} }
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA,
"match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", "" "match", "经过" + pathNode + "就可以到达" + placeB, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -176,15 +175,11 @@ public class MapConstructor extends ElementConstructor { ...@@ -176,15 +175,11 @@ public class MapConstructor extends ElementConstructor {
} }
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + conditionKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + conditionKeywords, "site::match-Include=" + placeA,
"match", "你可以去" + pathNode, "yaobuyao", "" "match", "你可以去" + pathNode, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
} }
...@@ -209,7 +204,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -209,7 +204,7 @@ public class MapConstructor extends ElementConstructor {
if (i == j) { if (i == j) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA,
"match", "你已经在" + placeB + "了", "yaobuyao", "" "match", "你已经在" + placeB + "了", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -220,13 +215,13 @@ public class MapConstructor extends ElementConstructor { ...@@ -220,13 +215,13 @@ public class MapConstructor extends ElementConstructor {
//如果两点相邻 //如果两点相邻
if (pathMatirx[i][j] == 1) { if (pathMatirx[i][j] == 1) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, conditionName + "::match-Include=" + placeKeywords,
"site::match-Keyword=" + placeA + "," + lastTaskCondition + "::match-Keyword=null" + "," + lastTaskReply + "::match-Keyword=null", "site::match-Include=" + placeA + "," + lastTaskCondition + "::match-Include=null" + "," + lastTaskReply + "::match-Include=null",
"match, reutrn-0", "地点尚未激活", "yaobuyao", "" "match, reutrn-0", "地点尚未激活", "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, "site::match-Keyword=" + placeA, conditionName + "::match-Include=" + placeKeywords, "site::match-Include=" + placeA,
"match", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeB + "-<-process-nextStep:var={" + lastTaskCondition +"-2}" "match", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeB + "-<-process-nextStep:var={" + lastTaskCondition +"-2}"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -241,8 +236,8 @@ public class MapConstructor extends ElementConstructor { ...@@ -241,8 +236,8 @@ public class MapConstructor extends ElementConstructor {
k = preTable[k][j]; k = preTable[k][j];
} }
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + placeKeywords, conditionName + "::match-Include=" + placeKeywords,
"site::match-Keyword=" + placeA, "site::match-Include=" + placeA,
"match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", "" "match", "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB, "yaobuyao", ""
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -253,22 +248,22 @@ public class MapConstructor extends ElementConstructor { ...@@ -253,22 +248,22 @@ public class MapConstructor extends ElementConstructor {
public void generateSurroundingPeople(){ public void generateSurroundingPeople(){
String conditionName = "know_exist_what"; String conditionName = "know_exist_what";
String conditionKeywords = "周围:人"; String conditionKeywords = "周围:人+附近:人";
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + conditionKeywords, " ", conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundNpcBySite:" "match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
public void generateSurroundingItem(){ public void generateSurroundingItem(){
String conditionName = "know_exist_what"; String conditionName = "know_exist_what";
String conditionKeywords = "周围:物品,周围:东西"; String conditionKeywords = "周围:物品+周围:东西+附近:物品+附近:东西";
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=" + conditionKeywords, " ", conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "{map_reply-2}", "yaobuyao", "map_reply:queryAroundGoodsBySite:" "match,return-0", "周围有{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:"
); );
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
......
...@@ -5,11 +5,15 @@ import com.alibaba.fastjson.JSONObject; ...@@ -5,11 +5,15 @@ import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.JConfig; import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import org.apache.http.message.BasicNameValuePair;
import processing.MyFunc;
import java.io.UnsupportedEncodingException;
import java.util.*; import java.util.*;
public class PlotConstructor extends ElementConstructor { public class PlotConstructor extends ElementConstructor {
String POST_URL = "http://localhost:1111/conditionProcess";
JSONArray plots = null; JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
...@@ -26,13 +30,31 @@ public class PlotConstructor extends ElementConstructor { ...@@ -26,13 +30,31 @@ public class PlotConstructor extends ElementConstructor {
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
JSONArray plots = jsonObject.getJSONArray("plots"); JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String) jsonObject.get("start"); String start = (String) jsonObject.get("start"), startCondition;
JSONObject returnMessage = null;
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
if(id2j.containsKey(start)) { if(id2j.containsKey(start)) {
JSONObject data = new JSONObject();
startCondition = (String)id2j.get(start).get("conditionName");
data.put("startCondition", startCondition);
data.put("botName_yhm", (String)jsonObject.get("botName"));
data.put("botName", (String)jsonObject.get("botName"));
data.put("botId", (Integer)jsonObject.get("botId"));
data.put("type", "game_plot_init");
userinfo.extraInfo.put("activeAction", startCondition);
try {
returnMessage = MyFunc.postJSON(POST_URL, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if((Integer)returnMessage.get("status") == 1) {
String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度";
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, start); varInitialMap.put(taskLineName, start);
...@@ -43,6 +65,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -43,6 +65,9 @@ public class PlotConstructor extends ElementConstructor {
BFSGenerate4(id2j.get(start), userinfo); BFSGenerate4(id2j.get(start), userinfo);
varInitialMap.put(start, "1"); varInitialMap.put(start, "1");
}else {
System.out.println("剧情初始化失败");
}
} else { } else {
System.out.println("start剧情不存在"); System.out.println("start剧情不存在");
...@@ -180,9 +205,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -180,9 +205,9 @@ public class PlotConstructor extends ElementConstructor {
extraUK = taskName + ":" + (taskStep + 1); extraUK = taskName + ":" + (taskStep + 1);
extraHP = taskName + "::match-Keyword=" + taskStep; extraHP = taskName + "::match-Include=" + taskStep;
if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1)) if (newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1))
extraHP += "," + nextId + "::match-Keyword=null"; extraHP += "," + nextId + "::match-Include=null";
extraUK += "-<-" + nextId + ":" + 1; extraUK += "-<-" + nextId + ":" + 1;
jConfig = new JConfig( jConfig = new JConfig(
...@@ -230,8 +255,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -230,8 +255,8 @@ public class PlotConstructor extends ElementConstructor {
//对于unknown的特殊处理 //对于unknown的特殊处理
if (curUnknownText.equals("")) { if (curUnknownText.equals("")) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=unknown", conditionName + "::match-Include=unknown",
extraHP = taskName + "::match-Keyword=" + taskStep, extraHP = taskName + "::match-Include=" + taskStep,
"match,return-0,post::all(" + CHITCHAT_URL + ")", "match,return-0,post::all(" + CHITCHAT_URL + ")",
" ", " ",
" ", " ",
...@@ -339,7 +364,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -339,7 +364,7 @@ public class PlotConstructor extends ElementConstructor {
branchSize = branch.size(); branchSize = branch.size();
//当两次出现unknown时给用户一下候选项 //当两次出现unknown时给用户一下候选项
keywordOptions = ""; keywordOptions = "";
extraHP = id + "::match-Keyword=" + 1; extraHP = id + "::match-Include=" + 1;
for (int i = 0; i < branchSize; i++) { for (int i = 0; i < branchSize; i++) {
...@@ -401,7 +426,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -401,7 +426,7 @@ public class PlotConstructor extends ElementConstructor {
* @param userinfo * @param userinfo
*/ */
public void BFSGenerate3(JSONObject root, UserInfo userinfo) { public void BFSGenerate3(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, 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; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
...@@ -415,6 +440,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -415,6 +440,7 @@ public class PlotConstructor extends ElementConstructor {
Queue<JSONObject> queue = new LinkedList<JSONObject>(); Queue<JSONObject> queue = new LinkedList<JSONObject>();
System.out.println("rootId");
queue.add(root); queue.add(root);
...@@ -475,9 +501,17 @@ public class PlotConstructor extends ElementConstructor { ...@@ -475,9 +501,17 @@ public class PlotConstructor extends ElementConstructor {
//额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location; 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}"; extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}";
jConfig = new JConfig( jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
...@@ -519,8 +553,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -519,8 +553,8 @@ public class PlotConstructor extends ElementConstructor {
//对于unknown的特殊处理 //对于unknown的特殊处理
if (curUnknownText.equals("")) { if (curUnknownText.equals("")) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=unknown", conditionName + "::match-Include=unknown",
extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId, extraHP = "任务线_" + location + "进度::match-Include=" + parentId,
"match,return-0,post::all(" + CHITCHAT_URL + ")", "match,return-0,post::all(" + CHITCHAT_URL + ")",
" ", " ",
" ", " ",
...@@ -557,7 +591,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -557,7 +591,7 @@ public class PlotConstructor extends ElementConstructor {
* @param userinfo * @param userinfo
*/ */
public void BFSGenerate4(JSONObject root, UserInfo userinfo) { public void BFSGenerate4(JSONObject root, UserInfo userinfo) {
String id = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName, 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; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
...@@ -634,7 +668,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -634,7 +668,8 @@ public class PlotConstructor extends ElementConstructor {
//额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
extraHP = taskLineName + "::match-Keyword=" + id + ",site::match-Keyword=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Keyword=null"; 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}" + extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":var={nextStep-3}" + "-<-" + lastTaskReply + ":var={reply-3}" +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1";; "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1";;
...@@ -679,8 +714,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -679,8 +714,8 @@ public class PlotConstructor extends ElementConstructor {
//对于unknown的特殊处理 //对于unknown的特殊处理
if (curUnknownText.equals("")) { if (curUnknownText.equals("")) {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Keyword=unknown", conditionName + "::match-Include=unknown",
extraHP = "任务线_" + location + "进度::match-Keyword=" + parentId, extraHP = "任务线_" + location + "进度::match-Include=" + parentId,
"match,return-0,post::all(" + CHITCHAT_URL + ")", "match,return-0,post::all(" + CHITCHAT_URL + ")",
" ", " ",
" ", " ",
...@@ -711,10 +746,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -711,10 +746,13 @@ public class PlotConstructor extends ElementConstructor {
@Override @Override
public void postProcessing(List<Integer> idList){ public void postProcessing(List<Integer> idList){
jConfig = new JConfig(" ", "", "activate", "", idList.get(idList.size()-2) + "," + idList.get(idList.size()-1), ""); if (idList.size() != 0) {
jConfig = new JConfig(" ", "", "activate", "", idList.get(idList.size() - 2) + "," + idList.get(idList.size() - 1), "");
jConfigList.add(jConfig); jConfigList.add(jConfig);
} }
}
} }
package processing; package processing;
import GameEnvironment.GameEnv;
import com.alibaba.fastjson.JSON;
import entity.ChatCache; import entity.ChatCache;
import entity.UserInfo; import entity.UserInfo;
import entity.World;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set;
public class ChatCacheController { public class ChatCacheController {
/** /**
...@@ -18,66 +19,66 @@ public class ChatCacheController { ...@@ -18,66 +19,66 @@ public class ChatCacheController {
* *
* @return 历史信息点,对话过程中引擎提取的用户信息 * @return 历史信息点,对话过程中引擎提取的用户信息
*/ */
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) { // public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context) {
//
World world = new World(); // GameEnv gameEnv = new GameEnv(chatKey);
Map<String, String> historyInfoPoint = null; // Map<String, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = null; // Map<String, Map<String, String>> chatCache = null;
if (context.getAttribute("chatCache") == null) { // if (context.getAttribute("chatCache") == null) {
chatCache = new HashMap<String, Map<String, String>>(); // chatCache = new HashMap<String, Map<String, String>>();
context.setAttribute("chatCache", chatCache); // context.setAttribute("chatCache", chatCache);
} else { // } else {
chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); // chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
} // }
String chatkey; // String chatkey;
//
//
try { // try {
historyInfoPoint = chatCache.get(chatKey); // historyInfoPoint = chatCache.get(chatKey);
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName); // //historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) { // } catch (Exception e) {
//
//可整合 // //可整合
historyInfoPoint = null; // historyInfoPoint = null;
//
} // }
//
return historyInfoPoint; // return historyInfoPoint;
} // }
/** /**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/ */
public static synchronized void updateChatCache4Delete(ServletContext context) { // public static synchronized void updateChatCache4Delete(ServletContext context) {
String chatKey; // String chatKey;
long lastChatTime, now; // long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>(); // Map<String, String> history = new HashMap<String, String>();
Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); // Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
//
//
Iterator<String> it = chatCache.keySet().iterator(); // Iterator<String> it = chatCache.keySet().iterator();
while (it.hasNext()) { // while (it.hasNext()) {
chatKey = it.next(); // chatKey = it.next();
history = chatCache.get(chatKey); // history = chatCache.get(chatKey);
lastChatTime = Long.valueOf(history.get("lastUpdateTime")); // lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis(); // now = System.currentTimeMillis();
if (now - lastChatTime > 300000) { // if (now - lastChatTime > 300000) {
it.remove(); // it.remove();
} // }
} // }
context.setAttribute("chatCache", chatCache); // context.setAttribute("chatCache", chatCache);
} // }
/** /**
* 根据chatKey更新chatCache的数据,并修改最后更新时间 * 根据chatKey更新chatCache的数据,并修改最后更新时间
*/ */
public static synchronized void updateChatCache4Insert(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) { // public static synchronized void updateChatCache4Insert(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); // historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache"); // Map<String, Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint); // keyCache.put(curInfoPoint.get("chat_key")[0], historyInfoPoint);
context.setAttribute("chatCache", keyCache); // context.setAttribute("chatCache", keyCache);
} // }
public static boolean saveChatCache(String userName, HashMap<String, String> infoPoints) throws IOException { public static boolean saveChatCache(String userName, HashMap<String, String> infoPoints) throws IOException {
String fileDir = System.getProperty("user.dir") + "/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
...@@ -138,12 +139,12 @@ public class ChatCacheController { ...@@ -138,12 +139,12 @@ public class ChatCacheController {
public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, Map<String, String[]> curInfoPoint, UserInfo userinfo) { public static synchronized ChatCache getChatCache2(String chatKey, ServletContext context, UserInfo userinfo) throws Exception {
Map<String, ChatCache> chatCacheMap = null; Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null; ChatCache chatCache = null;
if (context.getAttribute("chatCache") == null) { if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>(); chatCacheMap = new HashMap<String, ChatCache>();
chatCacheMap.put(chatKey, new ChatCache(curInfoPoint, userinfo)); chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap); context.setAttribute("chatCache", chatCacheMap);
} else { } else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
...@@ -154,13 +155,13 @@ public class ChatCacheController { ...@@ -154,13 +155,13 @@ public class ChatCacheController {
try { try {
chatCache = chatCacheMap.get(chatKey); chatCache = chatCacheMap.get(chatKey);
if(chatCache == null){ if(chatCache == null){
chatCache = new ChatCache(curInfoPoint, userinfo); chatCache = new ChatCache(userinfo);
chatCacheMap.put(chatKey, chatCache); chatCacheMap.put(chatKey, chatCache);
} }
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName); //historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) { } catch (Exception e) {
//可整合 //可整合
chatCache = new ChatCache(curInfoPoint, userinfo); chatCache = new ChatCache(userinfo);
} }
...@@ -197,14 +198,36 @@ public class ChatCacheController { ...@@ -197,14 +198,36 @@ public class ChatCacheController {
/** /**
* 根据chatKey更新chatCache的数据,并修改最后更新时间 * 根据chatKey更新chatCache的数据,并修改最后更新时间
*/ */
public static synchronized void updateChatCache4Insert2(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, World world, ServletContext context) { public static synchronized void updateChatCache4Insert2(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")[0]); ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("chat_key"));
chatCache.setInfoPoint(historyInfoPoint); chatCache.setInfoPoint(historyInfoPoint);
chatCache.setWorld(world); chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap); context.setAttribute("chatCache", keyCacheMap);
} }
public static synchronized String saveChatCache(String chatKey, ServletContext context){
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = chatCacheMap.get(chatKey);
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 "成功";
}
}
} }
package processing;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class LogWriter {
private PrintWriter recorder = null;
String PRINT_PATTERN = "<font color=\"%s\">%s" +
"----------------------------------------------------------------------------<br></font>";
Map<Integer, String> colerMap = new HashMap<Integer, String>(){
{
put(0, "black");
put(1, "gray");
put(2, "green");
put(3, "red");
}
};
public LogWriter(String filePath, String fileName) throws IOException {
File file = new File(filePath + "/" + fileName + ".html");
if (!file.exists()) {
file.createNewFile();
}
file.setReadable(true,false);
FileWriter fw = new FileWriter(file, true);
//BufferedWriter bw = new BufferedWriter(fos, "UTF-8");
//context.setAttribute("logWriter", bw);
BufferedWriter bw = new BufferedWriter(fw);
recorder = new PrintWriter(bw);
recorder.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>log</title>\n" +
"</head>");
}
public void record(String text, int level){
recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), text));
}
public void close(){
recorder.close();
}
}
package processing; package processing;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.Solution; import entity.Solution;
import net.sf.json.JSONObject; 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 javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader; import java.io.BufferedReader;
...@@ -9,7 +19,7 @@ import java.io.IOException; ...@@ -9,7 +19,7 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.*;
public class MyFunc { public class MyFunc {
...@@ -97,5 +107,41 @@ public class MyFunc { ...@@ -97,5 +107,41 @@ public class MyFunc {
return true; 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;
}
} }
package processing; package processing;
import GameEnvironment.GameEnv;
import entity.Solution; import entity.Solution;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import entity.World;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
...@@ -17,7 +17,6 @@ import org.apache.http.util.EntityUtils; ...@@ -17,7 +17,6 @@ import org.apache.http.util.EntityUtils;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
...@@ -34,18 +33,27 @@ public class QuestionMatcher { ...@@ -34,18 +33,27 @@ public class QuestionMatcher {
static String API_ERROR = "api处理过程中出错了"; static String API_ERROR = "api处理过程中出错了";
static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
public PrintWriter logWriter = null;
public LogWriter logWriter = null;
public UserInfo userinfo = null; public UserInfo userinfo = null;
public ServletContext context = null; public ServletContext context = null;
public World world = null; public GameEnv gameEnv = null;
public Map<String ,String> curInfoPoint = null;
public QuestionMatcher(PrintWriter logWriter, UserInfo userinfo, ServletContext context, World world) { public Map<String ,String> historyInfoPoint = null;
public WorldController worldController = null;
public QuestionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv) {
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.logWriter = logWriter; this.logWriter = logWriter;
this.userinfo = userinfo; this.userinfo = userinfo;
this.context = context; this.context = context;
this.world = world; this.gameEnv = gameEnv;
this.worldController = new WorldController(logWriter);
} }
/*
/**
public void updateDB(QuestionKeyWord qkw) throws SQLException { public void updateDB(QuestionKeyWord qkw) throws SQLException {
SqlHelper helper = new SqlHelper(); SqlHelper helper = new SqlHelper();
String result = helper.queryActionByKey(qkw.getChatKey()); String result = helper.queryActionByKey(qkw.getChatKey());
...@@ -60,9 +68,10 @@ public class QuestionMatcher { ...@@ -60,9 +68,10 @@ public class QuestionMatcher {
*/ */
public boolean infoPointPreprocessing(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException {
String return_str = "", k; String return_str = "", k;
String receiveParameterStr = "";
boolean debugFlag = false; boolean debugFlag = false;
HashSet<String> skipSet = new HashSet<String>() { HashSet<String> skipSet = new HashSet<String>() {
...@@ -77,39 +86,40 @@ public class QuestionMatcher { ...@@ -77,39 +86,40 @@ public class QuestionMatcher {
//输出所有actionName的值 //输出所有actionName的值
Iterator<String> iit = curInfoPoint.keySet().iterator(); Iterator<String> iit = receiveParameters.keySet().iterator();
logWriter.println("-----------------------------------------识别数据列表-------------------------------------------<br>"); receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------<br>";
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
// //
logWriter.write(k + ": "); receiveParameterStr += k + ": ";
curInfoPoint.put(k, receiveParameters.get(k)[0]);
if (k.equals("debug_mode")) if (k.equals("debug_mode"))
debugFlag = true; debugFlag = true;
String values[] = curInfoPoint.get(k); String values[] = receiveParameters.get(k);
for (String v : values) { for (String v : values) {
logWriter.write(v + " "); receiveParameterStr += v + " ";
} }
logWriter.write("<br>"); receiveParameterStr += "<br>";
if (values[0].equals(":")) { if (values[0].equals(":")) {
values[0] = ""; curInfoPoint.put(k, "");
curInfoPoint.put(k, values);
} }
if(! historyInfoPoint.containsKey(k))
historyInfoPoint.put(k, "");
} }
logWriter.println("---------------------------------------------------------------------------------------"); logWriter.record(receiveParameterStr, 0);
logWriter.write("<br>");
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator(); iit = curInfoPoint.keySet().iterator();
boolean unknown_flag = true; boolean unknown_flag = true;
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
String values[] = curInfoPoint.get(k); String values = curInfoPoint.get(k);
if (skipSet.contains(k)) if (skipSet.contains(k))
continue; continue;
if (values != null && !values[0].equals("")) { if (!values.equals("")) {
unknown_flag = false; unknown_flag = false;
break; break;
} }
...@@ -125,13 +135,13 @@ public class QuestionMatcher { ...@@ -125,13 +135,13 @@ public class QuestionMatcher {
currentAction = " "; currentAction = " ";
curInfoPoint.put("emptySet", new String[]{" ",}); curInfoPoint.put("emptySet", " ");
if (historyInfoPoint.get("activeList") == null) { if (historyInfoPoint.get("activeList") == null) {
historyInfoPoint.put("activeList", currentAction); historyInfoPoint.put("activeList", currentAction);
} }
if (unknown_flag && !currentAction.equals("")) { if (unknown_flag && !currentAction.equals("")) {
String i[] = {"unknown",}; String i = "unknown";
curInfoPoint.put(currentAction, i); curInfoPoint.put(currentAction, i);
} }
...@@ -142,12 +152,10 @@ public class QuestionMatcher { ...@@ -142,12 +152,10 @@ public class QuestionMatcher {
/** /**
* 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch
* *
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么
* @return bestMatch 状态表中满足条件最多的一条 * @return bestMatch 状态表中满足条件最多的一条
*/ */
public Condition getBestMatch(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, HashMap<String, List<Condition>> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { public Condition getBestMatch( HashMap<String, List<Condition>> conditionTable, ServletContext context, UserInfo userInfo) throws IOException {
Integer configId = 0; Integer configId = 0;
List<Condition> conditionList = null; List<Condition> conditionList = null;
...@@ -160,11 +168,11 @@ public class QuestionMatcher { ...@@ -160,11 +168,11 @@ public class QuestionMatcher {
while (it.hasNext()) { while (it.hasNext()) {
String conditionName = it.next(); String conditionName = it.next();
String[] keywords = curInfoPoint.get(conditionName); String keywords = curInfoPoint.get(conditionName);
String keyword = null; String keyword = null;
if (keywords != null && !keywords[0].equals("")) if (keywords != null && !keywords.equals(""))
keyword = keywords[0]; keyword = keywords;
if (keyword != null && conditionTable.get(conditionName) != null) { if (keyword != null && conditionTable.get(conditionName) != null) {
...@@ -173,8 +181,8 @@ public class QuestionMatcher { ...@@ -173,8 +181,8 @@ public class QuestionMatcher {
for (Condition condition : conditionList) { for (Condition condition : conditionList) {
if (condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { if (condition.status.equals("waiting") && conditionSatisfy(condition)) {
logWriter.println("-----更新匹配更新为------" + userInfo.id2config.get(condition.id) + "-----------<br>"); logWriter.record("-----匹配更新为------" + userInfo.id2config.get(condition.id) + "-----------<br>", 2);
if (condition.featureMap.get("instantPost") != null) { if (condition.featureMap.get("instantPost") != null) {
...@@ -186,7 +194,7 @@ public class QuestionMatcher { ...@@ -186,7 +194,7 @@ public class QuestionMatcher {
//有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。
bestMatch = condition; bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context); 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.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)) } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority))
bestMatch = condition; bestMatch = condition;
...@@ -195,29 +203,38 @@ public class QuestionMatcher { ...@@ -195,29 +203,38 @@ public class QuestionMatcher {
} }
} }
logWriter.record("----------------------匹配结束", 2);
bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context);
return bestMatch; return bestMatch;
} }
public Condition activatedQueueMatching(Condition bestMatch, Queue<Condition> activatedQueue, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) throws IOException { /**
* 在激活列表中选择满足匹配且优先级最高的一条配置条目
* @param bestMatch
* @param activatedQueue
* @param context
* @return
* @throws IOException
*/
public Condition activatedQueueMatching(Condition bestMatch, Queue<Condition> activatedQueue, ServletContext context) throws IOException {
Condition condition; Condition condition;
//待激活配置条目被激活后的匹配 //待激活配置条目被激活后的匹配
while (!activatedQueue.isEmpty()) { while (!activatedQueue.isEmpty()) {
condition = activatedQueue.remove(); condition = activatedQueue.remove();
activatedMap.remove(condition.id); activatedMap.remove(condition.id);
if (conditionSatisfy(curInfoPoint, historyInfoPoint, condition)) { if (conditionSatisfy(condition)) {
if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) {
logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-----------"); logWriter.record("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-----------", 0);
bestMatch = condition; bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.auxiliaryPriority, condition.nextStep, context); 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.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)) { } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) {
bestMatch = condition; bestMatch = condition;
logWriter.write("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-------<br>"); logWriter.record("------激活匹配更新为------" + userinfo.id2config.get(condition.id) + "-------<br>", 0);
} }
} }
...@@ -232,17 +249,16 @@ public class QuestionMatcher { ...@@ -232,17 +249,16 @@ public class QuestionMatcher {
* 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。
* currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件
* *
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @param condition 配置文件(状态表)的一行 * @param condition 配置文件(状态表)的一行
* @return 满足条件就为True, 不满足就为False * @return 满足条件就为True, 不满足就为False
*/ */
public boolean conditionSatisfy(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, Condition condition) { public boolean conditionSatisfy(Condition condition) {
boolean flag = true; boolean flag = true;
String actionName, keywords[], keyword, comparePair[], cmpType, premiseStr; String actionName, keywords, keyword, comparePair[], cmpType, premiseStr;
HashSet<String> keywordSet = null; HashSet<String> keywordSet = null;
logWriter.println("<br>" + "-----检索到配置条目------" + userinfo.id2config.get(condition.id) + "-----------"); logWriter.record("-----------------------------------检索到配置条目", 0);
logWriter.record(userinfo.id2config.get(condition.id), 1);
if (condition.featureMap.containsKey("match")) { if (condition.featureMap.containsKey("match")) {
Iterator<String> it = condition.currentPremise.keySet().iterator(); Iterator<String> it = condition.currentPremise.keySet().iterator();
...@@ -250,26 +266,25 @@ public class QuestionMatcher { ...@@ -250,26 +266,25 @@ public class QuestionMatcher {
premiseStr = it.next(); premiseStr = it.next();
comparePair = premiseStr.split("::"); comparePair = premiseStr.split("::");
actionName = comparePair[0]; actionName = comparePair[0];
keywords = curInfoPoint.get(actionName); cmpType = comparePair[1];
if (keywords == null) { keyword = getKeyword(curInfoPoint, actionName);
if (keyword == null) {
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配"); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过--------------------------------------------------------" +
"<br>--------------------------------------------------------", 0);
} }
break; break;
} }
keyword = keywords[0];
if (comparePair.length == 1)
cmpType = "match";
else
cmpType = comparePair[1];
keywordSet = condition.currentPremise.get(premiseStr); keywordSet = condition.currentPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint)) if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配"); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过--------------------------------" +
"<br>--------------------------------------------------------", 0);
} }
} }
...@@ -277,47 +292,70 @@ public class QuestionMatcher { ...@@ -277,47 +292,70 @@ public class QuestionMatcher {
while (flag && it.hasNext()) { while (flag && it.hasNext()) {
premiseStr = it.next(); premiseStr = it.next();
comparePair = premiseStr.split("::"); comparePair = premiseStr.split("::");
cmpType = comparePair[1];
actionName = comparePair[0]; actionName = comparePair[0];
keyword = historyInfoPoint.get(actionName); keyword = getKeyword(historyInfoPoint, actionName);
if (keyword == null) { if (keyword == null) {
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配"); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过-----------------------------" +
"<br>--------------------------------------------------------", 0);
} }
break; break;
} }
if (comparePair.length == 1)
cmpType = "match";
else
cmpType = comparePair[1];
keywordSet = condition.historyPremise.get(premiseStr); keywordSet = condition.historyPremise.get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet, curInfoPoint, historyInfoPoint)) if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.println("<br>" + premiseStr + "不匹配"); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过<br>", 0);
} }
} }
} }
return flag; return flag;
} }
public String getKeyword(Map<String, String> 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;
};
/** /**
* 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) * 单个条件的匹配,判断是否满足条件
* 比较类型分为 match、number、time、variable,
* curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息
* *
* @param keyword * @param keyword
* @param cmpType 比较类型 * @param cmpType 比较类型
* @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件
* @return 返回匹配或者不匹配 * @return 返回匹配或者不匹配
*/ */
public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) { public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet) {
boolean flag = true; boolean flag = true;
String operator = ""; String operator = "";
...@@ -330,6 +368,7 @@ public class QuestionMatcher { ...@@ -330,6 +368,7 @@ public class QuestionMatcher {
if (cmpType.equals("match")) { if (cmpType.equals("match")) {
if(operator.equals("Keyword") || operator.equals("Include")) {
if (!keywordSet.contains(keyword)) { if (!keywordSet.contains(keyword)) {
flag = false; flag = false;
} }
...@@ -340,6 +379,14 @@ public class QuestionMatcher { ...@@ -340,6 +379,14 @@ public class QuestionMatcher {
flag = true; flag = true;
} }
} }
} else if(operator.equals("Exclude")) {
if (keywordSet.contains(keyword)) {
flag = false;
}
}else {
flag = false;
}
} else if (cmpType.equals("number") && !keyword.equals("")) { } else if (cmpType.equals("number") && !keyword.equals("")) {
int candidateA = 0; int candidateA = 0;
...@@ -374,6 +421,8 @@ public class QuestionMatcher { ...@@ -374,6 +421,8 @@ public class QuestionMatcher {
flag = candidateA < candidateB; flag = candidateA < candidateB;
else if (operator.equals("SmallerOrEqual")) else if (operator.equals("SmallerOrEqual"))
flag = candidateA <= candidateB; flag = candidateA <= candidateB;
else if (operator.equals("NotEqual"))
flag = candidateA != candidateB;
} else if (cmpType.equals("time")) { } else if (cmpType.equals("time")) {
...@@ -411,10 +460,10 @@ public class QuestionMatcher { ...@@ -411,10 +460,10 @@ public class QuestionMatcher {
} }
} }
if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2)[0].equals("")) { if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) {
conditionValue2 = curInfoPoint.get(conditionName2)[0]; conditionValue2 = getKeyword(curInfoPoint, conditionName2);
}else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){
conditionValue2 = historyInfoPoint.get(conditionName2); conditionValue2 = getKeyword(historyInfoPoint, conditionName2);
}else { }else {
flag = false; flag = false;
} }
...@@ -459,6 +508,8 @@ public class QuestionMatcher { ...@@ -459,6 +508,8 @@ public class QuestionMatcher {
flag = candidateA <= candidateB; flag = candidateA <= candidateB;
else if (operator.equals("Equal")) else if (operator.equals("Equal"))
flag = candidateA == candidateB; flag = candidateA == candidateB;
else if (operator.equals("NotEqual"))
flag = candidateA != candidateB;
} else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日")
&& keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){
...@@ -475,6 +526,8 @@ public class QuestionMatcher { ...@@ -475,6 +526,8 @@ public class QuestionMatcher {
flag = candidateA <= candidateB; flag = candidateA <= candidateB;
else if (operator.equals("Equal")) else if (operator.equals("Equal"))
flag = candidateA == candidateB; flag = candidateA == candidateB;
else if (operator.equals("NotEqual"))
flag = candidateA != candidateB;
// 操作符为等于时可以比较两个字符串是否相同 // 操作符为等于时可以比较两个字符串是否相同
} }
...@@ -495,6 +548,8 @@ public class QuestionMatcher { ...@@ -495,6 +548,8 @@ public class QuestionMatcher {
flag = candidateA <= candidateB; flag = candidateA <= candidateB;
else if (operator.equals("Equal")) else if (operator.equals("Equal"))
flag = candidateA == candidateB; flag = candidateA == candidateB;
else if (operator.equals("NotEqual"))
flag = candidateA != candidateB;
} else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日")
&& conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){
...@@ -511,6 +566,8 @@ public class QuestionMatcher { ...@@ -511,6 +566,8 @@ public class QuestionMatcher {
flag = candidateA <= candidateB; flag = candidateA <= candidateB;
else if (operator.equals("Equal")) else if (operator.equals("Equal"))
flag = candidateA == candidateB; flag = candidateA == candidateB;
else if (operator.equals("NotEqual"))
flag = candidateA != candidateB;
// 操作符为等于时可以比较两个字符串是否相同 // 操作符为等于时可以比较两个字符串是否相同
} }
...@@ -623,11 +680,9 @@ public class QuestionMatcher { ...@@ -623,11 +680,9 @@ public class QuestionMatcher {
/** /**
* 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。
* *
* @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @return 返回给引擎的数据 * @return 返回给引擎的数据
*/ */
public Solution getSolution(Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { public Solution getSolution(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Iterator<String> it = curInfoPoint.keySet().iterator(); Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName, reply, variable; String actionName, reply, variable;
...@@ -642,7 +697,9 @@ public class QuestionMatcher { ...@@ -642,7 +697,9 @@ public class QuestionMatcher {
//post关键字 //post关键字
if (ansCondition.featureMap.containsKey("post")) { if (ansCondition.featureMap.containsKey("post")) {
ans = postToServer(ans, ansCondition, curInfoPoint, historyInfoPoint); logWriter.record("---------------------进入表单结束",1);
ans = postToServer(ans, ansCondition);
logWriter.record("---------------------提交表单结束",1);
//nextNext关键字 //nextNext关键字
} }
...@@ -650,13 +707,17 @@ public class QuestionMatcher { ...@@ -650,13 +707,17 @@ public class QuestionMatcher {
//updateKnowledge关键字 //updateKnowledge关键字
if (ansCondition.featureMap.containsKey("updateKnowledge")) { if (ansCondition.featureMap.containsKey("updateKnowledge")) {
updateKnowledge(ansCondition, curInfoPoint, historyInfoPoint); logWriter.record("---------------------进入更新答案【略】",1);
updateKnowledge(ansCondition);
logWriter.record("---------------------更新答案结束",1);
} }
if (ansCondition.featureMap.containsKey("newNext")) { if (ansCondition.featureMap.containsKey("newNext")) {
ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); logWriter.record("---------------------进入判断下一步【略】",1);
ans = findNewNext(ans, ansCondition);
logWriter.record("---------------------判断下一步结束",1);
//上一步 //上一步
} else if (ansCondition.featureMap.containsKey("return-1")) { } else if (ansCondition.featureMap.containsKey("return-1")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = historyInfoPoint.get("activeList").split("\\|");
...@@ -688,22 +749,6 @@ public class QuestionMatcher { ...@@ -688,22 +749,6 @@ public class QuestionMatcher {
try { try {
/*
it = historyInfoPoint.keySet().iterator();
String keyword1, keyword2;
while (it.hasNext()) {
actionName = it.next();
if(curInfoPoint.get(actionName) != null) {
keyword1 = curInfoPoint.get(actionName)[0];
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-1}", keyword1));//这里
}
keyword2 = historyInfoPoint.get(actionName);
ans.setAnswer(ans.getAnswer().replace("{" + actionName + "-2}", keyword2));
}
*/
//用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值
reply = ans.getAnswer(); reply = ans.getAnswer();
...@@ -711,8 +756,8 @@ public class QuestionMatcher { ...@@ -711,8 +756,8 @@ public class QuestionMatcher {
while (m.find()) { while (m.find()) {
variable = m.group(1).substring(1, m.group(1).length() - 3); variable = m.group(1).substring(1, m.group(1).length() - 3);
if (m.group(1).endsWith("-1}")) { if (m.group(1).endsWith("-1}")) {
if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals("")) if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals(""))
reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]); reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable));
} else if (m.group(1).endsWith("-2}")) { } else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null) if (historyInfoPoint.get(variable) != null)
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable));
...@@ -727,7 +772,13 @@ public class QuestionMatcher { ...@@ -727,7 +772,13 @@ public class QuestionMatcher {
return ans; return ans;
} }
public void infoTransfer(Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag) { /**
* 请求处理结束后台将当前信息的信息点转移到已知信息
* @param ans
* @param context
* @param debugFlag
*/
public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) {
//将当前信息点更新至历史信息点 //将当前信息点更新至历史信息点
Iterator<String> it = curInfoPoint.keySet().iterator(); Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName, lastReply; String actionName, lastReply;
...@@ -761,7 +812,7 @@ public class QuestionMatcher { ...@@ -761,7 +812,7 @@ public class QuestionMatcher {
if(skipSet.contains(actionName)) if(skipSet.contains(actionName))
continue; continue;
keyword1 = curInfoPoint.get(actionName)[0]; keyword1 = curInfoPoint.get(actionName);
keyword2 = historyInfoPoint.get(actionName); keyword2 = historyInfoPoint.get(actionName);
if (keyword2 == null) { if (keyword2 == null) {
historyInfoPoint.put(actionName, keyword1); historyInfoPoint.put(actionName, keyword1);
...@@ -772,8 +823,8 @@ public class QuestionMatcher { ...@@ -772,8 +823,8 @@ public class QuestionMatcher {
} }
ChatCacheController.updateChatCache4Insert2(curInfoPoint, historyInfoPoint, world, context); ChatCacheController.updateChatCache4Insert2(curInfoPoint, historyInfoPoint, gameEnv, context);
//context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint);
} catch (Exception e) { } catch (Exception e) {
...@@ -786,13 +837,11 @@ public class QuestionMatcher { ...@@ -786,13 +837,11 @@ public class QuestionMatcher {
* 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试
* *
* @param ans 最终返回的数据 * @param ans 最终返回的数据
* @param curInfoPoint 当前对话识别到的信息点
* @param historyInfoPoint 在当前对话之前采集到的所有用户信息点
* @param context * @param context
*/ */
public void appendDebugInfo(Solution ans, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context) { public void appendDebugInfo(Solution ans, ServletContext context) {
Iterator<String> it = null; Iterator<String> it = null;
String key, values[], value; String key, values, value;
HashSet<String> skipSet = new HashSet<String>() { HashSet<String> skipSet = new HashSet<String>() {
{ {
...@@ -812,8 +861,8 @@ public class QuestionMatcher { ...@@ -812,8 +861,8 @@ public class QuestionMatcher {
while (it.hasNext()) { while (it.hasNext()) {
key = it.next(); key = it.next();
values = curInfoPoint.get(key); values = curInfoPoint.get(key);
if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key)) if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key))
debugInfo += (" " + key + ":\'" + values[0] + "\' "); debugInfo += (" " + key + ":\'" + values + "\' ");
} }
debugInfo += ")(已知:"; debugInfo += ")(已知:";
...@@ -836,8 +885,8 @@ public class QuestionMatcher { ...@@ -836,8 +885,8 @@ public class QuestionMatcher {
* @param ans 返回给用户的数据 * @param ans 返回给用户的数据
* @param ansCondition 满足条件最多的condition(配置文件的某一行) * @param ansCondition 满足条件最多的condition(配置文件的某一行)
*/ */
public Solution postToServer(Solution ans, Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) throws IOException { public Solution postToServer(Solution ans, Condition ansCondition) throws IOException {
String url = null, elem[], subElem[], key, postType = "all"; String url = null, elem[], subElem[], key,keys, postType = "all";
Map<String, String> infoMap = new HashMap<String, String>(); Map<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> k_iter = null; Iterator<String> k_iter = null;
...@@ -860,9 +909,9 @@ public class QuestionMatcher { ...@@ -860,9 +909,9 @@ public class QuestionMatcher {
k_iter = curInfoPoint.keySet().iterator(); k_iter = curInfoPoint.keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next(); key = k_iter.next();
if (curInfoPoint.get(key)[0] != "") if (curInfoPoint.get(key) != "")
//infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]);
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)[0])); pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
} }
k_iter = historyInfoPoint.keySet().iterator(); k_iter = historyInfoPoint.keySet().iterator();
...@@ -879,14 +928,14 @@ public class QuestionMatcher { ...@@ -879,14 +928,14 @@ public class QuestionMatcher {
//提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值
} else if (postType.equals("term")) { } else if (postType.equals("term")) {
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")[0])); pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")[0])); pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")[0])); pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
k_iter = ansCondition.currentPremise.keySet().iterator(); k_iter = ansCondition.currentPremise.keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key)[0] != "") if (curInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)[0])); pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
} }
k_iter = ansCondition.historyPremise.keySet().iterator(); k_iter = ansCondition.historyPremise.keySet().iterator();
...@@ -898,6 +947,8 @@ public class QuestionMatcher { ...@@ -898,6 +947,8 @@ public class QuestionMatcher {
} }
} }
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.createDefault();
String respContent = null; String respContent = null;
...@@ -913,6 +964,7 @@ public class QuestionMatcher { ...@@ -913,6 +964,7 @@ public class QuestionMatcher {
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
logWriter.record("提交表单接收到的数据:<br>" + respContent, 2);
JSONObject jobj = JSONObject.fromString(respContent); JSONObject jobj = JSONObject.fromString(respContent);
Iterator<String> kit = jobj.keys(); Iterator<String> kit = jobj.keys();
...@@ -943,7 +995,7 @@ public class QuestionMatcher { ...@@ -943,7 +995,7 @@ public class QuestionMatcher {
} }
public Solution findNewNext(Solution ans, Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) { public Solution findNewNext(Solution ans, Condition ansCondition) {
String nextOptions[] = ansCondition.nextStep.split(","); String nextOptions[] = ansCondition.nextStep.split(",");
String conditionName, premises[], cpPair[]; String conditionName, premises[], cpPair[];
boolean flag = true; boolean flag = true;
...@@ -962,8 +1014,8 @@ public class QuestionMatcher { ...@@ -962,8 +1014,8 @@ public class QuestionMatcher {
for (String premise : premises) { for (String premise : premises) {
if (premise.equals("known")) { if (premise.equals("known")) {
//如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别
boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName)[0].equals("") && !curInfoPoint.get(conditionName)[0].equals("unknown"); 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"); boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset");
//只有前两者都为假时,conditionExist才为真 //只有前两者都为假时,conditionExist才为真
boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint);
...@@ -989,9 +1041,11 @@ public class QuestionMatcher { ...@@ -989,9 +1041,11 @@ public class QuestionMatcher {
} }
public void updateKnowledge(Condition condition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint) throws ParseException { public void updateKnowledge(Condition condition) throws ParseException {
String keyword, variableName, updateValue, returnStr = "1"; String keyword, variableName, updateValue, returnStr = "1";
Iterator<String> iit = condition.updateKnowledge.keySet().iterator(); Iterator<String> iit = condition.updateKnowledge.keySet().iterator();
while (iit.hasNext()) { while (iit.hasNext()) {
...@@ -1000,11 +1054,15 @@ public class QuestionMatcher { ...@@ -1000,11 +1054,15 @@ public class QuestionMatcher {
keyword = historyInfoPoint.get(variableName); keyword = historyInfoPoint.get(variableName);
//如果变量名开头为NPC或者item,就专门交给world处理 //如果变量名开头为NPC或者item,就专门交给world处理
if(variableName.startsWith("NPC_") || variableName.startsWith("item_") || variableName.startsWith("map")){ if(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_")){
returnStr = WorldController.worldOperation(world, variableName, updateValue, curInfoPoint, historyInfoPoint); try {
historyInfoPoint.put(variableName, returnStr); returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint);
break; updateValue = returnStr;
}catch (Exception e){
e.printStackTrace();
updateValue = "游戏模块处理出错";
} }
}else {
try { try {
//做数字加法 //做数字加法
...@@ -1044,7 +1102,7 @@ public class QuestionMatcher { ...@@ -1044,7 +1102,7 @@ public class QuestionMatcher {
keyword = ""; keyword = "";
updateValue = keyword.replace(updateValue.substring(4), ""); updateValue = keyword.replace(updateValue.substring(4), "");
}else if (updateValue.startsWith("int+=")) { } else if (updateValue.startsWith("int+=")) {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = "0"; keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
...@@ -1080,28 +1138,27 @@ public class QuestionMatcher { ...@@ -1080,28 +1138,27 @@ public class QuestionMatcher {
keyword = ""; keyword = "";
updateValue = keyword.replace(updateValue.substring(5), ""); updateValue = keyword.replace(updateValue.substring(5), "");
} } else if (updateValue.startsWith("var=")) {
else if (updateValue.startsWith("var=")) {
String conditionName = updateValue.substring(5, updateValue.length() - 3); String conditionName = updateValue.substring(5, updateValue.length() - 3);
if(updateValue.endsWith("-1}")){ if (updateValue.endsWith("-1}")) {
if(curInfoPoint.get(conditionName) != null){ if (curInfoPoint.get(conditionName) != null) {
updateValue = curInfoPoint.get(conditionName)[0]; updateValue = curInfoPoint.get(conditionName);
}else { } else {
updateValue = ""; updateValue = "";
} }
}else if(updateValue.endsWith("-2}")){ } else if (updateValue.endsWith("-2}")) {
if(historyInfoPoint.get(conditionName) != null){ if (historyInfoPoint.get(conditionName) != null) {
updateValue = historyInfoPoint.get(conditionName); updateValue = historyInfoPoint.get(conditionName);
}else { } else {
updateValue = ""; updateValue = "";
} }
}else if(updateValue.endsWith("nextStep-3}")){ } else if (updateValue.endsWith("nextStep-3}")) {
updateValue = condition.nextStep; updateValue = condition.nextStep;
}else if(updateValue.endsWith("reply-3}")){ } else if (updateValue.endsWith("reply-3}")) {
updateValue = condition.answer[0]; updateValue = condition.answer[0];
} }
if(variableName.startsWith("process-nextStep")){ if (variableName.startsWith("process-nextStep")) {
condition.nextStep = updateValue; condition.nextStep = updateValue;
updateValue = ""; updateValue = "";
} }
...@@ -1111,6 +1168,7 @@ public class QuestionMatcher { ...@@ -1111,6 +1168,7 @@ public class QuestionMatcher {
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
}
if(updateValue.equals("")) if(updateValue.equals(""))
...@@ -1123,8 +1181,8 @@ public class QuestionMatcher { ...@@ -1123,8 +1181,8 @@ public class QuestionMatcher {
} }
public void activateCondition(Queue<Condition> activatedQueue, String userName, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { public void activateCondition(Queue<Condition> activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException {
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(botAccount);
String configStr = ""; String configStr = "";
Integer configId; Integer configId;
Condition newCondition, originCondition; Condition newCondition, originCondition;
...@@ -1140,7 +1198,7 @@ public class QuestionMatcher { ...@@ -1140,7 +1198,7 @@ public class QuestionMatcher {
newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority);
//condition = QuestionMatcher.buildCondition(condition, configStr); //condition = QuestionMatcher.buildCondition(condition, configStr);
logWriter.write("------激活-------" + userinfo.id2config.get(configId) + "-------<br>"); logWriter.record("------激活-------" + userinfo.id2config.get(configId) + "-------<br>", 0);
if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) {
activatedMap.get(configId).activePriority = newCondition.activePriority; activatedMap.get(configId).activePriority = newCondition.activePriority;
...@@ -1154,13 +1212,22 @@ public class QuestionMatcher { ...@@ -1154,13 +1212,22 @@ public class QuestionMatcher {
} }
public Solution postActivate(Condition ansCondition, Map<String, String[]> curInfoPoint, Map<String, String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { /**
* 一个提交表单后在激活的操作
* @param ansCondition
* @param context
* @param userinfo
* @return
* @throws IOException
* @throws ParseException
*/
public Solution postActivate(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Queue<Condition> activatedQueue = new LinkedList<Condition>(); Queue<Condition> activatedQueue = new LinkedList<Condition>();
Solution bestMatch = null; Solution bestMatch = null;
activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); activateCondition(activatedQueue, userinfo.botAccount, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context);
ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); ansCondition = activatedQueueMatching(ansCondition, activatedQueue, context);
bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = getSolution(ansCondition, context, userinfo);
return bestMatch; return bestMatch;
......
...@@ -36,9 +36,9 @@ public class UserInfoController { ...@@ -36,9 +36,9 @@ public class UserInfoController {
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName, userinfo); context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) { } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -48,30 +48,30 @@ public class UserInfoController { ...@@ -48,30 +48,30 @@ public class UserInfoController {
} }
public static void userConfigInit(String userName, ServletContext context) throws IOException { public static void userConfigInit(String botAccount, ServletContext context) throws IOException {
String line; String line;
File userFile = new File(CONFIG_DIR + "/" + userName + ".txt"); File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt");
if (!userFile.exists()) { if (!userFile.exists()) {
BufferedReader br = new BufferedReader(new StringReader("")); BufferedReader br = new BufferedReader(new StringReader(""));
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(botAccount);
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName, userinfo); context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) { } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
FileReader reader = new FileReader(userFile); FileReader reader = new FileReader(userFile);
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(botAccount);
try { try {
userinfo = buildUserInfo(br, userinfo, true); userinfo = buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName, userinfo); context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) { } catch (Exception e) {
System.out.println(userinfo.userName + FILE_ERROR); System.out.println(userinfo.botAccount + FILE_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -265,20 +265,20 @@ public class UserInfoController { ...@@ -265,20 +265,20 @@ public class UserInfoController {
* @return 用户信息 * @return 用户信息
*/ */
public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException {
/*根据数据库得到userName改为直接得到 /*根据数据库得到botAccount改为直接得到
SqlHelper helper = new SqlHelper(); SqlHelper helper = new SqlHelper();
String userName = helper.queryUsernameByKey(chat_key); String botAccount = helper.querybotAccountByKey(chat_key);
*/ */
String userName = bot_name; String botAccount = bot_name;
UserInfo userinfo = null; UserInfo userinfo = null;
if (context.getAttribute(userName) == null) { if (context.getAttribute(botAccount) == null) {
userConfigInit(userName, context); userConfigInit(botAccount, context);
} }
if (context.getAttribute(userName) == null) { if (context.getAttribute(botAccount) == null) {
userinfo = new UserInfo(userName); userinfo = new UserInfo(botAccount);
userinfo.conditionTable = new HashMap<String, List<Condition>>(); userinfo.conditionTable = new HashMap<String, List<Condition>>();
} else { } else {
userinfo = (UserInfo) context.getAttribute(userName); userinfo = (UserInfo) context.getAttribute(botAccount);
} }
//helper.destroy(); //helper.destroy();
......
package processing; package processing;
import entity.World;
import GameEnvironment.GameEnv;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class WorldController { public class WorldController {
public LogWriter logWriter = null;
public WorldController(LogWriter logWriter) {
this.logWriter = logWriter;
}
public static String worldOperation(World world, String varName, String varValue, Map<String, String[]> currentInfoPoint, Map<String, String>historyInfoPoint){ public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map<String, String> currentInfoPoint, Map<String, String>historyInfoPoint){
String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr=""; String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr="";
String namePair[] = varName.split("_"); String namePair[] = varName.split("_");
boolean operationFlag = true; boolean operationFlag = true;
if (varName.startsWith("NPC_")) List<String> textList = null;
moduleName = "NPC"; String subValuePair[] = null;
else if(varName.startsWith("items"))
moduleName = "items"; logWriter.record(String.format("%s(%s, %s, %s)", varName, varValue, historyInfoPoint.get("site")), 0);
if(varName.startsWith("item_")) { if(valuePair[0].startsWith("query")){ //查询专用
if(varName.startsWith("goods_")) {
switch (valuePair[0]) { switch (valuePair[0]) {
case "addGoodsBase":
operationFlag = world.addGoodsBase(namePair[1], namePair[2], valuePair[1]);
break;
case "deleteGoods":
operationFlag = world.deleteGoods(namePair[1], namePair[2]);
break;
case "queryGoodsIntro": case "queryGoodsIntro":
returnStr = world.queryGoodsIntro(varName, historyInfoPoint.get("site")); returnStr = gameEnv.queryGoodsIntroByGoodsName(varName);
if(returnStr == null)
returnStr = "无";
break; break;
case "queryAttrByGoodsName": case "queryAttrByGoodsName":
String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2); subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = world.queryAttrByGoodsName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site")); returnStr = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]);
if(returnStr == null)
returnStr = "无";
break; break;
case "queryAllAttrByGoodsName": case "queryAllAttrByGoodsName":
List<String> attrs = world.queryAllAttrByGoodsName(varName, historyInfoPoint.get("site")); textList = gameEnv.queryGoodsAllAttrByGoodsName(varName);
break; if(textList == null)
case "updateAttrByGoodsName": returnStr = "无";
operationFlag = world.updateAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]); else {
break; for (String site : textList)
case "addAttrByGoodsName": returnStr += "、" + site;
operationFlag = world.addAttrByGoodsName(namePair[1], namePair[2], namePair[3], valuePair[1]); returnStr = returnStr.substring(1);
}
break; break;
case "deleteAttrByGoodsName": case "queryAroundGoodsByClassName":
operationFlag = world.deleteAttrByGoodsName(namePair[1], namePair[2], namePair[3]); textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site"));
if(textList == null)
returnStr = "无";
else {
for (String site : textList)
returnStr += "、" + site;
returnStr = returnStr.substring(1);
}
break; break;
default: default:
} }
}else if(varName.startsWith("NPC")) { }else if(varName.startsWith("NPC_")) {
switch(valuePair[0]){ switch(valuePair[0]){
case "addNpc":
operationFlag = world.addNpc(namePair[1], namePair[2], valuePair[1]);
break;
case "deleteNpc":
operationFlag = world.deleteNpc(namePair[1], namePair[2]);
break;
case "queryNpcIntro": case "queryNpcIntro":
//operationFlag = world.queryNpcIntro(valuePair[1], namePair[2]); //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]);
subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]);
if(returnStr == null)
returnStr = "无";
break; break;
case "queryAttrByNPCName": case "queryAttrByNPCName":
String subValuePair[] = currentInfoPoint.get(valuePair[1])[0].split(":", 2);
subValuePair[1] = subValuePair[1].replace("哪里", "location"); subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = world.queryAttrByNPCName(subValuePair[0], subValuePair[1], historyInfoPoint.get("site")); subValuePair[0] = subValuePair[0].replace("哪里", "location");
break; returnStr = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]);
case "updateLocationByNPCName": if(returnStr == null)
operationFlag = world.updateLocationByNPCName(namePair[1], namePair[2], namePair[3], ""); returnStr = "无";
break;
case "addAttrByNPCName":
operationFlag = world.addAttrByNPCName(namePair[1], namePair[2], namePair[3], valuePair[1]);
break;
case "deleteAttrByNPCName":
operationFlag = world.deleteAttrByNPCName(namePair[1], namePair[2], namePair[3]);
break; break;
default: default:
} }
}else if (varName.startsWith("map_")) {
}else if (varName.startsWith("map")){
List<String> sites = new ArrayList<>(); List<String> sites = new ArrayList<>();
switch(valuePair[0]){ switch (valuePair[0]) {
case "queryAroundAllBySite": case "queryAroundAllBySite":
sites = world.queryAroundAllBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site"));
break; break;
case "queryAroundNpcBySite": case "queryAroundNpcBySite":
sites = world.queryAroundNpcBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
break; break;
case "queryAroundGoodsBySite": case "queryAroundGoodsBySite":
sites = world.queryAroundGoodsBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site"));
break; break;
case "queryCanGoBySite": case "queryCanGoBySite":
sites = world.queryCanGoBySite(historyInfoPoint.get("site")); sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site"));
break; break;
case "queryPathBySite": case "queryPathBySite":
sites = world.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]); sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), valuePair[1]);
break; break;
} }
if(sites == null)
for(String site: sites){ returnStr = "无";
returnStr += site; else {
for (String site : sites)
returnStr += "、" + site;
returnStr = returnStr.substring(1);
}
}
}else { //增删改统一使用
gameEnv.CUD(varName, valuePair[0], valuePair[1]);
} }
} logWriter.record("return:" + returnStr, 0);
return returnStr; return returnStr;
} }
......
...@@ -24,7 +24,7 @@ import java.util.List; ...@@ -24,7 +24,7 @@ import java.util.List;
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer botId, projectId, dataId; Integer botId, projectId, dataId;
String userName = null, moduleName; String botAccount = null, moduleName, userName;
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
boolean flag; boolean flag;
SqlHelper helper = null; SqlHelper helper = null;
...@@ -46,18 +46,23 @@ public class GameDesignServlet extends HttpServlet { ...@@ -46,18 +46,23 @@ public class GameDesignServlet extends HttpServlet {
dataId = (Integer) jsonObject.get("id"); dataId = (Integer) jsonObject.get("id");
JSONObject gameElements = helper.queryGameElementsByBotId(dataId); JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
botId = Integer.parseInt((String) gameElements.get("botId")); botId = (Integer)gameElements.get("botId");
userName = (String) gameElements.get("userName"); botAccount = (String) gameElements.get("botAccount");
userName = (String)gameElements.get("userName");
//假设重新重新建用户信息
if (context.getAttribute(userName) == null) {
UserInfoController.userConfigInit(userName, context); System.out.println("botId:" + botId + ",botAccount:" + botAccount);
//假设重建用户信息
if (context.getAttribute(botAccount) == null) {
UserInfoController.userConfigInit(botAccount, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(botAccount);
//UserInfo userinfo = new UserInfo(userName); //UserInfo userinfo = new UserInfo(botAccount);
//清空之前生成的配置条目 //清空之前生成的配置条目
try { try {
...@@ -108,17 +113,16 @@ public class GameDesignServlet extends HttpServlet { ...@@ -108,17 +113,16 @@ public class GameDesignServlet extends HttpServlet {
StringReader sr = new StringReader(mergedConfigText.toString()); StringReader sr = new StringReader(mergedConfigText.toString());
BufferedReader br = new BufferedReader(sr); BufferedReader br = new BufferedReader(sr);
UserInfoController.buildUserInfo(br, userinfo, true); UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userName, userinfo); context.setAttribute(botAccount, userinfo);
ConditionTableController.writeConfigText(userName, userinfo); ConditionTableController.writeConfigText(botAccount, userinfo);
helper.destroy(); helper.destroy();
} }
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
response.setStatus(111);
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("完成\\\n"); out.println("完成");
} }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
......
package servlet; package servlet;
import entity.*; import entity.*;
import processing.ChatCacheController; import processing.*;
import processing.MyFunc;
import processing.QuestionMatcher;
import processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -25,42 +22,25 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -25,42 +22,25 @@ public class GetAnswerServlet extends HttpServlet {
*/ */
String NAME_MISSING_ERROR = "没找到bot名?"; String NAME_MISSING_ERROR = "没找到bot名?";
String LOG_PATH = "/var/www/html/logs/";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
Map<String, String[]> curInfoPoint = new HashMap<>(request.getParameterMap()); Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap());
Map<String ,String> curInfoPoint = new HashMap<String, String>();
Map<String, String> historyInfoPoint = null; Map<String, String> historyInfoPoint = null;
Solution bestMatch = null; Solution bestMatch = null;
Condition ansCondition = null; Condition ansCondition = null;
String ansJ, return_str = "", state = ""; String ansJ, return_str = "", state = "";
String chatKey = curInfoPoint.get("chat_key")[0]; String chatKey = receiveParamters.get("chat_key")[0];
String botName = receiveParamters.get("bot_name")[0];
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
boolean debugFlag = false; boolean debugFlag = false;
String fileName = "/var/www/html/logs/" + chatKey + ".html"; LogWriter logWriter = new LogWriter(LOG_PATH, chatKey);
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
file.setReadable(true,false);
FileWriter fw = new FileWriter(file, true);
//BufferedWriter bw = new BufferedWriter(fos, "UTF-8");
//context.setAttribute("logWriter", bw);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>log</title>\n" +
"</head>");
...@@ -77,28 +57,35 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -77,28 +57,35 @@ public class GetAnswerServlet extends HttpServlet {
} }
//获得用户历史信息 //获得用户历史信息
ChatCache chatCache = ChatCacheController.getChatCache2(chatKey, context, curInfoPoint, userinfo); ChatCache chatCache = null;
try {
chatCache = ChatCacheController.getChatCache2(chatKey, context, userinfo);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
historyInfoPoint = chatCache.getInfoPoint(); historyInfoPoint = chatCache.getInfoPoint();
//信息点预处理 //信息点预处理
QuestionMatcher matcher = new QuestionMatcher(pw,userinfo, context, chatCache.getWorld()); QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv());
debugFlag = matcher.infoPointPreprocessing(curInfoPoint, historyInfoPoint, userinfo, context); debugFlag = matcher.infoPointPreprocessing(receiveParamters, curInfoPoint, historyInfoPoint, userinfo, context);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context); //process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试 //System.out.println(userinfo.conditionTable); //测试
ansCondition = matcher.getBestMatch(curInfoPoint, historyInfoPoint, userinfo.conditionTable, context, userinfo); ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansCondition.priority == -1) if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { try {
bestMatch = matcher.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = matcher.getSolution(ansCondition, context, userinfo);
if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) { if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) {
//如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = matcher.postActivate(ansCondition, context, userinfo);
} }
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -117,16 +104,15 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -117,16 +104,15 @@ public class GetAnswerServlet extends HttpServlet {
if (debugFlag) { if (debugFlag) {
matcher.appendDebugInfo(bestMatch, curInfoPoint, historyInfoPoint, context); matcher.appendDebugInfo(bestMatch, context);
} }
matcher.infoTransfer(curInfoPoint, historyInfoPoint, bestMatch, context, debugFlag); matcher.infoTransfer(bestMatch, context, debugFlag);
bw.write("<br><br>" + logWriter.record("<br><br>" +
"-----------------------------------------对话处理结束-----------------------------------<br><br><br>"); "------------------------------------------------对话处理结束", 0);
bw.close(); logWriter.close();
fw.close();
ansJ = MyFunc.toJson(bestMatch); ansJ = MyFunc.toJson(bestMatch);
System.out.println(ansJ); System.out.println(ansJ);
out.write(ansJ.getBytes()); out.write(ansJ.getBytes());
......
package 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 {
}
}
...@@ -19,17 +19,17 @@ import java.io.*; ...@@ -19,17 +19,17 @@ import java.io.*;
public class ReloadConfigServlet extends HttpServlet { public class ReloadConfigServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName"); String botAccount = request.getParameter("botAccount");
boolean flag = true; boolean flag = true;
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(botAccount);
File configFile = new File(System.getProperty("user.dir") + "/config/" + userName + ".txt"); File configFile = new File(System.getProperty("user.dir") + "/config/" + botAccount + ".txt");
System.out.println(configFile.getAbsolutePath()); System.out.println(configFile.getAbsolutePath());
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
if (!configFile.exists()) { if (!configFile.exists()) {
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("文件不存在: " + userName); out.println("文件不存在: " + botAccount);
} else { } else {
...@@ -38,10 +38,10 @@ public class ReloadConfigServlet extends HttpServlet { ...@@ -38,10 +38,10 @@ public class ReloadConfigServlet extends HttpServlet {
try { try {
userinfo = UserInfoController.buildUserInfo(br, userinfo, true); userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName, userinfo); context.setAttribute(userinfo.botAccount, userinfo);
} catch (Exception e) { } catch (Exception e) {
flag = false; flag = false;
System.out.println(userinfo.userName + ".txt 有误"); System.out.println(userinfo.botAccount + ".txt 有误");
e.printStackTrace(); e.printStackTrace();
} }
...@@ -54,7 +54,7 @@ public class ReloadConfigServlet extends HttpServlet { ...@@ -54,7 +54,7 @@ public class ReloadConfigServlet extends HttpServlet {
response.setContentType("text/plain"); response.setContentType("text/plain");
response.setStatus(111); response.setStatus(111);
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("更新失败配置文件有误:" + userName + ".txt\\\n"); out.println("更新失败配置文件有误:" + botAccount + ".txt\\\n");
} else { } else {
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
......
package servlet;
import entity.ChatCache;
import 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<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)context.getAttribute("chatCache");
ChatCache chatCache = chatCacheMap.get(chatKey);
message = ChatCacheController.saveChatCache(chatKey, context);
out.write(message.getBytes());
out.flush();
}
}
...@@ -23,14 +23,14 @@ import java.util.List; ...@@ -23,14 +23,14 @@ import java.util.List;
@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"}) @WebServlet(name = "UpdateServlet", urlPatterns = {"/update"})
public class UpdateServlet extends HttpServlet { public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。 //在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
String line, extraElements[]; String line, extraElements[];
ArrayList<String> errorList = new ArrayList<String>(); ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
String userName = request.getParameter("userName"); String botAccount = request.getParameter("botAccount");
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(botAccount);
userinfo.conditionTable = new HashMap<String, List<Condition>>(); userinfo.conditionTable = new HashMap<String, List<Condition>>();
List<Condition> conditionList = null; List<Condition> conditionList = null;
...@@ -102,8 +102,8 @@ public class UpdateServlet extends HttpServlet { ...@@ -102,8 +102,8 @@ public class UpdateServlet extends HttpServlet {
System.out.println("success"); System.out.println("success");
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr); //request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
context.setAttribute(userName, userinfo); context.setAttribute(botAccount, userinfo);
String path = System.getProperty("user.dir") + "/config/" + userinfo.userName + ".txt"; String path = System.getProperty("user.dir") + "/config/" + userinfo.botAccount + ".txt";
File file = new File(path); File file = new File(path);
File dir = new File(System.getProperty("user.dir") + "/config"); File dir = new File(System.getProperty("user.dir") + "/config");
......
...@@ -92,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -92,7 +92,7 @@ public class UpdateSingleConfigServlet extends HttpServlet {
BufferedReader br = new BufferedReader(new StringReader(data)); BufferedReader br = new BufferedReader(new StringReader(data));
UserInfo userinfo = new UserInfo(userName); UserInfo userinfo = new UserInfo(userName);
userinfo = UserInfoController.buildUserInfo(br, userinfo, true); userinfo = UserInfoController.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName, userinfo); context.setAttribute(userinfo.botAccount, userinfo);
System.out.println("batchupdate"); System.out.println("batchupdate");
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment