From 21a106ae9b57749fae46a69bf31e60b038f35097 Mon Sep 17 00:00:00 2001 From: hxw Date: Sat, 23 Mar 2019 09:44:20 +0800 Subject: [PATCH] 上传完整文件夹 --- WEB-INF/web.xml | 16 ++++++++++++++++ chatbotbackend.iml | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ config.properties | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------ keywords2.txt | 202 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mvnw | 286 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mvnw.cmd | 161 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 6 ++++++ src/ChatbotBackendApplication.java | 14 -------------- src/Config/Config.java | 111 --------------------------------------------------------------------------------------------------------------- src/Config/ConfigInitializer.java | 75 --------------------------------------------------------------------------- src/GameEnvironment/C3p0Utils.java | 57 --------------------------------------------------------- src/GameEnvironment/DBUtil.java | 38 -------------------------------------- src/GameEnvironment/GameEnv.java | 861 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/GameEnvironment/ObjectFileUtil.java | 46 ---------------------------------------------- src/GameEnvironment/Util.java | 54 ------------------------------------------------------ src/GameEnvironment/bean/GoodsClass.java | 45 --------------------------------------------- src/GameEnvironment/bean/GoodsInstance.java | 64 ---------------------------------------------------------------- src/GameEnvironment/bean/Nickname.java | 38 -------------------------------------- src/GameEnvironment/bean/NpcClass.java | 45 --------------------------------------------- src/GameEnvironment/bean/NpcInstance.java | 61 ------------------------------------------------------------- src/GameEnvironment/bean/Place.java | 84 ------------------------------------------------------------------------------------ src/GameEnvironment/bean/PlaceLink.java | 28 ---------------------------- src/c3p0-config.xml | 33 --------------------------------- src/db/C3p0Utils.java | 70 ---------------------------------------------------------------------- src/db/DB.java | 24 ------------------------ src/db/DBCPUtils.java | 60 ------------------------------------------------------------ src/db/DBUtils.java | 4 ---- src/db/SqlHelper.java | 927 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/entity/Action.java | 173 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/entity/AnswerNextStep.java | 44 -------------------------------------------- src/entity/ArchiveInfo.java | 57 --------------------------------------------------------- src/entity/ChatCache.java | 127 ------------------------------------------------------------------------------------------------------------------------------- src/entity/ChatCache3.java | 93 --------------------------------------------------------------------------------------------- src/entity/Condition.java | 54 ------------------------------------------------------ src/entity/ConfigTerm.java | 531 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/entity/ConfigTermText.java | 528 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ src/entity/ConfigurationItem.java | 5 ----- src/entity/Goods.java | 4 ---- src/entity/JConfig.java | 495 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/entity/Npc.java | 4 ---- src/entity/Premise.java | 47 ----------------------------------------------- src/entity/QuestionKeyWord.java | 35 ----------------------------------- src/entity/Solution.java | 45 --------------------------------------------- src/entity/UserInfo.java | 36 ------------------------------------ src/entity/World.java | 36 ------------------------------------ src/gameDesign/CharacterConstructor.java | 170 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/ElementConstructor.java | 259 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/Floyd.java | 106 ---------------------------------------------------------------------------------------------------------- src/gameDesign/GameUtil.java | 30 ------------------------------ src/gameDesign/GlobalVariableConstructor.java | 60 ------------------------------------------------------------ src/gameDesign/ItemConstructor.java | 131 ----------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/ListeningConstructor.java | 124 ---------------------------------------------------------------------------------------------------------------------------- src/gameDesign/MapConstructor.java | 384 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ src/gameDesign/MapConstructor2.java | 560 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/PlotConstructor.java | 790 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/PlotConstructor2.java | 902 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/PlotConstructor3.java | 573 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/Scene.java | 5 ----- src/gameDesign/SceneConstructor.java | 4 ---- src/log4j.properties | 22 ---------------------- src/main/java/META-INF/MANIFEST.MF | 3 +++ src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java | 16 ++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/Config/Config.java | 172 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java | 38 ++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java | 861 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/ObjectFileUtil.java | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/Util.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Attr.java | 26 ++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsClass.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java | 38 ++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java | 28 ++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java | 34 ++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java | 33 +++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java | 8 ++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java | 149 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java | 36 ++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java | 27 +++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java | 1065 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java | 206 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java | 324 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java | 4 ++++ src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java | 159 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/controller/Hello.java | 13 +++++++++++++ src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/db/DB.java | 24 ++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java | 1575 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/Action.java | 173 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java | 467 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/Macro.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/Premise.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/Solution.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java | 36 ++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java | 170 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java | 259 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java | 131 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java | 382 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java | 886 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java | 1128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java | 291 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java | 262 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java | 270 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java | 507 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java | 472 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java | 377 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java | 226 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java | 30 ++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java | 34 ++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java | 705 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/application-dev.properties | 11 +++++++++++ src/main/resources/application-pro.properties | 8 ++++++++ src/main/resources/application.properties | 3 +++ src/main/resources/dev/c3p0-config.xml | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/dev/log4j.properties | 22 ++++++++++++++++++++++ src/main/resources/pro/c3p0-config.xml | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/pro/log4j.properties | 22 ++++++++++++++++++++++ src/main/resources/static/js/jquery-3.3.1.min.js | 2 ++ src/main/resources/static/update.html | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/templates/index.jsp | 16 ++++++++++++++++ src/main/resources/templates/update.html | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/templates/update3.html | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/resources/test/c3p0-config.xml | 33 +++++++++++++++++++++++++++++++++ src/main/resources/test/log4j.properties | 22 ++++++++++++++++++++++ src/processing/ActionMatcher.java | 1177 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/ChatCacheController.java | 308 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/ChatCacheController2.java | 278 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/FormsPoster.java | 262 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/LogWriter.java | 81 --------------------------------------------------------------------------------- src/processing/MyFunc.java | 214 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/ProcessQuestion.java | 852 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ src/processing/QuestionMatcher.java | 1056 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ src/processing/ResponseFilter.java | 208 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/ResponseFilter3.java | 260 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/SimpleUtil.java | 213 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/UserInfoController.java | 542 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/WorldController.java | 472 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/servlet/ContextDestroyListener.java | 58 ---------------------------------------------------------- src/servlet/FindCacheServlet.java | 55 ------------------------------------------------------- src/servlet/GameDesignServlet.java | 362 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/servlet/GetAnswerServlet.java | 213 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/servlet/GetConfigServlet.java | 44 -------------------------------------------- src/servlet/MyListener.java | 53 ----------------------------------------------------- src/servlet/ReloadChatCacheServlet.java | 19 ------------------- src/servlet/ReloadConfig.java | 76 ---------------------------------------------------------------------------- src/servlet/ReloadConfigServlet.java | 80 -------------------------------------------------------------------------------- src/servlet/SaveChatCacheServlet.java | 61 ------------------------------------------------------------- src/servlet/UpdateServlet.java | 130 ---------------------------------------------------------------------------------------------------------------------------------- src/servlet/UpdateSingleConfigServlet.java | 100 ---------------------------------------------------------------------------------------------------- src/task/utils/BasicBotUtil.java | 226 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/task/utils/ContextDestroyListener.java | 58 ---------------------------------------------------------- src/task/utils/ContextInitialListener.java | 30 ------------------------------ src/task/utils/DataDeliver.java | 34 ---------------------------------- src/task/utils/FileFinder.java | 123 --------------------------------------------------------------------------------------------------------------------------- src/task/utils/GameBotUtil.java | 709 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 189 files changed, 16810 insertions(+), 17545 deletions(-) create mode 100644 WEB-INF/web.xml create mode 100644 chatbotbackend.iml create mode 100644 keywords2.txt create mode 100755 mvnw create mode 100644 mvnw.cmd delete mode 100644 src/ChatbotBackendApplication.java delete mode 100644 src/Config/Config.java delete mode 100644 src/Config/ConfigInitializer.java delete mode 100644 src/GameEnvironment/C3p0Utils.java delete mode 100644 src/GameEnvironment/DBUtil.java delete mode 100644 src/GameEnvironment/GameEnv.java delete mode 100644 src/GameEnvironment/ObjectFileUtil.java delete mode 100644 src/GameEnvironment/Util.java delete mode 100644 src/GameEnvironment/bean/GoodsClass.java delete mode 100644 src/GameEnvironment/bean/GoodsInstance.java delete mode 100644 src/GameEnvironment/bean/Nickname.java delete mode 100644 src/GameEnvironment/bean/NpcClass.java delete mode 100644 src/GameEnvironment/bean/NpcInstance.java delete mode 100644 src/GameEnvironment/bean/Place.java delete mode 100644 src/GameEnvironment/bean/PlaceLink.java delete mode 100644 src/c3p0-config.xml delete mode 100644 src/db/C3p0Utils.java delete mode 100644 src/db/DB.java delete mode 100644 src/db/DBCPUtils.java delete mode 100644 src/db/DBUtils.java delete mode 100644 src/db/SqlHelper.java delete mode 100644 src/entity/Action.java delete mode 100644 src/entity/AnswerNextStep.java delete mode 100644 src/entity/ArchiveInfo.java delete mode 100644 src/entity/ChatCache.java delete mode 100644 src/entity/ChatCache3.java delete mode 100644 src/entity/Condition.java delete mode 100644 src/entity/ConfigTerm.java delete mode 100644 src/entity/ConfigTermText.java delete mode 100644 src/entity/ConfigurationItem.java delete mode 100644 src/entity/Goods.java delete mode 100644 src/entity/JConfig.java delete mode 100644 src/entity/Npc.java delete mode 100644 src/entity/Premise.java delete mode 100644 src/entity/QuestionKeyWord.java delete mode 100644 src/entity/Solution.java delete mode 100644 src/entity/UserInfo.java delete mode 100644 src/entity/World.java delete mode 100644 src/gameDesign/CharacterConstructor.java delete mode 100644 src/gameDesign/ElementConstructor.java delete mode 100644 src/gameDesign/Floyd.java delete mode 100644 src/gameDesign/GameUtil.java delete mode 100644 src/gameDesign/GlobalVariableConstructor.java delete mode 100644 src/gameDesign/ItemConstructor.java delete mode 100644 src/gameDesign/ListeningConstructor.java delete mode 100644 src/gameDesign/MapConstructor.java delete mode 100644 src/gameDesign/MapConstructor2.java delete mode 100644 src/gameDesign/PlotConstructor.java delete mode 100644 src/gameDesign/PlotConstructor2.java delete mode 100644 src/gameDesign/PlotConstructor3.java delete mode 100644 src/gameDesign/Scene.java delete mode 100644 src/gameDesign/SceneConstructor.java delete mode 100644 src/log4j.properties create mode 100644 src/main/java/META-INF/MANIFEST.MF create mode 100644 src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/Config/Config.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/ObjectFileUtil.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/Util.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Attr.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsClass.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/controller/Hello.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/db/DB.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/Action.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/Macro.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/Premise.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/Solution.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java create mode 100644 src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java create mode 100644 src/main/resources/application-dev.properties create mode 100644 src/main/resources/application-pro.properties create mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/dev/c3p0-config.xml create mode 100644 src/main/resources/dev/log4j.properties create mode 100644 src/main/resources/pro/c3p0-config.xml create mode 100644 src/main/resources/pro/log4j.properties create mode 100644 src/main/resources/static/js/jquery-3.3.1.min.js create mode 100644 src/main/resources/static/update.html create mode 100644 src/main/resources/templates/index.jsp create mode 100644 src/main/resources/templates/update.html create mode 100644 src/main/resources/templates/update3.html create mode 100644 src/main/resources/test/c3p0-config.xml create mode 100644 src/main/resources/test/log4j.properties delete mode 100644 src/processing/ActionMatcher.java delete mode 100644 src/processing/ChatCacheController.java delete mode 100644 src/processing/ChatCacheController2.java delete mode 100644 src/processing/FormsPoster.java delete mode 100644 src/processing/LogWriter.java delete mode 100644 src/processing/MyFunc.java delete mode 100644 src/processing/ProcessQuestion.java delete mode 100644 src/processing/QuestionMatcher.java delete mode 100644 src/processing/ResponseFilter.java delete mode 100644 src/processing/ResponseFilter3.java delete mode 100644 src/processing/SimpleUtil.java delete mode 100644 src/processing/UserInfoController.java delete mode 100644 src/processing/WorldController.java delete mode 100644 src/servlet/ContextDestroyListener.java delete mode 100644 src/servlet/FindCacheServlet.java delete mode 100644 src/servlet/GameDesignServlet.java delete mode 100644 src/servlet/GetAnswerServlet.java delete mode 100644 src/servlet/GetConfigServlet.java delete mode 100644 src/servlet/MyListener.java delete mode 100644 src/servlet/ReloadChatCacheServlet.java delete mode 100644 src/servlet/ReloadConfig.java delete mode 100644 src/servlet/ReloadConfigServlet.java delete mode 100644 src/servlet/SaveChatCacheServlet.java delete mode 100644 src/servlet/UpdateServlet.java delete mode 100644 src/servlet/UpdateSingleConfigServlet.java delete mode 100644 src/task/utils/BasicBotUtil.java delete mode 100644 src/task/utils/ContextDestroyListener.java delete mode 100644 src/task/utils/ContextInitialListener.java delete mode 100644 src/task/utils/DataDeliver.java delete mode 100644 src/task/utils/FileFinder.java delete mode 100644 src/task/utils/GameBotUtil.java diff --git a/WEB-INF/web.xml b/WEB-INF/web.xml new file mode 100644 index 0000000..87c4aa6 --- /dev/null +++ b/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + + + org.springframework.web.context.ContextLoaderListener + + + + + + + diff --git a/chatbotbackend.iml b/chatbotbackend.iml new file mode 100644 index 0000000..d0d10d3 --- /dev/null +++ b/chatbotbackend.iml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config.properties b/config.properties index ef5659e..aa9d2b4 100644 --- a/config.properties +++ b/config.properties @@ -1,24 +1,53 @@ -test_var=1111 + +# qa问答地址 qa_url=http://192.168.1.78:59000/game +# 中控url cc_url=http://localhost:8070/api/update/data -//condition_backend=http://192.168.1.82 +# condition后台url +condition_backend_url=http://192.168.1.82:6636/api + +# 数据模型url +automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train + +# action生成指定的后台地址 +service_url=http://192.168.1.178:8081/bot/dialog + +# +#qa_url=http://localhost:59100/game +#cc_url=http://localhost:8070/api/update/data +#condition_backend_url=http://localhost:6636/api +#automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train +#service_url=http://localhost:8081/bot/dialog + + +bot_backup_dir=tmp/ +config_dir=config/ unknown_text=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧 location_hint=请到%s game_start_hint=请说开始剧情或者继续剧情 +game_welcome_text=欢迎来到%s,请说继续剧情或者重新开始 game_module_error=游戏模块出错 +program_error=程序出现异常 +intent_not_understand=我不理解 # -------------------------------游戏生成--------------------------- +token_time_out=token超时了 +game_bot_category=游戏 delete_old_config_term_error=删除旧数据config失败 delete_old_variable_error=删除旧变量失败 delete_old_category_error=删除旧类别失败 -# ---------------------------------------------------------------- +name_mission_error=没找到bot名? +log_path=/var/www/html/logs/ + + +# ---------------------------------------------------------------- unknown_text_description=对于无法识别的问题做出的回答 game_step_description=QA问答游戏进度 @@ -41,6 +70,7 @@ plot_status=剧情%s状态 # --------------------------------------------------- plot_generation_error=剧情接口处理出现异常 +action_text_generate_error=action生成失败 默认condition default_condition=yaobuyao @@ -74,26 +104,64 @@ task_description_slot=[任务描述]" find_item_owner=[物品名]在[人名]身上 #---------------------------------------------- -# ---------------------文本解析--------------------- -text_parse_error=文本解析出错 -automatch_threshold=0.5 -game_condition_category=97 -service_url=http://192.168.1.178:8081/bot/dialog +#--------------------condition文本默认配置-------------------------- + options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat -automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train -idlelimit=180000 -condition_generate_url=http://192.168.1.178:1111/conditionProcess -condition_backend_url=http://192.168.1.82:6636/api -style=interrupt,multimatchvalues,bothvalue -fellow=pivot_httppost + +idle_limit=180000 +condition_fellow=pivot_httppost +automatch_threshold=0.5 +default_style=style=interrupt,bothvalue,multimatchvalues post_style1=style=httppost,bothvalue,multimatchvalues post_style2=style=httppost,multimatchvalues -post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s +# ---------------------condition解析生成--------------------- +bot_info_not_exist=bot信息不存在 +conditon_backend_error=condition后台报错 +text_parse_error=文本解析出错 + +game_condition_category=97 -# ----------------------condition增删改查异常---------------------------- +post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s\r\n + update_keyword_error=更新关键词单元失败 delete_user_data_error=删除用户数据失败 -game_condition_category_id=123 -platform_sql_init_error=新平台获取sql连接失败 \ No newline at end of file +platform_sql_init_error=新平台获取sql连接失败 + +json_format_error=json格式有误 +condition_insert_error=condition插入失败 +condition_update_error=condition更新失败 + +condition_name_dumplicate=condition名字重复 +update_error=更新失败 + + +# --------------------------配置文件增删改查----------------------------------- +config_pattern=%s|%s|%s|=>|%s|nextStep=%s|status=%s|configId=%s +config_delete_error=删除配置文件失败 +condition_name_update_error=更新语义关系名字失败 +config_insert_error=插入配置文件失败 +config_file_not_found=没有找到配置文件 + + +# -------------------------配置文件类别操作------------------------------------- +category_update_conflict="不可将父分组设为了当前分组的子分组" +category_update_error="类别更新失败" +category_insert_error="新建类别失败" +category_delete_error="类别删除失败" +category_query_error="类别查询失败" + + +# -------------------------变量操作------------------------------------------ +variable_name_dumplicate=变量名重复 +varibale_insert_error=变量插入失败 +variable_delete_error=变量删除失败 +variable_update_error=变量更新失败 +variable_sql_delete_error=从数据库删除变量失败 +variable_save_format=-varInitial-|%s|%s\n +extra_info_format=-extraInfo-|%s|%s\n +variable_update_format=%s---%s + +# ---------------------------数据库连接获取失败-------------------------------- +sql_connection_error=数据库连接获取失败 diff --git a/keywords2.txt b/keywords2.txt new file mode 100644 index 0000000..c42da21 --- /dev/null +++ b/keywords2.txt @@ -0,0 +1,202 @@ + + +# ------------------------------------------------------------------------------ +# 第一块,意图|相关的语义关系名 +意图语义关系名 + +# 第二块, 意图|语义关系名|关键词 + + +# ------------------------------------------------------------------------------ +WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + +WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +SURROUNDING_NPC|know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 +SURROUNDING_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 +SURROUNDING_NPC_CLASS|know_exist_what|+周围:name+附近:name +SURROUNDING_ITEM|know_exist_what|+周围:name+附近:name +SURROUNDING_PLACE|know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 +SURROUNDING_ITEM_CLASS|know_exist_what|+周围:name+附近:name + +WHAT_ITEM_I_HAVE|know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 +WHO_IN_THERE|shishui|+谁:里面+里面:人 + +GO_TO|yaobuyao|+去:name+到:name + +WHO_TO_FIND_NPC|xxx|+找到:name + +WHO_ARE_YOU|zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 +TASK_IS_WHAT|shishenme|+是什么:任务+qiwu:任务 + +FIND_NPC_LOCATION|xxx|+哪里:name+哪:name+地方:name+地点:name +FIND_ITEM_LOCATION|xxx|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +WHAT_NPC_IN_LOCATION|xxx|地点 +WAHT_ITEM_IN_LOCATION|xxx|地点 +WHAT_THINGS_IN_LOCATION|xxx|地点 + + + + + +# -------------------------------------------------------------------------- +# 地图在哪里 +map_zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +map_wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + + +# 能去哪里 +map_choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +# 周围有什么人 +people_know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 + +# 周围有什么物品 +item_know_exist_what|+周围:物品+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西 + +# 我有什么东西 +item_rencheng|+qiwu:东西 + +# 我有什么 +we_have_know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 + +# 里面的是谁 +inner_shishui|+谁:里面+里面:人 + +# 去某个地方 +map_yaobuyao|+去:name+到:name + +# 你是谁 +talker_zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 + +# 任务是什么 +task_shishenme|+是什么:任务+qiwu:任务 + +# 周围有什么 +things|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 + +# 周围有什么地方 +place_know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 + +# 周围有什么npc类名 +npc_class_pattern|+周围:name+附近:name + +# 周围有什么item类名 +item_class_pattern|+周围:name+附近:name + +# 怎么找到xxx +find_pattern|+找到:name + +# npc在哪里 +npc_location_pattern|+哪里:name+哪:name+地方:name+地点:name + +# 物品在哪里 +item_location_pattern|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +# 某地点有什么 +things_in_place_xxxx|+地点:什么 + +# 地点有什么人 +NPC_in_place_xxx|+地点:什么 + +# 地点有什么物品 +items_in_place_xxx|+地点:什么 + +# =====================================new add============================================ +people_rencheng|+机器人:谁+那个人:谁+人:谁+机器人:干嘛 + + + + + + +# ------------------------------------------------------------------------------ +# 格式 +# 意图|语义关系名字|关键词 +# name表示可以替换的名字,如物品名、角色名 +# attrName是属性名 +# qiwu就是玩家“我” + + + +# ------------------------------------------------------------------------------ +# 我在哪里 +WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方 +WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu + +# 我能去哪里 +WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu + +# 周围有什么人 +AROUND_NPC|know_exist_what|+周围:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人 + +# 周围有什么npc类别 +AROUND_NPC_CLASS|know_exist_what|+周围:name+附近:name + +# 周围有什么 +AROUND_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面 + +# 周围有什么物品 +AROUND_ITEM|know_exist_what|+周围:物品+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西 + +# 周围有什么地方 +AROUND_PLACE|know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点 + +# 周围有什么物品类别 +AROUND_ITEM_CLASS|know_exist_what|+周围:name+附近:name + +# 我有什么 +WHAT_ITEM_I_HAVE|know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方 + +# 里面有谁 +WHO_IN_THERE|shishui|+谁:里面+里面:人 + +# 去xx +GO_TO|yaobuyao|+去:name+到:name + +# 怎么找到NPC +HOW_TO_FIND_NPC|xxx|+找到:name + + +# 你是谁 +WHO_YOU_ARE|zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是 + +# 任务是什么 +TASK_IS_WHAT|shishenme|+是什么:任务+qiwu:任务 + +# npc在哪里 +NPC_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name + +# 物品在哪里 +ITEM_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name + +# 怎么找到npc +HOW_FIND_NPC|want_know_zenmezuo|+找到:name +#怎么找到物品 +HOW_FIND_ITEM|want_know_zenmezuo|+找到:name + +# 沙滩上有什么人 +WHAT_NPC_IN_LOCATION|xxx|地点 + +# xx上有什么东西 +WAHT_ITEM_IN_LOCATION|xxx|地点 + +# 地点上有什么 +WHAT_THINGS_IN_LOCATION|xxx|地点 + +# npc的属性是多少 +NPC_ATTR|nums|+name:attrName +NPC_ATTR|shishenme|+name:attrName + +# 物品的属性是多少 +ITEM_ATTR|nums|+name:attrName +ITEM_ATTR|shishenme|+name:attrName + +# 周围有什么物品类别 +AOURND_NPC_CLASS|know_exist_what|+周围:name+附近:name + +# 怎么去XXX +HOW_TO_THERE|want_know_zenmezuo|默认 + diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index 438dd0f..48c5c1c 100644 --- a/pom.xml +++ b/pom.xml @@ -98,6 +98,12 @@ 1.5.0 + + commons-io + commons-io + 2.5 + + diff --git a/src/ChatbotBackendApplication.java b/src/ChatbotBackendApplication.java deleted file mode 100644 index d31e972..0000000 --- a/src/ChatbotBackendApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.qiwu.chatbotbackend; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletComponentScan; - -@SpringBootApplication -@ServletComponentScan -public class ChatbotBackendApplication { - - public static void main(String[] args) { - SpringApplication.run(ChatbotBackendApplication.class, args); - } -} diff --git a/src/Config/Config.java b/src/Config/Config.java deleted file mode 100644 index 3da8bd0..0000000 --- a/src/Config/Config.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.qiwu.chatbotbackend.Config; - -import org.springframework.stereotype.Component; - -@Component -public class Config { - - public static String TEXT_PARSE_ERROR = null; - public static String CONDITION_URL = null; - public static String TEST_VAR = null; - public static String QA_URL = null; - public static String CC_URL = null; - public static String UNKNOWN_TEXT = null; - public static String LOCATION_HINT = null; - public static String GAME_START_HINT = null; - public static String GAME_MODULE_ERROR = null; - public static String DELETE_OLD_CONFIG_TERM_ERROR = null; - public static String DELETE_OLD_VARIABLE_ERROR = null; - public static String DELETE_OLD_CATEGORY_ERROR = null; - - public static String UNKNOWN_TEXT_DESCRIPTION = null; - public static String GAME_STEP_DESCRIPTION = null; - public static String START_PLOT_NOT_EXIST = null; - - - public static String ASSISTANT = null; - public static String ASSISTANT_EMOTION = null; - public static String TASK_DESCRIPTION = null; - - public static String TALKER_PATTERN = null; - public static String GAME_STEP_FORMAT = null; - - public static String PLOT_STATUS = null; - - public static String TASK_LINE = null; - public static String TASK_CONDITION = null; - public static String TASK_REPLY = null; - - public static String PLOT_GENERATION_ERROR = null; - - //默认condition - public static String DEFAULT_CONDITION = null; - - //去xx地方condition - public static String GOTO_CONDITION = null; - - - public static class Script { - public static String CODE = "subcode"; - public static int SIZE = 12; - }; - - - public static String POST_ACTION_ERROR = null; - public static String TOKEN_TIME_OUT = null; - public static String ENCODE_ERROR = null; - - - //话术 - public static String NOTHING_FOUND = null; - public static String DONT_FOUND = null; - public static String NOWHERE_CAN_GO = null; - public static String ATTRIBUTE_HIDDEN = null; - - - - public static String ATTR_VALUE_SLOT = null; - public static String ATTR_NAME_SLOT = null; - public static String NPC_NAME_SLOT = null; - public static String NPC_LIST_SLOT = null; - public static String SITE_SLOT = null; - public static String SITE_SLOT2 = null; - public static String ITEM_LIST_SLOT = null; - public static String ITEM_NAME_SLOT = null; - public static String NPC_ITEM_LIST_SLOT = null; - public static String CAN_GO_SITE_SLOT = null; - public static String PATH_SLOT = null; - public static String START_SLOT = null; - public static String DESTINATION_SLOT = null; - public static String SITE_LIST_SLOT = null; - public static String TASK_DESCRIPTION_SLOT = null; - - public static String FIND_ITEM_OWNER = null; - - - //生成action - public static String GAME_CONDITION_CATEGORY = null; - public static String AUTOMATCH_THRESHOLD = null; - public static String IDLE_LIMIT = null; - public static String CONDITION_BACKEND_URL = null; - public static String CONDITION_GENERATE_URL= null; - public static String OPTIONS = null; - public static String STYLE = null; - public static String AUTOMATCH_URL = null; - public static String SERVICE_URL = null; - - public static String FELLOW = null; - - public static String POST_STYLE1 = null; - public static String POST_STYLE2 = null; - - public static String POST_ACTION_HEAD=null; - - - - //condition增删改查异常 - public static String UPDATE_KEYWORD_ERROR = null; - - public static String DELETE_USER_DATA_ERROR = null; - -} diff --git a/src/Config/ConfigInitializer.java b/src/Config/ConfigInitializer.java deleted file mode 100644 index 39d6d30..0000000 --- a/src/Config/ConfigInitializer.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.qiwu.chatbotbackend.Config; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Properties; -import java.util.Set; - -public class ConfigInitializer { - - private static final String CONFIGFILE = "config.properties"; - private static final String CLASSPREFIX = "com.qiwu.chatbotbackend.config.config"; - - /** - * 读取配置文件 - */ - public static void init() { - InputStream configInputStream; - try { - BufferedReader bufferedReader = new BufferedReader(new FileReader(CONFIGFILE)); - Properties properties = new Properties(); - properties.load(bufferedReader); - - - initNextLevel(properties, Config.class); - } catch (Exception e) { - e.printStackTrace(); - } finally { - } - } - - public static void initNextLevel(Properties properties, Class nowClass) throws IllegalAccessException { - String baseClassName = nowClass.getName().toLowerCase().replaceAll("\\$", "\\."); - String shortName = baseClassName.replaceAll(CLASSPREFIX, "").replaceFirst("\\.", ""); - //key集合 - Set keys = properties.keySet(); - for (Field field : nowClass.getFields()) { - if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { - - String classParam = field.getName().toLowerCase(); - if (shortName.equals("")) { - if (keys.contains(classParam)) { - pushNewValue(classParam, properties, field); - } - } else { - if (keys.contains(shortName + "." + classParam)) { - pushNewValue(shortName + "." + classParam, properties, field); - } - } - } - } - for (Class aClass : nowClass.getClasses()) { - initNextLevel(properties, aClass); - } - } - - public static void pushNewValue(String classParam, Properties properties, Field field) throws IllegalAccessException { - String value = properties.getProperty(classParam); - if (value != null) { - Class type = field.getType(); - if (type.equals(int.class)) - field.set(null, Integer.valueOf(value)); - else if (type.equals(String.class)) - field.set(null, value); - else if (type.equals(long.class)) - field.set(null, Long.valueOf(value)); - else if (type.equals(boolean.class)) - field.set(null, Boolean.valueOf(value)); - else if (type.isEnum()) - field.set(null, Enum.valueOf((Class) type, value.toUpperCase())); - } - } -} diff --git a/src/GameEnvironment/C3p0Utils.java b/src/GameEnvironment/C3p0Utils.java deleted file mode 100644 index 4131214..0000000 --- a/src/GameEnvironment/C3p0Utils.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment; - - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import org.apache.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class C3p0Utils { - static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); - - //通过标识名来创建相应连接池 - static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); - - //从连接池中取用一个连接 - public static Connection getConnection() throws Exception { - try { - return dataSource.getConnection(); - - } catch (Exception e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - - //释放连接回连接池 - public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - if (pst != null) { - try { - pst.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - } -} diff --git a/src/GameEnvironment/DBUtil.java b/src/GameEnvironment/DBUtil.java deleted file mode 100644 index d4316ef..0000000 --- a/src/GameEnvironment/DBUtil.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -public class DBUtil { - - public static String queryEnvJsonByBotName(String botName) throws Exception{ - Connection conn = C3p0Utils.getConnection(); - String sql = "select * from generate_json_tb where bot_name = ?"; - String result = "{}"; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(botName)); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - result = rs.getString("env_json_text"); - - ps.close(); - rs.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - if (conn != null) { - try { - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - return result; - } - -} diff --git a/src/GameEnvironment/GameEnv.java b/src/GameEnvironment/GameEnv.java deleted file mode 100644 index 6232d34..0000000 --- a/src/GameEnvironment/GameEnv.java +++ /dev/null @@ -1,861 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment; - -import java.io.Serializable; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.alibaba.fastjson.JSON; -import com.qiwu.chatbotbackend.GameEnvironment.bean.GoodsClass; -import com.qiwu.chatbotbackend.GameEnvironment.bean.GoodsInstance; -import com.qiwu.chatbotbackend.GameEnvironment.bean.Nickname; -import com.qiwu.chatbotbackend.GameEnvironment.bean.NpcClass; -import com.qiwu.chatbotbackend.GameEnvironment.bean.NpcInstance; -import com.qiwu.chatbotbackend.GameEnvironment.bean.Place; -import com.qiwu.chatbotbackend.GameEnvironment.bean.PlaceLink; - -public class GameEnv implements Serializable{ - private static final long serialVersionUID = 2L; - // 角色快速查找数据 - public Map npcClassesMap = new HashMap(); - public Map npcInstancesMap = new HashMap(); - - // 玩家跟随的角色列表 - public Map followNpcesMap = new HashMap(); - - // 物品快速查找数据 - public Map goodsClassesMap = new HashMap(); - public Map goodsInstancesMap = new HashMap(); - - // 全局变量快速查找数据 - public Map globalAttrsMap = new HashMap(); - // 地点相关快速查找数据 - public Map placesMap = new HashMap(); - // goGlag=2 联通不相邻可达 - public Map placeLinkDirectGoesMap = new HashMap(); - // goGlag=2 任意可达到 - public Map placeNoLinkDirectGoesMap = new HashMap(); - - // 二维联通地图 - public byte[][] mapUnitMatrix; - // 联通图助手 - public Map placeNameIndexMap = new HashMap(); - public Map indexPlaceNameMap = new HashMap(); - - // 数据别名集合 - public Map nicknamesMap = new HashMap(); - - // 获取别名的助手,帮助创建 - private Nickname getNicknameUtil(String nickname) { - Nickname nicknameObject = this.nicknamesMap.get(nickname); - if(nicknameObject == null) { - nicknameObject = new Nickname(); - } - this.nicknamesMap.put(nickname, nicknameObject); - return nicknameObject; - } - - @SuppressWarnings("unchecked") - public GameEnv(String botName) throws Exception { - - // 从数据库获取环境数据的json字符串 - String jsonString = DBUtil.queryEnvJsonByBotName(botName); - - // 从文件中获取json字符串 -// String jsonString = Util.getJsonString("./data/195.json"); -// System.out.println(jsonString); - - Map gameProjectMap = JSON.parseObject(jsonString); - if(gameProjectMap!=null && !gameProjectMap.isEmpty()) { - // 地图数据处理 - Map placeTmpMap = (Map)gameProjectMap.get("place"); - if(placeTmpMap!=null && !placeTmpMap.isEmpty()) { - // 地图基本数据定义 - List placeNames = new ArrayList<>(placeTmpMap.keySet()); - for(int i=0; i placeMap = (Map)placeTmpMap.get(placeName); - Place place = new Place(); - place.setGoFlag((Integer)placeMap.get("goFlag")); - place.setIntro((String)placeMap.get("intro")); - place.setName(placeName); - this.placesMap.put(placeName, place); - // 为了生成单位矩阵使用 - this.placeNameIndexMap.put(placeName, new Integer(i)); - this.indexPlaceNameMap.put(new Integer(i), placeName); - } - - // 定义的单位矩阵 - this.mapUnitMatrix = new byte[this.placesMap.size()][this.placesMap.size()]; - - // 可去地点、别名、图的数据完善 - for(String placeName:placeTmpMap.keySet()) { - Map placeMap = (Map)placeTmpMap.get(placeName); - Place place = this.placesMap.get(placeName); - // 可去地点 - Map ableGoPlacesMap = new HashMap(); - List ableGoPlaceNames = (List)placeMap.get("ableGoes"); - for(int i=0; i nicknames = (List)placeMap.get("nicknames"); - for(int i=0; i nicknamePlaceMap = nickname.getPlaceMap(); - nicknamePlaceMap.put(place.getName(), place); - } - place.setNickname(nicknames); - place.setName(placeName); - } - - // 格式化图显示结构 - System.out.println("\n\n"); - System.out.print("\t\t"); - for(int i=0; i npcDataTmpMap = (Map)gameProjectMap.get("npc"); - // 角色类 - Map npcClassTmpMap = (Map)npcDataTmpMap.get("class"); - for(String npcClassName:npcClassTmpMap.keySet()) { - Map npcClassAttr = (Map)npcClassTmpMap.get(npcClassName); - NpcClass npcClass = new NpcClass(); - npcClass.setName(npcClassName); - npcClass.setPlace(this.placesMap.get(npcClassAttr.get("所在地点"))); - npcClassAttr.remove("所在地点"); - npcClass.setAttrs(npcClassAttr); - this.npcClassesMap.put(npcClassName, npcClass); - } - // 角色实例 - Map npcInstanceTmpMap = (Map)npcDataTmpMap.get("instance"); - for(String npcInstanceName:npcInstanceTmpMap.keySet()){ - Map npcInstanceAttr = (Map)npcInstanceTmpMap.get(npcInstanceName); - NpcInstance npcInstance = new NpcInstance(); - npcInstance.setName(npcInstanceName); - - // 角色类 - NpcClass npcClass = this.npcClassesMap.get(npcInstanceAttr.get("className")); - npcInstance.setNpcClass(npcClass); - Map npcInstancesClassMap = npcClass.getNpcInstances(); - npcInstancesClassMap.put(npcInstanceName, npcInstance); - npcClass.setNpcInstances(npcInstancesClassMap); - - // 地点 - Place place = this.placesMap.get(npcInstanceAttr.get("所在地点")); - Map npcInstancesPlaceMap = place.getNpcInstances(); - npcInstancesPlaceMap.put(npcInstanceName, npcInstance); - npcInstance.setPlace(place); - - // 别名 - List nicknames = (List)((Map)npcInstanceTmpMap.get(npcInstanceName)).get("nicknames"); - for(int i=0; i npcInstanceMap = nickname.getNpcInstanceMap(); - npcInstanceMap.put(npcInstanceName, npcInstance); - nickname.setNpcInstanceMap(npcInstanceMap); - } - npcInstance.setNickname(nicknames); - npcInstanceAttr.remove("nicknames"); - npcInstanceAttr.remove("className"); - npcInstanceAttr.remove("所在地点"); - npcInstance.setAttrs((Map)npcInstanceAttr); - this.npcInstancesMap.put(npcInstanceName, npcInstance); - } - - - /************************************* 物品 **********************************/ - Map goodsDataTmpMap = (Map)gameProjectMap.get("goods"); - // 物品类 - Map goodsClassTmpMap = (Map)goodsDataTmpMap.get("class"); - for(String goodsClassName:goodsClassTmpMap.keySet()) { - Map goodsClassAttr = (Map)goodsClassTmpMap.get(goodsClassName); - GoodsClass goodsClass = new GoodsClass(); - goodsClass.setName(goodsClassName); - goodsClass.setPlace(this.placesMap.get(goodsClassAttr.get("所在地点"))); - goodsClassAttr.remove("所在地点"); - goodsClass.setAttrs(goodsClassAttr); - this.goodsClassesMap.put(goodsClassName, goodsClass); - } - - // 物品实例 - Map goodsInstanceTmpMap = (Map)goodsDataTmpMap.get("instance"); - for(String goodsInstanceName:goodsInstanceTmpMap.keySet()){ - Map goodsInstanceAttr = (Map)goodsInstanceTmpMap.get(goodsInstanceName); - GoodsInstance goodsInstance = new GoodsInstance(); - goodsInstance.setName(goodsInstanceName); - - // 物品类 - GoodsClass goodsClass = this.goodsClassesMap.get(goodsInstanceAttr.get("className")); - goodsInstance.setGoodsClass(goodsClass); - Map goodsInstancesClassMap = goodsClass.getGoodsInstances(); - goodsInstancesClassMap.put(goodsInstanceName, goodsInstance); - goodsClass.setGoodsInstances(goodsInstancesClassMap); - - // 地点 - Place place = this.placesMap.get(goodsInstanceAttr.get("所在地点")); - Map goodsInstancesPlaceMap = place.getGoodsInstances(); - goodsInstancesPlaceMap.put(goodsInstanceName, goodsInstance); - goodsInstance.setPlace(place); - - // 别名 - List nicknames = (List)(((Map)goodsInstanceTmpMap.get(goodsInstanceName)).get("nicknames")); - for(int i=0; i goodsInstanceMap = nickname.getGoodsInstanceMap(); - goodsInstanceMap.put(goodsInstanceName, goodsInstance); - nickname.setGoodsInstanceMap(goodsInstanceMap); - } - // 所属角色 - // 更新NPC的物品列表 - NpcInstance npcInstance = this.npcInstancesMap.get(goodsInstanceAttr.get("所属角色")); - Map goodsInstancesMap = npcInstance.getGoodsInstances(); - goodsInstancesMap.put(goodsInstance.getName(), goodsInstance); - // 更新物品所属的NPC - goodsInstance.setNpcInstance(npcInstance); - goodsInstance.setNickname(nicknames); - goodsInstanceAttr.remove("nicknames"); - goodsInstanceAttr.remove("className"); - goodsInstanceAttr.remove("所在地点"); - goodsInstanceAttr.remove("所属角色"); - goodsInstance.setAttrs((Map)goodsInstanceAttr); - this.goodsInstancesMap.put(goodsInstanceName, goodsInstance); - } - - // 全局变量 - this.globalAttrsMap = (Map)gameProjectMap.get("globalAttr"); - } - } - // 查找别名数据 - public List queryNickname(String nicknameStr, String type) { - Nickname nickname = this.nicknamesMap.get(nicknameStr); - List nameIds = new ArrayList(); - if(type.equals("place")) { - if(nickname != null && !nickname.getPlaceMap().isEmpty()) { - nameIds.addAll(nickname.getPlaceMap().keySet()); - } - }else if(type.equals("goods")) { - if(nickname != null && !nickname.getGoodsInstanceMap().isEmpty()) { - nameIds.addAll(nickname.getGoodsInstanceMap().keySet()); - } - }else if(type.equals("npc")) { - if(nickname != null && !nickname.getNpcInstanceMap().isEmpty()) { - nameIds.addAll(nickname.getNpcInstanceMap().keySet()); - } - } - return nameIds; - } - public GoodsInstance findGoodsInstanceByNameOrNickname(String str1) { - GoodsInstance goodsInstance = queryGoodsByGoodsName(str1); - if(goodsInstance == null) { - List idNames = this.queryNickname(str1, "goods"); - if(idNames.size()!=0) { - goodsInstance = this.goodsInstancesMap.get(idNames.get(0)); - return goodsInstance; - }else { - return null; - } - }else { - return goodsInstance; - } - } - public NpcInstance findNpcInstanceByNameOrNickname(String str1) { - NpcInstance npcInstance = this.queryNpcByNpcName(str1); - if(npcInstance == null) { - List idNames = this.queryNickname(str1, "npc"); - if(idNames.size()!=0) { - npcInstance = this.npcInstancesMap.get(idNames.get(0)); - return npcInstance; - }else { - return null; - } - }else { - return npcInstance; - } - } - // 两点之间的路径 // 使用广度优先算法单源最短路的SPFA算法的全称是:Shortest Path Faster Algorithm。只有状态为2的时候使用 - public List getAllPath(String placeA, String placeB){ - List paths = new ArrayList(); - Deque placeDeque = new ArrayDeque(); - Integer start = this.placeNameIndexMap.get(placeA); - PlaceLink placeLink = new PlaceLink(); - placeLink.setIndex(start); - boolean[] marked = new boolean[this.placeNameIndexMap.size()]; - for(int j=0; j nickname = this.placesMap.get(this.indexPlaceNameMap.get(new Integer(i))).getNickname(); - if(this.indexPlaceNameMap.get(new Integer(i)).equals(placeB) || (nickname!=null && nickname.indexOf(placeB)>=0)) { - while(placeLinkNodeSecond.getPlaceLink() != null) { - paths.add(this.indexPlaceNameMap.get(new Integer(placeLinkNodeSecond.getIndex()))); - placeLinkNodeSecond = placeLinkNodeSecond.getPlaceLink(); - } - paths.add(this.indexPlaceNameMap.get(new Integer(placeLinkNodeSecond.getIndex()))); - flag = 1; - break; - } - placeDeque.push(placeLinkNodeSecond); - } - } - } - } - Collections.reverse(paths); - return paths; - } - // 两点之间的通过的地方 - public List queryPathBySite(String placeA, String placeB){ - List paths = this.getAllPath(placeA, placeB); - if(paths.size() < 2) { - // 返回null表示不能到达 - return null; - }else{ - // 返回空表示相邻直接去 - // 中间有数据说明需要经过... - return paths.subList(1, paths.size()-1); - } - } - /********************************************地点******************************************/ - // 周围有什么 - public List queryAroundAllBySite(String site){ - List somethings = new ArrayList(); - Place place = this.placesMap.get(site); - if(place==null) { - return somethings; - } - Map goodsInstances = place.getGoodsInstances(); - Map npcInstances = place.getNpcInstances(); - somethings.addAll(goodsInstances.keySet()); - somethings.addAll(npcInstances.keySet()); - return somethings; - } - // 周围有什么人 - public List queryAroundNpcBySite(String site){ - Place place = this.placesMap.get(site); - List queryNpc = new ArrayList(); - if(place == null) { - return queryNpc; - } - queryNpc.addAll(place.getNpcInstances().keySet()); - return queryNpc; - } - // 周围有什么物品 - public List queryAroundGoodsBySite(String site){ - List queryGoods = new ArrayList(); - Place place = this.placesMap.get(site); - if(place == null) { - return queryGoods; - } - queryGoods.addAll(place.getGoodsInstances().keySet()); - return queryGoods; - } - // 我现在能去哪 需要用到联通图算法 - public List queryCanGoBySite(String site){ - List ableGoStrs = new ArrayList(); - // 任意可达 - for(String placeName : this.placeNoLinkDirectGoesMap.keySet()) { - ableGoStrs.add(placeName); - } - // 查询附近地点 - Integer x = this.placeNameIndexMap.get(site); - if(x == null) { - return ableGoStrs; - } - for(int y=0; y paths = this.getAllPath(site, placeName); - if(paths.size()>0) { - ableGoStrs.add(placeName); - } - } - } - return ableGoStrs; - } - // 两个地点的位置关系 ### 这个接口有疑问 - /* - * 0:就在当前地点 - * 1:相邻可以到 - * 2:不相邻,联通可以到达 - * 3:联通直接可以到达 - * 4:任意可达 - * 5:不可到达 - * */ - public Integer isNeighbour(String placeA, String placeB) { - Place place = this.placesMap.get(placeA); - if(place == null) { - return new Integer(5); - } - - // 地点名称相同 - if(placeA.equals(placeB)) { - return 0; - } - - // 地点名和地点别名相同 - if(this.queryNickname(placeB, "place").indexOf(placeA) != -1) { - return 0; - } - - // 任意可达 - for(String placeName : this.placeNoLinkDirectGoesMap.keySet()) { - if(placeName.equals(placeB) || this.queryNickname(placeB, "place").indexOf(placeName) != -1) { - return 4; - } - } - - // 相邻可以去的地点 - int x = this.placeNameIndexMap.get(placeA); - for(int y=0; y paths = this.getAllPath(placeA, placeName); - if(paths.size()>0) { - return 3; - } - } - } - - // 联通不相邻不可以直达 - for(String placeName:this.placesMap.keySet()) { - if(!this.placeLinkDirectGoesMap.keySet().contains(placeName) && !this.placeNoLinkDirectGoesMap.keySet().contains(placeName)) { - if(placeName.equals(placeB) || this.queryNickname(placeB, "place").indexOf(placeName) != -1) { - List paths = this.getAllPath(placeA, placeName); - if(paths.size()>0) { - return 2; - } - } - } - } - - // 既不相邻,也不能到达 - return new Integer(5); - } - // 通过别名查询当前地点最近的地点 - public String getPlaceNameByNickname(String curPlaceName, String nickname) { - Place place = this.placesMap.get(curPlaceName); - if(place == null) { - return nickname; - } - if(place.getNickname().indexOf(nickname)>=0) { - return curPlaceName; - }else { - List placePath = this.getAllPath(curPlaceName, nickname); - if(placePath.size()>=2) { - return placePath.get(placePath.size()-1); - }else { - return nickname; - } - } - } - // 通过别名查询最近地点的角色 - public String queryCurPlaceNpcInstanceByNickname(String curPlaceName, String nickname) { - Map npcInstancesMap = this.placesMap.get(curPlaceName).getNpcInstances(); - for(String npcInstanceName:npcInstancesMap.keySet()) { - NpcInstance npcInstance = npcInstancesMap.get(npcInstanceName); - if(npcInstance.getNickname().indexOf(nickname) >= 0) { - return npcInstance.getName(); - } - } - return null; - } - // 通过别名查询最近地点的物品 - public String queryCurPlaceGoodsInstanceByNickname(String curPlaceName, String nickname) { - Map goodsInstancesMap = this.placesMap.get(curPlaceName).getGoodsInstances(); - for(String goodsInstanceName:goodsInstancesMap.keySet()) { - GoodsInstance goodsInstance = goodsInstancesMap.get(goodsInstanceName); - if(goodsInstance.getNickname().indexOf(nickname)>=0) { - return goodsInstance.getName(); - } - } - return null; - } - - // 通过别名查询当前地点最近的npc - public String getNpcNameByNickname(String curPlaceName, String nickname) { - // 寻找两层 - // 查询当前地点的所有,和当前地点可以去到的地点相应的所有 - String npcInstanceName = this.queryCurPlaceNpcInstanceByNickname(curPlaceName, nickname); - if(npcInstanceName!=null) { - return npcInstanceName; - } - Map placesMap = this.placesMap.get(curPlaceName).getAbleGoes(); - for(String placeName:placesMap.keySet()) { - Place place = placesMap.get(placeName); - npcInstanceName = this.queryCurPlaceNpcInstanceByNickname(place.getName(), nickname); - if(npcInstanceName!=null) { - return npcInstanceName; - } - } - return nickname; - } - - // 通过别名查询当前地点最近的物品 - public String getGoodsNameByNickname(String curPlaceName, String nickname) { - // 寻找两层 - // 查询当前地点的所有,和当前地点可以去到的地点相应的所有 - String npcInstanceName = this.queryCurPlaceGoodsInstanceByNickname(curPlaceName, nickname); - if(npcInstanceName!=null) { - return npcInstanceName; - } - Map cangoPlacesMap = this.placesMap.get(curPlaceName).getAbleGoes(); - for(String placeName:cangoPlacesMap.keySet()) { - Place place = cangoPlacesMap.get(placeName); - npcInstanceName = this.queryCurPlaceGoodsInstanceByNickname(place.getName(), nickname); - if(npcInstanceName!=null) { - return npcInstanceName; - } - } - return nickname; - } - - /*********************************通过npc获取物品列表**********************************/ - // 通过npcName获取所有物品名称列表 - public List queryGoodsByNpcName(String npcName){ - List goodsNames = new ArrayList(); - if(this.npcInstancesMap.get(npcName)!=null) { - Map goodsInstancesMap = this.npcInstancesMap.get(npcName).getGoodsInstances(); - if(goodsInstancesMap != null && !goodsInstancesMap.isEmpty()) { - for(String goodsInstanceName:goodsInstancesMap.keySet()) { - goodsNames.add(goodsInstancesMap.get(goodsInstanceName).getName()); - } - } - } - return goodsNames; - } - /**************************************goods****************************************/ - // 通过类和地点查询所有物品名称 - // 只有当可以询问的属性为是的时候才可以得到相应的物品列表 - public List queryGoodsByClassAndSite(String site, String className){ - List goodsNames = new ArrayList(); - if(this.placesMap.get(site)!=null && this.goodsClassesMap.get(className)!=null) { - Map placeGoodsInstances = this.placesMap.get(site).getGoodsInstances(); - Map classGoodsInstances = this.goodsClassesMap.get(className).getGoodsInstances(); - for(String placeGoodsInstanceName:placeGoodsInstances.keySet()) { - for(String classGoodsInstanceName:classGoodsInstances.keySet()) { - if(placeGoodsInstanceName.equals(classGoodsInstanceName)) { - goodsNames.add(placeGoodsInstanceName); - } - } - } - } - return goodsNames; - } - // 查询指定物品 - public GoodsInstance queryGoodsByGoodsName(String name){ - GoodsInstance goodsInstance = this.goodsInstancesMap.get(name); - return goodsInstance; - } - // 查询指定物品的简介 - public String queryGoodsIntroByGoodsName(String name){ - GoodsInstance goodsInstance = this.queryGoodsByGoodsName(name); - if(goodsInstance !=null) { - return goodsInstance.getAttrs().get("intro"); - }else { - return null; - } - } - - // 查询指定物品的属性值 - public String queryGoodsAttrByGoodsName(String str1, String str2){ - GoodsInstance goodsInstance = this.findGoodsInstanceByNameOrNickname(str1); - String attrName = str2; - if(goodsInstance == null) { - goodsInstance = this.findGoodsInstanceByNameOrNickname(str2); - attrName = str1; - } - if(goodsInstance != null) { - Map attrsMap = goodsInstance.getAttrs(); - if(attrName.equals("location")) { - if(goodsInstance.getPlace()!=null) { - return goodsInstance.getPlace().getName(); - } - } - if(attrName.equals("owner")) { - if(goodsInstance.getNpcInstance()!=null) { - return goodsInstance.getNpcInstance().getName(); - } - } - return attrsMap.get(attrName); - }else { - return null; - } - } - // 查询指定物品的所有属性 - public List queryGoodsAllAttrByGoodsName(String name){ - List attrnames = new ArrayList(); - GoodsInstance goodsInstance = findGoodsInstanceByNameOrNickname(name); - if(goodsInstance != null) { - Map attrsMap = goodsInstance.getAttrs(); - attrnames.addAll(attrsMap.keySet()); - return attrnames; - }else { - return null; - } - } - // 查询物品的地点 - public String queryGoodsSiteByGoodsName(String goodsName) { - return this.goodsInstancesMap.get(goodsName).getPlace().getName(); - } - - /**************************************npc*****************************************/ - // 通过地点和类查询所有的NPC实例 - public List queryNpcByClassAndSite(String site, String className){ - List npcNames = new ArrayList(); - Map placeNpcInstancesMap = this.placesMap.get(site).getNpcInstances(); - Map classNpcInstances = this.npcClassesMap.get(className).getNpcInstances(); - for(String placeNpcInstanceName:placeNpcInstancesMap.keySet()) { - for(String classNpcInstance:classNpcInstances.keySet()) { - if(placeNpcInstanceName.equals(classNpcInstance)) { - npcNames.add(placeNpcInstanceName); - } - } - } - - return npcNames; - } - // 查询指定的NPC - public NpcInstance queryNpcByNpcName(String npcName){ - NpcInstance npcInstance = this.npcInstancesMap.get(npcName); - return npcInstance; - } - // 查询指定NPC简介 - public String queryNpcIntroByNpcName(String name){ - NpcInstance npcInstance = queryNpcByNpcName(name); - return npcInstance.getAttrs().get("intro"); - } - // 查询指定npc的属性值 - public String queryNpcAttrByNpcName(String str1, String str2){ - NpcInstance npcInstance = this.findNpcInstanceByNameOrNickname(str1); - String attrName = str2; - if(npcInstance == null) { - npcInstance = this.findNpcInstanceByNameOrNickname(str2); - attrName = str1; - } - if(npcInstance != null) { - if(attrName.equals("location")) { - if(npcInstance.getPlace()!=null) { - return npcInstance.getPlace().getName(); - } - } - Map npcInstanceAttrsMap = npcInstance.getAttrs(); - return npcInstanceAttrsMap.get(attrName); - }else { - return null; - } - } - // 查询指定npc的所有属性 - public List queryNpcAttrsByNpcName(String name){ - List attrNames = new ArrayList(); - NpcInstance npcInstance = queryNpcByNpcName(name); - if(npcInstance != null) { - attrNames.addAll(npcInstance.getAttrs().keySet()); - return attrNames; - }else { - return null; - } - } - // 查询角色的地点 - public String queryNpcSiteByNpcName(String npcName) { - return this.queryNpcByNpcName(npcName).getPlace().getName(); - } - // 增加 - public boolean insert(String name){ - return true; - } - // 改变 - public boolean update(String name, String value) { - String[] names = name.split("_"); - if(names.length == 4){ - if(names[0].equals("goods")){ - if(this.goodsClassesMap.get(names[1])!=null) { - Map goodsInstancesByClass = this.goodsClassesMap.get(names[1]).getGoodsInstances(); - GoodsInstance goodsInstance = this.goodsInstancesMap.get(names[2]); - if(goodsInstancesByClass.get(goodsInstance.getName())!=null) { - Map goodsInstanceAttrsMap = goodsInstance.getAttrs(); - if(names[3].equals("所在地点")) { - Place placeOrigin = goodsInstance.getPlace(); - Map goodsInstancesMap = placeOrigin.getGoodsInstances(); - goodsInstancesMap.remove(goodsInstance.getName()); - Place place= this.placesMap.get(value); - goodsInstance.setPlace(place); - goodsInstancesMap = place.getGoodsInstances(); - goodsInstancesMap.put(goodsInstance.getName(), goodsInstance); - return true; - }else if(names[3].equals("所属角色")) { - NpcInstance npcInstance= goodsInstance.getNpcInstance(); - if(npcInstance != null) { - Map goodsInstancesMap = npcInstance.getGoodsInstances(); - goodsInstancesMap.remove(goodsInstance.getName()); - } - npcInstance = this.npcInstancesMap.get(value); - goodsInstance.setNpcInstance(npcInstance); - Map goodsInstances = npcInstance.getGoodsInstances(); - goodsInstances.put(goodsInstance.getName(), goodsInstance); - npcInstance.setGoodsInstances(goodsInstances); - return true; - }else { - goodsInstanceAttrsMap.put(names[3], value); - return true; - } - }else { - return false; - } - }else { - return false; - } - }else if(names[0].equals("npc")) { - NpcInstance npcInstance = this.npcInstancesMap.get(names[2]); - if(npcInstance!=null) { - if(npcInstance.getNpcClass().getName().equals(names[1])) { - Map npcInstanceAttrMap = npcInstance.getAttrs(); - if(names[3].equals("跟随玩家")) { - if(value.equals("是")) { - this.followNpcesMap.put(npcInstance.getName(), npcInstance); - }else if(value.equals("否")) { - this.followNpcesMap.remove(npcInstance.getName()); - }else { - return true; - } - }else if(names[3].equals("所在地点")) { - Place placeOrigin = npcInstance.getPlace(); - Map npcInstancesMap = placeOrigin.getNpcInstances(); - npcInstancesMap.remove(npcInstance.getName()); - Place place= this.placesMap.get(value); - npcInstance.setPlace(place); - npcInstancesMap = place.getNpcInstances(); - npcInstancesMap.put(npcInstance.getName(), npcInstance); - // 更新跟随的NPC物品的位置 - return true; - }else { - npcInstanceAttrMap.put(names[3], value); - return true; - } - }else { - return false; - } - }else { - return false; - } - }else if(names.length == 3 && names[0].equals("place")) { - Place place = this.placesMap.get(names[1]); - if(place!=null) { - if(names[2].equals("到达条件")) { - place.setGoFlag(Integer.parseInt(value)); - if(place.getGoFlag().equals(1)) { - this.placeLinkDirectGoesMap.put(place.getName(),place); - this.placeNoLinkDirectGoesMap.remove(place.getName()); - }else if(place.getGoFlag().equals(2)) { - this.placeLinkDirectGoesMap.put(place.getName(),place); - this.placeNoLinkDirectGoesMap.remove(place.getName()); - } - return true; - }else if(names[2].equals("可去地点")) { - String[] ableGos = value.split("~"); - if(this.placeNameIndexMap.get(place.getName()) != null){ - // 找到可去地点的那一行 - byte[] line = this.mapUnitMatrix[this.placeNameIndexMap.get(place.getName())]; - // 将可去地点清空 - for(int ag=0; ag ableGoes = new HashMap(); - for(int ag=0; ag attrs; - // 类下面有哪些实例 - private Map goodsInstances = new HashMap(); - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Place getPlace() { - return place; - } - public void setPlace(Place place) { - this.place = place; - } - public Map getAttrs() { - return attrs; - } - public void setAttrs(Map attrs) { - this.attrs = attrs; - } - public Map getGoodsInstances() { - return goodsInstances; - } - public void setGoodsInstances(Map goodsInstances) { - this.goodsInstances = goodsInstances; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "GoodsClass [name=" + name + "place" +place.getName()+ ", attrs=" + attrs + ", goodsInstances=" + goodsInstances + "]"; - } -} diff --git a/src/GameEnvironment/bean/GoodsInstance.java b/src/GameEnvironment/bean/GoodsInstance.java deleted file mode 100644 index 6325160..0000000 --- a/src/GameEnvironment/bean/GoodsInstance.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class GoodsInstance implements Serializable{ - private static final long serialVersionUID = 2L; - private String name; - private List nickname = new ArrayList(); - private Map attrs = new HashMap(); - private GoodsClass goodsClass; - private NpcInstance npcInstance; - private Place place; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public List getNickname() { - return nickname; - } - public void setNickname(List nickname) { - this.nickname = nickname; - } - public Map getAttrs() { - return attrs; - } - public void setAttrs(Map attrs) { - this.attrs = attrs; - } - public NpcInstance getNpcInstance() { - return npcInstance; - } - public void setNpcInstance(NpcInstance npcInstance) { - this.npcInstance = npcInstance; - } - public GoodsClass getGoodsClass() { - return goodsClass; - } - public void setGoodsClass(GoodsClass goodsClass) { - this.goodsClass = goodsClass; - } - public Place getPlace() { - return place; - } - public void setPlace(Place place) { - this.place = place; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "GoodsInstance [nickname=" + nickname + "name="+name+", attrs=" + attrs + ", goodsClass=" + goodsClass.getName() - + ", npcInstance=" + npcInstance.getName() + ", place=" + place.getName() + "]"; - } - - -} diff --git a/src/GameEnvironment/bean/Nickname.java b/src/GameEnvironment/bean/Nickname.java deleted file mode 100644 index 6fd5504..0000000 --- a/src/GameEnvironment/bean/Nickname.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -public class Nickname implements Serializable{ - private static final long serialVersionUID = 2L; - private Map goodsInstanceMap = new HashMap(); - private Map npcInstanceMap = new HashMap(); - private Map placeMap = new HashMap(); - public Map getGoodsInstanceMap() { - return goodsInstanceMap; - } - public void setGoodsInstanceMap(Map goodsInstanceMap) { - this.goodsInstanceMap = goodsInstanceMap; - } - public Map getNpcInstanceMap() { - return npcInstanceMap; - } - public void setNpcInstanceMap(Map npcInstanceMap) { - this.npcInstanceMap = npcInstanceMap; - } - public Map getPlaceMap() { - return placeMap; - } - public void setPlaceMap(Map placeMap) { - this.placeMap = placeMap; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "Nickname [goodsInstanceMap=" + goodsInstanceMap + ", npcInstanceMap=" + npcInstanceMap + ", placeMap=" - + placeMap + "]"; - } -} diff --git a/src/GameEnvironment/bean/NpcClass.java b/src/GameEnvironment/bean/NpcClass.java deleted file mode 100644 index 43351e8..0000000 --- a/src/GameEnvironment/bean/NpcClass.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -public class NpcClass implements Serializable{ - private static final long serialVersionUID = 2L; - private String name; - private Place place; - private Map attrs = new HashMap(); - // 类下面有哪些实例 - private Map npcInstances = new HashMap(); - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Place getPlace() { - return place; - } - public void setPlace(Place place) { - this.place = place; - } - public Map getAttrs() { - return attrs; - } - public void setAttrs(Map attrs) { - this.attrs = attrs; - } - public Map getNpcInstances() { - return npcInstances; - } - public void setNpcInstances(Map npcInstances) { - this.npcInstances = npcInstances; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "NpcClass [name=" + name + ",place" + place.getName()+", attrs=" + attrs + ", npcInstances=" + npcInstances + "]"; - } -} diff --git a/src/GameEnvironment/bean/NpcInstance.java b/src/GameEnvironment/bean/NpcInstance.java deleted file mode 100644 index a07eeb1..0000000 --- a/src/GameEnvironment/bean/NpcInstance.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class NpcInstance implements Serializable{ - private static final long serialVersionUID = 2L; - private String name; - private List nickname = new ArrayList(); - private Map attrs = new HashMap(); - private NpcClass npcClass; - private Place place; - private Map goodsInstances = new HashMap(); - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public List getNickname() { - return nickname; - } - public void setNickname(List nickname) { - this.nickname = nickname; - } - public Map getAttrs() { - return attrs; - } - public void setAttrs(Map attrs) { - this.attrs = attrs; - } - public NpcClass getNpcClass() { - return npcClass; - } - public void setNpcClass(NpcClass npcClass) { - this.npcClass = npcClass; - } - public Place getPlace() { - return place; - } - public void setPlace(Place place) { - this.place = place; - } - public Map getGoodsInstances() { - return goodsInstances; - } - public void setGoodsInstances(Map goodsInstances) { - this.goodsInstances = goodsInstances; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "NpcInstance [name=" + name + ", nickname=" + nickname + ", attrs=" + attrs + ", npcClass=" + npcClass.getName() - + ", place=" + place.getName() + ", goodsInstances=" + goodsInstances + "]"; - } -} diff --git a/src/GameEnvironment/bean/Place.java b/src/GameEnvironment/bean/Place.java deleted file mode 100644 index 61fe1f4..0000000 --- a/src/GameEnvironment/bean/Place.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Place implements Serializable{ - private static final long serialVersionUID = 2L; - private String name; - /* - * 1:联通相邻可去 - * 2:联通不相邻可去 - * 3:不联通不相邻可去 - * */ - private String intro; - private Integer goFlag; - private List nickname = new ArrayList(); - private Map ableGoes = new HashMap(); - private Map npcInstances = new HashMap(); - private Map goodsInstances = new HashMap(); - public String transformGoFlag(Integer goFlag) { - if(goFlag.equals(new Integer(1))) { - return "联通相邻可去"; - }else if(goFlag.equals(new Integer(2))){ - return "联通不相邻可去"; - }else if(goFlag.equals(new Integer(3))) { - return "不联通不相邻可去"; - }else { - return "错误 go flag!"; - } - } - 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 Integer getGoFlag() { - return goFlag; - } - public void setGoFlag(Integer goFlag) { - this.goFlag = goFlag; - } - public List getNickname() { - return nickname; - } - public void setNickname(List nickname) { - this.nickname = nickname; - } - public Map getAbleGoes() { - return ableGoes; - } - public void setAbleGoes(Map ableGoes) { - this.ableGoes = ableGoes; - } - public Map getNpcInstances() { - return npcInstances; - } - public void setNpcInstances(Map npcInstances) { - this.npcInstances = npcInstances; - } - public Map getGoodsInstances() { - return goodsInstances; - } - public void setGoodsInstances(Map goodsInstances) { - this.goodsInstances = goodsInstances; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "Place [name=" + name + ",intro" + intro +", goFlag=" + this.transformGoFlag(goFlag) + ", nickname=" + nickname + ", ableGo=" + ableGoes.keySet() - + ", npcInstances=" + npcInstances + ", goodsInstances=" + goodsInstances + "]"; - } -} diff --git a/src/GameEnvironment/bean/PlaceLink.java b/src/GameEnvironment/bean/PlaceLink.java deleted file mode 100644 index 408030d..0000000 --- a/src/GameEnvironment/bean/PlaceLink.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.qiwu.chatbotbackend.GameEnvironment.bean; - -import java.io.Serializable; - -public class PlaceLink implements Serializable{ - private static final long serialVersionUID = 2L; - private Integer index; - private PlaceLink placeLink; - public Integer getIndex() { - return index; - } - public void setIndex(Integer index) { - this.index = index; - } - public PlaceLink getPlaceLink() { - return placeLink; - } - public void setPlaceLink(PlaceLink placeLink) { - this.placeLink = placeLink; - } - public static long getSerialversionuid() { - return serialVersionUID; - } - @Override - public String toString() { - return "PlaceLink [index=" + index + ", placeLink=" + placeLink + "]"; - } -} diff --git a/src/c3p0-config.xml b/src/c3p0-config.xml deleted file mode 100644 index 4287ee0..0000000 --- a/src/c3p0-config.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 10 - 30 - 50 - 10 - 200 - - - - - com.mysql.jdbc.Driver - - jdbc:mysql://192.168.1.81:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 - - root - admin - 10 - 30 - 50 - 10 - 200 - - - - ...... - - ...... - - ...... - \ No newline at end of file diff --git a/src/db/C3p0Utils.java b/src/db/C3p0Utils.java deleted file mode 100644 index cccd088..0000000 --- a/src/db/C3p0Utils.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.qiwu.chatbotbackend.db; - - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import org.apache.log4j.Logger; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class C3p0Utils { - static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); - - //通过标识名来创建相应连接池 - static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); - //通过标识名来创建相应连接池 - static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("mysql2"); - - //从连接池中取用一个连接 - public static Connection getConnection() throws SQLException { - try { - return dataSource.getConnection(); - - } catch (Exception e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - - //从连接池中取用一个连接 - public static Connection getEngineConnection() throws SQLException { - try { - return dataSource2.getConnection(); - - } catch (Exception e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - - //释放连接回连接池 - public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - if (pst != null) { - try { - pst.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - logger.error("Exception in C3p0Utils!", e); - throw e; - } - } - } -} diff --git a/src/db/DB.java b/src/db/DB.java deleted file mode 100644 index 2a0a658..0000000 --- a/src/db/DB.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.qiwu.chatbotbackend.db; - -import java.sql.Connection; -import java.sql.DriverManager; - -public class DB { - private static String driver = "com.mysql.jdbc.Driver"; - private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; - private static String user = "root"; - private static String pwd = "admin"; - - public static Connection getConnection() { - Connection conn = null; - try { - Class.forName(driver); - conn = DriverManager.getConnection(url, user, pwd); - - } catch (Exception e) { - e.printStackTrace(); - } - - return conn; - } -} diff --git a/src/db/DBCPUtils.java b/src/db/DBCPUtils.java deleted file mode 100644 index 4746731..0000000 --- a/src/db/DBCPUtils.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.qiwu.chatbotbackend.db; - - -import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory; - -import javax.sql.DataSource; -import java.io.File; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - - -public class DBCPUtils { - private static DataSource ds;//定义一个连接池对象 - - static { - try { - Properties pro = new Properties(); - File file = new File("dbcpconfig.properties"); - pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties")); - ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象 - } catch (Exception e) { - e.printStackTrace(); - //throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); - } - } - - //从池中获取一个连接 - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - public static void closeAll(ResultSet rs, Statement stmt, Connection conn) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - if (conn != null) { - try { - conn.close();//关闭 - } catch (SQLException e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/src/db/DBUtils.java b/src/db/DBUtils.java deleted file mode 100644 index 5dc4aaa..0000000 --- a/src/db/DBUtils.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.qiwu.chatbotbackend.db; - -public class DBUtils { -} diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java deleted file mode 100644 index a3020ff..0000000 --- a/src/db/SqlHelper.java +++ /dev/null @@ -1,927 +0,0 @@ -package com.qiwu.chatbotbackend.db; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.actiongenerate.entity.BotInfo; -import com.qiwu.actiongenerate.entity.Condition; -import com.qiwu.chatbotbackend.entity.ArchiveInfo; -import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import static com.qiwu.chatbotbackend.Config.Config.*; - -public class SqlHelper { - private Connection conn = null; - /* - public SqlHelper(){ - conn = DB.getConnection(); - } - */ - - public SqlHelper() throws SQLException { - conn = C3p0Utils.getConnection(); - } - - - public void destroy() { - if (conn != null) { - try { - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - } - //----------------------------------------condition操作--------------------------------------------------------------- - //------------------------------------------------------------------------------------------------------------ - - - public Boolean deleteUserData(int botId){ - - String sql1 = "delete from chatbot_config where botId = ?"; - String sql2 = "delete from chatbot_condition where botId = ?"; - String sql3 = "delete from config_categories where botId = ?"; - String sql4 = "delete from chatbot_variable where botId = ?"; - Boolean b1, b2, b3, b4; - - try{ - PreparedStatement ps1 = conn.prepareStatement(sql1); - ps1.setInt(1, botId); - b1 = ps1.execute(); - PreparedStatement ps2 = conn.prepareStatement(sql2); - ps2.setInt(1, botId); - b2 = ps1.execute(); - PreparedStatement ps3 = conn.prepareStatement(sql3); - ps3.setInt(1, botId); - b3 = ps1.execute(); - PreparedStatement ps4 = conn.prepareStatement(sql4); - ps4.setInt(1, botId); - b4 = ps1.execute(); - } catch (SQLException e) { - System.out.println(DELETE_USER_DATA_ERROR); - e.printStackTrace(); - return false; - } - return b1&&b2&&b3&&b4; - - } - - public Boolean batchInsertCondition(List insertList){ - int count[]; - boolean insertFlag = true; - String sql = "", varName, varValue, description; - - - try { - conn.setAutoCommit(false); - - - sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)"; - PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - for(String[] elements:insertList){ - ps.setString(1, elements[0]); - ps.setString(2, elements[1]); - ps.setString(3, elements[2]); - ps.setString(4, elements[3]); - ps.setString(5, elements[4]); - ps.addBatch(); - } - - count = ps.executeBatch(); - - conn.commit(); - - for (int i : count) { - if (i == 0) { - conn.rollback(); - System.out.println("======出现异常,回滚========="); - insertFlag = false; - } - } - ps.close(); - - } catch (SQLException e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - System.out.println("------出现异常,回滚----------"); - e.printStackTrace(); - } - - return insertFlag; - } - - public List queryActionTextList(int botId){ - String sql = "select actionText from chatbot_condition where botId= ?"; - String pre_name = ""; - List actionTextList = new ArrayList(); - try{ - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1,botId); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - actionTextList.add(rs.getString("actionText")); - } - - - - }catch(Exception e){ - e.printStackTrace(); - } - return actionTextList; - } - - public Condition queryActiveCondition(int botId){ - Condition condition = null; - - String sql = "select * from chatbot_condition where active= 1"; - String pre_name = ""; - List actionTextList = new ArrayList(); - try{ - PreparedStatement ps = conn.prepareStatement(sql); - ResultSet rs = ps.executeQuery(); - if(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - } - - - - }catch(Exception e){ - e.printStackTrace(); - } - return condition; - - } - - - public List queryConditionCategoriesById(int botId){ - String sql = "select categoryStr from chatbot_condition where botId= ?"; - String pre_name = ""; - List categoryList = new ArrayList(); - try{ - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1,botId); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - categoryList.add(rs.getString("categoryStr")); - } - - - - }catch(Exception e){ - e.printStackTrace(); - } - return categoryList; - } - - - - public BotInfo queryBotInfo(int botId){ - String sql = "select * from bot_info where botId = ?"; - BotInfo botInfo = null; - - try{ - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1,botId); - ResultSet rs = ps.executeQuery(); - if(rs.next()){ - botInfo = new BotInfo(rs.getInt("botId"), rs.getString("welcomText"), rs.getString("goodbyeText"), rs.getString("postURL"), rs.getString("defaultConfigCategory"), - rs.getString("bothValue"), rs.getString("queryTextTransfer")); - } - - - }catch(Exception e){ - e.printStackTrace(); - } - return botInfo; - } - - public Boolean updateConditionById(Condition condition){ - boolean b; - - try { - String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?"; - PreparedStatement ps1 = conn.prepareStatement(sql); - ps1.setString(1, condition.getConditionJsonText()); - ps1.setString(2, condition.getActionText()); - ps1.setString(3, condition.getCategory()); - ps1.setString(4, condition.getActive()); - ps1.setInt(5, condition.getBotId()); - ps1.setInt(6, condition.getConditionId()); - - b = ps1.execute(); - ps1.close(); - - return b; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return false; - } - } - - - public boolean batchUpdateCondition(int botId, List conditionList) { - - int count[]; - boolean insertFlag = true; - - - try { - conn.setAutoCommit(false); - - - String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?"; - PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - - for(Condition condition:conditionList){ - ps.setString(1, condition.getConditionJsonText()); - ps.setString(2, condition.getActionText()); - ps.setString(3, condition.getCategory()); - ps.setString(4, condition.getActive()); - ps.setInt(5, condition.getBotId()); - ps.setInt(6, condition.getConditionId()); - ps.addBatch(); - } - - count = ps.executeBatch(); - - conn.commit(); - - for (int i : count) { - if (i == 0) { - conn.rollback(); - System.out.println("======出现异常,回滚========="); - insertFlag = false; - } - } - ps.close(); - - } catch (SQLException e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - System.out.println("------出现异常,回滚----------"); - e.printStackTrace(); - } - - return insertFlag; - - } - - public List queryConditionByCategory(String category){ - boolean b; - List conditionList = new ArrayList(); - Condition condition = null; - - try { - String sql = "query chatbot_condition wher botId = ? where categoryStr = ?"; - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, category); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - conditionList.add(condition); - } - ps.close(); - rs.close(); - - - return conditionList; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return conditionList; - } - } - - - - public List queryConditionByCategory(int botId, String category){ - boolean b; - List conditionList = new ArrayList(); - Condition condition = null; - - try { - String sql = "select * from chatbot_condition wher botId = ? and categoryStr = ?"; - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1, botId); - ps.setString(2, category); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - conditionList.add(condition); - } - ps.close(); - rs.close(); - - - return conditionList; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return conditionList; - } - } - - public Condition queryConditionByConditionId(int botId, int conditionId){ - boolean b; - List conditionList = new ArrayList(); - Condition condition = null; - - try { - String sql = "select * from chatbot_condition wher botId = ? and conditionId = ?"; - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1, botId); - ps.setInt(2, conditionId); - ResultSet rs = ps.executeQuery(); - if(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - } - ps.close(); - rs.close(); - - - return condition; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return condition; - } - } - - - public List queryConditionAll(int botId){ - boolean b; - List conditionList = new ArrayList(); - Condition condition = null; - - try { - String sql = "select * from chatbot_condition wher botId = ? where botId = ?"; - PreparedStatement ps = conn.prepareStatement(sql); - ps.setInt(1, botId); - ResultSet rs = ps.executeQuery(); - while(rs.next()){ - condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), - rs.getString("conditionData"), rs.getString("actionText"), - rs.getString("categoryStr"), rs.getString("active")); - conditionList.add(condition); - } - ps.close(); - rs.close(); - - - return conditionList; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return conditionList; - } - } - - - - - //------------------------------------------------------------------------------------------------------------ - //------------------------------------------------------------------------------------------------------------ - - private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException { - C3p0Utils.close(_conn, _st, _rs); - } - - public String queryUsernameByKey(String chat_key) { - String sql = "select * from chats where chat_key = ?"; - String userName = ""; - String result = "empty"; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, chat_key); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - result = rs.getString("bot"); - - ps.close(); - rs.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - - public boolean deleteConfigByIdGroup(int botId, List idGroup) throws SQLException { - - StringBuilder inClause = new StringBuilder(); - boolean firstValue = true; - int batchSize = idGroup.size(); - - for (int i = 0; i < batchSize; i++) { - inClause.append('?'); - if (firstValue) { - firstValue = false; - } else { - inClause.append(','); - } - } - - String sql = "delete from chatbot_config where botId = ? and configId in (" + inClause.toString() + ')'; - String userName = ""; - boolean b = true; - - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(botId)); - b = ps.execute(); - - ps.close(); - - return b; - } catch (Exception e) { - e.printStackTrace(); - } - return b; - } - - public boolean deleteConfigByBotId(int botId) { - boolean b; - - try { - PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); - ps1.setString(1, String.valueOf(botId)); - b = ps1.execute(); - ps1.close(); - - return b; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); - e.printStackTrace(); - return false; - } - } - - public boolean deleteVariableByBotId(int botId) { - String sql = "delete from chatbot_variable where botId= ?"; - boolean b; - - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(botId)); - b = ps.execute(); - - ps.close(); - - return b; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_VARIABLE_ERROR); - e.printStackTrace(); - return false; - } - } - - - public boolean deleteCategoryByBotId(int botId) { - String sql = "delete from config_categories where botId= ?"; - boolean b; - - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(botId)); - b = ps.execute(); - - ps.close(); - - return b; - - } catch (SQLException e) { - System.out.println(DELETE_OLD_CATEGORY_ERROR); - e.printStackTrace(); - return false; - } - } - - public boolean batchInsertVariableByBotId(int botId, ElementConstructor constructor) { - - int count[]; - boolean insertFlag = true; - String sql = "", varName, varValue, description; - - - try { - conn.setAutoCommit(false); - - - sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; - PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - Iterator iit = constructor.getVarInitialMap().keySet().iterator(); - while (iit.hasNext()) { - varName = iit.next(); - varValue = constructor.getVarInitialMap().get(varName); - if (constructor.getConditionDescription().get(varName) == null) - description = ""; - else - description = constructor.getConditionDescription().get(varName); - - ps2.setString(1, String.valueOf(botId)); - ps2.setString(2, varName); - ps2.setString(3, description); - ps2.setString(4, varValue); - ps2.addBatch(); - } - - count = ps2.executeBatch(); - - conn.commit(); - - for (int i : count) { - if (i == 0) { - conn.rollback(); - System.out.println("======出现异常,回滚========="); - insertFlag = false; - } - } - ps2.close(); - - } catch (SQLException e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - System.out.println("------出现异常,回滚----------"); - e.printStackTrace(); - } - - return insertFlag; - - } - - public boolean batchInsertConfigByBotId(int botId, List jsonList, List idList, int categoryId) { - int count[]; - boolean insertFlag = true; - String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; - - - try { - conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 - PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - for (JSONObject json : jsonList) { - ps.setString(1, String.valueOf(botId)); - ps.setString(2, String.valueOf(categoryId)); - ps.setString(3, json.toJSONString()); - ps.setString(4, (String)json.get("configName")); - - ps.addBatch(); - } - - count = ps.executeBatch(); - conn.commit(); - - for (int i : count) { - if (i == 0) { - conn.rollback(); - System.out.println("======出现异常,回滚========="); - insertFlag = false; - } - } - - - ResultSet rs = ps.getGeneratedKeys(); - while (rs.next()) - idList.add(rs.getInt(1)); - - - ps.close(); - rs.close(); - - } catch (SQLException e) { - try { - conn.rollback(); - - } catch (SQLException e1) { - e1.printStackTrace(); - } - System.out.println("------出现异常,回滚----------"); - e.printStackTrace(); - } - - return insertFlag; - } - - - public boolean batchInsertCategoryByBotId(int botId, Map categoryMap) { - - int count[], iterNum = 0, id; - boolean insertFlag = true; - String sql = "", varName, varValue, description; - ArrayList nameList = new ArrayList(); - - - try { - conn.setAutoCommit(false); - - - sql = "insert into config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, -1, ?, 'avaliable')"; - PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - Iterator iit = categoryMap.keySet().iterator(); - while (iit.hasNext()) { - varName = iit.next(); - - nameList.add(varName); - ps.setString(1, String.valueOf(botId)); - ps.setString(2, varName); - ps.addBatch(); - } - - count = ps.executeBatch(); - - conn.commit(); - - for (int i : count) { - if (i == 0) { - conn.rollback(); - System.out.println("======出现异常,回滚========="); - insertFlag = false; - } - } - - - - ResultSet rs = ps.getGeneratedKeys(); - while (rs.next()){ - id = rs.getInt(1); - categoryMap.put(nameList.get(iterNum), id); - iterNum++; - } - - - ps.close(); - rs.close(); - - } catch (SQLException e) { - try { - conn.rollback(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - System.out.println("------出现异常,回滚----------"); - e.printStackTrace(); - } - - return insertFlag; - - } - - - public JSONObject queryGameElementsByBotId(int id) { - String sql = "select * from generate_json_tb where project_id = ?"; - String userName = ""; - String result = "{}"; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(id)); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - result = rs.getString("json_text"); - - ps.close(); - rs.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return JSONObject.parseObject(result); - - } - - public static String queryEnvJsonByBotName(String botName) throws SQLException { - String sql = "select * from generate_json_tb where bot_name = ?"; - Connection conn = C3p0Utils.getConnection(); - String result = "{}"; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(botName)); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - result = rs.getString("env_json_text"); - - ps.close(); - rs.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return result; - } - - public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) { - String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; - String userName = ""; - String result = "empty"; - boolean b = true; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(id)); - ps.setString(2, variableName); - ps.setString(3, description); - ps.setString(4, defaultValue); - b = ps.execute(); - - ps.close(); - conn.commit(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return b; - - } - - public boolean insertConfigByBotId(int botId, JSONObject json, List idList, int categoryId) { - String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; - int id = 0; - boolean b = true; - int bNum = 0; - try { - PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, String.valueOf(botId)); - ps.setString(2, String.valueOf(categoryId)); - ps.setString(3, json.toJSONString()); - ps.setString(4, (String)json.get("configName")); - - System.out.println(ps.toString()); - - bNum = ps.executeUpdate(); - ResultSet rs = ps.getGeneratedKeys(); - if(rs.next()){ - id = rs.getInt(1); - idList.add(id); - } - ps.close(); - rs.close(); - conn.commit(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return b; - - } - - - public Boolean insertArchiveInfo(String archiveName, String userKey, String site){ - String sql = "insert into game_archive (archive_id, user_key, site, plot) VALUES (?, ?, ?, '')"; - int id = 0; - boolean b = true; - int bNum = 0; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(archiveName)); - ps.setString(2, String.valueOf(userKey)); - ps.setString(3, String.valueOf(site)); - - - System.out.println(ps.toString()); - - bNum = ps.executeUpdate(); - ps.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return bNum == 1; - } - - public ArchiveInfo queryUserLastGameArchive(String userKey){ - String sql = "select * from game_archive where user_key = ? order by update_time desc"; - String result = "{}"; - ArchiveInfo archiveInfo = null; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, String.valueOf(userKey)); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - archiveInfo = new ArchiveInfo(rs.getString("archive_id"),rs.getString("user_key"), - rs.getString("site"),rs.getString("update_time"),rs.getString("plot")); - - ps.close(); - rs.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return archiveInfo; - } - - - public ArchiveInfo queryUserLastGameArchiveBySite(String userKey, String site){ - String sql = "select * from game_archive where user_key = ? and site = ? order by update_time desc"; - String result = "{}"; - ArchiveInfo archiveInfo = null; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, userKey); - ps.setString(2, site); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"), - rs.getString("site"), rs.getString("update_time"), rs.getString("plot")); - } - - ps.close(); - rs.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return archiveInfo; - } - - - public boolean deleteArchiveByBotAccount(String botAccount) { - String sql = "delete from game_archive where user_key like ?"; - boolean b; - - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, "%" + botAccount); - b = ps.execute(); - - ps.close(); - - return b; - - } catch (SQLException e) { - System.out.println("删除游戏存档失败"); - e.printStackTrace(); - return false; - } - } - - public List queryArchiveByUserKey(String userKey){ - String sql = "select * from game_archive where user_key = ? order by update_time desc"; - List archiveList = new ArrayList(); - ArchiveInfo archiveInfo = null; - try { - PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1, userKey); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"), - rs.getString("site"), rs.getString("update_time"), rs.getString("plot")); - archiveList.add(archiveInfo); - } - - ps.close(); - rs.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return archiveList; - } - - - - -} diff --git a/src/entity/Action.java b/src/entity/Action.java deleted file mode 100644 index a4ca8be..0000000 --- a/src/entity/Action.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; - - -/** - * 保存配置文件每一行(单行)解析后的信息的实体类。 - * 独立于引擎的另一种condition - */ -public class Action { - private int priority = -1; - //public int activePriority = 0; //如果本condition被其他condition激活 - private int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 - private HashSet keywordSet = new HashSet(); - private HashMap> historyPremise = new HashMap>(); - private HashMap> currentPremise = new HashMap>(); - private HashMap updateKnowledge = new LinkedHashMap(); - private String[] answer = {"",}; - private String nextStep = ""; - private HashMap featureMap = new HashMap(); - private String indexName = ""; - private int id = 0; - private String configName = ""; - private String status = "waiting"; - //public ArrayList indexName = new ArrayList(); - - public Action(int priority) { - this.priority = priority; - //this.activePriority = priority; - } - - - /** - * - * @param originAction 这个action的初始状态 - * @param basePriority 激活originAction的action的条件数量 - * @param baseAuxiliaryPriority 激活originAction的action的辅助优先级 - */ - public Action(Action originAction, int basePriority, int baseAuxiliaryPriority) { - this.priority = originAction.priority; - this.keywordSet = originAction.keywordSet; - this.historyPremise = originAction.historyPremise; - this.currentPremise = originAction.currentPremise; - this.answer = originAction.answer; - this.nextStep = originAction.nextStep; - this.featureMap = originAction.featureMap; - this.updateKnowledge = originAction.updateKnowledge; - this.indexName = originAction.indexName; - this.id = originAction.id; - this.configName = originAction.configName; - this.status = originAction.status; - this.priority = originAction.priority + basePriority + 1; //如果激活的配置没有条件 - - - this.auxiliaryPriority = originAction.auxiliaryPriority + baseAuxiliaryPriority; //优先级为两者之和 -// //如果激活originAction的action,它的辅助优先级高于originAction,那么。。 -// if(baseAuxiliaryPriority > originAction.auxiliaryPriority) -// this.auxiliaryPriority = baseAuxiliaryPriority; -// else -// this.auxiliaryPriority = originAction.auxiliaryPriority; -// -// this.auxiliaryPriority = this.getAuxiliaryPriority() + 1; - } - - public Action() { - } - - public int getPriority() { - return priority; - } - - public int getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - public void setAuxiliaryPriority(int auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public HashSet getKeywordSet() { - return keywordSet; - } - - public HashMap> getHistoryPremise() { - return historyPremise; - } - - public HashMap> getCurrentPremise() { - return currentPremise; - } - - public HashMap getUpdateKnowledge() { - return updateKnowledge; - } - - public String[] getAnswer() { - return answer; - } - - public String getNextStep() { - return nextStep; - } - - public HashMap getFeatureMap() { - return featureMap; - } - - public String getIndexName() { - return indexName; - } - - public int getId() { - return id; - } - - public String getConfigName() { - return configName; - } - - public String getStatus() { - return status; - } - - public void setKeywordSet(HashSet keywordSet) { - this.keywordSet = keywordSet; - } - - public void setHistoryPremise(HashMap> historyPremise) { - this.historyPremise = historyPremise; - } - - public void setCurrentPremise(HashMap> currentPremise) { - this.currentPremise = currentPremise; - } - - public void setUpdateKnowledge(HashMap updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - public void setAnswer(String[] answer) { - this.answer = answer; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - - public void setFeatureMap(HashMap featureMap) { - this.featureMap = featureMap; - } - - public void setIndexName(String indexName) { - this.indexName = indexName; - } - - public void setId(int id) { - this.id = id; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - public void setStatus(String status) { - this.status = status; - } -} diff --git a/src/entity/AnswerNextStep.java b/src/entity/AnswerNextStep.java deleted file mode 100644 index ecc898d..0000000 --- a/src/entity/AnswerNextStep.java +++ /dev/null @@ -1,44 +0,0 @@ -package entity; - - -/** - * 包含后台返回数据的实体类。 - */ -public class AnswerNextStep { - int status = 0; - String answer; - String next; - - public String getAnswer() { - return answer; - } - - public int getStatus() { - return status; - } - - - - public void setAnswer(String answer) { - this.answer = answer; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - public AnswerNextStep(int status, String answers, String next){ - this.answer = answers; - this.next = next; - this.status = status; - } - public AnswerNextStep(){} -} diff --git a/src/entity/ArchiveInfo.java b/src/entity/ArchiveInfo.java deleted file mode 100644 index 068a3e9..0000000 --- a/src/entity/ArchiveInfo.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -public class ArchiveInfo { - String archiveId; - String userKey; - String site; - String updateTime; - String plot; - - public String getArchiveId() { - return archiveId; - } - - public void setArchiveId(String archiveId) { - this.archiveId = archiveId; - } - - public String getUserKey() { - return userKey; - } - - public void setUserKey(String userKey) { - this.userKey = userKey; - } - - public String getSite() { - return site; - } - - public void setSite(String site) { - this.site = site; - } - - public String getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(String updateTime) { - this.updateTime = updateTime; - } - - public String getPlot() { - return plot; - } - - public void setPlot(String plot) { - this.plot = plot; - } - - public ArchiveInfo(String archiveId, String userKey, String site, String updateTime, String plot) { - this.archiveId = archiveId; - this.userKey = userKey; - this.site = site; - this.updateTime = updateTime; - this.plot = plot; - } -} diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java deleted file mode 100644 index 0bb4e75..0000000 --- a/src/entity/ChatCache.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import org.springframework.beans.factory.DisposableBean; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class ChatCache implements DisposableBean { - - - public String ENV_ERROR = "游戏平台初始化失败"; -// private String chatKey = "不知道"; - private String userKey = ""; - private String randKey = ""; - private String botAccount = ""; - - private Map infoPoint = null; - private GameEnv gameEnv = null; - private Boolean gameStart = false; - private Boolean reload = false; - - - public String getBotAccount() { - return botAccount; - } - - public void setBotAccount(String botAccount) { - this.botAccount = botAccount; - } - - - public String getUserKey() { - return userKey; - } - - public void setUserKey(String userKey) { - this.userKey = userKey; - } - - public String getRandKey() { - return randKey; - } - - public void setRandKey(String randKey) { - this.randKey = randKey; - } - - public Map getInfoPoint() { - return infoPoint; - } - - public void setInfoPoint(Map infoPoint) { - this.infoPoint = infoPoint; - } - - public boolean isGameStart() { - return gameStart; - } - - public void setGameStart(boolean gameStart) { - this.gameStart = gameStart; - } - - public Boolean getReload() { - return reload; - } - - public void setReload(Boolean reload) { - this.reload = reload; - } - - public GameEnv getGameEnv() { - return gameEnv; - } - - public void setGameEnv(GameEnv gameEnv) { - this.gameEnv = gameEnv; - } - - public ChatCache(String userKey, String randKey, GameEnv gameEnv, Map infoPoint) { - this.userKey = userKey; - this.randKey = randKey; - this.gameEnv = gameEnv; - this.infoPoint = infoPoint; - } - - - @Override - public void destroy() throws IOException { - } - - public ChatCache(UserInfo userInfo, String userKey, String randKey, String botType) throws Exception { - - if(botType.equals("game")) { - try { - this.gameEnv = new GameEnv(userInfo.botAccount); - System.out.println("初始化时:" + this.gameEnv); - } catch (Exception e) { - System.out.println(ENV_ERROR); - - this.infoPoint.put("error_message", ENV_ERROR); - e.printStackTrace(); - } - } - - String k; - this.botAccount = userInfo.botAccount; - this.infoPoint = new HashMap(); - Iterator iit = userInfo.varInitialMap.keySet().iterator(); - while (iit.hasNext()) { - k = iit.next(); - this.infoPoint.put(k, userInfo.varInitialMap.get(k)); - } - this.infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - this.randKey = randKey; - this.userKey = userKey; - - } - - public ChatCache(String userKey, String randKey) { - this.userKey = userKey; - this.randKey = randKey; - } -} diff --git a/src/entity/ChatCache3.java b/src/entity/ChatCache3.java deleted file mode 100644 index a0ce10a..0000000 --- a/src/entity/ChatCache3.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.processing.ChatCacheController; -import org.springframework.beans.factory.DisposableBean; - - -import javax.annotation.PreDestroy; - -public class ChatCache3 implements DisposableBean { - - -// private String chatKey = "不知道"; - private String chatKey = ""; - private String botAccount = ""; - - private Map infoPoint = null; - private GameEnv gameEnv = null; - private boolean reloading = false; - - - public String getBotAccount() { - return botAccount; - } - - public void setBotAccount(String botAccount) { - this.botAccount = botAccount; - } - - public boolean isReloading() { - return reloading; - } - - - public void setReloading(boolean reloading) { - this.reloading = reloading; - } - - public Map getInfoPoint() { - return infoPoint; - } - - public void setInfoPoint(Map infoPoint) { - this.infoPoint = infoPoint; - } - - public GameEnv getGameEnv() { - return gameEnv; - } - - public void setGameEnv(GameEnv gameEnv) { - this.gameEnv = gameEnv; - } - - public ChatCache3(String chatKey, GameEnv gameEnv, Map infoPoint) { - this.chatKey = chatKey; - this.gameEnv = gameEnv; - this.infoPoint = infoPoint; - } - - - @Override - public void destroy() throws IOException { - } - - public ChatCache3(UserInfo userInfo) throws Exception { - try { - gameEnv = new GameEnv(userInfo.botAccount); - } catch (Exception e) { - System.out.println("游戏平台初始化失败"); - e.printStackTrace(); - } - - String k; - this.botAccount = userInfo.botAccount; - infoPoint = new HashMap(); - Iterator iit = userInfo.varInitialMap.keySet().iterator(); - while (iit.hasNext()) { - k = iit.next(); - infoPoint.put(k, userInfo.varInitialMap.get(k)); - } - infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - - } - - -} diff --git a/src/entity/Condition.java b/src/entity/Condition.java deleted file mode 100644 index bc78ed4..0000000 --- a/src/entity/Condition.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; - - -/** - * 保存配置文件每一行(单行)解析后的信息的实体类。 - * 独立于引擎的另一种condition - */ -public class Condition { - public int priority = -1; - public int activePriority = 0; //如果本condition被其他condition激活 - public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 - public HashSet keywordSet = new HashSet(); - public HashMap> historyPremise = new HashMap>(); - public HashMap> currentPremise = new HashMap>(); - public HashMap updateKnowledge = new LinkedHashMap(); - public String[] answer = {"",}; - public String nextStep = ""; - public HashMap featureMap = new HashMap(); - public String indexName = ""; - public int id = 0; - public String configName = ""; - public String status = "waiting"; - //public ArrayList indexName = new ArrayList(); - - public Condition(int priority) { - this.priority = priority; - this.activePriority = priority; - } - - public Condition(Condition originCondition, int basePriority, int baseAuxiliaryPriority) { - this.priority = originCondition.priority; - this.keywordSet = originCondition.keywordSet; - this.historyPremise = originCondition.historyPremise; - this.currentPremise = originCondition.currentPremise; - this.answer = originCondition.answer; - this.nextStep = originCondition.nextStep; - this.featureMap = originCondition.featureMap; - this.updateKnowledge = originCondition.updateKnowledge; - this.indexName = originCondition.indexName; - this.id = originCondition.id; - this.configName = originCondition.configName; - this.status = originCondition.status; - this.activePriority = originCondition.activePriority + basePriority; - this.auxiliaryPriority = originCondition.auxiliaryPriority + baseAuxiliaryPriority; - } - - public Condition() { - } - -} diff --git a/src/entity/ConfigTerm.java b/src/entity/ConfigTerm.java deleted file mode 100644 index a1f3725..0000000 --- a/src/entity/ConfigTerm.java +++ /dev/null @@ -1,531 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class ConfigTerm implements Cloneable{ - - ThreadLocal iterNum=new ThreadLocal() { - protected Integer initialValue() { - return 0; - } - }; - ThreadLocal> conditionCount = new ThreadLocal>(){ - protected Map initialValue(){ - return new HashMap(); - }; - }; - - - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - - - private String curPremise = ""; - private String hisPremise = ""; - private String feature = ""; - private String reply = ""; - private String nextStep = ""; - private String updateKnowledge = ""; - private String nextStepStatus = "return"; - private String configName = ""; - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - public String getFeature() { - return feature; - } - - public void setFeature(String feature) { - this.feature = feature; - } - - public String getCurPremise() { - return curPremise; - } - - public String getNextStep() { - return nextStep; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName, Boolean append) { - - if(append) { - - iterNum.set(iterNum.get() + 1); - - //iterNum++; - this.configName = configName + "_" + iterNum.get(); - }else{ - this.configName = configName; - } - } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - - public void setCurPremise(String curPremise) { - this.curPremise = curPremise; - } - - public String getHisPremise() { - return hisPremise; - } - - public void setHisPremise(String hisPremise) { - this.hisPremise = hisPremise; - } - - public String getReply() { - return reply; - } - - public void setReply(String reply) { - this.reply = reply; - } - - public String getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public String getStatus() { - return status; - } - - public String getNextStepStatus() { - return nextStepStatus; - } - - public String getUpdateKnowledge() { - return updateKnowledge; - } - - public void setUpdateKnowledge(String updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - - static Map statusMap = new HashMap() { - { - put("return", "return"); - put("return-1", "back"); - put("return-0", "stay"); - put("activate", "activate"); - put("activate:after", "activate:after"); - } - }; - - public void setStatus(String status) { - this.status = status; - } - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public void setNextStepStatus(String nextStepStatus) { - this.nextStepStatus = nextStepStatus; - } - - public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - if (!updateKnowledge.equals("")) - this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); - //if (!updateKnowledge.equals("")) - // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - - public ConfigTerm(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { - this.curPremise = appendPremiseStr(curPremise, extraCP); - this.hisPremise = appendPremiseStr(hisPremise, extraHP); - this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; - this.auxiliaryPriority = auxiliaryPriority; - } - - public String appendPremiseStr(List premises, String extraPremise) { - StringBuffer sb = new StringBuffer(); - String premiseStr = "", conditionName; - Map nameCount = new HashMap(); - - for (Premise premise : premises){ - //设置初始值 - //System.out.println("nameCount" + nameCount); - conditionName = premise.getConditionName(); - - nameCount.putIfAbsent(conditionName, 0); - - //nameCount加一 - nameCount.put(conditionName, nameCount.get(conditionName) + 1); - - //在conditionName后添加count - if(nameCount.get(conditionName) > 1) { - premise.setConditionName(conditionName + nameCount.get(conditionName)); - } - - - - sb.append(","); - sb.append(premise.getConditionName()); - sb.append("::"); - sb.append(premise.getCmpType()); - sb.append("-"); - sb.append(premise.getOperator()); - sb.append("="); - sb.append(premise.getKeyword()); - } - if (sb.length() > 0) - sb.deleteCharAt(0); //删除第一个逗号 - - - if (!extraPremise.equals("")) { - if (sb.length() == 0) - sb.append(extraPremise); - else - sb.append("," + extraPremise); - } else if (sb.length() == 0) { - sb.append(" "); - } - premiseStr = sb.toString(); - - return premiseStr; - } - - public String appendKnowledgeStr(Map knowledge, String extraKL) { - StringBuffer sb = new StringBuffer(); - String varName = "", varValue = "", knowledgeStr; - Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 - String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; - - while (iit.hasNext()) { - varName = iit.next(); - varValue = knowledge.get(varName); - - if(varValue.startsWith("updateFollowerLocation")){ - delayUpdateFollowerLocation = true; - delayUpdateFollowerLocationKey = varName; - delayUpdateFollowerLocationValue = varValue; - continue; - } - sb.append("-<-").append(varName).append(":").append(varValue); - - } - if (!extraKL.equals("")) { - sb.append("-<-" + extraKL); - } - - if(delayUpdateFollowerLocation){ - sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); - } - - if (sb.length() > 0) - knowledgeStr = "updateKnowledge" + sb.toString(); - else - knowledgeStr = ""; - - return knowledgeStr; - } - - - public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { - //System.out.println(premise); - - String pair1[] = premise.split("=", 2); - String key = pair1[0]; - - String keywords = pair1[1]; - String pair2[] = key.split("::"); - String conditionName = pair2[0]; - String pair3[] = pair2[1].split("-"); - String cmpType = pair3[0]; - String operator = ""; - if (pair3.length > 1) - operator = pair3[1]; - - String question = ""; - if (conditionDescription.get(conditionName) != null) - question = conditionDescription.get(conditionName); - - JSONObject premiseJ = new JSONObject(); - premiseJ.put("keywords", keywords); - premiseJ.put("actionName", conditionName); - premiseJ.put("cmpType", cmpType); - premiseJ.put("question", question); - premiseJ.put("operator", operator); - - premiseList.add(premiseJ); - - } - - public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { - String pair[] = knowledge.split(":", 2); - - if (knowledge.equals("") || pair.length < 2) - return; - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - JSONObject knowledgeJ = new JSONObject(); - knowledgeJ.put("variableName", pair[0]); - knowledgeJ.put("keyword", pair[1]); - - knowledgeList.add(knowledgeJ); - } - - public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { - String pair[] = next.split("-"); - JSONObject nextStepJ = new JSONObject(); - JSONArray exceptJ = new JSONArray(); - - for (int i = 1; i < pair.length; i++) - exceptJ.add(pair[i]); - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - nextStepJ.put("nextStep", pair[0]); - nextStepJ.put("except", exceptJ); - nextStepJ.put("nextStepText", question); - nextStepList.add(nextStepJ); - } - - public JSONObject toJson(Map conditionDescription) { - JSONObject data = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - JSONArray hisPremiseList = new JSONArray(); - - //添加当前对话内容 - for (String premise : curPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise, conditionDescription); - } - data.put("currentPremiseList", curPremiseList); - - //添加已知信息的内容 - for (String premise : hisPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise, conditionDescription); - } - data.put("historyPremiseList", hisPremiseList); - - //添加下一步状态 - - - //添加configName - data.put("configName", configName); - - //添加config状态 - data.put("configStatus", jStatus); - - - boolean doPost = false; - String postURL = "", postType = "all", pair[]; - - for (String feat : feature.split(",")) { - if (feat.startsWith("post")) { - doPost = true; - pair = feat.substring(0, feat.length() - 1).split("\\(", 2); - postURL = pair[1]; - postType = pair[0].split("::")[1]; - }else if(feat.equals("return-0")){ - nextStepStatus = "return-0"; - }else if(feat.equals("activate")){ - nextStepStatus = "activate"; - }else if(feat.equals("activate:after")){ - nextStepStatus = "activate:after"; - } - } - - - data.put("nextStepStatus", statusMap.get(nextStepStatus)); - //添加post参数 - data.put("doPost", doPost); - data.put("postURL", postURL); - data.put("postType", postType); - - //添加回答 - data.put("reply", reply); - - //添加config类别id - data.put("categoryId", 0); - - //添加辅助优先级 - data.put("auxiliaryPriority", auxiliaryPriority); - - //添加更新答案处的信息 - JSONArray knowledgeList = new JSONArray(); - if (!updateKnowledge.equals("")) { - for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge, conditionDescription); - } - } - data.put("updateKnowledge", knowledgeList); - - //添加下一步 - JSONArray nextStepList = new JSONArray(); - for (String next : nextStep.split(",")) { - appendJNextStep(nextStepList, next, conditionDescription); - } - data.put("nextStepList", nextStepList); - - return data; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - - sb.append(curPremise).append("|"); - sb.append(hisPremise); - sb.append("|").append(feature).append(","); - sb.append(updateKnowledge).append(","); - sb.append(nextStepStatus).append( "|"); - sb.append("auxiliaryPriority="); - sb.append(auxiliaryPriority).append("|").append("configName="); - sb.append(configName); - sb.append("|=>|").append(reply); - sb.append("|").append("nextStep="); - sb.append(nextStep).append("|"); - sb.append("status=").append(status); - sb.append("|").append("configId="); - - return sb.toString(); - } - - public Object clone() { - Object o=null; - try{ - o= super.clone(); - }catch(CloneNotSupportedException e){ - System.out.println(e.toString()); - } - return o; - } - - - public static void activateCopy(ConfigTerm configTerm, List configTermList, String name){ - - configTerm.setReply(configTerm.getReply() + "{临时变量reply-2}"); - - - ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); - - if(configTerm2.getUpdateKnowledge().equals("")) - configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); - else - configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - configTerm2.setConfigName(name, true); - - configTermList.add(configTerm2); - - } - - - public ConfigTerm simpleCopy(ConfigTerm configTerm){ - - ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); - - return configTerm2; - } -} diff --git a/src/entity/ConfigTermText.java b/src/entity/ConfigTermText.java deleted file mode 100644 index 2a2dfa2..0000000 --- a/src/entity/ConfigTermText.java +++ /dev/null @@ -1,528 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class ConfigTermText implements Cloneable{ - - public static ThreadLocal iterNum=new ThreadLocal() { - protected Integer initialValue() { - return 0; - } - }; - - - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - - - private String curPremise = ""; - private String hisPremise = ""; - private String feature = ""; - private String reply = ""; - private String nextStep = ""; - private String updateKnowledge = ""; - private String nextStepStatus = "return"; - private String configName = ""; - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - public String getFeature() { - return feature; - } - - public void setFeature(String feature) { - this.feature = feature; - } - - public String getCurPremise() { - return curPremise; - } - - public String getNextStep() { - return nextStep; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName, Boolean append) { - - if(append) { - - iterNum.set(iterNum.get() + 1); - - System.out.println("iterNum:" + iterNum.get()); - //iterNum++; - this.configName = configName + "_" + iterNum.get(); - }else{ - this.configName = configName; - } - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - - public void setCurPremise(String curPremise) { - this.curPremise = curPremise; - } - - public String getHisPremise() { - return hisPremise; - } - - public void setHisPremise(String hisPremise) { - this.hisPremise = hisPremise; - } - - public String getReply() { - return reply; - } - - public void setReply(String reply) { - this.reply = reply; - } - - public String getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public String getStatus() { - return status; - } - - public String getNextStepStatus() { - return nextStepStatus; - } - - public String getUpdateKnowledge() { - return updateKnowledge; - } - - public void setUpdateKnowledge(String updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - - static Map statusMap = new HashMap() { - { - put("return", "return"); - put("return-1", "back"); - put("return-0", "stay"); - put("activate", "activate"); - put("activate:after", "activate:after"); - } - }; - - public void setStatus(String status) { - this.status = status; - } - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public void setNextStepStatus(String nextStepStatus) { - this.nextStepStatus = nextStepStatus; - } - - public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - if (!updateKnowledge.equals("")) - this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); - //if (!updateKnowledge.equals("")) - // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - - public ConfigTermText(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { - this.curPremise = appendPremiseStr(curPremise, extraCP); - this.hisPremise = appendPremiseStr(hisPremise, extraHP); - this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; - this.auxiliaryPriority = auxiliaryPriority; - } - - public String appendPremiseStr(List premises, String extraPremise) { - StringBuffer sb = new StringBuffer(); - String premiseStr = "", conditionName; - Map nameCount = new HashMap(); - - for (Premise premise : premises){ - //设置初始值 - //System.out.println("nameCount" + nameCount); - conditionName = premise.getConditionName(); - - nameCount.putIfAbsent(conditionName, 0); - - //nameCount加一 - nameCount.put(conditionName, nameCount.get(conditionName) + 1); - - //在conditionName后添加count - if(nameCount.get(conditionName) > 1) { - premise.setConditionName(conditionName + nameCount.get(conditionName)); - } - - - - sb.append(","); - sb.append(premise.getConditionName()); - sb.append("::"); - sb.append(premise.getCmpType()); - sb.append("-"); - sb.append(premise.getOperator()); - sb.append("="); - sb.append(premise.getKeyword()); - } - if (sb.length() > 0) - sb.deleteCharAt(0); //删除第一个逗号 - - - if (!extraPremise.equals("")) { - if (sb.length() == 0) - sb.append(extraPremise); - else - sb.append("," + extraPremise); - } else if (sb.length() == 0) { - sb.append(" "); - } - premiseStr = sb.toString(); - - return premiseStr; - } - - public String appendKnowledgeStr(Map knowledge, String extraKL) { - StringBuffer sb = new StringBuffer(); - String varName = "", varValue = "", knowledgeStr; - Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 - String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; - - while (iit.hasNext()) { - varName = iit.next(); - varValue = knowledge.get(varName); - - if(varValue.startsWith("updateFollowerLocation")){ - delayUpdateFollowerLocation = true; - delayUpdateFollowerLocationKey = varName; - delayUpdateFollowerLocationValue = varValue; - continue; - } - sb.append("-<-").append(varName).append(":").append(varValue); - - } - if (!extraKL.equals("")) { - sb.append("-<-" + extraKL); - } - - if(delayUpdateFollowerLocation){ - sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); - } - - if (sb.length() > 0) - knowledgeStr = "updateKnowledge" + sb.toString(); - else - knowledgeStr = ""; - - return knowledgeStr; - } - - - public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { - //System.out.println(premise); - - String pair1[] = premise.split("=", 2); - String key = pair1[0]; - - String keywords = pair1[1]; - String pair2[] = key.split("::"); - String conditionName = pair2[0]; - String pair3[] = pair2[1].split("-"); - String cmpType = pair3[0]; - String operator = ""; - if (pair3.length > 1) - operator = pair3[1]; - - String question = ""; - if (conditionDescription.get(conditionName) != null) - question = conditionDescription.get(conditionName); - - JSONObject premiseJ = new JSONObject(); - premiseJ.put("keywords", keywords); - premiseJ.put("actionName", conditionName); - premiseJ.put("cmpType", cmpType); - premiseJ.put("question", question); - premiseJ.put("operator", operator); - - premiseList.add(premiseJ); - - } - - public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { - String pair[] = knowledge.split(":", 2); - - if (knowledge.equals("") || pair.length < 2) - return; - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - JSONObject knowledgeJ = new JSONObject(); - knowledgeJ.put("variableName", pair[0]); - knowledgeJ.put("keyword", pair[1]); - - knowledgeList.add(knowledgeJ); - } - - public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { - String pair[] = next.split("-"); - JSONObject nextStepJ = new JSONObject(); - JSONArray exceptJ = new JSONArray(); - - for (int i = 1; i < pair.length; i++) - exceptJ.add(pair[i]); - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - nextStepJ.put("nextStep", pair[0]); - nextStepJ.put("except", exceptJ); - nextStepJ.put("nextStepText", question); - nextStepList.add(nextStepJ); - } - - public JSONObject toJson(Map conditionDescription) { - JSONObject data = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - JSONArray hisPremiseList = new JSONArray(); - - //添加当前对话内容 - for (String premise : curPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise, conditionDescription); - } - data.put("currentPremiseList", curPremiseList); - - //添加已知信息的内容 - for (String premise : hisPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise, conditionDescription); - } - data.put("historyPremiseList", hisPremiseList); - - //添加下一步状态 - - - //添加configName - data.put("configName", configName); - - //添加config状态 - data.put("configStatus", jStatus); - - - boolean doPost = false; - String postURL = "", postType = "all", pair[]; - - for (String feat : feature.split(",")) { - if (feat.startsWith("post")) { - doPost = true; - pair = feat.substring(0, feat.length() - 1).split("\\(", 2); - postURL = pair[1]; - postType = pair[0].split("::")[1]; - }else if(feat.equals("return-0")){ - nextStepStatus = "return-0"; - }else if(feat.equals("activate")){ - nextStepStatus = "activate"; - }else if(feat.equals("activate:after")){ - nextStepStatus = "activate:after"; - } - } - - - data.put("nextStepStatus", statusMap.get(nextStepStatus)); - //添加post参数 - data.put("doPost", doPost); - data.put("postURL", postURL); - data.put("postType", postType); - - //添加回答 - data.put("reply", reply); - - //添加config类别id - data.put("categoryId", 0); - - //添加辅助优先级 - data.put("auxiliaryPriority", auxiliaryPriority); - - //添加更新答案处的信息 - JSONArray knowledgeList = new JSONArray(); - if (!updateKnowledge.equals("")) { - for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge, conditionDescription); - } - } - data.put("updateKnowledge", knowledgeList); - - //添加下一步 - JSONArray nextStepList = new JSONArray(); - for (String next : nextStep.split(",")) { - appendJNextStep(nextStepList, next, conditionDescription); - } - data.put("nextStepList", nextStepList); - - return data; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - - sb.append(curPremise).append("|"); - sb.append(hisPremise); - sb.append("|").append(feature).append(","); - sb.append(updateKnowledge).append(","); - sb.append(nextStepStatus).append( "|"); - sb.append("auxiliaryPriority="); - sb.append(auxiliaryPriority).append("|").append("configName="); - sb.append(configName); - sb.append("|=>|").append(reply); - sb.append("|").append("nextStep="); - sb.append(nextStep).append("|"); - sb.append("status=").append(status); - sb.append("|").append("configId="); - - return sb.toString(); - } - - public Object clone() { - Object o=null; - try{ - o= super.clone(); - }catch(CloneNotSupportedException e){ - System.out.println(e.toString()); - } - return o; - } - - - public static void activateCopy(ConfigTermText configTermText, List configTermTextList, String name){ - - configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}"); - - - ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone(); - - if(configTermText2.getUpdateKnowledge().equals("")) - configTermText2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); - else - configTermText2.setUpdateKnowledge(configTermText2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - configTermText2.setConfigName(name, true); - - configTermTextList.add(configTermText2); - - } - - - public ConfigTermText simpleCopy(ConfigTermText configTermText){ - - ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone(); - - return configTermText2; - } -} diff --git a/src/entity/ConfigurationItem.java b/src/entity/ConfigurationItem.java deleted file mode 100644 index be8bdb6..0000000 --- a/src/entity/ConfigurationItem.java +++ /dev/null @@ -1,5 +0,0 @@ -package entity; - -public class ConfigurationItem { - -} diff --git a/src/entity/Goods.java b/src/entity/Goods.java deleted file mode 100644 index 8a36aa2..0000000 --- a/src/entity/Goods.java +++ /dev/null @@ -1,4 +0,0 @@ -package entity; - -public class Goods { -} diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java deleted file mode 100644 index be49382..0000000 --- a/src/entity/JConfig.java +++ /dev/null @@ -1,495 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class JConfig implements Cloneable{ - - static int iterNum = 0; - - private int id = 0; - private String jCurPremise = ""; - private String jHisPremise = ""; - private String jFeature = ""; - - - private String jNextStep = ""; - private String jReply = ""; - private String jAuxiliaryPriority = "0"; - private int jStatus = 0; - - - private String curPremise = ""; - private String hisPremise = ""; - private String feature = ""; - private String reply = ""; - private String nextStep = ""; - private String updateKnowledge = ""; - private String nextStepStatus = "return"; - private String configName = ""; - private String auxiliaryPriority = "1"; - private String status = "waiting"; - - - public void setjStatus(int jStatus) { - this.jStatus = jStatus; - } - public String getFeature() { - return feature; - } - - public void setFeature(String feature) { - this.feature = feature; - } - - public String getCurPremise() { - return curPremise; - } - - public String getNextStep() { - return nextStep; - } - - public void setNextStep(String nextStep) { - this.nextStep = nextStep; - } - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName, Boolean append) { - - if(append) { - iterNum++; - this.configName = configName + iterNum; - }else{ - this.configName = configName; - } - } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - - public String getjCurPremise() { - return jCurPremise; - } - - public void setjCurPremise(String jCurPremise) { - this.jCurPremise = jCurPremise; - } - - public String getjHisPremise() { - return jHisPremise; - } - - public void setjHisPremise(String jHisPremise) { - this.jHisPremise = jHisPremise; - } - - public String getjFeature() { - return jFeature; - } - - public void setjFeature(String jFeature) { - this.jFeature = jFeature; - } - - public String getjNextStep() { - return jNextStep; - } - - public void setjNextStep(String jNextStep) { - this.jNextStep = jNextStep; - } - - public String getjReply() { - return jReply; - } - - public void setjReply(String jReply) { - this.jReply = jReply; - } - - public String getjAuxiliaryPriority() { - return jAuxiliaryPriority; - } - - public void setjAuxiliaryPriority(String jAuxiliaryPriority) { - this.jAuxiliaryPriority = jAuxiliaryPriority; - } - - public int getjStatus() { - return jStatus; - } - - public void setCurPremise(String curPremise) { - this.curPremise = curPremise; - } - - public String getHisPremise() { - return hisPremise; - } - - public void setHisPremise(String hisPremise) { - this.hisPremise = hisPremise; - } - - public String getReply() { - return reply; - } - - public void setReply(String reply) { - this.reply = reply; - } - - public String getAuxiliaryPriority() { - return auxiliaryPriority; - } - - public String getStatus() { - return status; - } - - public String getNextStepStatus() { - return nextStepStatus; - } - - public String getUpdateKnowledge() { - return updateKnowledge; - } - - public void setUpdateKnowledge(String updateKnowledge) { - this.updateKnowledge = updateKnowledge; - } - - - static Map statusMap = new HashMap() { - { - put("return", "return"); - put("return-1", "back"); - put("return-0", "stay"); - put("activate", "activate"); - put("activate:after", "activate:after"); - } - }; - - public void setStatus(String status) { - this.status = status; - } - public void setAuxiliaryPriority(String auxiliaryPriority) { - this.auxiliaryPriority = auxiliaryPriority; - } - - public void setNextStepStatus(String nextStepStatus) { - this.nextStepStatus = nextStepStatus; - } - - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - if (!updateKnowledge.equals("")) - this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { - this.curPremise = curPremise; - this.hisPremise = hisPremise; - this.feature = feature; - this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); - //if (!updateKnowledge.equals("")) - // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; - - this.reply = reply; - this.nextStep = nextStep; - } - - - public JConfig(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { - this.curPremise = appendPremiseStr(curPremise, extraCP); - this.hisPremise = appendPremiseStr(hisPremise, extraHP); - this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); - this.feature = feature; - this.reply = reply; - this.nextStep = nextStep; - this.auxiliaryPriority = auxiliaryPriority; - } - - public String appendPremiseStr(List premises, String extraPM) { - StringBuffer sb = new StringBuffer(); - String premiseStr = ""; - - for (String premise : premises) - sb.append("," + premise); - if (sb.length() > 0) - sb.deleteCharAt(0); //删除第一个逗号 - - - if (!extraPM.equals("")) { - if (sb.length() == 0) - sb.append(extraPM); - else - sb.append("," + extraPM); - } else if (sb.length() == 0) { - sb.append(" "); - } - premiseStr = sb.toString(); - - return premiseStr; - } - - public String appendKnowledgeStr(Map knowledge, String extraKL) { - StringBuffer sb = new StringBuffer(); - String varName = "", varValue = "", knowledgeStr; - Iterator iit = knowledge.keySet().iterator(); - Boolean delayUpdateFollowerLocation = false; - String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; - - while (iit.hasNext()) { - varName = iit.next(); - varValue = knowledge.get(varName); - - if(varValue.startsWith("updateFollowerLocation")){ - delayUpdateFollowerLocation = true; - delayUpdateFollowerLocationKey = varName; - delayUpdateFollowerLocationValue = varValue; - continue; - } - sb.append("-<-").append(varName).append(":").append(varValue); - - } - if (!extraKL.equals("")) { - sb.append("-<-" + extraKL); - } - - if(delayUpdateFollowerLocation){ - sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); - } - - if (sb.length() > 0) - knowledgeStr = "updateKnowledge" + sb.toString(); - else - knowledgeStr = ""; - - return knowledgeStr; - } - - - public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { - //System.out.println(premise); - - String pair1[] = premise.split("=", 2); - String key = pair1[0]; - - String keywords = pair1[1]; - String pair2[] = key.split("::"); - String conditionName = pair2[0]; - String pair3[] = pair2[1].split("-"); - String cmpType = pair3[0]; - String operator = ""; - if (pair3.length > 1) - operator = pair3[1]; - - String question = ""; - if (conditionDescription.get(conditionName) != null) - question = conditionDescription.get(conditionName); - - JSONObject premiseJ = new JSONObject(); - premiseJ.put("keywords", keywords); - premiseJ.put("actionName", conditionName); - premiseJ.put("cmpType", cmpType); - premiseJ.put("question", question); - premiseJ.put("operator", operator); - - premiseList.add(premiseJ); - - } - - public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { - String pair[] = knowledge.split(":", 2); - - if (knowledge.equals("") || pair.length < 2) - return; - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - JSONObject knowledgeJ = new JSONObject(); - knowledgeJ.put("variableName", pair[0]); - knowledgeJ.put("keyword", pair[1]); - - knowledgeList.add(knowledgeJ); - } - - public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { - String pair[] = next.split("-"); - JSONObject nextStepJ = new JSONObject(); - JSONArray exceptJ = new JSONArray(); - - for (int i = 1; i < pair.length; i++) - exceptJ.add(pair[i]); - - String question = ""; - if (conditionDescription.get(pair[0]) != null) - question = conditionDescription.get(pair[0]); - - nextStepJ.put("nextStep", pair[0]); - nextStepJ.put("except", exceptJ); - nextStepJ.put("nextStepText", question); - nextStepList.add(nextStepJ); - } - - public JSONObject toJson(Map conditionDescription) { - JSONObject data = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - JSONArray hisPremiseList = new JSONArray(); - - //添加当前对话内容 - for (String premise : curPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(curPremiseList, premise, conditionDescription); - } - data.put("currentPremiseList", curPremiseList); - - //添加已知信息的内容 - for (String premise : hisPremise.split(",")) { - if (!premise.equals("") && !premise.equals(" ")) - appendJPremise(hisPremiseList, premise, conditionDescription); - } - data.put("historyPremiseList", hisPremiseList); - - //添加下一步状态 - - - //添加configName - data.put("configName", configName); - - //添加config状态 - data.put("configStatus", jStatus); - - - boolean doPost = false; - String postURL = "", postType = "all", pair[]; - - for (String feat : feature.split(",")) { - if (feat.startsWith("post")) { - doPost = true; - pair = feat.substring(0, feat.length() - 1).split("\\(", 2); - postURL = pair[1]; - postType = pair[0].split("::")[1]; - }else if(feat.equals("return-0")){ - nextStepStatus = "return-0"; - }else if(feat.equals("activate")){ - nextStepStatus = "activate"; - }else if(feat.equals("activate:after")){ - nextStepStatus = "activate:after"; - } - } - - - data.put("nextStepStatus", statusMap.get(nextStepStatus)); - //添加post参数 - data.put("doPost", doPost); - data.put("postURL", postURL); - data.put("postType", postType); - - //添加回答 - data.put("reply", reply); - - //添加config类别id - data.put("categoryId", 0); - - //添加辅助优先级 - data.put("auxiliaryPriority", auxiliaryPriority); - - //添加更新答案处的信息 - JSONArray knowledgeList = new JSONArray(); - if (!updateKnowledge.equals("")) { - for (String knowledge : updateKnowledge.split("-<-")) { - appendJKnowledge(knowledgeList, knowledge, conditionDescription); - } - } - data.put("updateKnowledge", knowledgeList); - - //添加下一步 - JSONArray nextStepList = new JSONArray(); - for (String next : nextStep.split(",")) { - appendJNextStep(nextStepList, next, conditionDescription); - } - data.put("nextStepList", nextStepList); - - return data; - } - - public String toString() { - - String text = curPremise + "|" + - hisPremise + "|" + - feature + "," + updateKnowledge + "," + nextStepStatus + "|" + - "auxiliaryPriority=" + auxiliaryPriority + "|" + - "configName=" + configName + "|=>|" + - reply + "|" + - "nextStep=" + nextStep + "|" + - "status=" + status + "|" + - "configId="; - - return text; - } - - public Object clone() { - Object o=null; - try{ - o= super.clone(); - }catch(CloneNotSupportedException e){ - System.out.println(e.toString()); - } - return o; - } - - - public static void activateCopy(JConfig jConfig, List jConfigList, String name){ - - jConfig.setReply(jConfig.getReply() + "{临时变量reply-2}"); - - - JConfig jConfig2 = (JConfig) jConfig.clone(); -// if(jConfig.getHisPremise().equals(" ")) -// jConfig.setHisPremise("临时变量condition::match-Include=+null"); -// else -// jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); -// jConfig.setConfigName(name, true); - - if(jConfig2.getUpdateKnowledge().equals("")) - jConfig2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); - else - jConfig2.setUpdateKnowledge(jConfig2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - jConfig2.setConfigName(name, true); - - - //jConfigList.add(jConfig); - jConfigList.add(jConfig2); - - } - - - public static JConfig simpleCopy(JConfig jConfig){ - - JConfig jConfig2 = (JConfig) jConfig.clone(); - - return jConfig2; - } -} diff --git a/src/entity/Npc.java b/src/entity/Npc.java deleted file mode 100644 index dda10d9..0000000 --- a/src/entity/Npc.java +++ /dev/null @@ -1,4 +0,0 @@ -package entity; - -public class Npc { -} diff --git a/src/entity/Premise.java b/src/entity/Premise.java deleted file mode 100644 index f15c76e..0000000 --- a/src/entity/Premise.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -public class Premise { - private String conditionName = ""; - private String cmpType = ""; - private String operator = ""; - private String keyword = ""; - - public Premise(String conditionName, String cmpType, String operator, String keyword) { - this.conditionName = conditionName; - this.cmpType = cmpType; - this.operator = operator; - this.keyword = keyword; - } - - public String getConditionName() { - return conditionName; - } - - public void setConditionName(String conditionName) { - this.conditionName = conditionName; - } - - public String getCmpType() { - return cmpType; - } - - public void setCmpType(String cmpType) { - this.cmpType = cmpType; - } - - public String getOperator() { - return operator; - } - - public void setOperator(String operator) { - this.operator = operator; - } - - public String getKeyword() { - return keyword; - } - - public void setKeyword(String keyword) { - this.keyword = keyword; - } -} diff --git a/src/entity/QuestionKeyWord.java b/src/entity/QuestionKeyWord.java deleted file mode 100644 index c1b9ca6..0000000 --- a/src/entity/QuestionKeyWord.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - - -/** - * 暂时没用 - */ -public class QuestionKeyWord { - private String actionName; - private String chatKey; - private String keyWord; - - public String getActionName() { - return actionName; - } - - public String getChatKey() { - return chatKey; - } - - public String getKeyWord() { - return keyWord; - } - - public void setActionName(String actionName) { - this.actionName = actionName; - } - - public void setChatKey(String chatKey) { - this.chatKey = chatKey; - } - - public void setKeyWord(String keyWord) { - this.keyWord = keyWord; - } -} diff --git a/src/entity/Solution.java b/src/entity/Solution.java deleted file mode 100644 index 3435ea3..0000000 --- a/src/entity/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - - -/** - * 包含后台返回数据的实体类。 - */ -public class Solution { - private int status = 0; - private String answer; - private String next; - - public String getAnswer() { - return answer; - } - - public int getStatus() { - return status; - } - - - public void setAnswer(String answer) { - this.answer = answer; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - public Solution(int status, String answers, String next) { - this.answer = answers; - this.next = next; - this.status = status; - } - - public Solution() { - } -} diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java deleted file mode 100644 index cfe6ada..0000000 --- a/src/entity/UserInfo.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.qiwu.chatbotbackend.entity; - -import java.util.HashMap; -import java.util.List; - -/** - * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 - */ -public class UserInfo { - public UserInfo(String botAccount) { - this.conditionTable = new HashMap>(); - this.configStr = ""; - this.botAccount = botAccount; - this.extraInfo = new HashMap() { - { - put("activeAction", " "); - } - }; - this.id2config = new HashMap(); - this.id2condition = new HashMap(); - this.varInitialMap = new HashMap(); - this.name2condition = new HashMap(); - } - - public HashMap> conditionTable; - public String configStr; - public String botAccount; - public HashMap extraInfo; - public HashMap id2config; - public HashMap id2condition; - public HashMap name2condition; - //存储需要初始化的变量 - public HashMap varInitialMap; - - -} diff --git a/src/entity/World.java b/src/entity/World.java deleted file mode 100644 index a4e8059..0000000 --- a/src/entity/World.java +++ /dev/null @@ -1,36 +0,0 @@ -package entity; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class World { - - public List queryAroundAllBySite(String site){ return new ArrayList<>();}; // 返回所有模块下的实例名称列表 - public List queryAroundNpcBySite(String site){ return new ArrayList<>();}; // 返回npcname 字符串列表 - public List queryAroundGoodsBySite(String site){ return new ArrayList<>();}; // 返回goodsname 字符串列表 - public List queryCanGoBySite(String site){ return new ArrayList<>();}; //地点名称的列表 - public List queryPathBySite(String start, String destination){ return new ArrayList<>();}; // 返回一条,地点名称的列表 - - - public boolean addGoodsBase(String categoryName, String instanceName, String goodsIntro){ return true;};; // 添加成功为 true,否则false - public boolean deleteGoods(String categoryName, String instanceName){ return true;};; // 删除成功为 true,否则false - public boolean updateGoodsBase(String categoryName, String instanceName, String goodsIntro){ return true;};; // 更新成功为 true,否则false - public String queryGoodsIntro(String name, String site){ return "";};; // 返回一个物品简介 - public String queryAttrByGoodsName(String name, String attrName, String site){ return "";}; // - public List queryAllAttrByGoodsName(String name, String site){ return new ArrayList<>();}; // 获得所有属性名称列表 - public boolean updateAttrByGoodsName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 更新成功为 true,否则false - public boolean addAttrByGoodsName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 添加成功为 true,否则false - public boolean deleteAttrByGoodsName(String categoryName, String instanceName, String attrName){ return true;}; // 删除成功为 true,否则false - - - public boolean addNpc(String categoryName, String instanceName, String npcIntro){ return true;}; // 添加成功为 true,否则false - public boolean deleteNpc(String categoryName, String instanceName){ return true;}; // 删除成功为 true,否则false - public boolean updateNpc(String categoryName, String instanceName, String npcIntro){ return true;}; // 更新成功为 true,否则false - public String queryNpcIntro(String categoryName, String instanceName){ return "";}; // 返回一个npc简介 - public String queryAttrByNPCName(String categoryName, String instanceName, String attrName){ return "沙滩";}; // 返回npc属性值 - public boolean updateLocationByNPCName(String categoryName, String instanceName, String attrName, String value){ return true;}; // 更新成功为 true,否则false - public boolean addAttrByNPCName(String categoryName, String instanceName, String attrName,String value){ return true;}; // 添加成功为 true,否则false - public boolean deleteAttrByNPCName(String categoryName, String instanceName, String attrName){ return true;}; // 删除成功为 true,否则false - -} diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java deleted file mode 100644 index 178b608..0000000 --- a/src/gameDesign/CharacterConstructor.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -public class CharacterConstructor extends ElementConstructor { - - public CharacterConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject gameElements, UserInfo userinfo) { - String category, name, className, description, attrValue,botName = (String)gameElements.get("botName"); - - try { - - //FIND_NPC_LOCATION - String pattern; - StringBuffer onlineModeTalkers = new StringBuffer(","); - - - JSONArray allNPC = gameElements.getJSONArray("npc"); - Map attribute = null; - HashSet classSet = new HashSet(); - List replaceList = new ArrayList(); - - - - copyPattern("HOW_FIND_NPC"); - copyPattern("NPC_LOCATION"); - copyPattern("AOURND_NPC_CLASS"); - copyPattern("NPC_ATTR"); - copyPattern("WHO_YOU_ARE"); - - - - - - for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { - replaceList.clear(); - - - name = character.getString("name"); - - replaceList.add(new String[]{"name", name}); - - - - //找到所有处于离线模式的npc - if(character.getBoolean("offline")!= null && !character.getBoolean("offline")){ - onlineModeTalkers.append(name).append(","); - } - List nameList = new ArrayList(); - nameList.add(name); - - //添加词性 - className = (String) character.get("class"); - appendPOS(POS, name, "人名"); - appendPOS(POS, className, "人名"); - - - appendReplacedKeyword("NPC_LOCATION", replaceList); - appendReplacedKeyword("HOW_FIND_NPC", replaceList); - - //添加别名 - if(character.containsKey("nickname")){ - for(String nickname:JSONArray.parseArray(character.getJSONArray("nickname").toJSONString(), String.class)){ - if(!nickname.equals("")) { - appendPOS(POS, nickname, "人名"); - nameList.add(nickname); - - replaceList.get(0)[1] = nickname; - appendReplacedKeyword("NPC_LOCATION", replaceList); - appendReplacedKeyword("HOW_FIND_NPC", replaceList); - } - } - } - - - - //添加类名称 - if (!classSet.contains(className)) { - classSet.add(className); - //替换后的名字改为类名 - replaceList.get(0)[1] = className; - appendReplacedKeyword("AOURND_NPC_CLASS", replaceList); - - } - - - attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); - - //替换后的名字改为npc名 - replaceList.get(0)[1] = name; - replaceList.add(new String[]{"attrName", ""}); - - for(String attrName:attribute.keySet()){ - - replaceList.get(1)[1] = attrName; - - appendPOS(POS, attrName, "名词"); - - for(String NPCName:nameList) { - appendReplacedKeyword("NPC_ATTR", replaceList); - } - - } - - } - - replaceList.add(new String[]{"botName", botName}); - appendReplacedKeyword("WHO_YOU_ARE", replaceList); - - - keywordMap.put("onlineModeTalkers", onlineModeTalkers); - varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); - conditionDescription.put("onlineModeTalkers", "所有在线npc"); - - - - //同时识别zainali和wenzainali - configTermText = new ConfigTermText( - "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," + - "wenzainali::match-Keyword=" + keywordMap.get("NPC_LOCATION_wenzainali").toString(), " ", - "match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:wenzainali" - ); - ConfigTermText.activateCopy(configTermText, configTermTextList, "npc"); - - //根据根据NPC的名字查询地点 - queryTypeConfigTermGenerate(keywordMap, "NPC_LOCATION", "npc", "queryLocationByConditionName"); - - //根据根据NPC名字和属性查询属性值 - queryTypeConfigTermGenerate(keywordMap, "NPC_ATTR", "npc", "queryAttrByNPCName"); - - //根据根据NPC类别和地点属性查询所有NPC实例 - - queryTypeConfigTermGenerate(keywordMap, "AOURND_NPC_CLASS", "npc", "queryAroundNpcByClassName"); - - - //根据类名查询周围所有实例 - - queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_NPC", "npc", "queryFindNPCWay"); - - //查询说话的人 - //WHO_YOU_ARE - queryTypeConfigTermGenerate(keywordMap, "WHO_YOU_ARE", "npc", "queryLastTalker"); - - }catch (Exception e){ - operationStatus = 0; - message = "NPC接口处理出现异常"; - e.printStackTrace(); - return; - } - - - } - - -} diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java deleted file mode 100644 index 753f4b3..0000000 --- a/src/gameDesign/ElementConstructor.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -public class ElementConstructor { - - - int botId = 0; - - - - int operationStatus = 1; - Map keywordMap = null; - SqlHelper helper = null; - HashSet exceptRelation = null; - ConfigTermText configTermText = null; - String botAccount; - - - - String message = ""; - - - List configDataList = new ArrayList(); - List configTermTextList = new ArrayList(); - StringBuffer configText = new StringBuffer(); - Map varInitialMap = new HashMap(); - Map conditionDescription = new HashMap(); - StringBuffer POS = new StringBuffer(); - - - public String getMessage() { return message; } - - public int getOperationStatus() { return operationStatus; } - - public Map getVarInitialMap() { - return varInitialMap; - } - - public void construct(JSONObject gameElements, UserInfo userinfo) { } - - public List getConfigTermTextList() { - return configTermTextList; - } - - public Map getConditionDescription() { - return conditionDescription; - } - - public List getConfigDataList() { - return configDataList; - } - - public void ElementConstructor(String userName) { - this.botAccount = botAccount; - } - - public String getConfigText() { - return configText.toString(); - } - - //生成完整的后台配置文件 - public void generateConfigText(List idList) { - int id, length = idList.size(); - String varValue; - ConfigTermText configTermText = null; - for (int i = 0; i < length; i++) { - configTermText = configTermTextList.get(i); - id = idList.get(i); - - configText.append(configTermText.toString() + id + "\n"); - } - - //变量 - for (String varName : varInitialMap.keySet()) { - varValue = varInitialMap.get(varName); - configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); - } - - } - - - /** - * 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition - * @param config - * @param relationKeywords - * @param exceptRelation - * @param botName - */ - public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation, String botName){ - String conditionName, pair[]; - for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ - conditionName = (String) premise.get("actionName"); - - - - if(!exceptRelation.contains(conditionName)) { - - //初始化 - if(!relationKeywords.containsKey(conditionName + "_head")) { - relationKeywords.put(conditionName + "_head", new HashSet()); - relationKeywords.put(conditionName + "_tail", new HashSet()); - } - - //visitorname和bot的替换 - premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); - - for (String keyword : ((String) premise.get("keywords")).split("\\+")) { - - if(keyword.equals("")){ - continue; - - - } else if(keyword.contains(":")){ - //有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域 - pair = keyword.split(":",2); - - if(pair[1].equals("")) - continue; - - - relationKeywords.get(conditionName + "_head").add(pair[0]); - relationKeywords.get(conditionName + "_tail").add(pair[1]); - - } else { - relationKeywords.get(conditionName + "_tail").add(keyword); - } - - } - } - - } - for(Map premise:JSONArray.parseArray(config.getJSONArray("historyPremiseList").toJSONString(), Map.class)){ - conditionName = (String) premise.get("actionName"); - - if(conditionName.startsWith("npc_") || conditionName.startsWith("goods_")) - continue; - - - - if(!exceptRelation.contains(conditionName)) { - - - if(!relationKeywords.containsKey(conditionName + "_head")) { - relationKeywords.put(conditionName + "_head", new HashSet()); - relationKeywords.put(conditionName + "_tail", new HashSet()); - } - - premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); - - for (String keyword : ((String) premise.get("keywords")).split("\\+")) { - - if(keyword.equals("")){ - continue; - - - } else if(keyword.contains(":")){ - pair = keyword.split(":",2); - - if(pair[1].equals("")) - continue; - - - relationKeywords.get(conditionName + "_head").add(pair[0]); - relationKeywords.get(conditionName + "_tail").add(pair[1]); - - } else { - relationKeywords.get(conditionName + "_tail").add(keyword); - } - } - } - } - } - - - /** - * 根据插入的数据做后处理 - * @param idList - */ - public void postProcessing(List idList, int categoryId){} - - /** - * 构造参数配置文件的json版 - */ - public void buildJconfig() { - - } - - - public void appendPOS(StringBuffer POS, String name, String tag){ - if(!name.equals("")) { - POS.append("="); - POS.append(name); - POS.append("|"); - POS.append(tag); - POS.append("\n"); - } - } - - - public void queryTypeConfigTermGenerate(Map keywordMap, String intent, String module, String queryMethod){ - - String conditionKeywords = ""; - String conditionNameList[] = keywordMap.get(intent).toString().split(","); - for (String conditionName : conditionNameList) { - conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString(); - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", - "", - " ", - module + "_query:" + queryMethod + ":" + conditionName - ); - //ConfigTermText.activateCopy(configTermText, configTermTextList, module); - - - //查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面 - configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}"); - - - configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); - configTermText.setConfigName(module, true); - - configTermTextList.add(configTermText); - } - } - - /** - * 将condition的关键词复制一份,然后清空原来关键词 - * @param intent - */ - public void copyPattern(String intent){ - for(String conditionName:keywordMap.get(intent).toString().split(",")){ - keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName))); - keywordMap.get(intent + "_" + conditionName).setLength(0); - } - } - - - public void appendReplacedKeyword(String intent, List replaceList){ - String pattern, replaceText; - for(String conditionName:keywordMap.get(intent).toString().split(",")){ - pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString(); - for(String[] replacePair: replaceList){ - pattern = pattern.replace(replacePair[0], replacePair[1]); - } - keywordMap.get(intent + "_" + conditionName).append(pattern); - } - - - } - -} diff --git a/src/gameDesign/Floyd.java b/src/gameDesign/Floyd.java deleted file mode 100644 index b28d28d..0000000 --- a/src/gameDesign/Floyd.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -/** - * 弗洛伊德算法,用于构造地图时求最短路径 - */ -public class Floyd { - - - /** - * 表示正无穷 - */ - int MAX_WEIGHT = Integer.MAX_VALUE; - /** - * 路径矩阵 - */ - int[][] pathMatirx; - /** - * 前驱表 - */ - int[][] preTable; - - - public void findShortestPath(int[][] matrix, int length) { - //路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。 - pathMatirx = new int[length][length]; - //前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值 - preTable = new int[length][length]; - - /* - System.out.println("matrix"); - for (int i = 0; i < length; i++){ - for(int j = 0; j < length; j++){ - System.out.print(matrix[i][j] + " "); - } - System.out.println(); - } - */ - - //初始化D,P - for (int i = 0; i < length; i++) { - for (int j = 0; j < length; j++) { - pathMatirx[i][j] = matrix[i][j]; - preTable[i][j] = j; - } - } - - //循环 中间经过顶点 - for (int k = 0; k < length; k++) { - //循环所有路径 - for (int m = 0; m < length; m++) { - - for (int n = 0; n < length; n++) { - - int mn = pathMatirx[m][n]; - int mk = pathMatirx[m][k]; - int kn = pathMatirx[k][n]; - int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn; - - if (mn > addedPath) { - //如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个 - pathMatirx[m][n] = addedPath; - //前驱设置为经过下标为k的顶点 - preTable[m][n] = preTable[m][k]; - } - - } - } - } - - /* - System.out.println("pathMatrix"); - for (int i = 0; i < length; i++){ - for(int j = 0; j < length; j++){ - System.out.print(pathMatirx[i][j] + " "); - } - System.out.println(); - } - */ - } - - /** - * 打印 所有最短路径 - */ - public void printPath(int[][] matrix, int length) { - - - for (int m = 0; m < length; m++) { - for (int n = m + 1; n < length; n++) { - - int k = preTable[m][n]; - System.out.print("(" + m + "," + n + ")" + pathMatirx[m][n] + ": "); - System.out.print(m); - while (k != n) { - System.out.print("->" + k); - k = preTable[k][n]; - } - - System.out.println("->" + n); - } - System.out.println(); - } - - - } - -} diff --git a/src/gameDesign/GameUtil.java b/src/gameDesign/GameUtil.java deleted file mode 100644 index cb04909..0000000 --- a/src/gameDesign/GameUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.processing.LogWriter; -import com.qiwu.chatbotbackend.processing.WorldController; - -import java.util.Map; - -public class GameUtil { - - public GameEnv gameEnv = null; - public Map curInfoPoint = null; - public Map historyInfoPoint = null; - public WorldController worldController = null; - - public GameUtil(GameEnv gameEnv, WorldController worldController, Map curInfoPoint, Map historyInfoPoint) { - this.gameEnv = gameEnv; - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; - this.worldController = worldController; - } - - public void gamePreprocessing(LogWriter logWriter){ - - } - - public void gamePostprocessing(LogWriter logWriter){ - - } -} diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java deleted file mode 100644 index 07a793a..0000000 --- a/src/gameDesign/GlobalVariableConstructor.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - -import static com.qiwu.chatbotbackend.Config.Config.CC_URL; - -public class GlobalVariableConstructor extends ElementConstructor { - - public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject gameElements, UserInfo userinfo) { - - try { - String category, name, description, attrValue; - JSONObject globalVariable = gameElements.getJSONObject("globalVariable"); - Map attribute = null; - Iterator attrIter = null; - - - - - for(String attrName:globalVariable.keySet()) { - attrValue = (String)globalVariable.get(attrName); - varInitialMap.put("globalVariable_" + attrName, attrValue); - } - - - varInitialMap.put("botType", "game"); - varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); - varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); - varInitialMap.put("CC_URL", CC_URL); - - - JSONObject script = gameElements.getJSONObject("speechcraft"); - for(String key:script.keySet()){ - attrValue = (String)script.get(key); - varInitialMap.put(key, attrValue); - } - }catch (Exception e){ - operationStatus = 0; - message = "全局变量处理出现异常"; - e.printStackTrace(); - return; - } - } -} diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java deleted file mode 100644 index b5a01ba..0000000 --- a/src/gameDesign/ItemConstructor.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -public class ItemConstructor extends ElementConstructor { - - - - public ItemConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - - public void construct(JSONObject gameElements, UserInfo userinfo) { - try { - - String pattern; - String category, name, className, description, attrValue; - JSONArray goods = gameElements.getJSONArray("goods"); - Map attribute = null; - Iterator attrIter = null; - HashSet classSet = new HashSet(); - - - copyPattern("HOW_FIND_ITEM"); - copyPattern("ITEM_LOCATION"); - copyPattern("AROUND_ITEM_CLASS"); - copyPattern("ITEM_ATTR"); - - List replaceList = new ArrayList(); - - for (JSONObject good : goods.toJavaList(JSONObject.class)) { - name = (String) good.get("name"); - - replaceList.clear(); - replaceList.add(new String[]{"name", name}); - - List nameList = new ArrayList(); - nameList.add(name); - - //添加词性 - className = (String) good.get("class"); - appendPOS(POS, name, "名词"); - appendPOS(POS, className, "名词"); - - appendReplacedKeyword("ITEM_LOCATION", replaceList); - appendReplacedKeyword("HOW_FIND_ITEM", replaceList); - - if(good.containsKey("nickname")){ - for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){ - if(!nickname.equals("")) { - appendPOS(POS, nickname, "名词"); - nameList.add(nickname); - replaceList.get(0)[1] = nickname; - appendReplacedKeyword("ITEM_LOCATION", replaceList); - appendReplacedKeyword("HOW_FIND_ITEM", replaceList); - } - } - } - - //添加类名称 - if (!classSet.contains(className)) { - classSet.add(className); - replaceList.get(0)[1] = className; - appendReplacedKeyword("AROUND_ITEM_CLASS", replaceList); - } - - - attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); - - replaceList.get(0)[1] = name; - replaceList.add(new String[]{"attrName", ""}); - for(String attrName: attribute.keySet()){ - replaceList.get(1)[1] = attrName; - - appendPOS(POS, attrName, "名词"); - - -// for(String itemName:nameList) { -// for(String conditionName:keywordMap.get("ITEM_ATTR").toString().split(",")){ -// //pattern = keywordMap.get("NPC_ATTR_" + conditionName + "_pattern").toString(); -// keywordMap.get("ITEM_ATTR_" + conditionName).append("+").append(itemName).append(":").append(attrName); -// } -// } - appendReplacedKeyword("ITEM_ATTR", replaceList); - - } - } - - - configTermText = new ConfigTermText( - "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," + - "wenzainali::match-Keyword=" + keywordMap.get("ITEM_LOCATION_wenzainali").toString(), " ", - "match,return-0", "", "yaobuyao", "goods_query:queryLocationByConditionName:wenzainali" - ); - ConfigTermText.activateCopy(configTermText, configTermTextList, "item"); - - - queryTypeConfigTermGenerate(keywordMap, "ITEM_LOCATION", "goods", "queryLocationByConditionName"); - - //根据根据物品名字和属性查询属性值 - queryTypeConfigTermGenerate(keywordMap, "ITEM_ATTR", "goods", "queryAttrByGoodsName"); - - //根据类名查询周围所有实例 - queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM_CLASS", "goods", "queryAroundGoodsByClassName"); - //根据类名查询周围所有实例 - queryTypeConfigTermGenerate(keywordMap, "WHAT_ITEM_I_HAVE", "goods", "queryPlayerItems"); - - queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_ITEM", "goods", "queryFindItemWay"); - - } catch(Exception e){ - operationStatus = 0; - message = "物品处理出现异常"; - e.printStackTrace(); - return; - } - - } -} diff --git a/src/gameDesign/ListeningConstructor.java b/src/gameDesign/ListeningConstructor.java deleted file mode 100644 index 99cba08..0000000 --- a/src/gameDesign/ListeningConstructor.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.Premise; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -import static com.qiwu.chatbotbackend.Config.Config.*; - -public class ListeningConstructor extends ElementConstructor{ - - public ListeningConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - - - - } - - public static void cc(String botAccount, JSONObject gameELments, HashMap plotIndex, List configTermTextList){ - int size = 0; - String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; - String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; - Boolean autoJump = false; - List curPremiseList = new ArrayList(); - List hisPremiseList = new ArrayList(); - JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); - JSONObject plotNode = null; - - if(listeningActions == null) - return; - - size = listeningActions.size(); - JSONObject config = null; - - for(int i = 0; i < size;i++){ - plotNode = null; - autoJump = false; - priority = "2"; - feature = "match"; - config = listeningActions.getJSONObject(i); - curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), Premise.class); - hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), Premise.class); - Map updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); - nextPlotId = config.getString("nextPlotId"); - - if(nextPlotId != null){ - plotNode = plotIndex.get(nextPlotId); - } - - - if(plotNode != null){ - reply = plotNode.getString("plotText"); - nextCondition = plotNode.getString("conditionName"); - nextLocation = plotNode.getString("place"); - autoJump = plotNode.getBoolean("autoJump"); - - - if(nextCondition == null || nextCondition.equals("")){ - nextCondition = DEFAULT_CONDITION; - } - - if(autoJump){ - feature = "match,activate:after"; - updateKnowledge.put("plot_jump_text", "str+" + reply); - nextCondition = "plot_" + nextPlotId; - reply = ""; - }else{ - feature = "match"; - - } - - if(config.getString("priority") != null) - priority = config.getString("priority"); - - updateKnowledge.put(nextLocation + "_activate_by", ""); - updateKnowledge.put(nextLocation + "_activate_ready", "0"); - updateKnowledge.put("site", nextLocation); - - - nTaskLineName = String.format(TASK_LINE, nextLocation); - //任务线最后一个condition - lastTaskCondition = String.format(TASK_CONDITION, nextLocation); - lastTaskReply = String.format(TASK_REPLY, nextLocation); - nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextPlotId); - - - - updateKnowledge.put(lastTaskCondition, nextCondition); - updateKnowledge.put(lastTaskReply, reply); - updateKnowledge.put(nextPlotId, "1"); //下一步设为1 - updateKnowledge.put(nTaskLineName, nextGameStep); - updateKnowledge.put("game_step", nextGameStep); - }else{ - feature = "match,return-0"; - } - - ConfigTermText configTermText = new ConfigTermText( - curPremiseList, - hisPremiseList, - updateKnowledge, - "", "", "", feature, reply, nextCondition, priority - ); - - System.out.println("生成:" + curPremiseList.get(0)); - configTermTextList.add(configTermText); - } - } - - -} diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java deleted file mode 100644 index ab1a547..0000000 --- a/src/gameDesign/MapConstructor.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -import static com.qiwu.chatbotbackend.Config.Config.TASK_CONDITION; -import static com.qiwu.chatbotbackend.Config.Config.TASK_LINE; -import static com.qiwu.chatbotbackend.Config.Config.TASK_REPLY; - -public class MapConstructor extends ElementConstructor { - - int[][] matrix; - int locationNum; - HashMap id2j = new HashMap(); - Map question2keyword = new HashMap(); - Map> name2nickname = new HashMap>(); - JSONArray locations = null; - - Map script = null; //话术模板 - - - - public MapConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - - public void constructGreph(JSONArray locations) { - - JSONObject jobj = null; - int locationId, index; - String locationName, taskLineName = ""; - - locationNum = locations.size(); - StringBuffer nameSet = null; - keywordMap.putIfAbsent("site_list", new StringBuffer()); - - for (int i = 0; i < locationNum; i++) { - jobj = locations.getJSONObject(i); - jobj.put("index", i); - locationName = (String) jobj.get("name"); - keywordMap.get("site_list").append("+").append(locationName); - - - taskLineName = String.format(TASK_LINE, locationName); - - - if (!varInitialMap.containsKey(taskLineName)) { - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, ""); - } - - nameSet = new StringBuffer(); - nameSet.append(locationName); - name2nickname.putIfAbsent(locationName, new ArrayList<>()); - POS.append("=" + locationName + "|地名\r\n"); - if(jobj.containsKey("nickname")){ - - for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ - if(!nickname.equals("")) { - nameSet.append("+").append(nickname); - POS.append("=").append(nickname).append("|地名\r\n"); - name2nickname.get(locationName).add(nickname); - } - } - } - jobj.put("nameSet", nameSet.toString()); - - locationId = (Integer) jobj.get("id"); - id2j.put(locationId, jobj); - } - - //邻接矩阵初始化 - matrix = new int[locationNum][locationNum]; - for (int i = 0; i < locationNum; i++) { - for (int j = 0; j < locationNum; j++) { - matrix[i][j] = Integer.MAX_VALUE; - } - } - - for (int i = 0; i < locationNum; i++) { - List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); - for (int neighbourId : neighbours) { - JSONObject neighbourObject = id2j.get(neighbourId); - //System.out.println(neighbourObject); - index = (Integer) neighbourObject.get("index"); - matrix[i][index] = 1; - matrix[index][i] = 1; - } - } - } - - - public void construct(JSONObject gameElements, UserInfo userinfo) { - - try { - - conditionDescription.put("site", "当前地点"); - - JSONObject map = gameElements.getJSONObject("map"); - Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); - script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); - - - - - - if(script == null){ - throw new Exception("话术不存在"); - } - JSONArray locations = map.getJSONArray("locations"); - String userName = (String) gameElements.get("userName"); - this.locations = locations; - this.question2keyword = question2keyword; - //通过邻接表构造邻接矩阵 - constructGreph(locations); - - //用弗洛伊德算法求最短路径 - //Floyd floyd = new Floyd(); - //floyd.findShortestPath(matrix, locationNum); - //floyd.printPath(matrix, locationNum); - generateWantToThere(gameElements, keywordMap); - generateHowToThere(gameElements, keywordMap); - - //查询类型配置条目的生成 - queryTypeConfigTermGenerate(keywordMap, "WHERE_I_AM", "map", "queryWhereIam"); - queryTypeConfigTermGenerate(keywordMap, "WHERE_CAN_I_GO", "map", "queryCanGoBySite"); - queryTypeConfigTermGenerate(keywordMap, "AROUND_NPC", "map", "queryAroundNpcBySite"); - queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM", "map", "queryAroundGoodsBySite"); - queryTypeConfigTermGenerate(keywordMap, "AROUND_THINGS", "map", "queryAroundAllBySite"); - - queryTypeConfigTermGenerate(keywordMap, "AROUND_PLACE", "map", "queryAroundPlace"); - queryTypeConfigTermGenerate(keywordMap, "WHO_IN_THERE", "map", "queryInnerNpcBySite"); - queryTypeConfigTermGenerate(keywordMap, "TASK_IS_WHAT", "map", "queryTaskDescription"); - queryTypeConfigTermGenerate(keywordMap, "WHAT_THINGS_IN_LOCATION", "map", "queryItemsInPlace"); - - - - } catch(Exception e){ - operationStatus = 0; - e.printStackTrace(); - message = "地图处理出现异常:"; - return; - } - - } - - - /** - * 生成‘怎么去哪里’所需要的配置文件 - */ - public void generateHowToThere(JSONObject gameElements, Map keywordMap) { - //String conditionName = "want_know_zenmezuo"; - String intent = "HOW_TO_THERE", placeA, keywordPattern, gotoSite; - String conditionNameList[] = keywordMap.get(intent).toString().split(","); - StringBuffer placeKeywords = new StringBuffer(); - - String nameSet; - - - for(String conditionName:conditionNameList) { - placeKeywords.setLength(0); - - keywordPattern = keywordMap.get(intent + "_" + conditionName).toString(); - - - - - - //提取关键词 - //conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString(); - - for (int i = 0; i < locationNum; i++) { - - placeA = (String) locations.getJSONObject(i).get("name"); - gotoSite = keywordPattern.replace("name", placeA); - //toAllSiteskeywords.append(gotoSite); - //toSitekeywords.append(gotoSite); - placeKeywords.append(gotoSite); - for (String nickname : name2nickname.get(placeA)) { - gotoSite = keywordPattern.replace("name", nickname); - placeKeywords.append(gotoSite); - //toSitekeywords.append(gotoSite); - } - - - //nameSet = (String) locations.getJSONObject(i).get("nameSet"); - //placeKeywords.append("+").append(nameSet); - } - - - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:" + conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - configTermText.setNextStepStatus("return-0"); - configTermText.setAuxiliaryPriority("1"); - ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); - - - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAdjoin:" - ); - configTermText.setNextStepStatus("return-0"); - configTermText.setAuxiliaryPriority("1"); - ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); - - - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:" + conditionName + "::match-Include=2", - " ", - "match,return-0", - "", - " ", - "map_query:queryHowToPathBySite:" + conditionName - ); - configTermText.setNextStepStatus("return-0"); - configTermText.setAuxiliaryPriority("1"); - ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); - - } - - - } - - - - /** - * 生成‘我要去那里’所需要的配置文件 - */ - public void generateWantToThere(JSONObject gameElements, Map keywordMap) { - String placeA, lastTaskCondition, lastTaskReply, taskLine; - String intent = "GO_TO", keywordPattern; - String conditionName = keywordMap.get(intent).toString().split(",")[0]; - - keywordPattern = keywordMap.get(intent + "_" + conditionName).toString(); - - //包含去xx的所有地点的关键词集合 - StringBuffer toAllSiteskeywords = new StringBuffer(); - - //包含去xx这个特定地点的关键词的集合(包含别名) - StringBuffer toSitekeywords = new StringBuffer(); - - - String gotoSite = ""; - - - for (int i = 0; i < locationNum; i++) { - toSitekeywords.setLength(0); - placeA = (String) locations.getJSONObject(i).get("name"); - gotoSite = keywordPattern.replace("name", placeA); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - for (String nickname : name2nickname.get(placeA)) { - gotoSite = keywordPattern.replace("name", nickname); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - } - - lastTaskCondition = String.format(TASK_CONDITION, placeA); - lastTaskReply = String.format(TASK_REPLY, placeA); - taskLine = String.format(TASK_LINE, placeA); - - - //地点任务和地点回答的初始化 - if (!varInitialMap.containsKey(lastTaskCondition)) { - varInitialMap.put(lastTaskCondition, conditionName); - varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); - conditionDescription.put(lastTaskCondition, lastTaskCondition); - conditionDescription.put(lastTaskReply, lastTaskReply); - } - - - /** - * 要去某个地方,并且该地点相邻或者可以直接到达 - */ - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", - - " ", - "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" - - ); - configTermText.setConfigName("map", true); - configTermTextList.add(configTermText); - - - //上一个配置文件激活时的默认选项(兜底),上一条一定会激活下一条,下一条是没有条件的,如果没有找到其他可以激活的配置条目,则激活下一条 - configTermText = new ConfigTermText( - " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA - + "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("plot_" + placeA + "_doudi", false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - //上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step - configTermText = new ConfigTermText( - lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA - + "-<-npc_update:updateFollowerLocation:" + placeA - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("plot_" + placeA + "_doudi2", false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - } - - /** - * 要去的地方就在当前地点 - */ - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - configTermText.setConfigName("map", true); - configTermTextList.add(configTermText); - - - /** - * 要去的地方要经过几个地点才能到达 - */ - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=2", - " ", - "match,return-0", - "", - " ", - "map_query:queryToDoPathBySite:" + conditionName - ); - configTermText.setConfigName("map", true); - configTermTextList.add(configTermText); - - /** - * 要去的地方不可到达 - */ - configTermText = new ConfigTermText( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=5", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathNotExist:" - ); - configTermText.setConfigName("map", true); - configTermTextList.add(configTermText); - - } -} \ No newline at end of file diff --git a/src/gameDesign/MapConstructor2.java b/src/gameDesign/MapConstructor2.java deleted file mode 100644 index 8e57a13..0000000 --- a/src/gameDesign/MapConstructor2.java +++ /dev/null @@ -1,560 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.util.*; - -public class MapConstructor2 extends ElementConstructor { - - String nickname = "qiwu"; - int[][] matrix; - int locationNum; - HashMap id2j = new HashMap(); - Map question2keyword = new HashMap(); - Map> name2nickname = new HashMap>(); - JSONArray locations = null; - - Map script = null; //话术模板 - - - - public MapConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - - public void constructGreph(JSONArray locations) { - - JSONObject jobj = null; - int locationId, index; - String locationName, taskLineName = ""; - - locationNum = locations.size(); - StringBuffer nameSet = null; - keywordMap.putIfAbsent("site_list", new StringBuffer()); - - for (int i = 0; i < locationNum; i++) { - jobj = locations.getJSONObject(i); - jobj.put("index", i); - locationName = (String) jobj.get("name"); - keywordMap.get("site_list").append("+").append(locationName); - - - taskLineName = String.format(PlotConstructor.TASK_LINE, locationName); - - - if (!varInitialMap.containsKey(taskLineName)) { - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, ""); - } - - nameSet = new StringBuffer(); - nameSet.append(locationName); - name2nickname.putIfAbsent(locationName, new ArrayList<>()); - POS.append("=" + locationName + "|地名\r\n"); - if(jobj.containsKey("nickname")){ - - for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ - if(!nickname.equals("")) { - nameSet.append("+").append(nickname); - POS.append("=").append(nickname).append("|地名\r\n"); - name2nickname.get(locationName).add(nickname); - } - } - } - jobj.put("nameSet", nameSet.toString()); - - locationId = (Integer) jobj.get("id"); - id2j.put(locationId, jobj); - } - - //邻接矩阵初始化 - matrix = new int[locationNum][locationNum]; - for (int i = 0; i < locationNum; i++) { - for (int j = 0; j < locationNum; j++) { - matrix[i][j] = Integer.MAX_VALUE; - } - } - - for (int i = 0; i < locationNum; i++) { - List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); - for (int neighbourId : neighbours) { - JSONObject neighbourObject = id2j.get(neighbourId); - System.out.println(neighbourObject); - index = (Integer) neighbourObject.get("index"); - matrix[i][index] = 1; - matrix[index][i] = 1; - } - } - } - - - public void construct(JSONObject gameElements, UserInfo userinfo) { - - try { - - conditionDescription.put("site", "当前地点"); - - JSONObject map = gameElements.getJSONObject("map"); - Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); - script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); - - if(!script.containsKey("PATH_AT")) - script.put("PATH_AT", "你已经在[地点名]了"); - if(!script.containsKey("WHERE_I_AM")) - script.put("WHERE_I_AM", "在[地点名]"); - if(!script.containsKey("PATH_ADJOINT")) - script.put("PATH_ADJOINT", "就在附近哦"); - if(!script.containsKey("PATH_EXIST")) - script.put("PATH_EXIST", "通过[途径]可以到达[目的地]"); - if(!script.containsKey("PATH_NOT_EXIST")) - script.put("PATH_NOT_EXIST", "不可到达"); - if(!script.containsKey("CAN_GO_SITES")) - script.put("CAN_GO_SITES", "你可以去[可去列表]"); - if(!script.containsKey("CAN_GO_NOWHERE")) - script.put("CAN_GO_NOWHERE", "没什么地方可去的,继续玩吧"); - if(!script.containsKey("SITE_NOT_ACTIVE")) - script.put("SITE_NOT_ACTIVE", "你来到了[地点名]"); - if(!script.containsKey("SITE_NOT_ADJOINT")) - script.put("SITE_NOT_ADJOINT", "通过[途径]可以到达[目的地]"); - if(!script.containsKey("AROUND_PEOPLE")) - script.put("AROUND_PEOPLE", "周围有[人物列表]"); - if(!script.containsKey("AROUND_ITEMS")) - script.put("AROUND_ITEMS", "周围有[物品列表]"); - if(!script.containsKey("AROUND_THINGS")) - script.put("AROUND_THINGS", "周围有[人物物品列表]"); - if(!script.containsKey("FIND_ITEM_LOCATION")) - script.put("FIND_ITEM_LOCATION", "[物品名]在[地点]"); - if(!script.containsKey("FIND_NPC_LOCATION")) - script.put("FIND_NPC_LOCATION", "[人名]在[地点]"); - if(!script.containsKey("AROUND_PLACE")) - script.put("AROUND_PLACE", "周围有[地点列表]"); - if(!script.containsKey("FIND_ITEM_WAY")) - script.put("FIND_ITEM_WAY", "[人名]在[地点]"); - if(!script.containsKey("FIND_NPC_WAY")) - script.put("FIND_NPC_WAY", "[物品名]在[地点]"); - if(!script.containsKey("GET_ITEM_ATTR")) - script.put("GET_ITEM_ATTR", "[物品名]的[属性名]是[属性值]"); - if(!script.containsKey("WE_HAVE")) - script.put("WE_HAVE", "我们有[物品列表]"); - if(!script.containsKey("GET_NPC_ATTR")) - script.put("GET_NPC_ATTR", "[人名]的[属性名]是[属性值]"); - if(!script.containsKey("INNER_PEOPLE")) - script.put("INNER_PEOPLE", "里面有[人物列表]"); - if(!script.containsKey("WHO_YOU_ARE")) - script.put("WHO_YOU_ARE", "我是[人名]"); - if(!script.containsKey("TASK_DESCRIPTION")) - script.put("TASK_DESCRIPTION", "我们的任务是[任务描述]"); - - - if(script == null){ - throw new Exception("话术不存在"); - } - JSONArray locations = map.getJSONArray("locations"); - String userName = (String) gameElements.get("userName"); - this.locations = locations; - this.question2keyword = question2keyword; - //通过邻接表构造邻接矩阵 - constructGreph(locations); - - //用弗洛伊德算法求最短路径 - Floyd floyd = new Floyd(); - floyd.findShortestPath(matrix, locationNum); - floyd.printPath(matrix, locationNum); - generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereIam(gameElements, userName, keywordMap); - generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateSurroundingItem(keywordMap); - generateSurroundingPeople(keywordMap); - generateSurroundThings(keywordMap); - generateSurroundPlace(keywordMap); - generateWeHave(keywordMap); - generateInnerPeople(keywordMap); - generateTaskDescription(keywordMap); - - - } catch(Exception e){ - operationStatus = 0; - e.printStackTrace(); - message = "地图处理出现异常:"; - return; - } - - } - - /** - * 生成‘我在哪里’所需要的配置文件 - */ - public void generateWhereIam(JSONObject gameElements, String botAccount, Map keywordMap) { - String conditionNameList[] = {"zainali", "wenzainali"}; - String conditionKeywords = ""; - - - for(String condition:conditionNameList) { - - conditionKeywords = keywordMap.get("map_" + condition).toString(); - - jConfig = new JConfig( - condition + "::match-Include=" + conditionKeywords, " ", - "match", "", "yaobuyao", - "map_query:queryWhereIam:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - } - - - } - - - - /** - * 生成‘怎么去哪里’所需要的配置文件 - */ - public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String conditionName = "want_know_zenmezuo"; - StringBuffer placeKeywords = new StringBuffer(); - - String nameSet; - - - for (int i = 0; i < locationNum; i++) { - nameSet = (String) locations.getJSONObject(i).get("nameSet"); - placeKeywords.append("+").append(nameSet); - } - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", - " " , - "match,return-0", - "", - " ", - "map_query:queryPathAdjoin:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=2", - " " , - "match,return-0", - "", - " ", - "map_query:queryHowToPathBySite:" + conditionName - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - - - } - - - /** - * 生成‘我能去哪里’所需要的配置文件 - */ - public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String conditionName = "choose_gowhere"; - String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); - - String placeA, placeB, pathNode; - - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryCanGoBySite:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘我要去那里’所需要的配置文件 - */ - public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply; - String conditionName = "yaobuyao"; - String conditionKeywords = "地点"; - String start = (String) gameElements.get("start"); - String placeKeywords; - - //包含去xx的所有地点的关键词集合 - StringBuffer toAllSiteskeywords = new StringBuffer(); - - //包含去xx这个特定地点的关键词的集合(包含别名) - StringBuffer toSitekeywords = new StringBuffer(); - - - String goRelateConditions[] = {"yaobuyao"}; - String gotoMapptern = keywordMap.get("map_" + goRelateConditions[0]).toString(), gotoSite = ""; - - - for (int i = 0; i < locationNum; i++) { - toSitekeywords.setLength(0); - placeA = (String) locations.getJSONObject(i).get("name"); - gotoSite = gotoMapptern.replace("name", placeA); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - for (String nickname : name2nickname.get(placeA)) { - gotoSite = gotoMapptern.replace("name", nickname); - toAllSiteskeywords.append(gotoSite); - toSitekeywords.append(gotoSite); - } - - lastTaskCondition = String.format(PlotConstructor.TASK_CONDITION, placeA); - lastTaskReply = String.format(PlotConstructor.TASK_REPLY, placeA); - - - //地点任务和地点回答的初始化 - if (!varInitialMap.containsKey(lastTaskCondition)) { - varInitialMap.put(lastTaskCondition, goRelateConditions[0]); - varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); - conditionDescription.put(lastTaskCondition, lastTaskCondition); - conditionDescription.put(lastTaskReply, lastTaskReply); - } - - - /** - * 要去某个地方,并且该地点相邻或者可以直接到达 - */ - conditionName = goRelateConditions[0]; - jConfig = new JConfig( - conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", - - " ", - "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" - - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - //上一个配置文件激活时的默认选项 - jConfig = new JConfig( - " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA - + "-<-npc_update:updateFollowerLocation:" + placeA - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + placeA + "_doudi", false); - jConfig.setjStatus(1); - jConfigList.add(jConfig); - - - } - - /** - * 要去的地方就在当前地点 - */ - jConfig = new JConfig( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=0", - " ", - "match,return-0", - "", - " ", - "map_query:queryPathAt:" - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - /** - * 要去的地方要经过几个地点才能到达 - */ - jConfig = new JConfig( - conditionName + "::match-Include=" + toAllSiteskeywords - + ",isNeighbour:" + conditionName + "::match-Include=2", - " ", - "match,return-0", - "", - " ", - "map_query:queryToDoPathBySite:" + conditionName - ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); - - - } - - - - /** - * 生成‘周围有什么人’所需要的配置文件 - */ - public void generateSurroundingPeople(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("people_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundNpcBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘周围有什么物品’所需要的配置文件 - */ - public void generateSurroundingItem(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("item_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundGoodsBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘周围有什么(包含人和物品)’所需要的配置文件 - */ - public void generateSurroundThings(Map keywordMap){ - String conditionName = "know_exist_what_mohu"; - String conditionKeywords = keywordMap.get("things_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", "yaobuyao", - "map_query:queryAroundAllBySite:" - ); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - /** - * 生成‘周围有什么地点’所需要的配置文件 - */ - public void generateSurroundPlace(Map keywordMap){ - String conditionName = "know_exist_what"; - String conditionKeywords = keywordMap.get("place_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryAroundPlace:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘我们有什么’所需要的配置文件 - */ - public void generateWeHave(Map keywordMap){ - String conditionName = "know_exist_what_mohu"; - String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "goods_query:queryPlayerItems:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘里面有什么人’所需要的配置文件 - */ - public void generateInnerPeople(Map keywordMap){ - - - //与里面有谁相关的condition - String innerNPCRelateConditions[] = {"shishui"}; - - keywordMap.putIfAbsent("inner_shishui", new StringBuffer()); - String conditionName = "shishui"; - String conditionKeywords = keywordMap.get("inner_" + conditionName).toString(); - - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryInnerNpcBySite:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - - - /** - * 生成‘我们的任务是什么’所需要的配置文件 - */ - public void generateTaskDescription(Map keywordMap){ - - - //与里面有谁相关的condition - String innerNPCRelateConditions[] = {}; - - keywordMap.putIfAbsent("task_shishenme", new StringBuffer()); - String conditionName = "shishenme"; - String conditionKeywords = keywordMap.get("task_" + conditionName).toString(); - - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "", " ", - "map_query:queryTaskDescription:" - ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); - - } - - -} \ No newline at end of file diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java deleted file mode 100644 index 9537a9f..0000000 --- a/src/gameDesign/PlotConstructor.java +++ /dev/null @@ -1,790 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.io.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - - -public class PlotConstructor extends ElementConstructor { - - public static String ASSISTANT = "globalVariable_智能助手"; - public static String ASSISTANT_EMOTION = "正常"; - public static String TASK_DESCRIPTION = "globalVariable_任务"; - - public static String TALKER_PATTERN = "【%s@%s】"; - String GAME_STEP_FORMAT = "%s_plot_%s"; - - JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); - private HashMap plotIndex = new HashMap(); - private HashMap plotTextIndex = new HashMap(); - HashMap visited = new HashMap(); - - - public static String TASK_LINE = "任务线_%s进度"; - public static String TASK_CONDITION = "任务线%s最后一个condition"; - public static String TASK_REPLY = "任务线%s最后的回答"; - - - public PlotConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - try { - addGameStartPlot(jsonObject, keywordMap); - - JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"), startCondition; - JSONObject returnMessage = null; - - - - - this.plots = plots; - constructAdjList(plots); - - if (plotIndex.containsKey(start)) { - String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; - conditionDescription.put(taskLineName, taskLineName); - - if(jsonObject.get("firstUnknownText") == null) - varInitialMap.put("unknownText", "你说啥?"); - else - varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - - - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - conditionDescription.put("game_step", "QA问答游戏进度"); - - BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); - - varInitialMap.put(start, "1"); - - - } else { - System.out.println("start剧情不存在"); - operationStatus = 0; - message = "开始剧情不存在,请到剧情列表设置"; - return; - } - - - - } catch(Exception e){ - operationStatus = 0; - message = "剧情接口处理出现异常"; - e.printStackTrace(); - return; - } - } - - //根据id构造邻接表 - public void constructAdjList(JSONArray plots) { - int length = plots.size(), branchSize; - String id = "", nextPlotId = "", nextPlotText; - JSONObject plot = null; - JSONArray branch = null; - - for (int i = 0; i < length; i++) { - plot = plots.getJSONObject(i); - id = (String) plot.get("id"); - plot.put("index", i); - - if (adjList.get(id) == null) { - adjList.put(id, new ArrayList<>()); - } - - //添加branch中的下一个plot - branch = plot.getJSONArray("branch"); - branchSize = branch.size(); - for (int j = 0; j < branchSize; j++) { - nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); - nextPlotText = branch.getJSONObject(j).getString("reply"); - plotTextIndex.put(nextPlotId, nextPlotText); - if (revAdjList.get(nextPlotId) == null) { - revAdjList.put(nextPlotId, new ArrayList<>()); - } - varSlotFilt(branch.getJSONObject(j), keywordMap); - adjList.get(id).add(nextPlotId); - revAdjList.get(nextPlotId).add(id); - - } - plotIndex.put(id, plot); - } - } - - /** - * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 - * @param branchNode - */ - public static void varSlotFilt(JSONObject branchNode, Map keywordMap){ - - - String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; - Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); - Matcher m = replacePattern.matcher(branchNode.getString("reply")); - while (m.find()) { - npcName = m.group(1); - //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 - //System.out.println("npcName" + npcName); - //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); - if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { - varSlot = m.group(3); - middleText = m.group(2); - branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); - } - - } - } - - - - /** - * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 - * 加上剧情计数器, null时未激活,大于等于1时表示已激活 - * @param root - * @param userinfo - */ - public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { - String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, nextGameStep, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation, extraBeforeJumpUK; - JSONObject node = null, branchNode = null, adjNode = null; - StringBuffer skipText = new StringBuffer(); - String extraHP = "", extraUK = "", extraFT = ""; - JSONArray branch = null; - - - int branchSize; - - List curPremiseList, historyPremiseList; - - root.put("nextUnknownText", varInitialMap.get("unknownText")); - root.put("parentId", "null"); - jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); - - if(root.get("conditionName") != null && !root.get("conditionName").equals("")) - conditionName = (String)root.get("conditionName"); - else{ - conditionName = "yaobuyao"; - root.put("conditionName", conditionName); - } - - - - String startPlace = ((String)root.get("place")).split("\\+")[0]; - String startTaskLine = String.format(PlotConstructor.TASK_LINE, startPlace); - String startTaskCondition = String.format(PlotConstructor.TASK_CONDITION, startPlace); - String startTaskReply = String.format(PlotConstructor.TASK_REPLY, startPlace); - varInitialMap.put("site", startPlace); - varInitialMap.put(startTaskLine, rootId); - varInitialMap.put(startTaskCondition, ""); - varInitialMap.put(startTaskReply, ""); - conditionDescription.put(startTaskLine, startTaskLine); - conditionDescription.put(startTaskCondition,startTaskCondition); - conditionDescription.put(startTaskReply, startTaskReply); - - - - //generateStartGame(root, jsonObject, startPlace, conditionName); - Queue queue = new LinkedList(); - Map autoJumpUpdateKnowledge = new HashMap(); - - queue.add(root); - - while (!queue.isEmpty()) { - node = queue.remove(); - id = (String) node.get("id"); - location = ((String) node.get("place")).split("\\+")[0]; - conditionName = (String) node.get("conditionName"); - curUnknownText = (String) node.get("nextUnknownText"); - taskLineName = String.format(PlotConstructor.TASK_LINE, location); - conditionDescription.put(id, "剧情" + id + "状态"); - varInitialMap.put(id ,""); - - //本任务线的最后一个condition和本任务线的最后一个回答 - - - - - branch = node.getJSONArray("branch"); - branchSize = branch.size(); - - - - for (int i = 0; i < branchSize; i++) { - - System.out.println("branch:" + i); - skipText.setLength(0); - - branchNode = branch.getJSONObject(i); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - - //System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString()); - - nextUnknownText = updateKnowledge.get("unknownText"); - //System.out.println(id + "分支内" +nextUnknownText); - nextId = (String)branchNode.get("nextPlotId"); - //skipText.append(); - - - if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ - nextId = id + "_end"; - branchNode.put("nextPlotId", nextId); - createEndNode(node, id, nextId, curUnknownText); - } - - //保留下一步剧情的地点 - beforeJumpLocatin = ((String)plotIndex.get(nextId).get("place")).split("\\+")[0]; - autoJumpUpdateKnowledge.clear(); - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ - nextId = (String)branchNode.get("nextPlotId"); - JSONObject jumpNextNode = plotIndex.get(nextId); - JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); - - skipText.append((String)branchNode.get("reply")); - branchNode.put("reply", jumpBranchNode.get("reply")); - Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); - autoJumpUpdateKnowledge.putAll(newUpdateKnowledge); - - nextUnknownText = (String)newUpdateKnowledge.get("unknownText"); - System.out.println("循环内" +nextUnknownText); - //updateKnowledge.putAll(newUpdateKnowledge); - - - jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); - - //如果下一步剧情存在 - if(jumpNextNextId != null && !jumpNextNextId.equals("") && plotIndex.containsKey(jumpNextNextId)){ - System.out.println(jumpNextNextId); - System.out.println(plotIndex.get(jumpNextNextId)); - jumpNextNextLocation = (String)plotIndex.get(jumpNextNextId).get("place"); - - autoJumpUpdateKnowledge.put("site", jumpNextNextLocation); - autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); - branchNode.put("autoJump", jumpBranchNode.get("autoJump")); - - }else { - jumpNextNextId = nextId + "_end"; - jumpBranchNode.put("nextPlotId", jumpNextNextId); - createEndNode(node, nextId, jumpNextNextId, curUnknownText); - branchNode.put("autoJump", false); - - } - - branchNode.put("nextPlotId", jumpNextNextId); - } - - - nextId = (String) branchNode.get("nextPlotId"); - - reply = (String)branchNode.get("reply"); - if(reply.equals("")) - reply = curUnknownText; - - - - //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - nextCondition = (String) plotIndex.get(nextId).get("conditionName"); - if(nextCondition.equals("")) - nextCondition = "yaobuyao"; - - nextLocation = ((String) plotIndex.get(nextId).get("place")).split("\\+")[0]; - - //任务线 - nTaskLineName = String.format(TASK_LINE, nextLocation); - //任务线最后一个condition - lastTaskCondition = String.format(TASK_CONDITION, nextLocation); - lastTaskReply = String.format(TASK_REPLY, nextLocation); - - - /** - * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: - * 1: 将剧情停留在最后一步剧情 - * 2. 设一个专门的剧情表示剧情的结尾 - */ - - //现在暂时放开下一步剧情未发生过的限制条件 - //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; - extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText; - - if(!beforeJumpLocatin.equals(nextLocation)) { - //extraBeforeJumpUK = - } - if(nextId.endsWith("_end")) - nextGameStep = id; - else - nextGameStep = nextId; - - - /** - * 1. 主角是否随剧情移动 - * 如果随剧情移动,则更新地点和game_step - * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 - * - * 2. 当前条件是否为空 - * 如果当前条件为空,则提交qa激活并进入下一步剧情 - * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 - * - * 3. 下一部剧情是否为空 - * - * - * 4. 有没有说去XX - * - * 主角不随剧情移动+当前条件为空+去沙滩 - * 1、沙滩无剧情 - * 2、沙滩有剧情 - * - * 5. 地点变化 - * 1. 当前所处地点 - * 2. 下一步剧情所处地点(包含自动跳转的情况) - * 3. 自动跳转完成后的地点 - */ - - /** - * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) - * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) - * 2. 自动跳转剧情文本保存到beforeJumpTaskReply - * 3. 当前剧情和下一步剧情更新状态 - */ - - String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin); - String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin); - String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; - - if(branchNode.containsKey("activateExtraPlot")) { - //激活除了下一步剧情以外的剧情 - beforeJumpUK = extraActivatedPlot(beforeJumpUK, nextLocation, JSONArray.parseArray(branchNode.getJSONArray("activateExtraPlot").toJSONString(), String.class)); - } - - - //如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新 - if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) { - extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep); - - - - - //自动跳转剧情如果有更新属性,这些数据也需要更新 - updateKnowledge.putAll(autoJumpUpdateKnowledge); - - }else { - - //任务线最后一个condition - - - - - /** - * 注意,比较的是当前地点和跳转前的地点 - * 地点更新为跳转后的地点 - */ - //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!location.equals(beforeJumpLocatin)){ - //System.out.println(id + "报异常" + curUnknownText); - if(curUnknownText.equals("")) { - reply = "请到" + beforeJumpLocatin; - //如果当前地点和下一步剧情地点不同,要提示 - }else { - reply = curUnknownText; - } - - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - - - jConfig = new JConfig( - "yaobuyao::match-Keyword=+" + beforeJumpLocatin, - "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1, - "match", (String)branchNode.get("reply"), (String) nextCondition, - extraUK + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep) - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation, autoJumpUpdateKnowledge - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + beforeJumpLocatin + "_" + id,false); - jConfig.setjStatus(1); - - jConfigList.add(jConfig); - - - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - updateKnowledge.remove("unknownText"); - updateKnowledge.remove("site"); - extraUK = beforeJumpUK; - - //如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说 - skipText.setLength(0); - - //必须在上一个jConfig添加完之后 - //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); - - } - } - - - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); - - - - extraFT = ""; - //是否将当前识别到的数据加入到已知数据列表 - if((Boolean)branchNode.get("includeCurInfo")){ - extraFT += ",includeCurInfo"; - } - - if(branchNode.get("extraFeature") != null){ - extraFT += "," + branchNode.getString("extraFeature"); - } - - jConfig = new JConfig( - curPremiseList, - historyPremiseList, - updateKnowledge, - "", extraHP, extraUK, - "match"+extraFT, reply, (String) nextCondition, "1" - ); - - - //当剧情没有条件限制时的操作 - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){ - unconditionalPlotProcess(jConfig, nextCondition); - } - if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) - jConfig.setAuxiliaryPriority("3"); - jConfigList.add(jConfig); - - - - //将子结点加入队列 - adjId = (String) branchNode.get("nextPlotId"); - if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { - visited.put(adjId, true); - adjNode = plotIndex.get(adjId); - - adjNode.put("parentId", id); - //System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText); - adjNode.put("nextUnknownText", nextUnknownText); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); - varInitialMap.put(adjId, ""); - } - - - } - - - } - - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 不设剧情不设条件时的处理 - * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 - * 2. 如果qa返回小于90则只回答剧情文本 - * 3. 如果qa返回not_found则只回答剧情文本 - * 4. 无论哪种情况都会跳下一步剧情 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 待激活列表,用于qa问答 - */ - - //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - jConfig.setNextStepStatus("active"); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - //--------------------------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------------------------- - - - /** - * ---------------------------------------------------------------------------------------------------- - * 用于存档 - */ - jConfig = new JConfig( - "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" - ); - jConfig.setAuxiliaryPriority("4"); - jConfigList.add(jConfig); - - - } - - /** - * 游戏开始的配置 - */ - public void generateStartGame(JSONObject root, JSONObject jsonObject, String startPlace, String conditionName){ - - //用于开始游戏的配置 - jConfig = new JConfig( - "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - (String)jsonObject.get("plotStartText"), - conditionName, - "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - "请说开始游戏或者继续游戏", - "start_options", - "" - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - } - - @Override - public void postProcessing(List idList, int categoryId){ - } - - public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ - - String condition = (String) node.get("conditionName"); - String location = ((String) node.get("place")).split("\\+")[0]; - - String nextCondition = condition; - String nextLocation = location; - String nTaskLineName = String.format(TASK_LINE, nextCondition); - - - JSONObject endNode = new JSONObject(); - endNode.put("place", location); - endNode.put("conditionName", condition); - endNode.put("id", nextId); - endNode.put("reply", nextUnknownText); - endNode.put("includeCurInfo", true); - endNode.put("updateKnowledge", new ArrayList()); - - - plotIndex.put(nextId, endNode); - visited.put(nextId, true); - - } - - void addGameStartPlot(JSONObject gameElements, Map keywordMap){ - - - File file = null; - FileReader fr = null; - BufferedReader br = null; - try { - file = new File("gameconfig.txt"); - fr = new FileReader(file); - - br = new BufferedReader(fr); - String jsonStr = br.readLine(); - - jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); - jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); - jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); - jsonStr = jsonStr.replace("startId", gameElements.getString("start")); - jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); - JSONObject config = JSONObject.parseObject(jsonStr); - - System.out.println(config.toJSONString()); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); -// jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); - gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); - gameElements.put("start", "start1"); - gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); - - - br.close(); - fr.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - - //如果是无条件剧情,那么需要跟着一个激活操作 - public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); - jConfig.setNextStep("queryskip*,map*,item*,npc*"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - jConfig.setNextStepStatus("active"); - } - - public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ - int strLen = premiseStr.length(); - - - if(strLen == 0 || strLen == 1){ - premiseStr = new StringBuffer(); - }else{ - premiseStr.append(","); - } - - premiseStr.append(conditionName); - premiseStr.append("::"); - premiseStr.append(cmpType); - premiseStr.append("-"); - premiseStr.append(operator); - premiseStr.append("="); - premiseStr.append(value); - - } - - public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ - knowledgeStr.append("-<-"); - knowledgeStr.append(key); - knowledgeStr.append(":"); - knowledgeStr.append(value); - - } - - public String extraActivatedPlot(String updateKnowledge, String nextPlotLocation, List activateExtraPlot){ - JSONObject plot = null; - String location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = ""; - StringBuffer newUK = new StringBuffer(updateKnowledge); - for(String plotId:activateExtraPlot){ - plot = plotIndex.get(plotId); - conditionName = plot.getString("conditionName"); - location = plot.getString("location"); - plotText = plotTextIndex.get(plotId); - - lastTaskCondition = String.format(TASK_CONDITION, location); - lastTaskReply = String.format(TASK_REPLY, location); - - newUK.append("-<-").append(lastTaskCondition).append(":").append(conditionName).append("-<-").append(lastTaskReply).append(":").append(plotText); - - } - - return newUK.toString(); - - } - - - -} diff --git a/src/gameDesign/PlotConstructor2.java b/src/gameDesign/PlotConstructor2.java deleted file mode 100644 index a1e084c..0000000 --- a/src/gameDesign/PlotConstructor2.java +++ /dev/null @@ -1,902 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.Premise; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import java.io.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.qiwu.chatbotbackend.Config.Config.*; - - -public class PlotConstructor2 extends ElementConstructor { - - - JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); - private HashMap plotIndex = new HashMap(); - HashMap visited = new HashMap(); - - public HashMap getPlotIndex() { - return plotIndex; - } - - - public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - try { - addGameStartPlot(jsonObject, keywordMap); - - JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"), startCondition; - JSONObject returnMessage = null; - - - - this.plots = plots; - constructAdjList(plots); - - if (plotIndex.containsKey(start)) { - //String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; - String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place")); - conditionDescription.put(taskLineName, taskLineName); - - if(jsonObject.get("firstUnknownText") == null) - varInitialMap.put("unknownText", "你说啥?"); - else - varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - - - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); - conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION); - conditionDescription.put("game_step", GAME_STEP_DESCRIPTION); - - BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); - - varInitialMap.put(start, "1"); - ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList); - - - } else { - System.out.println(START_PLOT_NOT_EXIST); - operationStatus = 0; - message = START_PLOT_NOT_EXIST; - return; - } - } catch(Exception e){ - operationStatus = 0; - message = PLOT_GENERATION_ERROR; - e.printStackTrace(); - return; - } - } - - - /** - * 根据id构造邻接表 - * @param plots - */ - public void constructAdjList(JSONArray plots) { - int length = plots.size(), branchSize; - String id = "", nextPlotId = "", nextPlotText; - JSONObject plot = null; - JSONArray branch = null; - - for (int i = 0; i < length; i++) { - plot = plots.getJSONObject(i); - id = (String) plot.get("id"); - plot.put("index", i); - - if (adjList.get(id) == null) { - adjList.put(id, new ArrayList<>()); - } - - varSlotFilt(plot, keywordMap); - - //添加branch中的下一个plot - branch = plot.getJSONArray("branch"); - branchSize = branch.size(); - for (int j = 0; j < branchSize; j++) { - nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); - - branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise"))); - branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise"))); - - - //将剧情和相应文本相对应 - //plotTextIndex.put(nextPlotId, nextPlotText); - - if (revAdjList.get(nextPlotId) == null) { - revAdjList.put(nextPlotId, new ArrayList<>()); - } - - adjList.get(id).add(nextPlotId); - revAdjList.get(nextPlotId).add(id); - - } - plotIndex.put(id, plot); - } - } - - - /** - * 将条件文本中的一些特殊字符过滤调 - * @param premiseList 条件列表 - * @return - */ - JSONArray premiseTextFilt(JSONArray premiseList){ - JSONObject premise = null; - int size = premiseList.size(); - for(int i = 0;i < size;i++){ - premise = premiseList.getJSONObject(i); - premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", "")); - premiseList.set(i, premise); - } - - return premiseList; - } - - /** - * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 - * @param plot - */ - public static void varSlotFilt(JSONObject plot, Map keywordMap){ - - String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 - //System.out.println(plot.getString("id")); - Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); - Matcher m = replacePattern.matcher(plot.getString("plotText")); - while (m.find()) { - npcName = m.group(1); - //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 - //System.out.println("npcName" + npcName); - //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); - if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { - varSlot = m.group(3); - middleText = m.group(2); - plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); - } - - } - } - - - - /** - * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 - * 加上剧情计数器, null时未激活,大于等于1时表示已激活 - * @param root - * @param userinfo - */ - public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { - String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION, - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - String hint, gameStep, nextGameStep; - JSONObject node = null, branchNode = null; - Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false; - StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer(); - JSONArray branch = null; - - - int branchSize; - - List curPremiseList, historyPremiseList; - - root.put("nextUnknownText", varInitialMap.get("unknownText")); - root.put("parentId", "null"); - root.put("autoJump", false); - root.put("prevAutoJump", false); - jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); - - if(root.get("conditionName") != null && !root.get("conditionName").equals("")) - conditionName = (String)root.get("conditionName"); - else{ - conditionName = DEFAULT_CONDITION; - root.put("conditionName", conditionName); - } - - - - String startPlace = ((String)root.get("place")).split("\\+")[0]; - String startTaskLine = String.format(TASK_LINE, startPlace); - String startTaskCondition = String.format(TASK_CONDITION, startPlace); - String startTaskReply = String.format(TASK_REPLY, startPlace); - varInitialMap.put("site", startPlace); - varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); - varInitialMap.put(startTaskCondition, ""); - varInitialMap.put(startTaskReply, ""); - conditionDescription.put(startTaskLine, startTaskLine); - conditionDescription.put(startTaskCondition,startTaskCondition); - conditionDescription.put(startTaskReply, startTaskReply); - - - - //generateStartGame(root, jsonObject, startPlace, conditionName); - Queue queue = new LinkedList(); - - queue.add(root); - //System.out.println(root.toJSONString()); - - while (!queue.isEmpty()) { - node = queue.remove(); - id = (String) node.get("id"); - location = ((String) node.get("place")).split("\\+")[0]; - conditionName = (String) node.get("conditionName"); - curAutoJump = node.getBoolean("autoJump"); - prevAutoJump = node.getBoolean("prevAutoJump"); - curUnknownText = (String) node.get("unknownText"); - taskLineName = String.format(TASK_LINE, location); - conditionDescription.put(id, String.format(PLOT_STATUS, id)); - varInitialMap.put(id ,""); - - //本任务线的最后一个condition和本任务线的最后一个回答 - - - - - branch = node.getJSONArray("branch"); - branchSize = branch.size(); - - - - for (int i = 0; i < branchSize; i++) { - - skipText.setLength(0); - - branchNode = branch.getJSONObject(i); - //reply = branchNode.getString("reply"); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - - - - nextId = branchNode.getString("nextPlotId"); - moveWithPlot = branchNode.getBoolean("moveWithPlot"); - if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ - nextId = id + "_end"; - createEndNode(node, id, nextId, curUnknownText); - } - - if(moveWithPlot == null || curAutoJump) - moveWithPlot = true; - - - - nextUnknownText = plotIndex.get(nextId).getString("unknownText"); - nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump"); - reply = plotIndex.get(nextId).getString("plotText"); - - - - - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - - - if(reply.equals("")) - reply = curUnknownText; - - - - //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - nextCondition = plotIndex.get(nextId).getString("conditionName"); - if(nextCondition.equals("")) - nextCondition = DEFAULT_CONDITION; - - nextLocation = plotIndex.get(nextId).getString("place"); - - //任务线 - nTaskLineName = String.format(TASK_LINE, nextLocation); - //任务线最后一个condition - lastTaskCondition = String.format(TASK_CONDITION, nextLocation); - lastTaskReply = String.format(TASK_REPLY, nextLocation); - -// if(nextId.endsWith("_end")) -// nextGameStep = id; -// else -// nextGameStep = nextId; - - - gameStep = String.format(GAME_STEP_FORMAT, botAccount, id); - nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId); - - - - /** - * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: - * 1: 将剧情停留在最后一步剧情 - * 2. 设一个专门的剧情表示剧情的结尾 - */ - - //现在暂时放开下一步剧情未发生过的限制条件 - //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; - appendPremise(extraHP, taskLineName, "match", "Include", gameStep); - appendPremise(extraHP, "site", "match", "Include", location); - appendPremise(extraHP, id, "match", "Include", "1"); - - - appendKnowledge(extraUK, lastTaskCondition, nextCondition); - appendKnowledge(extraUK, lastTaskReply, reply); - appendKnowledge(extraUK, id, "+1"); //当前剧情状态加一 - appendKnowledge(extraUK, nextId, "1"); //下一步设为1 - appendKnowledge(extraUK, nTaskLineName, nextGameStep); - - - - - //如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end - if(nextId.endsWith("_end")) { - nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id); - } - - - //System.out.println(id); - - appendFeature(extraFT, "match"); - //下一步为自动跳转且地点相同,则将回答放在plot_jump_text - if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ - appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); - } - - - - /** - * 1. 主角是否随剧情移动 - * 如果随剧情移动,则更新地点和game_step - * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 - * - * 2. 当前条件是否为空 - * 如果当前条件为空,则提交qa激活并进入下一步剧情 - * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 - * - * 3. 下一部剧情是否为空 - * - * - * 4. 有没有说去XX - * - * 主角不随剧情移动+当前条件为空+去沙滩 - * 1、沙滩无剧情 - * 2、沙滩有剧情 - * - * 5. 地点变化 - * 1. 当前所处地点 - * 2. 下一步剧情所处地点(包含自动跳转的情况) - * 3. 自动跳转完成后的地点 - */ - - /** - * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) - * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) - * 2. 自动跳转剧情文本保存到beforeJumpTaskReply - * 3. 当前剧情和下一步剧情更新状态 - */ - - - if(branchNode.containsKey("activateExtraPlot")) { - //激活除了下一步剧情以外的剧情 - extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot")); - } - - - //如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新 - if(moveWithPlot || location.equals(nextLocation)) { - appendKnowledge(extraUK, "site", nextLocation); - appendKnowledge(extraUK, "game_step", nextGameStep); - appendKnowledge(extraUK,"unknownText", nextUnknownText); - //extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep; - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - - - - } else { - - //任务线最后一个condition - - - - - /** - * 注意,比较的是当前地点和跳转前的地点 - * 地点更新为跳转后的地点 - */ - //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!location.equals(nextLocation)){ - //System.out.println(id + "报异常" + curUnknownText); - if(curUnknownText.equals("")) { - - //如果没有unknown,就提示他到下一个地点 - hint = String.format(LOCATION_HINT, nextLocation); - //hint = "请到" + nextLocation; - //如果当前地点和下一步剧情地点不同,要提示 - }else { - //如果有unknown,就提示unknown文本 - hint = curUnknownText; - } - - - - //下一部剧情在不同地点时,为了防止到达下个地点的剧情重复执行,需要加一个标志表示下一步剧情是否已经发生过 - appendKnowledge(extraUK, nextLocation + "_activate_by", id); - appendKnowledge(extraUK, nextLocation + "_activate_ready", "1"); - - - - - arriveActivatePlot2(jsonObject, id, nextId, nextLocation); - - //如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说 - reply = hint; - - - - //必须在上一个jConfig添加完之后 - //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); - - } - } - - //System.out.println(branchNode); - - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class); - - - - //是否将当前识别到的数据加入到已知数据列表 - if((Boolean)branchNode.get("includeCurInfo")){ - appendFeature(extraFT, "includeCurInfo"); - } - - if(branchNode.get("extraFeature") != null){ - appendFeature(extraFT, branchNode.getString("extraFeature")); - } - - - if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ - appendFeature(extraFT, "activate:after"); - nextCondition = "plot_" + nextId; - } - - configTermText = new ConfigTermText( - curPremiseList, - historyPremiseList, - updateKnowledge, - "", extraHP.toString(), extraUK.toString(), - extraFT.toString(), reply, nextCondition, "1" - ); - configTermText.setConfigName("plot_" + id, false); - - - //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !prevAutoJump){ - Boolean activateFlag = false; - if(extraFT.indexOf("activate") != -1) - activateFlag = true; - unconditionalPlotProcess(configTermText, nextCondition, activateFlag); - } - if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) - configTermText.setAuxiliaryPriority("3"); - configTermTextList.add(configTermText); - - - - //将子结点加入队列 - adjId = nextId; - plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump); - if(branchNode.getJSONObject("activateExtraPlot") != null){ - for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){ - plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump); - } - } - - extraFT.setLength(0); - extraHP.setLength(0); - extraUK.setLength(0); - skipText.setLength(0); - arriveUK.setLength(0); - - - - - } - - - } - - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 不设剧情不设条件时的处理 - * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 - * 2. 如果qa返回小于90则只回答剧情文本 - * 3. 如果qa返回not_found则只回答剧情文本 - * 4. 无论哪种情况都会跳下一步剧情 - */ - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", - "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("queryskip1",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", - "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("queryskip2",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=not_found", "match", - "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("queryskip3",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 待激活列表,用于qa问答 - */ - - //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - configTermText = new ConfigTermText(" ", " ", "activate,post::gameQA(" + QA_URL + ")", - "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - configTermText.setNextStepStatus("active"); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=not_found", "match,return-0", - "{unknownText-2}", " ", "" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("unknown1",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - UNKNOWN_TEXT, - " ", "" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("unknown2",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", - UNKNOWN_TEXT, - " ", "" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("unknown3",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", - "{unknownText-2}", " ", "" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("unknown4",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - - - //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - configTermText = new ConfigTermText( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", - "" ," ", "" - ); - configTermText.setStatus("sleeping"); - configTermText.setConfigName("common_answer",false); - configTermText.setjStatus(1); - configTermText.setAuxiliaryPriority("0"); - configTermTextList.add(configTermText); - //--------------------------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------------------------- - - - /** - * ---------------------------------------------------------------------------------------------------- - * 用于存档 - */ - configTermText = new ConfigTermText( - "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", - "{archiveOperation-2}" ," ", "" - ); - configTermText.setAuxiliaryPriority("4"); - configTermTextList.add(configTermText); - - - } - - - /** - * 新建一个剧情结点 - * @param node - * @param id - * @param nextId - * @param nextUnknownText - */ - public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ - - String condition = (String) node.get("conditionName"); - String location = ((String) node.get("place")).split("\\+")[0]; - - String nextCondition = condition; - String nextLocation = location; - String nTaskLineName = String.format(TASK_LINE, nextCondition); - - - JSONObject endNode = new JSONObject(); - endNode.put("place", location); - endNode.put("conditionName", condition); - endNode.put("id", nextId); - endNode.put("plotText", nextUnknownText); - endNode.put("autoJump", false); - endNode.put("includeCurInfo", true); - endNode.put("updateKnowledge", new ArrayList()); - endNode.put("unknownText", ""); - - - plotIndex.put(nextId, endNode); - visited.put(nextId, true); - - } - - - /** - * 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档 - * @param gameElements - * @param keywordMap - */ - void addGameStartPlot(JSONObject gameElements, Map keywordMap){ - - - File file = null; - FileReader fr = null; - BufferedReader br = null; - try { - file = new File("gameconfig.txt"); - fr = new FileReader(file); - - br = new BufferedReader(fr); - String jsonStr = br.readLine(); - - jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); - jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); - jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); - jsonStr = jsonStr.replace("startId", gameElements.getString("start")); - jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); - - //System.out.println("JSONSTR ------------------------------\n" + jsonStr); - JSONObject config = JSONObject.parseObject(jsonStr); - - - gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); - gameElements.put("start", "start1"); - gameElements.put("firstUnknownText", GAME_START_HINT); - - - br.close(); - fr.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - - //如果是无条件剧情,那么需要跟着一个激活操作 - public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){ - configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); - - // - //if() - if(activateFlag){ - configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); - }else { - configTermText.setNextStep("queryskip*,map*,item*,npc*"); - } - - //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition - configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - configTermText.setNextStepStatus("active"); - } - - - /** - * 在条件文本后面添加一个条件 - * @param premiseStr - * @param conditionName - * @param cmpType - * @param operator - * @param value - */ - public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ - int strLen = premiseStr.length(); - String split_punt = ""; - - - if(premiseStr.length() != 0) - split_punt = ","; - - premiseStr.append(split_punt); - premiseStr.append(conditionName); - premiseStr.append("::"); - premiseStr.append(cmpType); - premiseStr.append("-"); - premiseStr.append(operator); - premiseStr.append("="); - premiseStr.append(value); - - } - - public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ - knowledgeStr.append("-<-"); - knowledgeStr.append(key); - knowledgeStr.append(":"); - knowledgeStr.append(value); - } - - public void appendFeature(StringBuffer featureStr, String key){ - featureStr.append(","); - featureStr.append(key); - } - - - /** - * 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B - * @param updateKnowledge - * @param nextPlotLocation - * @param activateExtraPlot 激活id列表 - */ - public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ - JSONObject plot = null; - String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; - StringBuffer newUK = updateKnowledge; - - Iterator plotIter = activateExtraPlot.keySet().iterator(); - - while(plotIter.hasNext()){ - plotId = plotIter.next(); - plotText = (String)activateExtraPlot.get(plotId); - - plot = plotIndex.get(plotId); - conditionName = plot.getString("conditionName"); - - if(conditionName == null || conditionName.equals("")){ - conditionName = DEFAULT_CONDITION; - } - location = plot.getString("place"); - - lastTaskCondition = String.format(TASK_CONDITION, location); - lastTaskReply = String.format(TASK_REPLY, location); - taskLine = String.format(TASK_LINE, location); - - - appendKnowledge(newUK, lastTaskCondition, conditionName); - appendKnowledge(newUK, lastTaskReply, plotText); - appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); - appendKnowledge(newUK, plotId, "1"); - - - } - } - - - - void plotEnQueue(Queue queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){ - JSONObject adjNode; - if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { - visited.put(adjId, true); - adjNode = plotIndex.get(adjId); - - adjNode.put("parentId", parentId); - adjNode.put("prevAutoJump", thisAutoJump); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId)); - varInitialMap.put(adjId, ""); - } - } - - - /** - * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况,将这块处理当做listening模块的一个剧情处理 - */ - void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ - - JSONObject updateKnowledge = new JSONObject(); - JSONArray curPremiseList = new JSONArray(); - //curPremiseList.add(curPremise.toString()); - - JSONArray hisPremiseList = new JSONArray(); - //hisPremiseList.add(hisPremise.toString()); - - - - //激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达 - // 2.3 两个条件是特意加的 - curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation)); - hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); - hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); - hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4")); - - - - JSONObject listeningConfig = new JSONObject(); - listeningConfig.put("curPremise", curPremiseList); - listeningConfig.put("hisPremise", hisPremiseList); - listeningConfig.put("updateKnowledge", updateKnowledge); - listeningConfig.put("nextPlotId", nextId); - listeningConfig.put("priority", "1"); - - if(gameElements.getJSONArray("listeningActions") == null) - gameElements.put("listeningActions", new JSONArray()); - - gameElements.getJSONArray("listeningActions").add(listeningConfig); - - } - - Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) { - - return nextAutoJump && (location.equals(nextLocation) || moveWithPlot); - } - - - - -} diff --git a/src/gameDesign/PlotConstructor3.java b/src/gameDesign/PlotConstructor3.java deleted file mode 100644 index 4d20473..0000000 --- a/src/gameDesign/PlotConstructor3.java +++ /dev/null @@ -1,573 +0,0 @@ -package com.qiwu.chatbotbackend.gameDesign; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.FormsPoster; -import org.apache.http.message.BasicNameValuePair; -import com.qiwu.chatbotbackend.processing.MyFunc; - -import java.io.UnsupportedEncodingException; -import java.util.*; - -import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL; - - -public class PlotConstructor3 extends ElementConstructor { - - public static String ASSISTANT = "globalVariable_默认_智能助手"; - public static String TASK_DESCRIPTION = "globalVariable_默认_任务"; - - public static String TALKER_PATTERN = "【%s】"; - String GAME_STEP_FORMAT = "%s_plot_%s"; - - JSONArray plots = null; - HashMap> adjList = new HashMap>(); - HashMap> revAdjList = new HashMap>(); - private HashMap id2j = new HashMap(); - HashMap visited = new HashMap(); - - - - public static String TASK_LINE = "任务线_%s进度"; - public static String TASK_CONDITION = "任务线%s最后一个condition"; - public static String TASK_REPLY = "任务线%s最后的回答"; - - public HashMap getId2j() { - return id2j; - } - - public PlotConstructor3(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { - super(); - this.helper = helper; - this.botId = botId; - this.botAccount = botAccount; - this.exceptRelation = exceptRelation; - this.keywordMap = keywordMap; - this.POS = POS; - } - - public void construct(JSONObject jsonObject, UserInfo userinfo) { - - try { - JSONArray plots = jsonObject.getJSONArray("plots"); - String start = (String) jsonObject.get("start"), startCondition; - JSONObject returnMessage = null; - - this.plots = plots; - constructAdjList(plots); - - if (id2j.containsKey(start)) { - String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; - conditionDescription.put(taskLineName, taskLineName); - - if(jsonObject.get("firstUnknownText") == null) - varInitialMap.put("unknownText", "你说啥?"); - else - varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - - - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id"))); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - conditionDescription.put("game_step", "QA问答游戏进度"); - - - BFSGenerate4(id2j.get(start), userinfo, jsonObject); - - varInitialMap.put(start, "1"); - - - - - - } else { - System.out.println("start剧情不存在"); - operationStatus = 0; - message = "开始剧情不存在,请到剧情列表设置"; - return; - } - - - - } catch(Exception e){ - operationStatus = 0; - message = "剧情接口处理出现异常"; - e.printStackTrace(); - return; - } - } - - //根据id构造邻接表 - public void constructAdjList(JSONArray plots) { - int length = plots.size(), branchSize; - String id = "", nextPlotId = ""; - JSONObject plot = null; - JSONArray branch = null; - - for (int i = 0; i < length; i++) { - plot = plots.getJSONObject(i); - id = (String) plot.get("id"); - plot.put("index", i); - - if (adjList.get(id) == null) { - adjList.put(id, new ArrayList<>()); - } - - //添加branch中的下一个plot - branch = plot.getJSONArray("branch"); - branchSize = branch.size(); - for (int j = 0; j < branchSize; j++) { - nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); - if (revAdjList.get(nextPlotId) == null) { - revAdjList.put(nextPlotId, new ArrayList<>()); - } - adjList.get(id).add(nextPlotId); - revAdjList.get(nextPlotId).add(id); - - } - id2j.put(id, plot); - } - } - - - - /** - * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 - * 加上剧情计数器, 每一步分为三个状态 - * @param root - * @param userinfo - */ - public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { - String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", extraFT, nextTaskName, keywordOptions, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, jumpLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - Boolean newBranch, manyParent, autoJump, includeCurInfo; - JSONObject node = null, branchNode = null, adjNode = null; - StringBuffer skipText = new StringBuffer(); - JSONArray branch = null; - - - List adjNodeList = null; - int priority, taskStep, nextPriority, nextTaskStep, branchSize; - - List curPremiseList, historyPremiseList; - - root.put("nextUnknownText", varInitialMap.get("unknownText")); - root.put("parentId", "null"); - jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); - - if(root.get("conditionName") != null && !root.get("conditionName").equals("")) - conditionName = (String)root.get("conditionName"); - - - String startPlace = ((String)root.get("place")).split("\\+")[0]; - varInitialMap.put("site", startPlace); - varInitialMap.put("任务线" + startPlace + "最后一个condition", ""); - varInitialMap.put("任务线" + startPlace + "最后的回答", ""); - conditionDescription.put("任务线" + startPlace + "最后一个condition","任务线" + startPlace + "最后一个condition"); - conditionDescription.put("任务线" + startPlace + "最后的回答", "任务线" + startPlace + "最后的回答"); - - - - //用于开始游戏的配置 - jConfig = new JConfig( - "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - (String)jsonObject.get("plotStartText"), - conditionName, - "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - "请说开始游戏或者继续游戏", - "start_options", - "" - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - - - Queue queue = new LinkedList(); - - queue.add(root); - - while (!queue.isEmpty()) { - node = queue.remove(); - id = (String) node.get("id"); - parentId = (String) node.get("parentId"); - location = ((String) node.get("place")).split("\\+")[0]; - jumpLocation = location; - conditionName = (String) node.get("conditionName"); - curUnknownText = (String) node.get("nextUnknownText"); - taskLineName = "任务线_" + location + "进度"; - conditionDescription.put(id, "剧情" + id + "状态"); - varInitialMap.put(id ,""); - nextUnknownText = ""; - skipText = new StringBuffer(); - //本任务线的最后一个condition和本任务线的最后一个回答 - - - - if (!varInitialMap.containsKey(taskLineName)) { - conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put(taskLineName, ""); - } - - //初始化 - newBranch = false; - manyParent = false; - - adjNodeList = adjList.get(id); - visited.put(id, true); - - - branch = node.getJSONArray("branch"); - branchSize = branch.size(); - //当两次出现unknown时给用户一下候选项 - keywordOptions = ""; - - String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation; - - - for (int i = 0; i < branchSize; i++) { - - branchNode = branch.getJSONObject(i); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - beforeJumpLocatin = (String)branchNode.get("place"); - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ - nextId = (String)branchNode.get("nextPlotId"); - JSONObject jumpNextNode = id2j.get(nextId); - JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); - - skipText.append((String)jumpBranchNode.get("reply")); - Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); - updateKnowledge.putAll(newUpdateKnowledge); - - - jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); - - if(jumpNextNextId != null && !jumpNextNextId.equals("")){ - jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place"); - - jumpLocation = jumpNextNextLocation; - updateKnowledge.put("site", jumpNextNextLocation); - updateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); - - } - - branchNode.put("autoJump", jumpBranchNode.get("autoJump")); - branchNode.put("nextPlotId", jumpNextNextId); - - } - - nextId = (String) branchNode.get("nextPlotId"); - reply = (String)branchNode.get("reply"); - - if(updateKnowledge.containsKey("unknownText")) - nextUnknownText = updateKnowledge.get("unknownText"); - else - nextUnknownText = "unknown"; - - - //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - if (id2j.get(nextId) != null) { - nextCondition = (String) id2j.get(nextId).get("conditionName"); - if(nextCondition.equals("")) - nextCondition = "yaobuyao"; - nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0]; - nTaskLineName = "任务线_" + nextLocation + "进度"; - } else { - //如果不存在下一剧情,就将condition设为空,任务线进度不变 - - nextId = id; - nTaskLineName = taskLineName; - nextLocation = location; - nextCondition = "yaobuyao"; - branchNode.put("reply", curUnknownText); - reply = curUnknownText; - branchNode.put("moveWithPlot", false); - } - - lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; - lastTaskReply = "任务线" + nextLocation + "最后的回答"; - - - /** - * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: - * 1: 将剧情停留在最后一步剧情 - * 2. 设一个专门的剧情表示剧情的结尾 - */ - - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; - if(!id.equals(nextId)){ - extraHP += "," + nextId + "::match-Include=null"; - } - - extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; - - - /** - * 1. 主角是否随剧情移动 - * 如果随剧情移动,则更新地点和game_step - * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 - * - * 2. 当前条件是否为空 - * 如果当前条件为空,则提交qa激活并进入下一步剧情 - * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 - * - * 3. 下一部剧情是否为空 - * 如果下一部剧情为空,剧情编号、任务线、地点、不变,condition改为yaobuyao,reply改为当前unknown文本,主角不随剧情移动 - * - * 4. 有没有说去XX - * - * 主角不随剧情移动+当前条件为空+去沙滩 - * 1、沙滩无剧情 - * 2、沙滩有剧情 - * - * 5. 地点变化 - * 1. 当前所处地点 - * 2. 下一步剧情所处地点(包含自动跳转的情况) - * 3. 自动跳转完成后的地点 - */ - - //如果主角的位置随着剧情移动 - if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) { - extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId); - - }else { - - //如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!jumpLocation.equals(nextLocation)){ - if(curUnknownText.equals("")) - reply = "请到" + nextLocation; - //如果当前地点和下一步剧情地点不同,要提示 - else - reply = curUnknownText; - - - - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - - - jConfig = new JConfig( - "yaobuyao::match-Keyword=+" + nextLocation, - "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1 - + "," + nextId + "::number-BiggerOrEqual=" + 1, - "match", (String)branchNode.get("reply") + skipText , (String) nextCondition, - "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId) - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + nextLocation + "_" + id,false); - jConfig.setjStatus(1); - - jConfigList.add(jConfig); - - - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - updateKnowledge.remove("unknownText"); - - //必须在上一个jConfig添加完之后 - //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); - - } - } - - - curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); - historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); - - includeCurInfo = (Boolean)branchNode.get("includeCurInfo"); - if((Boolean)branchNode.get("includeCurInfo")){ - extraFT = ",includeCurInfo"; - }else{ - extraFT = ""; - } - - jConfig = new JConfig( - curPremiseList, - historyPremiseList, - updateKnowledge, - "", extraHP, extraUK, - "match"+extraFT, reply + skipText, (String) nextCondition, "1" - ); - - - //没有当前条件的限制, - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); - jConfig.setNextStep("queryskip*,map*,item*,npc*"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - jConfig.setNextStepStatus("active"); - } - - - - - jConfigList.add(jConfig); - - - if (branchNode.get("nextPlotId") != null) { - adjId = (String) branchNode.get("nextPlotId"); - if (visited.get(adjId) == null) { - if (id2j.get(adjId) != null) { - adjNode = id2j.get(adjId); - - adjNode.put("parentId", id); - adjNode.put("nextUnknownText", nextUnknownText); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); - varInitialMap.put(adjId, ""); - } - } - } - } - - - } - - - /** - * ---------------------------------------------------------------------------------------------------- - * 不设剧情不设条件时的处理 - * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 - * 2. 如果qa返回小于90则只回答剧情文本 - * 3. 如果qa返回not_found则只回答剧情文本 - * 4. 无论哪种情况都会跳下一步剧情 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - - - /** - * ---------------------------------------------------------------------------------------------------- - * 待激活列表,用于qa问答 - */ - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", - " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - - - //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); - //--------------------------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------------------------- - - - /** - * ---------------------------------------------------------------------------------------------------- - * 用于处理开始游戏或者继续游戏 - * - * - */ - - - } - - @Override - public void postProcessing(List idList, int categoryId){ - if (idList.size() != 0) { - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + QA_URL+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - jConfig.setNextStepStatus("active"); - JSONObject json = jConfig.toJson(this.getConditionDescription()); - helper.insertConfigByBotId(botId, json, idList, categoryId); - jConfigList.add(jConfig); - } - } - - - -} diff --git a/src/gameDesign/Scene.java b/src/gameDesign/Scene.java deleted file mode 100644 index 845fd2e..0000000 --- a/src/gameDesign/Scene.java +++ /dev/null @@ -1,5 +0,0 @@ -package gameDesign; - -public class Scene { - -} diff --git a/src/gameDesign/SceneConstructor.java b/src/gameDesign/SceneConstructor.java deleted file mode 100644 index 213dca5..0000000 --- a/src/gameDesign/SceneConstructor.java +++ /dev/null @@ -1,4 +0,0 @@ -package gameDesign; - -public class SceneConstructor { -} diff --git a/src/log4j.properties b/src/log4j.properties deleted file mode 100644 index 6e86266..0000000 --- a/src/log4j.properties +++ /dev/null @@ -1,22 +0,0 @@ -### 设置### -log4j.rootLogger=debug,stdout,D,E -### 输出信息到控制抬 ### -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.Threshold=INFO -log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n -### 输出DEBUG 级别以上的日志文件设置 ### -log4j.appender.D=org.apache.log4j.DailyRollingFileAppender -log4j.appender.D.File=vincent_player_debug.log -log4j.appender.D.Append=true -log4j.appender.D.Threshold=DEBUG -log4j.appender.D.layout=org.apache.log4j.PatternLayout -log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n -### 输出ERROR 级别以上的日志文件设置 ### -log4j.appender.E=org.apache.log4j.DailyRollingFileAppender -log4j.appender.E.File=vincent_player_error.log -log4j.appender.E.Append=true -log4j.appender.E.Threshold=ERROR -log4j.appender.E.layout=org.apache.log4j.PatternLayout -log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000..3fd3a09 --- /dev/null +++ b/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: com.qiwu.chatbotbackend.ChatbotBackendApplication + diff --git a/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java new file mode 100644 index 0000000..4d7ab2f --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/ChatbotBackendApplication.java @@ -0,0 +1,16 @@ +package com.qiwu.chatbotbackend; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ServletComponentScan +@ComponentScan +public class ChatbotBackendApplication { + + public static void main(String[] args) { + SpringApplication.run(ChatbotBackendApplication.class, args); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/Config/Config.java b/src/main/java/com/qiwu/chatbotbackend/Config/Config.java new file mode 100644 index 0000000..172e7b8 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/Config/Config.java @@ -0,0 +1,172 @@ +package com.qiwu.chatbotbackend.Config; + +import org.springframework.stereotype.Component; + +@Component +public class Config { + + //url + public static String CONDITION_URL = null; + public static String QA_URL = null; + public static String CC_URL = null; + + //名字,地址 + public static String GAME_BOT_CATEGORY = null; + + //错误信息 + public static String UPDATE_ERROR = null; + + //游戏生成 + public static String BOT_INFO_NOT_EXIST = null; + public static String INTENT_NOT_UNDERSTAND = null; + public static String PROGRAM_ERROR = null; + public static String NAME_MISSING_ERROR = null; + public static String LOG_PATH = null; + + public static String TEXT_PARSE_ERROR = null; + public static String GAME_MODULE_ERROR = null; + public static String DELETE_OLD_CONFIG_TERM_ERROR = null; + public static String DELETE_OLD_VARIABLE_ERROR = null; + public static String DELETE_OLD_CATEGORY_ERROR = null; + + + + public static String UNKNOWN_TEXT = null; + public static String LOCATION_HINT = null; + public static String GAME_START_HINT = null; + public static String GAME_WELCOME_TEXT = null; + + + public static String UNKNOWN_TEXT_DESCRIPTION = null; + public static String GAME_STEP_DESCRIPTION = null; + public static String START_PLOT_NOT_EXIST = null; + + + public static String ASSISTANT = null; + public static String ASSISTANT_EMOTION = null; + public static String TASK_DESCRIPTION = null; + + public static String TALKER_PATTERN = null; + public static String GAME_STEP_FORMAT = null; + + public static String PLOT_STATUS = null; + + public static String TASK_LINE = null; + public static String TASK_CONDITION = null; + public static String TASK_REPLY = null; + + public static String PLOT_GENERATION_ERROR = null; + + //默认condition + public static String DEFAULT_CONDITION = null; + + //去xx地方condition + public static String GOTO_CONDITION = null; + + + public static class Script { + public static String CODE = "subcode"; + public static int SIZE = 12; + }; + + //condition增删改查 + public static String CONDITION_UPDATE_ERROR = null; + public static String CONDITION_INSERT_ERROR = null; + + public static String CONDITION_BACKEND_ERROR = null; + public static String TOKEN_TIME_OUT = null; + public static String ENCODE_ERROR = null; + + + //话术 + public static String NOTHING_FOUND = null; + public static String DONT_FOUND = null; + public static String NOWHERE_CAN_GO = null; + public static String ATTRIBUTE_HIDDEN = null; + + + + public static String ATTR_VALUE_SLOT = null; + public static String ATTR_NAME_SLOT = null; + public static String NPC_NAME_SLOT = null; + public static String NPC_LIST_SLOT = null; + public static String SITE_SLOT = null; + public static String SITE_SLOT2 = null; + public static String ITEM_LIST_SLOT = null; + public static String ITEM_NAME_SLOT = null; + public static String NPC_ITEM_LIST_SLOT = null; + public static String CAN_GO_SITE_SLOT = null; + public static String PATH_SLOT = null; + public static String START_SLOT = null; + public static String DESTINATION_SLOT = null; + public static String SITE_LIST_SLOT = null; + public static String TASK_DESCRIPTION_SLOT = null; + + public static String FIND_ITEM_OWNER = null; + + + //生成action + public static String ACTION_TEXT_GENERATE_ERROR = null; + public static String CONDITION_NAME_DUMPLICATE = null; + public static String CONDITION_NAME_UPDATE_ERROR = null; + public static String GAME_CONDITION_CATEGORY = null; + public static String AUTOMATCH_THRESHOLD = null; + public static String IDLE_LIMIT = null; + public static String CONDITION_BACKEND_URL = null; + public static String OPTIONS = null; + public static String DEFAULT_STYLE = null; + public static String SERVICE_URL = null; + + public static String FELLOW = null; + + public static String POST_STYLE1 = null; + public static String POST_STYLE2 = null; + + public static String POST_ACTION_HEAD=null; + + + + //condition增删改查异常 + public static String UPDATE_KEYWORD_ERROR = null; + + public static String DELETE_USER_DATA_ERROR = null; + + public static String PLATFORM_SQL_INIT_ERROR = null; + + public static String CATEGORY_UPDATE_CONFLICT = null; + public static String CATEGORY_UPDATE_ERROR = null; + + public static String CATEGORY_DELETE_ERROR = null; + public static String CATEGORY_INSERT_ERROR = null; + public static String CATEGORY_QUERY_ERROR = null; + + public static String JSON_FORMAT_ERROR = null; + + //配置文件增删改查异常 + public static String CONFIG_FILE_NOT_FOUND = null; + public static String CONFIG_DELETE_ERROR = null; + public static String CONFIG_INSERT_ERROR = null; + + //变量 + public static String VARIABLE_NAME_DUMPLICATE = null; + public static String VARIABLE_INSERT_ERROR = null; + public static String VARIABLE_SAVE_FORMAT = null; + public static String VARIABLE_UPDATE_FORMAT = null; + public static String EXTRA_INFO_FORMAT = null; + + public static String VARIABLE_DELETE_ERROR = null; + public static String VARIABLE_SQL_DELETE_ERROR = null; + + public static String VARIABLE_UPDATE_ERROR = null; + + public static String SQL_CONNECTION_ERROR = null; + + public static String BOT_BACKUP_DIR = null; + public static String CONFIG_DIR = null; + + public static String BACKUP_PATH = null; + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java b/src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java new file mode 100644 index 0000000..39d6d30 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/Config/ConfigInitializer.java @@ -0,0 +1,75 @@ +package com.qiwu.chatbotbackend.Config; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Properties; +import java.util.Set; + +public class ConfigInitializer { + + private static final String CONFIGFILE = "config.properties"; + private static final String CLASSPREFIX = "com.qiwu.chatbotbackend.config.config"; + + /** + * 读取配置文件 + */ + public static void init() { + InputStream configInputStream; + try { + BufferedReader bufferedReader = new BufferedReader(new FileReader(CONFIGFILE)); + Properties properties = new Properties(); + properties.load(bufferedReader); + + + initNextLevel(properties, Config.class); + } catch (Exception e) { + e.printStackTrace(); + } finally { + } + } + + public static void initNextLevel(Properties properties, Class nowClass) throws IllegalAccessException { + String baseClassName = nowClass.getName().toLowerCase().replaceAll("\\$", "\\."); + String shortName = baseClassName.replaceAll(CLASSPREFIX, "").replaceFirst("\\.", ""); + //key集合 + Set keys = properties.keySet(); + for (Field field : nowClass.getFields()) { + if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { + + String classParam = field.getName().toLowerCase(); + if (shortName.equals("")) { + if (keys.contains(classParam)) { + pushNewValue(classParam, properties, field); + } + } else { + if (keys.contains(shortName + "." + classParam)) { + pushNewValue(shortName + "." + classParam, properties, field); + } + } + } + } + for (Class aClass : nowClass.getClasses()) { + initNextLevel(properties, aClass); + } + } + + public static void pushNewValue(String classParam, Properties properties, Field field) throws IllegalAccessException { + String value = properties.getProperty(classParam); + if (value != null) { + Class type = field.getType(); + if (type.equals(int.class)) + field.set(null, Integer.valueOf(value)); + else if (type.equals(String.class)) + field.set(null, value); + else if (type.equals(long.class)) + field.set(null, Long.valueOf(value)); + else if (type.equals(boolean.class)) + field.set(null, Boolean.valueOf(value)); + else if (type.isEnum()) + field.set(null, Enum.valueOf((Class) type, value.toUpperCase())); + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java new file mode 100644 index 0000000..4131214 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/C3p0Utils.java @@ -0,0 +1,57 @@ +package com.qiwu.chatbotbackend.GameEnvironment; + + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import org.apache.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class C3p0Utils { + static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); + + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); + + //从连接池中取用一个连接 + public static Connection getConnection() throws Exception { + try { + return dataSource.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //释放连接回连接池 + public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + if (pst != null) { + try { + pst.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java new file mode 100644 index 0000000..d4316ef --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/DBUtil.java @@ -0,0 +1,38 @@ +package com.qiwu.chatbotbackend.GameEnvironment; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class DBUtil { + + public static String queryEnvJsonByBotName(String botName) throws Exception{ + Connection conn = C3p0Utils.getConnection(); + String sql = "select * from generate_json_tb where bot_name = ?"; + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + return result; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java new file mode 100644 index 0000000..6232d34 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/GameEnv.java @@ -0,0 +1,861 @@ +package com.qiwu.chatbotbackend.GameEnvironment; + +import java.io.Serializable; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.qiwu.chatbotbackend.GameEnvironment.bean.GoodsClass; +import com.qiwu.chatbotbackend.GameEnvironment.bean.GoodsInstance; +import com.qiwu.chatbotbackend.GameEnvironment.bean.Nickname; +import com.qiwu.chatbotbackend.GameEnvironment.bean.NpcClass; +import com.qiwu.chatbotbackend.GameEnvironment.bean.NpcInstance; +import com.qiwu.chatbotbackend.GameEnvironment.bean.Place; +import com.qiwu.chatbotbackend.GameEnvironment.bean.PlaceLink; + +public class GameEnv implements Serializable{ + private static final long serialVersionUID = 2L; + // 角色快速查找数据 + public Map npcClassesMap = new HashMap(); + public Map npcInstancesMap = new HashMap(); + + // 玩家跟随的角色列表 + public Map followNpcesMap = new HashMap(); + + // 物品快速查找数据 + public Map goodsClassesMap = new HashMap(); + public Map goodsInstancesMap = new HashMap(); + + // 全局变量快速查找数据 + public Map globalAttrsMap = new HashMap(); + // 地点相关快速查找数据 + public Map placesMap = new HashMap(); + // goGlag=2 联通不相邻可达 + public Map placeLinkDirectGoesMap = new HashMap(); + // goGlag=2 任意可达到 + public Map placeNoLinkDirectGoesMap = new HashMap(); + + // 二维联通地图 + public byte[][] mapUnitMatrix; + // 联通图助手 + public Map placeNameIndexMap = new HashMap(); + public Map indexPlaceNameMap = new HashMap(); + + // 数据别名集合 + public Map nicknamesMap = new HashMap(); + + // 获取别名的助手,帮助创建 + private Nickname getNicknameUtil(String nickname) { + Nickname nicknameObject = this.nicknamesMap.get(nickname); + if(nicknameObject == null) { + nicknameObject = new Nickname(); + } + this.nicknamesMap.put(nickname, nicknameObject); + return nicknameObject; + } + + @SuppressWarnings("unchecked") + public GameEnv(String botName) throws Exception { + + // 从数据库获取环境数据的json字符串 + String jsonString = DBUtil.queryEnvJsonByBotName(botName); + + // 从文件中获取json字符串 +// String jsonString = Util.getJsonString("./data/195.json"); +// System.out.println(jsonString); + + Map gameProjectMap = JSON.parseObject(jsonString); + if(gameProjectMap!=null && !gameProjectMap.isEmpty()) { + // 地图数据处理 + Map placeTmpMap = (Map)gameProjectMap.get("place"); + if(placeTmpMap!=null && !placeTmpMap.isEmpty()) { + // 地图基本数据定义 + List placeNames = new ArrayList<>(placeTmpMap.keySet()); + for(int i=0; i placeMap = (Map)placeTmpMap.get(placeName); + Place place = new Place(); + place.setGoFlag((Integer)placeMap.get("goFlag")); + place.setIntro((String)placeMap.get("intro")); + place.setName(placeName); + this.placesMap.put(placeName, place); + // 为了生成单位矩阵使用 + this.placeNameIndexMap.put(placeName, new Integer(i)); + this.indexPlaceNameMap.put(new Integer(i), placeName); + } + + // 定义的单位矩阵 + this.mapUnitMatrix = new byte[this.placesMap.size()][this.placesMap.size()]; + + // 可去地点、别名、图的数据完善 + for(String placeName:placeTmpMap.keySet()) { + Map placeMap = (Map)placeTmpMap.get(placeName); + Place place = this.placesMap.get(placeName); + // 可去地点 + Map ableGoPlacesMap = new HashMap(); + List ableGoPlaceNames = (List)placeMap.get("ableGoes"); + for(int i=0; i nicknames = (List)placeMap.get("nicknames"); + for(int i=0; i nicknamePlaceMap = nickname.getPlaceMap(); + nicknamePlaceMap.put(place.getName(), place); + } + place.setNickname(nicknames); + place.setName(placeName); + } + + // 格式化图显示结构 + System.out.println("\n\n"); + System.out.print("\t\t"); + for(int i=0; i npcDataTmpMap = (Map)gameProjectMap.get("npc"); + // 角色类 + Map npcClassTmpMap = (Map)npcDataTmpMap.get("class"); + for(String npcClassName:npcClassTmpMap.keySet()) { + Map npcClassAttr = (Map)npcClassTmpMap.get(npcClassName); + NpcClass npcClass = new NpcClass(); + npcClass.setName(npcClassName); + npcClass.setPlace(this.placesMap.get(npcClassAttr.get("所在地点"))); + npcClassAttr.remove("所在地点"); + npcClass.setAttrs(npcClassAttr); + this.npcClassesMap.put(npcClassName, npcClass); + } + // 角色实例 + Map npcInstanceTmpMap = (Map)npcDataTmpMap.get("instance"); + for(String npcInstanceName:npcInstanceTmpMap.keySet()){ + Map npcInstanceAttr = (Map)npcInstanceTmpMap.get(npcInstanceName); + NpcInstance npcInstance = new NpcInstance(); + npcInstance.setName(npcInstanceName); + + // 角色类 + NpcClass npcClass = this.npcClassesMap.get(npcInstanceAttr.get("className")); + npcInstance.setNpcClass(npcClass); + Map npcInstancesClassMap = npcClass.getNpcInstances(); + npcInstancesClassMap.put(npcInstanceName, npcInstance); + npcClass.setNpcInstances(npcInstancesClassMap); + + // 地点 + Place place = this.placesMap.get(npcInstanceAttr.get("所在地点")); + Map npcInstancesPlaceMap = place.getNpcInstances(); + npcInstancesPlaceMap.put(npcInstanceName, npcInstance); + npcInstance.setPlace(place); + + // 别名 + List nicknames = (List)((Map)npcInstanceTmpMap.get(npcInstanceName)).get("nicknames"); + for(int i=0; i npcInstanceMap = nickname.getNpcInstanceMap(); + npcInstanceMap.put(npcInstanceName, npcInstance); + nickname.setNpcInstanceMap(npcInstanceMap); + } + npcInstance.setNickname(nicknames); + npcInstanceAttr.remove("nicknames"); + npcInstanceAttr.remove("className"); + npcInstanceAttr.remove("所在地点"); + npcInstance.setAttrs((Map)npcInstanceAttr); + this.npcInstancesMap.put(npcInstanceName, npcInstance); + } + + + /************************************* 物品 **********************************/ + Map goodsDataTmpMap = (Map)gameProjectMap.get("goods"); + // 物品类 + Map goodsClassTmpMap = (Map)goodsDataTmpMap.get("class"); + for(String goodsClassName:goodsClassTmpMap.keySet()) { + Map goodsClassAttr = (Map)goodsClassTmpMap.get(goodsClassName); + GoodsClass goodsClass = new GoodsClass(); + goodsClass.setName(goodsClassName); + goodsClass.setPlace(this.placesMap.get(goodsClassAttr.get("所在地点"))); + goodsClassAttr.remove("所在地点"); + goodsClass.setAttrs(goodsClassAttr); + this.goodsClassesMap.put(goodsClassName, goodsClass); + } + + // 物品实例 + Map goodsInstanceTmpMap = (Map)goodsDataTmpMap.get("instance"); + for(String goodsInstanceName:goodsInstanceTmpMap.keySet()){ + Map goodsInstanceAttr = (Map)goodsInstanceTmpMap.get(goodsInstanceName); + GoodsInstance goodsInstance = new GoodsInstance(); + goodsInstance.setName(goodsInstanceName); + + // 物品类 + GoodsClass goodsClass = this.goodsClassesMap.get(goodsInstanceAttr.get("className")); + goodsInstance.setGoodsClass(goodsClass); + Map goodsInstancesClassMap = goodsClass.getGoodsInstances(); + goodsInstancesClassMap.put(goodsInstanceName, goodsInstance); + goodsClass.setGoodsInstances(goodsInstancesClassMap); + + // 地点 + Place place = this.placesMap.get(goodsInstanceAttr.get("所在地点")); + Map goodsInstancesPlaceMap = place.getGoodsInstances(); + goodsInstancesPlaceMap.put(goodsInstanceName, goodsInstance); + goodsInstance.setPlace(place); + + // 别名 + List nicknames = (List)(((Map)goodsInstanceTmpMap.get(goodsInstanceName)).get("nicknames")); + for(int i=0; i goodsInstanceMap = nickname.getGoodsInstanceMap(); + goodsInstanceMap.put(goodsInstanceName, goodsInstance); + nickname.setGoodsInstanceMap(goodsInstanceMap); + } + // 所属角色 + // 更新NPC的物品列表 + NpcInstance npcInstance = this.npcInstancesMap.get(goodsInstanceAttr.get("所属角色")); + Map goodsInstancesMap = npcInstance.getGoodsInstances(); + goodsInstancesMap.put(goodsInstance.getName(), goodsInstance); + // 更新物品所属的NPC + goodsInstance.setNpcInstance(npcInstance); + goodsInstance.setNickname(nicknames); + goodsInstanceAttr.remove("nicknames"); + goodsInstanceAttr.remove("className"); + goodsInstanceAttr.remove("所在地点"); + goodsInstanceAttr.remove("所属角色"); + goodsInstance.setAttrs((Map)goodsInstanceAttr); + this.goodsInstancesMap.put(goodsInstanceName, goodsInstance); + } + + // 全局变量 + this.globalAttrsMap = (Map)gameProjectMap.get("globalAttr"); + } + } + // 查找别名数据 + public List queryNickname(String nicknameStr, String type) { + Nickname nickname = this.nicknamesMap.get(nicknameStr); + List nameIds = new ArrayList(); + if(type.equals("place")) { + if(nickname != null && !nickname.getPlaceMap().isEmpty()) { + nameIds.addAll(nickname.getPlaceMap().keySet()); + } + }else if(type.equals("goods")) { + if(nickname != null && !nickname.getGoodsInstanceMap().isEmpty()) { + nameIds.addAll(nickname.getGoodsInstanceMap().keySet()); + } + }else if(type.equals("npc")) { + if(nickname != null && !nickname.getNpcInstanceMap().isEmpty()) { + nameIds.addAll(nickname.getNpcInstanceMap().keySet()); + } + } + return nameIds; + } + public GoodsInstance findGoodsInstanceByNameOrNickname(String str1) { + GoodsInstance goodsInstance = queryGoodsByGoodsName(str1); + if(goodsInstance == null) { + List idNames = this.queryNickname(str1, "goods"); + if(idNames.size()!=0) { + goodsInstance = this.goodsInstancesMap.get(idNames.get(0)); + return goodsInstance; + }else { + return null; + } + }else { + return goodsInstance; + } + } + public NpcInstance findNpcInstanceByNameOrNickname(String str1) { + NpcInstance npcInstance = this.queryNpcByNpcName(str1); + if(npcInstance == null) { + List idNames = this.queryNickname(str1, "npc"); + if(idNames.size()!=0) { + npcInstance = this.npcInstancesMap.get(idNames.get(0)); + return npcInstance; + }else { + return null; + } + }else { + return npcInstance; + } + } + // 两点之间的路径 // 使用广度优先算法单源最短路的SPFA算法的全称是:Shortest Path Faster Algorithm。只有状态为2的时候使用 + public List getAllPath(String placeA, String placeB){ + List paths = new ArrayList(); + Deque placeDeque = new ArrayDeque(); + Integer start = this.placeNameIndexMap.get(placeA); + PlaceLink placeLink = new PlaceLink(); + placeLink.setIndex(start); + boolean[] marked = new boolean[this.placeNameIndexMap.size()]; + for(int j=0; j nickname = this.placesMap.get(this.indexPlaceNameMap.get(new Integer(i))).getNickname(); + if(this.indexPlaceNameMap.get(new Integer(i)).equals(placeB) || (nickname!=null && nickname.indexOf(placeB)>=0)) { + while(placeLinkNodeSecond.getPlaceLink() != null) { + paths.add(this.indexPlaceNameMap.get(new Integer(placeLinkNodeSecond.getIndex()))); + placeLinkNodeSecond = placeLinkNodeSecond.getPlaceLink(); + } + paths.add(this.indexPlaceNameMap.get(new Integer(placeLinkNodeSecond.getIndex()))); + flag = 1; + break; + } + placeDeque.push(placeLinkNodeSecond); + } + } + } + } + Collections.reverse(paths); + return paths; + } + // 两点之间的通过的地方 + public List queryPathBySite(String placeA, String placeB){ + List paths = this.getAllPath(placeA, placeB); + if(paths.size() < 2) { + // 返回null表示不能到达 + return null; + }else{ + // 返回空表示相邻直接去 + // 中间有数据说明需要经过... + return paths.subList(1, paths.size()-1); + } + } + /********************************************地点******************************************/ + // 周围有什么 + public List queryAroundAllBySite(String site){ + List somethings = new ArrayList(); + Place place = this.placesMap.get(site); + if(place==null) { + return somethings; + } + Map goodsInstances = place.getGoodsInstances(); + Map npcInstances = place.getNpcInstances(); + somethings.addAll(goodsInstances.keySet()); + somethings.addAll(npcInstances.keySet()); + return somethings; + } + // 周围有什么人 + public List queryAroundNpcBySite(String site){ + Place place = this.placesMap.get(site); + List queryNpc = new ArrayList(); + if(place == null) { + return queryNpc; + } + queryNpc.addAll(place.getNpcInstances().keySet()); + return queryNpc; + } + // 周围有什么物品 + public List queryAroundGoodsBySite(String site){ + List queryGoods = new ArrayList(); + Place place = this.placesMap.get(site); + if(place == null) { + return queryGoods; + } + queryGoods.addAll(place.getGoodsInstances().keySet()); + return queryGoods; + } + // 我现在能去哪 需要用到联通图算法 + public List queryCanGoBySite(String site){ + List ableGoStrs = new ArrayList(); + // 任意可达 + for(String placeName : this.placeNoLinkDirectGoesMap.keySet()) { + ableGoStrs.add(placeName); + } + // 查询附近地点 + Integer x = this.placeNameIndexMap.get(site); + if(x == null) { + return ableGoStrs; + } + for(int y=0; y paths = this.getAllPath(site, placeName); + if(paths.size()>0) { + ableGoStrs.add(placeName); + } + } + } + return ableGoStrs; + } + // 两个地点的位置关系 ### 这个接口有疑问 + /* + * 0:就在当前地点 + * 1:相邻可以到 + * 2:不相邻,联通可以到达 + * 3:联通直接可以到达 + * 4:任意可达 + * 5:不可到达 + * */ + public Integer isNeighbour(String placeA, String placeB) { + Place place = this.placesMap.get(placeA); + if(place == null) { + return new Integer(5); + } + + // 地点名称相同 + if(placeA.equals(placeB)) { + return 0; + } + + // 地点名和地点别名相同 + if(this.queryNickname(placeB, "place").indexOf(placeA) != -1) { + return 0; + } + + // 任意可达 + for(String placeName : this.placeNoLinkDirectGoesMap.keySet()) { + if(placeName.equals(placeB) || this.queryNickname(placeB, "place").indexOf(placeName) != -1) { + return 4; + } + } + + // 相邻可以去的地点 + int x = this.placeNameIndexMap.get(placeA); + for(int y=0; y paths = this.getAllPath(placeA, placeName); + if(paths.size()>0) { + return 3; + } + } + } + + // 联通不相邻不可以直达 + for(String placeName:this.placesMap.keySet()) { + if(!this.placeLinkDirectGoesMap.keySet().contains(placeName) && !this.placeNoLinkDirectGoesMap.keySet().contains(placeName)) { + if(placeName.equals(placeB) || this.queryNickname(placeB, "place").indexOf(placeName) != -1) { + List paths = this.getAllPath(placeA, placeName); + if(paths.size()>0) { + return 2; + } + } + } + } + + // 既不相邻,也不能到达 + return new Integer(5); + } + // 通过别名查询当前地点最近的地点 + public String getPlaceNameByNickname(String curPlaceName, String nickname) { + Place place = this.placesMap.get(curPlaceName); + if(place == null) { + return nickname; + } + if(place.getNickname().indexOf(nickname)>=0) { + return curPlaceName; + }else { + List placePath = this.getAllPath(curPlaceName, nickname); + if(placePath.size()>=2) { + return placePath.get(placePath.size()-1); + }else { + return nickname; + } + } + } + // 通过别名查询最近地点的角色 + public String queryCurPlaceNpcInstanceByNickname(String curPlaceName, String nickname) { + Map npcInstancesMap = this.placesMap.get(curPlaceName).getNpcInstances(); + for(String npcInstanceName:npcInstancesMap.keySet()) { + NpcInstance npcInstance = npcInstancesMap.get(npcInstanceName); + if(npcInstance.getNickname().indexOf(nickname) >= 0) { + return npcInstance.getName(); + } + } + return null; + } + // 通过别名查询最近地点的物品 + public String queryCurPlaceGoodsInstanceByNickname(String curPlaceName, String nickname) { + Map goodsInstancesMap = this.placesMap.get(curPlaceName).getGoodsInstances(); + for(String goodsInstanceName:goodsInstancesMap.keySet()) { + GoodsInstance goodsInstance = goodsInstancesMap.get(goodsInstanceName); + if(goodsInstance.getNickname().indexOf(nickname)>=0) { + return goodsInstance.getName(); + } + } + return null; + } + + // 通过别名查询当前地点最近的npc + public String getNpcNameByNickname(String curPlaceName, String nickname) { + // 寻找两层 + // 查询当前地点的所有,和当前地点可以去到的地点相应的所有 + String npcInstanceName = this.queryCurPlaceNpcInstanceByNickname(curPlaceName, nickname); + if(npcInstanceName!=null) { + return npcInstanceName; + } + Map placesMap = this.placesMap.get(curPlaceName).getAbleGoes(); + for(String placeName:placesMap.keySet()) { + Place place = placesMap.get(placeName); + npcInstanceName = this.queryCurPlaceNpcInstanceByNickname(place.getName(), nickname); + if(npcInstanceName!=null) { + return npcInstanceName; + } + } + return nickname; + } + + // 通过别名查询当前地点最近的物品 + public String getGoodsNameByNickname(String curPlaceName, String nickname) { + // 寻找两层 + // 查询当前地点的所有,和当前地点可以去到的地点相应的所有 + String npcInstanceName = this.queryCurPlaceGoodsInstanceByNickname(curPlaceName, nickname); + if(npcInstanceName!=null) { + return npcInstanceName; + } + Map cangoPlacesMap = this.placesMap.get(curPlaceName).getAbleGoes(); + for(String placeName:cangoPlacesMap.keySet()) { + Place place = cangoPlacesMap.get(placeName); + npcInstanceName = this.queryCurPlaceGoodsInstanceByNickname(place.getName(), nickname); + if(npcInstanceName!=null) { + return npcInstanceName; + } + } + return nickname; + } + + /*********************************通过npc获取物品列表**********************************/ + // 通过npcName获取所有物品名称列表 + public List queryGoodsByNpcName(String npcName){ + List goodsNames = new ArrayList(); + if(this.npcInstancesMap.get(npcName)!=null) { + Map goodsInstancesMap = this.npcInstancesMap.get(npcName).getGoodsInstances(); + if(goodsInstancesMap != null && !goodsInstancesMap.isEmpty()) { + for(String goodsInstanceName:goodsInstancesMap.keySet()) { + goodsNames.add(goodsInstancesMap.get(goodsInstanceName).getName()); + } + } + } + return goodsNames; + } + /**************************************goods****************************************/ + // 通过类和地点查询所有物品名称 + // 只有当可以询问的属性为是的时候才可以得到相应的物品列表 + public List queryGoodsByClassAndSite(String site, String className){ + List goodsNames = new ArrayList(); + if(this.placesMap.get(site)!=null && this.goodsClassesMap.get(className)!=null) { + Map placeGoodsInstances = this.placesMap.get(site).getGoodsInstances(); + Map classGoodsInstances = this.goodsClassesMap.get(className).getGoodsInstances(); + for(String placeGoodsInstanceName:placeGoodsInstances.keySet()) { + for(String classGoodsInstanceName:classGoodsInstances.keySet()) { + if(placeGoodsInstanceName.equals(classGoodsInstanceName)) { + goodsNames.add(placeGoodsInstanceName); + } + } + } + } + return goodsNames; + } + // 查询指定物品 + public GoodsInstance queryGoodsByGoodsName(String name){ + GoodsInstance goodsInstance = this.goodsInstancesMap.get(name); + return goodsInstance; + } + // 查询指定物品的简介 + public String queryGoodsIntroByGoodsName(String name){ + GoodsInstance goodsInstance = this.queryGoodsByGoodsName(name); + if(goodsInstance !=null) { + return goodsInstance.getAttrs().get("intro"); + }else { + return null; + } + } + + // 查询指定物品的属性值 + public String queryGoodsAttrByGoodsName(String str1, String str2){ + GoodsInstance goodsInstance = this.findGoodsInstanceByNameOrNickname(str1); + String attrName = str2; + if(goodsInstance == null) { + goodsInstance = this.findGoodsInstanceByNameOrNickname(str2); + attrName = str1; + } + if(goodsInstance != null) { + Map attrsMap = goodsInstance.getAttrs(); + if(attrName.equals("location")) { + if(goodsInstance.getPlace()!=null) { + return goodsInstance.getPlace().getName(); + } + } + if(attrName.equals("owner")) { + if(goodsInstance.getNpcInstance()!=null) { + return goodsInstance.getNpcInstance().getName(); + } + } + return attrsMap.get(attrName); + }else { + return null; + } + } + // 查询指定物品的所有属性 + public List queryGoodsAllAttrByGoodsName(String name){ + List attrnames = new ArrayList(); + GoodsInstance goodsInstance = findGoodsInstanceByNameOrNickname(name); + if(goodsInstance != null) { + Map attrsMap = goodsInstance.getAttrs(); + attrnames.addAll(attrsMap.keySet()); + return attrnames; + }else { + return null; + } + } + // 查询物品的地点 + public String queryGoodsSiteByGoodsName(String goodsName) { + return this.goodsInstancesMap.get(goodsName).getPlace().getName(); + } + + /**************************************npc*****************************************/ + // 通过地点和类查询所有的NPC实例 + public List queryNpcByClassAndSite(String site, String className){ + List npcNames = new ArrayList(); + Map placeNpcInstancesMap = this.placesMap.get(site).getNpcInstances(); + Map classNpcInstances = this.npcClassesMap.get(className).getNpcInstances(); + for(String placeNpcInstanceName:placeNpcInstancesMap.keySet()) { + for(String classNpcInstance:classNpcInstances.keySet()) { + if(placeNpcInstanceName.equals(classNpcInstance)) { + npcNames.add(placeNpcInstanceName); + } + } + } + + return npcNames; + } + // 查询指定的NPC + public NpcInstance queryNpcByNpcName(String npcName){ + NpcInstance npcInstance = this.npcInstancesMap.get(npcName); + return npcInstance; + } + // 查询指定NPC简介 + public String queryNpcIntroByNpcName(String name){ + NpcInstance npcInstance = queryNpcByNpcName(name); + return npcInstance.getAttrs().get("intro"); + } + // 查询指定npc的属性值 + public String queryNpcAttrByNpcName(String str1, String str2){ + NpcInstance npcInstance = this.findNpcInstanceByNameOrNickname(str1); + String attrName = str2; + if(npcInstance == null) { + npcInstance = this.findNpcInstanceByNameOrNickname(str2); + attrName = str1; + } + if(npcInstance != null) { + if(attrName.equals("location")) { + if(npcInstance.getPlace()!=null) { + return npcInstance.getPlace().getName(); + } + } + Map npcInstanceAttrsMap = npcInstance.getAttrs(); + return npcInstanceAttrsMap.get(attrName); + }else { + return null; + } + } + // 查询指定npc的所有属性 + public List queryNpcAttrsByNpcName(String name){ + List attrNames = new ArrayList(); + NpcInstance npcInstance = queryNpcByNpcName(name); + if(npcInstance != null) { + attrNames.addAll(npcInstance.getAttrs().keySet()); + return attrNames; + }else { + return null; + } + } + // 查询角色的地点 + public String queryNpcSiteByNpcName(String npcName) { + return this.queryNpcByNpcName(npcName).getPlace().getName(); + } + // 增加 + public boolean insert(String name){ + return true; + } + // 改变 + public boolean update(String name, String value) { + String[] names = name.split("_"); + if(names.length == 4){ + if(names[0].equals("goods")){ + if(this.goodsClassesMap.get(names[1])!=null) { + Map goodsInstancesByClass = this.goodsClassesMap.get(names[1]).getGoodsInstances(); + GoodsInstance goodsInstance = this.goodsInstancesMap.get(names[2]); + if(goodsInstancesByClass.get(goodsInstance.getName())!=null) { + Map goodsInstanceAttrsMap = goodsInstance.getAttrs(); + if(names[3].equals("所在地点")) { + Place placeOrigin = goodsInstance.getPlace(); + Map goodsInstancesMap = placeOrigin.getGoodsInstances(); + goodsInstancesMap.remove(goodsInstance.getName()); + Place place= this.placesMap.get(value); + goodsInstance.setPlace(place); + goodsInstancesMap = place.getGoodsInstances(); + goodsInstancesMap.put(goodsInstance.getName(), goodsInstance); + return true; + }else if(names[3].equals("所属角色")) { + NpcInstance npcInstance= goodsInstance.getNpcInstance(); + if(npcInstance != null) { + Map goodsInstancesMap = npcInstance.getGoodsInstances(); + goodsInstancesMap.remove(goodsInstance.getName()); + } + npcInstance = this.npcInstancesMap.get(value); + goodsInstance.setNpcInstance(npcInstance); + Map goodsInstances = npcInstance.getGoodsInstances(); + goodsInstances.put(goodsInstance.getName(), goodsInstance); + npcInstance.setGoodsInstances(goodsInstances); + return true; + }else { + goodsInstanceAttrsMap.put(names[3], value); + return true; + } + }else { + return false; + } + }else { + return false; + } + }else if(names[0].equals("npc")) { + NpcInstance npcInstance = this.npcInstancesMap.get(names[2]); + if(npcInstance!=null) { + if(npcInstance.getNpcClass().getName().equals(names[1])) { + Map npcInstanceAttrMap = npcInstance.getAttrs(); + if(names[3].equals("跟随玩家")) { + if(value.equals("是")) { + this.followNpcesMap.put(npcInstance.getName(), npcInstance); + }else if(value.equals("否")) { + this.followNpcesMap.remove(npcInstance.getName()); + }else { + return true; + } + }else if(names[3].equals("所在地点")) { + Place placeOrigin = npcInstance.getPlace(); + Map npcInstancesMap = placeOrigin.getNpcInstances(); + npcInstancesMap.remove(npcInstance.getName()); + Place place= this.placesMap.get(value); + npcInstance.setPlace(place); + npcInstancesMap = place.getNpcInstances(); + npcInstancesMap.put(npcInstance.getName(), npcInstance); + // 更新跟随的NPC物品的位置 + return true; + }else { + npcInstanceAttrMap.put(names[3], value); + return true; + } + }else { + return false; + } + }else { + return false; + } + }else if(names.length == 3 && names[0].equals("place")) { + Place place = this.placesMap.get(names[1]); + if(place!=null) { + if(names[2].equals("到达条件")) { + place.setGoFlag(Integer.parseInt(value)); + if(place.getGoFlag().equals(1)) { + this.placeLinkDirectGoesMap.put(place.getName(),place); + this.placeNoLinkDirectGoesMap.remove(place.getName()); + }else if(place.getGoFlag().equals(2)) { + this.placeLinkDirectGoesMap.put(place.getName(),place); + this.placeNoLinkDirectGoesMap.remove(place.getName()); + } + return true; + }else if(names[2].equals("可去地点")) { + String[] ableGos = value.split("~"); + if(this.placeNameIndexMap.get(place.getName()) != null){ + // 找到可去地点的那一行 + byte[] line = this.mapUnitMatrix[this.placeNameIndexMap.get(place.getName())]; + // 将可去地点清空 + for(int ag=0; ag ableGoes = new HashMap(); + for(int ag=0; ag attrs; + // 类下面有哪些实例 + private Map goodsInstances = new HashMap(); + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public Map getAttrs() { + return attrs; + } + public void setAttrs(Map attrs) { + this.attrs = attrs; + } + public Map getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(Map goodsInstances) { + this.goodsInstances = goodsInstances; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "GoodsClass [name=" + name + "place" +place.getName()+ ", attrs=" + attrs + ", goodsInstances=" + goodsInstances + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java new file mode 100644 index 0000000..6325160 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/GoodsInstance.java @@ -0,0 +1,64 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GoodsInstance implements Serializable{ + private static final long serialVersionUID = 2L; + private String name; + private List nickname = new ArrayList(); + private Map attrs = new HashMap(); + private GoodsClass goodsClass; + private NpcInstance npcInstance; + private Place place; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public List getNickname() { + return nickname; + } + public void setNickname(List nickname) { + this.nickname = nickname; + } + public Map getAttrs() { + return attrs; + } + public void setAttrs(Map attrs) { + this.attrs = attrs; + } + public NpcInstance getNpcInstance() { + return npcInstance; + } + public void setNpcInstance(NpcInstance npcInstance) { + this.npcInstance = npcInstance; + } + public GoodsClass getGoodsClass() { + return goodsClass; + } + public void setGoodsClass(GoodsClass goodsClass) { + this.goodsClass = goodsClass; + } + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "GoodsInstance [nickname=" + nickname + "name="+name+", attrs=" + attrs + ", goodsClass=" + goodsClass.getName() + + ", npcInstance=" + npcInstance.getName() + ", place=" + place.getName() + "]"; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java new file mode 100644 index 0000000..6fd5504 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Nickname.java @@ -0,0 +1,38 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class Nickname implements Serializable{ + private static final long serialVersionUID = 2L; + private Map goodsInstanceMap = new HashMap(); + private Map npcInstanceMap = new HashMap(); + private Map placeMap = new HashMap(); + public Map getGoodsInstanceMap() { + return goodsInstanceMap; + } + public void setGoodsInstanceMap(Map goodsInstanceMap) { + this.goodsInstanceMap = goodsInstanceMap; + } + public Map getNpcInstanceMap() { + return npcInstanceMap; + } + public void setNpcInstanceMap(Map npcInstanceMap) { + this.npcInstanceMap = npcInstanceMap; + } + public Map getPlaceMap() { + return placeMap; + } + public void setPlaceMap(Map placeMap) { + this.placeMap = placeMap; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "Nickname [goodsInstanceMap=" + goodsInstanceMap + ", npcInstanceMap=" + npcInstanceMap + ", placeMap=" + + placeMap + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java new file mode 100644 index 0000000..43351e8 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcClass.java @@ -0,0 +1,45 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class NpcClass implements Serializable{ + private static final long serialVersionUID = 2L; + private String name; + private Place place; + private Map attrs = new HashMap(); + // 类下面有哪些实例 + private Map npcInstances = new HashMap(); + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public Map getAttrs() { + return attrs; + } + public void setAttrs(Map attrs) { + this.attrs = attrs; + } + public Map getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(Map npcInstances) { + this.npcInstances = npcInstances; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "NpcClass [name=" + name + ",place" + place.getName()+", attrs=" + attrs + ", npcInstances=" + npcInstances + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java new file mode 100644 index 0000000..a07eeb1 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/NpcInstance.java @@ -0,0 +1,61 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NpcInstance implements Serializable{ + private static final long serialVersionUID = 2L; + private String name; + private List nickname = new ArrayList(); + private Map attrs = new HashMap(); + private NpcClass npcClass; + private Place place; + private Map goodsInstances = new HashMap(); + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public List getNickname() { + return nickname; + } + public void setNickname(List nickname) { + this.nickname = nickname; + } + public Map getAttrs() { + return attrs; + } + public void setAttrs(Map attrs) { + this.attrs = attrs; + } + public NpcClass getNpcClass() { + return npcClass; + } + public void setNpcClass(NpcClass npcClass) { + this.npcClass = npcClass; + } + public Place getPlace() { + return place; + } + public void setPlace(Place place) { + this.place = place; + } + public Map getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(Map goodsInstances) { + this.goodsInstances = goodsInstances; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "NpcInstance [name=" + name + ", nickname=" + nickname + ", attrs=" + attrs + ", npcClass=" + npcClass.getName() + + ", place=" + place.getName() + ", goodsInstances=" + goodsInstances + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java new file mode 100644 index 0000000..61fe1f4 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/Place.java @@ -0,0 +1,84 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Place implements Serializable{ + private static final long serialVersionUID = 2L; + private String name; + /* + * 1:联通相邻可去 + * 2:联通不相邻可去 + * 3:不联通不相邻可去 + * */ + private String intro; + private Integer goFlag; + private List nickname = new ArrayList(); + private Map ableGoes = new HashMap(); + private Map npcInstances = new HashMap(); + private Map goodsInstances = new HashMap(); + public String transformGoFlag(Integer goFlag) { + if(goFlag.equals(new Integer(1))) { + return "联通相邻可去"; + }else if(goFlag.equals(new Integer(2))){ + return "联通不相邻可去"; + }else if(goFlag.equals(new Integer(3))) { + return "不联通不相邻可去"; + }else { + return "错误 go flag!"; + } + } + 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 Integer getGoFlag() { + return goFlag; + } + public void setGoFlag(Integer goFlag) { + this.goFlag = goFlag; + } + public List getNickname() { + return nickname; + } + public void setNickname(List nickname) { + this.nickname = nickname; + } + public Map getAbleGoes() { + return ableGoes; + } + public void setAbleGoes(Map ableGoes) { + this.ableGoes = ableGoes; + } + public Map getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(Map npcInstances) { + this.npcInstances = npcInstances; + } + public Map getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(Map goodsInstances) { + this.goodsInstances = goodsInstances; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "Place [name=" + name + ",intro" + intro +", goFlag=" + this.transformGoFlag(goFlag) + ", nickname=" + nickname + ", ableGo=" + ableGoes.keySet() + + ", npcInstances=" + npcInstances + ", goodsInstances=" + goodsInstances + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java new file mode 100644 index 0000000..408030d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/PlaceLink.java @@ -0,0 +1,28 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; + +public class PlaceLink implements Serializable{ + private static final long serialVersionUID = 2L; + private Integer index; + private PlaceLink placeLink; + public Integer getIndex() { + return index; + } + public void setIndex(Integer index) { + this.index = index; + } + public PlaceLink getPlaceLink() { + return placeLink; + } + public void setPlaceLink(PlaceLink placeLink) { + this.placeLink = placeLink; + } + public static long getSerialversionuid() { + return serialVersionUID; + } + @Override + public String toString() { + return "PlaceLink [index=" + index + ", placeLink=" + placeLink + "]"; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java new file mode 100644 index 0000000..54d9e5e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/GameEnvironment/bean/SuperClass.java @@ -0,0 +1,53 @@ +package com.qiwu.chatbotbackend.GameEnvironment.bean; + +import java.io.Serializable; +import java.util.List; + +public class SuperClass implements Serializable{ + private static final long serialVersionUID = 1L; + private String name; + private String intro; + private List attrs; + private List goodsInstances; + private List npcInstances; + + public List getGoodsInstances() { + return goodsInstances; + } + public void setGoodsInstances(List goodsInstances) { + this.goodsInstances = goodsInstances; + } + public List getNpcInstances() { + return npcInstances; + } + public void setNpcInstances(List npcInstances) { + this.npcInstances = npcInstances; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getIntro() { + return intro; + } + public void setIntro(String intro) { + this.intro = intro; + } + public List getAttrs() { + return attrs; + } + public void setAttrs(List attrs) { + this.attrs = attrs; + } + @Override + public String toString() { + int goodsInstanceSize = 0; + if(goodsInstances!=null) { + goodsInstanceSize = goodsInstances.size(); + } + return "SuperClass [name=" + name + ", intro=" + intro + "goodsInstancesSize="+goodsInstanceSize+", attrs=" + attrs + "]"; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java new file mode 100644 index 0000000..8686840 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/EngineUtils.java @@ -0,0 +1,185 @@ +package com.qiwu.chatbotbackend.actiongenerate.DB; + +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.EngineUnit; +import com.qiwu.chatbotbackend.db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EngineUtils { + + private Connection conn = null; + + + public EngineUtils() throws SQLException { + conn = C3p0Utils.getEngineConnection(); + } + + + public void destroy() { + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + + + public String queryKeywordUnitText(int botId){ + String sql = "select text from units where user_id = ? and name = 'keywords'"; + String keywordText = ""; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + keywordText = (rs.getString("text")); + } + + ps.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return keywordText; + } + + public Boolean updateKeywordUnitText(int botId, String keywordText){ + Boolean b = true; + String sql = "update units set text = ? where user_id = ? and name = 'keywords'"; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, keywordText); + ps.setInt(2,botId); + + b = ps.executeUpdate() == 1; + ps.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return b; + } + + + + public Boolean updateWelcomeText(int botId, String welcome){ + boolean b; + + try { + String sql = "update users set welcome = ? where id=?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, welcome + "#welcome"); + ps1.setInt(2, botId); + + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + + + public Map queryConditionPatternText(int botId, List patternRelationList){ + String sql = "select user_id, text from `users` join `units` on users.id = units.user_id where users.username in ('" + Joiner.on("','").join(patternRelationList)+ "') and units.name = 'actions'"; + String keywordText = ""; + Map patternTextMap = new HashMap(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + //ps.setString(1, Joiner.on(",").join(patternRelationList)); + ResultSet rs = ps.executeQuery(); + + + + while(rs.next()){ + patternTextMap.put(rs.getInt("user_id"), rs.getString("text")); + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return patternTextMap; + } + + public Map queryUnitsByIdList(List idList){ + String sql = "select user_id, name, text from units where user_id in (" + Joiner.on(",").join(idList) + ") and name in ('actions','keywords')"; + + Integer id; + Map id2unit= new HashMap(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + //ps.setArray(1, idList.toArray()); + ResultSet rs = ps.executeQuery(); + + while(rs.next()){ + id = rs.getInt("user_id"); + if(id2unit.get(id) == null){ + id2unit.put(id, new EngineUnit()); + } + switch(rs.getString("name")){ + case "actions": + id2unit.get(id).setActions(rs.getString("text")); + break; + case "keywords": + id2unit.get(id).setKeywords(rs.getString("text")); + break; + } + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return id2unit; + } + + + public String queryBotAccountByBotId(int botId){ + String sql = "select username from users where id= ?"; + String botAccount = ""; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + botAccount = rs.getString("username"); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return botAccount; + } + + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java new file mode 100644 index 0000000..8cd2e5d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/DB/PlatformUtils.java @@ -0,0 +1,56 @@ +package com.qiwu.chatbotbackend.actiongenerate.DB; + +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.db.C3p0Utils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class PlatformUtils { + + private Connection conn = null; + + + public PlatformUtils() throws SQLException { + conn = C3p0Utils.getPlatformConnection(); + } + + + public void destroy() { + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + public List queryConditionIdByTypetreeId(List typetreeIdList){ + String sql = "select conditionId from typetreeNcondition where typetreeId in (?)"; + String keywordText = ""; + List idList = new ArrayList(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1,Joiner.on(",").join(typetreeIdList)); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + idList.add(rs.getInt("conditionId")); + } + + ps.close(); + rs.close(); + + }catch(Exception e){ + e.printStackTrace(); + } + return idList; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java new file mode 100644 index 0000000..cdcde08 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ActionPostElem.java @@ -0,0 +1,113 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONArray; + +public class ActionPostElem { + String botName = ""; + String actionText = ""; + String authorization = ""; + Integer botId = 0; + String categoryName = ""; + JSONArray conditionIdPair = new JSONArray(); + String botType = ""; + + public ActionPostElem(String actionText, Integer botId, String botName, String categoryName, String authorization) { + this.botId = botId; + this.botName = botName; + this.actionText = actionText; + this.categoryName = categoryName; + this.authorization = authorization; + } + + + public ActionPostElem(String actionText, Integer botId, String botName, String categoryName, String authorization, String botType) { + this.botId = botId; + this.botName = botName; + this.actionText = actionText; + this.categoryName = categoryName; + this.authorization = authorization; + + if(botType != null) + this.botType = botType; + + } + + + + public ActionPostElem(Integer botId, String botName, String authorization) { + this.authorization = authorization; + this.botId = botId; + this.botName = botName; + } + + + public ActionPostElem(Integer botId, String botName, String actionText, String authorization, String categoryName, JSONArray conditionIdPair) { + this.botName = botName; + this.actionText = actionText; + this.authorization = authorization; + this.botId = botId; + this.categoryName = categoryName; + this.conditionIdPair = conditionIdPair; + } + + public String getBotName() { + return botName; + } + + public void setBotName(String botName) { + this.botName = botName; + } + + public String getActionText() { + return actionText; + } + + public void setActionText(String actionText) { + this.actionText = actionText; + } + + public String getAuthorization() { + return authorization; + } + + public void setAuthorization(String authorization) { + this.authorization = authorization; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + + public Integer getBotId() { + return botId; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public JSONArray getConditionIdPair() { + return conditionIdPair; + } + + public void setConditionIdPair(JSONArray conditionIdPair) { + this.conditionIdPair = conditionIdPair; + } + + + public String getBotType() { + return botType; + } + + public void setBotType(String botType) { + this.botType = botType; + } +} + + + diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java new file mode 100644 index 0000000..64df68a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Backup.java @@ -0,0 +1,91 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import java.util.List; + +public class Backup { + + int botId; + String botName; + String botCategoryName; + List conditionList =null; + List configTermList = null; + List categoryList = null; + List variableList = null; + BotInfo botInfo = null; + + public Backup(int botId, String botName, String botCategoryName, + List conditionList, List configTermList, List categoryList, List variableList, BotInfo botInfo) { + this.botId = botId; + this.botName = botName; + this.botCategoryName = botCategoryName; + this.conditionList = conditionList; + this.configTermList = configTermList; + this.categoryList = categoryList; + this.variableList = variableList; + this.botInfo = botInfo; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public String getBotName() { + return botName; + } + + public void setBotName(String botName) { + this.botName = botName; + } + + public String getBotCategoryName() { + return botCategoryName; + } + + public void setBotCategoryName(String botCategoryName) { + this.botCategoryName = botCategoryName; + } + + public List getConditionList() { + return conditionList; + } + + public void setConditionList(List conditionList) { + this.conditionList = conditionList; + } + + public List getConfigTermList() { + return configTermList; + } + + public void setConfigTermList(List configTermList) { + this.configTermList = configTermList; + } + + public List getCategoryList() { + return categoryList; + } + + public void setCategoryList(List categoryList) { + this.categoryList = categoryList; + } + + public List getVariablesList() { + return variableList; + } + + public void setVariablesList(List variableList) { + this.variableList = variableList; + } + + public BotInfo getBotInfo() { + return botInfo; + } + + public void setBotInfo(BotInfo botInfo) { + this.botInfo = botInfo; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java new file mode 100644 index 0000000..27a2ee7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/BotInfo.java @@ -0,0 +1,80 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class BotInfo { + Integer botId; + String welcomeText; + String goodbyeText; + String postURL; + String defaultConfigCategory; + String bothValue; + String queryTextTransfer; + + public BotInfo(Integer botId, String welcomeText, String goodbyeText, + String postURL, String defaultConfigCategory, + String bothValue, String queryTextTransfer) { + this.botId = botId; + this.welcomeText = welcomeText; + this.goodbyeText = goodbyeText; + this.postURL = postURL; + this.defaultConfigCategory = defaultConfigCategory; + this.bothValue = bothValue; + this.queryTextTransfer = queryTextTransfer; + } + + + public Integer getBotId() { + return botId; + } + + public String getWelcomeText() { + return welcomeText; + } + + public String getGoodbyeText() { + return goodbyeText; + } + + public String getPostURL() { + return postURL; + } + + public String getDefaultConfigCategory() { + return defaultConfigCategory; + } + + public String getBothValue() { + return bothValue; + } + + public String getQueryTextTransfer() { + return queryTextTransfer; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public void setWelcomeText(String welcomeText) { + this.welcomeText = welcomeText; + } + + public void setGoodbyeText(String goodbyeText) { + this.goodbyeText = goodbyeText; + } + + public void setPostURL(String postURL) { + this.postURL = postURL; + } + + public void setDefaultConfigCategory(String defaultConfigCategory) { + this.defaultConfigCategory = defaultConfigCategory; + } + + public void setBothValue(String bothValue) { + this.bothValue = bothValue; + } + + public void setQueryTextTransfer(String queryTextTransfer) { + this.queryTextTransfer = queryTextTransfer; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java new file mode 100644 index 0000000..10a57db --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Category.java @@ -0,0 +1,58 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Category { + int botId; + int categoryId; + int parentId; + String name; + String status = "avaliable"; + + public Category(int botId, int categoryId, int parentId, String name) { + this.botId = botId; + this.categoryId = categoryId; + this.parentId = parentId; + this.name = name; + } + + public Category(int botId, int parentId, String name) { + this.botId = botId; + this.parentId = parentId; + this.name = name; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public int getParentId() { + return parentId; + } + + public void setParentId(int parentId) { + this.parentId = parentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java new file mode 100644 index 0000000..ceac338 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Condition.java @@ -0,0 +1,86 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Condition { + + int botId; + int conditionId; + String conditionJsonText; + String actionText; + String category; + String active; + Integer displayOrder = 999; + + public Condition(int botId, int conditionId, String conditionJsonText, String actionText, String category, String active, Integer displayOrder) { + this.botId = botId; + this.conditionId = conditionId; + this.conditionJsonText = conditionJsonText; + this.actionText = actionText; + this.category = category; + this.active = active; + this.displayOrder = displayOrder; + } + + public Condition(int botId, String conditionJsonText, String actionText, String category, String active) { + this.botId = botId; + this.conditionJsonText = conditionJsonText; + this.actionText = actionText; + this.category = category; + this.active = active; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getConditionId() { + return conditionId; + } + + public void setConditionId(int conditionId) { + this.conditionId = conditionId; + } + + public String getConditionJsonText() { + return conditionJsonText; + } + + public void setConditionJsonText(String conditionJsonText) { + this.conditionJsonText = conditionJsonText; + } + + public String getActionText() { + return actionText; + } + + public void setActionText(String actionText) { + this.actionText = actionText; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public Integer getDisplayOrder() { + return displayOrder; + } + + public void setDisplayOrder(Integer displayOrder) { + this.displayOrder = displayOrder; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java new file mode 100644 index 0000000..ba1f1a0 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/ConfigTerm.java @@ -0,0 +1,72 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONObject; + +public class ConfigTerm { + int botId; + int configId; + int categoryId; + String configJsonText; + String configName = ""; + String configTerm = "waiting"; + + public ConfigTerm(int botId, int configId, + int categoryId, String configJsonText, String configName) { + this.botId = botId; + this.configId = configId; + this.categoryId = categoryId; + this.configJsonText = configJsonText; + this.configName = configName; + } + + public ConfigTerm(int botId, int configId, int categoryId, JSONObject configData) { + this.botId = botId; + this.configId = configId; + this.categoryId = categoryId; + this.configJsonText = configData.toJSONString(); + + if(configData.containsKey("configName")){ + this.configName = configData.getString("configName"); + } + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getConfigId() { + return configId; + } + + public void setConfigId(int configId) { + this.configId = configId; + } + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public String getConfigJsonText() { + return configJsonText; + } + + public void setConfigJsonText(String configJsonText) { + this.configJsonText = configJsonText; + } + + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java new file mode 100644 index 0000000..2daad27 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/EngineUnit.java @@ -0,0 +1,34 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class EngineUnit { + Integer conditionid; + String keywords; + String actions; + + public EngineUnit() { + } + + public Integer getConditionid() { + return conditionid; + } + + public void setConditionid(Integer conditionid) { + this.conditionid = conditionid; + } + + public String getKeywords() { + return keywords; + } + + public void setKeywords(String keywords) { + this.keywords = keywords; + } + + public String getActions() { + return actions; + } + + public void setActions(String actions) { + this.actions = actions; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java new file mode 100644 index 0000000..aeabcd9 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/IntervalStatus.java @@ -0,0 +1,33 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class IntervalStatus { + int status = 1; + String message = ""; + Object extraData = null; + + + public IntervalStatus(int status, String message, Object extraData) { + this.status = status; + this.message = message; + this.extraData = extraData; + } + + public IntervalStatus(int status, String message) { + this.status = status; + this.message = message; + } + + public int getStatus() { + return status; + } + + public String getMessage() { + return message; + } + + public Object getExtraData() { + return extraData; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java new file mode 100644 index 0000000..df58c7e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Solution.java @@ -0,0 +1,8 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +import com.alibaba.fastjson.JSONObject; + +public class Solution { + int status = 0; + JSONObject payload = null; +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java new file mode 100644 index 0000000..a5d0052 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/entity/Variable.java @@ -0,0 +1,81 @@ +package com.qiwu.chatbotbackend.actiongenerate.entity; + +public class Variable { + + Integer botId; + Integer variableId; + Integer categoryId = 0; + String description; + String name; + String value; + + public Variable(Integer botId, Integer categoryId, String name, String description, String value) { + this.botId = botId; + + if(categoryId != null) + this.categoryId = categoryId; + this.description = description; + this.name = name; + this.value = value; + } + + public Variable(Integer botId, Integer variableId, Integer categoryId, String name, String description, String value) { + this.botId = botId; + this.variableId = variableId; + if(categoryId != null) + this.categoryId = categoryId; + this.description = description; + this.name = name; + this.value = value; + } + + public void setBotId(Integer botId) { + this.botId = botId; + } + + public void setVariableId(Integer variableId) { + this.variableId = variableId; + } + + public void setCategoryId(Integer categoryId) { + this.categoryId = categoryId; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } + + public Integer getBotId() { + return botId; + } + + public Integer getVariableId() { + return variableId; + } + + public Integer getCategoryId() { + return categoryId; + } + + public String getDescription() { + return description; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java new file mode 100644 index 0000000..188fc27 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ActionServlet.java @@ -0,0 +1,149 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +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.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "ActionServlet", urlPatterns = {"/condition"}) +public class ActionServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botName = ""; + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + + if(receiveParameters.getString("botId").equals("undefined")) + botId = -1; + else + botId = receiveParameters.getInteger("botId"); + botName = receiveParameters.getString("botName_yhm"); + + + try { + EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + ActionUtils actionUtils = new ActionUtils(engine, helper); + + + switch(operationType) { + case "query_bot_info": + actionUtils.queryBotInfo(receiveParameters); + break; + case "bot_init": + actionUtils.createBot(receiveParameters, auth); + break; + case "query_category": + actionUtils.queryCategory(receiveParameters); + break; + case "query_condition": + actionUtils.queryCondition(receiveParameters); + break; + case "update_condition_display_order": + actionUtils.updateConditionDisplayOrder(receiveParameters); + break; + case "update_bot_info": + actionUtils.updateBotInfo(receiveParameters); + break; + case "update_goodbye": + actionUtils.updateGoodbye(receiveParameters); + break; + + default: + + //condition的增删改都需要先查询condition的信息 + actionUtils.getBotConditionInfo(botId, botName, auth); + switch(operationType) { + case "insert_condition": + actionUtils.insertCondition(receiveParameters); + break; + case "delete_condition": + actionUtils.deleteCondition(receiveParameters, auth); + break; + case "update_condition": + actionUtils.updateCondition(receiveParameters); + break; + case "change_active": + actionUtils.changeActive(receiveParameters); + break; + case "detect_template_update": + actionUtils.updateRelation(receiveParameters); + break; + case "update_condition_name": + actionUtils.updateConditionName(receiveParameters); + break; + } + if(actionUtils.intervalStatus.getStatus() == 1) + actionUtils.query4post(receiveParameters); + + + + } + helper.destroy(); + engine.destroy(); + + switch (actionUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", actionUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", actionUtils.intervalStatus.getMessage()); + } + + + } catch (SQLException e) { + e.printStackTrace(); + } + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java new file mode 100644 index 0000000..1cf3a7f --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/BackupServlet.java @@ -0,0 +1,150 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.CategoryUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +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.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; +import static com.qiwu.chatbotbackend.Config.Config.SQL_CONNECTION_ERROR; + +@WebServlet(name = "BackupServlet", urlPatterns = {"/save2file"}) +public class BackupServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + IntervalStatus intervalStatus = new IntervalStatus(1, ""); + ServletContext context = request.getServletContext(); + + + //读取并解析json数据 + String operationType = "", botName = "", botCategoryName; + String jsonStr = SimpleUtil.readJSONString(request), fileData; + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId = 0, categoryIndex; + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + + try { + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + JSONObject backupFile = new JSONObject(); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + botName = receiveParameters.getString("botName_yhm"); + botCategoryName = receiveParameters.getString("catName"); + + + EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + BotInfo botInfo = null; + List conditionList = new ArrayList(); + List configTermList = new ArrayList(); + List childCategoryIds = new ArrayList(); + List childCategories = new ArrayList(); + List variablesList = new ArrayList(); + + ActionUtils actionUtils = new ActionUtils(engine, helper); + CategoryUtils categoryUtils = new CategoryUtils(helper); + ConfigTermUtils configUtils = new ConfigTermUtils(botName, helper, context); + //actionUtils. + + //如果需要保存condition,查询所有condition + if (receiveParameters.containsKey("saveCondition") && receiveParameters.getBoolean("saveCondition")){ + conditionList = helper.queryConditionAll(botId); + } + + //如果需要保存配置文件,则从根目录开始保存配置文件 + if(receiveParameters.containsKey("saveConfig") && receiveParameters.getBoolean("saveConfig")){ + + categoryIndex = receiveParameters.getInteger("indexCategory"); + //查询某个类别下的所有类别 + childCategoryIds = categoryUtils.findChildCategoryIds(botId, categoryIndex, childCategories); + //查询属于以上类别列表的所有配置条目 + configTermList = helper.queryConfigByCategoryIdList(botId, childCategoryIds); + + } + + if(!receiveParameters.containsKey("saveVariable") || receiveParameters.getBoolean("saveVariable")){ + variablesList = helper.queryVariableAll(botId); + } + + botInfo = helper.queryBotInfo(botId); + + Backup backup = new Backup(botId, botName, botCategoryName, conditionList, configTermList, childCategories, variablesList, botInfo); + + //; + //backupFile.put("botId"); + + + + try { + writeFile(BOT_BACKUP_DIR + botId + ".backup",JSON.toJSONString(backup)); +// ReadFile("D:\\8.json"); + System.out.println(); + } catch (IOException e) { + e.printStackTrace(); + } + + helper.destroy(); + engine.destroy(); + + + } catch (SQLException e) { + intervalStatus = new IntervalStatus(0, SQL_CONNECTION_ERROR); + } + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append( + botId + ".backup"); + out.flush(); + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + /** + * 写文件到.Json + * @param filePath + * @param sets + * @throws IOException + */ + public static void writeFile(String filePath, String sets) + throws IOException { + FileWriter fw = new FileWriter(filePath); + PrintWriter out = new PrintWriter(fw); + out.write(sets); + out.println(); + fw.close(); + out.close(); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java new file mode 100644 index 0000000..4db6edc --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/ConfigTermServlet.java @@ -0,0 +1,154 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.utils.CategoryUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +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.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "ConfigTermServlet", urlPatterns = {"/config"}) +public class ConfigTermServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //读取并解析json数据 + String botAccount = "", operationType = "",auth = request.getHeader("authorization"); + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + + System.out.println(jsonStr); + + Integer botId; + CategoryUtils categoryUtils = null; + JSONObject responseJSONObject = new JSONObject(); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); + receiveParaneters.put("Authorization", auth); + + operationType = receiveParaneters.getString("type"); + botId = receiveParaneters.getInteger("botId"); + + + try { + //EngineUtils engine = new EngineUtils(); + SqlHelper helper = new SqlHelper(); + EngineUtils engine = null; + ConfigTermUtils configUtils = null; + + IntervalStatus intervalStatus = null; + + if(operationType.equals("query_config") || operationType.equals("query_sleeping_config")){ + configUtils = new ConfigTermUtils(helper); + switch(operationType){ + case "query_config": + + configUtils.queryConfig(receiveParaneters); + intervalStatus = configUtils.intervalStatus; + break; + case "query_sleeping_config": + configUtils.querySleepingConfig(receiveParaneters); + break; + } + intervalStatus = configUtils.intervalStatus; + + } + else if(operationType.endsWith("config")){ + engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + System.out.println("botAccount" + botAccount); + configUtils = new ConfigTermUtils(botAccount, helper, context); + switch (operationType){ + case "insert_config": + configUtils.insertConfigTerm(receiveParaneters); + break; + case "update_config": + configUtils.updateConfig(receiveParaneters); + break; + case "delete_config": + configUtils.deleteConfig(receiveParaneters); + break; + } + intervalStatus = configUtils.intervalStatus; + engine.destroy(); + }else{ + categoryUtils = new CategoryUtils(helper); + switch(operationType) { + case "query_category": + categoryUtils.queryCategory(receiveParaneters); + break; + case "insert_category": + categoryUtils.insertCategory(receiveParaneters); + break; + case "update_category": + categoryUtils.updateCategory(receiveParaneters); + break; + case "delete_category": + categoryUtils.deleteCategory(receiveParaneters); + break; + + } + intervalStatus = categoryUtils.intervalStatus; + } + helper.destroy(); + + + + switch (intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", intervalStatus.getMessage()); + break; + } + + + } catch (SQLException e) { + + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", "0"); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java new file mode 100644 index 0000000..c8dc570 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/CorsFilter.java @@ -0,0 +1,36 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@Component +public class CorsFilter implements Filter { + + //解决跨域问题 + + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + HttpServletResponse response = (HttpServletResponse) res; + + HttpServletRequest reqs = (HttpServletRequest) req; + + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); + + chain.doFilter(req, res); + } + + public void init(FilterConfig filterConfig) { + } + + public void destroy() { + } +} \ No newline at end of file diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java new file mode 100644 index 0000000..23087c4 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetBackupServlet.java @@ -0,0 +1,59 @@ +package com.qiwu.chatbotbackend.actiongenerate.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.*; +import java.net.URLEncoder; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; + +@WebServlet(name = "GetBackupServlet", urlPatterns = {"/download"}) +public class GetBackupServlet extends HttpServlet { + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String filename = request.getParameter("filename"); + try{ + response.reset();// 清空输出流 + + String resultFileName = filename; + resultFileName = URLEncoder.encode(resultFileName,"UTF-8"); + response.setCharacterEncoding("UTF-8"); + response.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头 + response.setContentType("application/msexcel");// 定义输出类型 + //输入流:本地文件路径 + DataInputStream in = new DataInputStream( + new FileInputStream(new File(BOT_BACKUP_DIR + filename))); + //输出流 + OutputStream out = response.getOutputStream(); + //输出文件 + int bytes = 0; + byte[] bufferOut = new byte[1024]; + while ((bytes = in.read(bufferOut)) != -1) { + out.write(bufferOut, 0, bytes); + } + out.close(); + in.close(); + } catch(Exception e){ + e.printStackTrace(); + response.reset(); + try { + OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + String data = ""; + writer.write(data); + writer.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + doPost(request, response); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java new file mode 100644 index 0000000..5b4f423 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/GetNextstepExceptionServlet.java @@ -0,0 +1,27 @@ +package com.qiwu.chatbotbackend.actiongenerate.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; +import java.io.PrintWriter; + +@WebServlet(name = "GetNextstepExceptionServlet", urlPatterns = {"/getNextStepException"}) +public class GetNextstepExceptionServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + response.setHeader("Access-Control-Allow-Origin", "*"); + + + PrintWriter out = response.getWriter(); + out.append("active known"); //在有多个下一步时,可以选择已被激活跳过或者是答案已知跳过 + out.flush(); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java new file mode 100644 index 0000000..28764c7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/MacroServlet.java @@ -0,0 +1,97 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +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.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "MacroServlet", urlPatterns = {"/macro"}) +public class MacroServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botAccount = ""; + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + System.out.println("xxx"); + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + + + try { + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + VariableUtils variableUtils = null; + + helper.destroy(); + + switch (variableUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getMessage()); + break; + } + + + } catch (SQLException e) { + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java new file mode 100644 index 0000000..22a41d7 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/RecoveryServlet.java @@ -0,0 +1,224 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.SimpleUtil; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.sql.SQLException; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +@WebServlet(name = "RecoveryServlet") +public class RecoveryServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + ServletContext context = request.getServletContext(); + //读取并解析json数据 + String operationType = "", botName = "", conditionName = "", botAccount; + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(), configTermJson, conditionJson; + JSONArray conditionIdPair = new JSONArray(), idPair; + Boolean flag = true; + Integer botId = 0, newCategoryId = 0, len, id; + IntervalStatus intervalStatus = new IntervalStatus(1, ""); + StringBuffer completeConfigText = new StringBuffer(); + ActionPostElem ape = null; + System.out.println(jsonStr); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + JSONObject data = receiveParameters.getJSONObject("data"); + botId = receiveParameters.getInteger("botId"); + botAccount = receiveParameters.getString("botName"); + botName = receiveParameters.getString("botName_yhm"); + + + + + + try { + Map idReplaceMap = new HashMap(); + + + ConfigTermText configTermText = null; + Set variableNameSet1, variableNameSet2, conditionNameSet1, conditionNameSet2; + List actionTextList = new ArrayList(); + //List originConditionList = null; + //List<> + List categoryList = data.getJSONArray("categoryList").toJavaList(Category.class); + List originConditionList = null, conditionList = data.getJSONArray("conditionList").toJavaList(Condition.class); + List configTermList = data.getJSONArray("configTermList").toJavaList(ConfigTerm.class); + List originVariableList, variableList = data.getJSONArray("variablesList").toJavaList(Variable.class); + BotInfo botInfo = data.getJSONObject("botInfo").toJavaObject(BotInfo.class); + + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + + ActionUtils actionUtils = new ActionUtils(engine, helper); + VariableUtils variableUtils = new VariableUtils(helper); + ConfigTermUtils configTermUtils = new ConfigTermUtils(helper); + + + //是否删除之前的数据 + if (!data.containsKey("dataOverride") || data.getBoolean("dataOverride")) { + //清空数据 + helper.deleteUserData(botId); + } + + originConditionList =helper.queryConditionAll(botId); + originVariableList = helper.queryVariableAll(botId); + conditionNameSet1 = actionUtils.getConditionNameSet(originConditionList); + conditionNameSet2 = actionUtils.getConditionNameSet(conditionList); + variableNameSet1 = variableUtils.getVariableNameSet(originVariableList); + variableNameSet2 = variableUtils.getVariableNameSet(variableList); + + variableNameSet1.retainAll(variableNameSet2); + conditionNameSet1.retainAll(conditionNameSet2); + //监测是否重名 + //求交集,如果交集大于0,则说明重复,返回重复列表 + if(conditionNameSet1.size() > 0){ + intervalStatus = new IntervalStatus(0, "dumplicate", JSONArray.toJSON(conditionNameSet1)); + }else if(variableNameSet1.size() > 0){ + intervalStatus = new IntervalStatus(0, "dumplicate", JSONArray.toJSON(variableNameSet1)); + }else{ + + for(Category category:categoryList){ + category.setBotId(botId); + + if(idReplaceMap.containsKey(category.getParentId())){ + category.setParentId(idReplaceMap.get(category.getParentId())); + } + + newCategoryId = helper.insertCategoryByBotId(category); + idReplaceMap.put(category.getCategoryId(), newCategoryId); + } + + + //修改botid,并批量插入condition + len = conditionList.size(); + //替换配置文件相应类别的id + for(int i =0;i < len;i++){ + conditionList.get(i).setBotId(botId); + conditionJson = JSON.parseObject(conditionList.get(i).getConditionJsonText()); + if(conditionList.get(i).getActive().equals("1")){ + completeConfigText.append(String.format(EXTRA_INFO_FORMAT, "activeAction", conditionJson.getString("conditionName"))); + } + idPair = new JSONArray(); + idPair.add(conditionJson.getInteger("originConditionId")); + idPair.add(conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0")); + conditionIdPair.add(idPair); + actionTextList.add(conditionList.get(i).getActionText()); + + } + helper.batchInsertCondition(conditionList); + + + len = variableList.size(); + //替换变量相应的botid + for(int i =0;i < len;i++){ + variableList.get(i).setBotId(botId); + + completeConfigText.append(String.format(VARIABLE_SAVE_FORMAT, variableList.get(i).getName(), variableList.get(i).getValue())); + } + helper.batchInsertVariable(botId, variableList); + + + + len = configTermList.size(); + //替换配置文件相应类别的id + for(ConfigTerm configTerm:configTermList){ + if(idReplaceMap.containsKey(configTerm.getCategoryId())){ + configTerm.setCategoryId(idReplaceMap.get(configTerm.getCategoryId())); + }else{ + configTerm.setCategoryId(0); + } + + configTermJson = JSON.parseObject(configTerm.getConfigJsonText()); + configTermText = configTermUtils.configPreprocessing(configTermJson); + id = helper.insertConfig(botId, configTermJson, configTerm.getCategoryId()); + completeConfigText.append(configTermText.toString()).append(id).append("\n"); + + + } + //helper.batchInsertConfig(botId, configTermList); + + batchUpdate(botAccount, completeConfigText.toString(), context, true); + ape = new ActionPostElem(botId, botName, actionUtils.generateCompleteActionText(receiveParameters, actionTextList), auth, GAME_BOT_CATEGORY,conditionIdPair); + actionUtils.postAction(ape); + + intervalStatus = actionUtils.intervalStatus; + + + } + engine.destroy(); + helper.destroy(); + + }catch (SQLException e){ + intervalStatus = new IntervalStatus(0, SQL_CONNECTION_ERROR); + } + + } + + + switch(intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", intervalStatus.getMessage()); + break; + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } + + public void batchUpdate(String userName, String data, ServletContext context, Boolean writeFile) throws IOException { + BufferedReader br = new BufferedReader(new StringReader(data)); + UserInfo userinfo = new UserInfo(userName); + userinfo = UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + System.out.println("batchupdate"); + + if(writeFile){ + UserInfoController.writeConfigText(userName, userinfo); + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java new file mode 100644 index 0000000..2b60693 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/servlet/VariableServlet.java @@ -0,0 +1,128 @@ +package com.qiwu.chatbotbackend.actiongenerate.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.utils.VariableUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +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.PrintWriter; +import java.sql.SQLException; + +import static com.qiwu.chatbotbackend.Config.Config.JSON_FORMAT_ERROR; + +@WebServlet(name = "VariableServlet", urlPatterns = {"/variable"}) +public class VariableServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //读取并解析json数据 + String operationType = "", botAccount = ""; + ServletContext context = request.getServletContext(); + String jsonStr = SimpleUtil.readJSONString(request); + String auth = request.getHeader("authorization"); + JSONObject responseJSONObject = new JSONObject(); + Boolean flag = true; + Integer botId; + + System.out.println("xxx"); + + + if (jsonStr != null && !jsonStr.equals("")) { + + System.out.println(jsonStr); + JSONObject receiveParameters = JSONObject.parseObject(jsonStr); + receiveParameters.put("Authorization", auth); + + operationType = receiveParameters.getString("type"); + botId = receiveParameters.getInteger("botId"); + + + try { + SqlHelper helper = new SqlHelper(); + EngineUtils engine = new EngineUtils(); + botAccount = engine.queryBotAccountByBotId(botId); + VariableUtils variableUtils = null; + + + if(operationType.equals("query_variable")){ + variableUtils = new VariableUtils(helper); + variableUtils.queryVariable(receiveParameters); + }else{ + variableUtils = new VariableUtils(botAccount, helper, context); + switch (operationType){ + + case "insert_variable": + variableUtils.insertVariable(receiveParameters); + break; + case "delete_variable": + variableUtils.deleteVairiable(receiveParameters); + break; + case "update_variable": + variableUtils.updateVariable(receiveParameters); + break; + } + } + + switch(operationType) { + case "query_variable": + variableUtils.queryVariable(receiveParameters); + break; + + + } + + + switch (variableUtils.intervalStatus.getStatus()){ + case 1: + responseJSONObject.put("status", 1); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getExtraData()); + break; + case 0: + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", variableUtils.intervalStatus.getMessage()); + break; + } + + helper.destroy(); + engine.destroy(); + + + } catch (SQLException e) { + e.printStackTrace(); + } + + + + + }else{ + responseJSONObject.put("status", 0); + responseJSONObject.put("parameter", JSON_FORMAT_ERROR); + } + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + //System.out.println("xx:" + responseJSONObject.toJSONString()); + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + + } + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java new file mode 100644 index 0000000..100e51d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionParser.java @@ -0,0 +1,129 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.Arrays; + +public class ActionParser { + public static JSONObject parse(String actionText){ + String name; + JSONObject action = new JSONObject(); + + + for(String line:actionText.split("\r\n")){ + name = line.trim().split("=")[0]; + + if(name.equals("") || name.equals("#actions")){ + // + }else{ + + switch(name) { + case "name": + //parseName(line, action); + break; + case "status": + parseStatus(line, action); + break; + case "condition": + parseCondition(line, action); + break; + case "style": + parseStyle(line, action); + break; + case "action": + parseAction(line, action); + break; + case "conflict": + + break; + case "process": + break; + default: + ; + } + } + } + + if(!action.containsKey("styleList")){ + action.put("styleList", new JSONArray()); + } + + return action; + + } + + public static void parseName(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("actionName", elem[1]); + } + + public static void parseAction(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("actionType", elem[1]); + } + public static void parseStatus(String text, JSONObject action){ + String elem[] = text.split("="); + action.put("status", elem[1]); + } + public static void parseStyle(String text, JSONObject action){ + String elem[] = text.split("="); + String subElem[] = elem[1].split(","); + action.put("styleList", new JSONArray(Arrays.asList(subElem))); + } + + public static void parseConflict(String text, JSONObject action){ + // + } + + public static void parseCondition(String text, JSONObject action){ + String elem[] = text.split("\\|", 4); + String condition = elem[0]; + String relation = elem[1]; + String questionText = elem[2]; + String repeatStr = elem[3]; + String conditionName = "", relationList[], questionElem[]; + JSONArray questionList = new JSONArray(); + JSONArray repeatList = new JSONArray(); + + String conditionElem[] = condition.split("="); + conditionElem = conditionElem[1].split(":"); + + action.put("conditionName", conditionElem[0]); + if(conditionElem.length >=2) + action.put("dataType", conditionElem[1]); + + relationList = relation.split(","); + action.put("relationHead", relationList[0]); + action.put("relationName", relationList[1]); + action.put("relationTail", relationList[2]); + + + for(String question:questionText.split("~")){ + questionElem = question.split(":"); + JSONObject iterDict = new JSONObject(); + iterDict.put("que_start_time",questionElem[0]); + iterDict.put("que_stop_time" ,questionElem[1]); + iterDict.put("que_sen" ,questionElem[2]); + + if(questionElem.length == 4 && questionElem[3].equals("base")) + iterDict.put("base", 1); + else + iterDict.put("base", 0); + + questionList.add(iterDict); + } + + action.put("questionList", questionList); + + for(String repeat:repeatStr.split("~")){ + JSONObject repeatDict = new JSONObject(); + elem = repeat.split("=", 2); + repeatDict.put("repeatString", elem[0]); + repeatDict.put("repeatKeywords", elem[1]); + repeatList.add(repeatDict); + } + action.put("repeatList", repeatList); + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java new file mode 100644 index 0000000..157eede --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ActionUtils.java @@ -0,0 +1,1065 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.DB.PlatformUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import java.io.UnsupportedEncodingException; +import java.sql.SQLException; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class ActionUtils { + EngineUtils engine = null; + SqlHelper helper = null; + String activeCondition = ""; + ActionPostElem ape = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public ActionUtils(EngineUtils engine, SqlHelper helper){ + this.engine = engine; + this.helper = helper; + } + + public void insertCondition(JSONObject parameters){ + + String conditionName = "", text = "", categoryStr, conditionJsonStr = "", isActive = ""; + Integer count = 0; + JSONObject conditionJson = null; + Condition condition = null; + List conditionList = new ArrayList(); + Boolean insertFlag = false; + JSONArray conditions = parameters.getJSONArray("conditionData"); + Integer botId = parameters.getInteger("botId"); + List actionTextList = helper.queryActionTextList(botId); + Set conditionNameSet = new HashSet(); + + + for(String actionText:actionTextList){ + //从action文本取出condition的名字 + //System.out.println("--" + actionText.trim().substring(100).split("\r\n")[0] + "---"); + conditionName = actionText.trim().split("\r\n")[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + } + + count = conditions.size(); + if(count > 0){ + + for(int i =0; i < count;i++){ + conditionJson = conditions.getJSONObject(i); + conditionName = conditionJson.getString("conditionName"); + + //condition名字已存在 + if(conditionNameSet.contains(conditionName)){ + for(int j =2;j < 100 && conditionNameSet.contains(conditionName);j++){ + + conditionName = conditionJson.getString("conditionName") + j; + } + conditionJson.put("conditionName", conditionName); + } + + text = generateSingleActionText(conditionName, conditionJson); + actionTextList.add(text); + if(conditionJson.getBoolean("active")) + isActive = "1"; + else + isActive = "0"; + categoryStr = conditionJson.getString("conditionCategory"); + conditionJson.put("displayOrder", 999); //展示顺序为condition的展示顺序,越小排在越前面 + conditionJsonStr = JSONObject.toJSONString(condition); + + + + condition = new Condition(botId, conditionJson.toJSONString(), text, categoryStr, isActive); + conditionList.add(condition); + + insertIdElemIfNotExist(conditionJson.getInteger("originConditionId"), conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0")); + + } + insertFlag = helper.batchInsertCondition(conditionList); + } + if(insertFlag) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, "插入失败"); + } + + public void insertIdElemIfNotExist(Integer originConditionId, String relationName){ + int len = 0; + Boolean exist = false; + if(ape.getConditionIdPair() != null){ + len = ape.getConditionIdPair().size(); + } + for(int i = 0;i < len;i++){ + if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ + exist = true; + break; + } + } + + if(!exist){ + ape.getConditionIdPair().add(new JSONArray(){{add(originConditionId);add(relationName);}}); + } + } + + public void deleteIdElemIfExist(Integer originConditionId){ + int len = 0; + Boolean exist = false; + if(ape.getConditionIdPair() != null){ + len = ape.getConditionIdPair().size(); + } + for(int i = 0;i < len;i++){ + if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ + ape.getConditionIdPair().remove(i); + } + } + } + + public String generateSingleActionText(String conditionName, JSONObject condition){ + + StringBuffer sb = new StringBuffer(); + String listeningText = ""; + StringBuffer actionText = new StringBuffer(); + + + appendActionHead(conditionName, actionText, "waiting"); + appendCondition(conditionName, actionText, condition); + appendProcess(conditionName, actionText, condition); + + + + listeningText = actionText.toString().replace("name=" + conditionName, "name=" +conditionName + "_listening"); + listeningText = listeningText.replace("status=waiting", "states=listening"); + actionText.append(listeningText); + + return actionText.toString(); + } + + public String generateCompleteActionText(JSONObject parameters, List actionTextList){ + Integer botId = parameters.getInteger("botId"); + BotInfo botInfo = helper.queryBotInfo(botId); + Boolean bothValue = true; + String styleText = "", serviceURL = "", elements[], conditionName; + Set conditionNameSet = new HashSet(); + StringBuffer postActionText = null, processText = new StringBuffer(), fullActionText = new StringBuffer(); + + if(botInfo == null){ + styleText = POST_STYLE1; + serviceURL = SERVICE_URL; + }else{ + if(botInfo.getBothValue().equals("1")){ + styleText = POST_STYLE1; + }else{ + styleText = POST_STYLE2; + } + if(!botInfo.getPostURL().equals("")){ + serviceURL = botInfo.getPostURL(); + }else{ + serviceURL = SERVICE_URL; + } + } + + postActionText = new StringBuffer(String.format(POST_ACTION_HEAD, styleText, serviceURL)); + + for(String text:actionTextList){ + + for(String line:text.split("\r\n")){ + if(line.startsWith("condition")){ + //System.out.println("line====" + line); + line = line.replace("condition", "reference"); + postActionText.append(line); + postActionText.append("\r\n"); + + elements = line.trim().split("\\|"); + + + conditionName = elements[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + break; + + } + } + } + + for(String name:conditionNameSet){ + postActionText.append("process=nextStep="); + postActionText.append(name); + postActionText.append("|"); + postActionText.append(name); + postActionText.append("=active|\r\n"); + } + + + for(String actionText:actionTextList){ + postActionText.append(actionText); + } + + postActionText.append("\r\n\r\n"); + + return postActionText.toString(); + } + + + public void appendProcess(String conditionName, StringBuffer actionText, JSONObject condition){ + + } + + /** + * + * 构建action的头部信息,包括name、status、style、fellow等信息 + * 其中addition_element,就是前段传的一些参数 + * + * @param actionText + * @param actionStatus + */ + public void appendActionHead(String conditionName, StringBuffer actionText, String actionStatus){ + + actionText.append("\r\n\r\n"); + actionText.append("name=").append(conditionName).append("\r\n"); + actionText.append("status=").append(actionStatus).append("\r\n"); + actionText.append("action=select\r\n"); + + if(AUTOMATCH_THRESHOLD != null && !AUTOMATCH_THRESHOLD.equals("")) + actionText.append("automatchthreshold=").append(AUTOMATCH_THRESHOLD).append("\r\n"); + + actionText.append(DEFAULT_STYLE).append("\r\n"); + actionText.append("fellow=pivot_httppost\r\n"); + + } + + public void queryCondition(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String category = parameters.getString("category"); + String queryType = parameters.getString("queryType"); + List conditionList = null; + JSONObject data = new JSONObject(){ + { + put("conditionList", new JSONArray()); + } + }; + + JSONObject conditionJson = null; + + if(queryType != null && queryType.equals("category")){ + conditionList = helper.queryConditionByCategory(botId, category); + }else{ + conditionList = helper.queryConditionAll(botId); + } + + for(Condition condition:conditionList){ + conditionJson = JSON.parseObject(condition.getConditionJsonText()); + conditionJson.put("conditionId", condition.getConditionId()); + data.getJSONArray("conditionList").add(conditionJson); + } + + intervalStatus = new IntervalStatus(1, "", data); + + + + } + + public void queryCategory(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String[] categoryChain; + + List conditionCategories = helper.queryConditionCategoriesById(botId); + JSONObject categoryTree = new JSONObject(), categoryTreeJson = new JSONObject(), finalCategory = new JSONObject(); + + if(conditionCategories.size() != 0 ){ + for(String category:conditionCategories){ + categoryChain = category.split("-"); + for(String node: categoryChain){ + categoryTree.putIfAbsent(node, new JSONObject()); //设置默认子节点 + categoryTree = categoryTree.getJSONObject(node); //进入子节点 + } + } + + categoryTreeJson.putIfAbsent("-1", new JSONObject(){ + { + put("children", new JSONArray()); + } + }); + constructCategoryTreeJson(categoryTree, categoryTreeJson, "-1"); + + finalCategory.put("category", categoryTreeJson.getJSONObject("-1").getJSONArray("children")); + + }else{ + finalCategory.put("category", new JSONArray()); + } + + intervalStatus = new IntervalStatus(1, "", finalCategory); + + } + + public void query4post(JSONObject parameters){ + + Integer activedConditionId = -1; + + String finalText = ""; + JSONObject conditionJson = null; + int botId = parameters.getInteger("botId"); + List conditionList = helper.queryConditionAll(botId); + List conditionTextList = new ArrayList(); + + + for(Condition condition:conditionList){ + if(condition.getActive().equals("1")) + activedConditionId = condition.getConditionId(); + + conditionTextList.add(condition.getActionText()); + } + + if(activedConditionId == -1 && conditionList.size() >= 1){ + conditionTextList.set(0, conditionTextList.get(0).replace("status=waiting","status=active")); + } + finalText = generateCompleteActionText(parameters, conditionTextList); + ape.setActionText(finalText); + + postAction(ape); + + } + + public void constructCategoryTreeJson(JSONObject categoryTree, JSONObject categoryTreeJson, String root){ + String namePair[]; + JSONObject node = categoryTreeJson.getJSONObject(root); + JSONObject childNode = null; + for(String key:categoryTree.keySet()){ + namePair = key.split(":"); //id:名字 + childNode = new JSONObject(); + childNode.put("value", namePair[0]); + childNode.put("label", namePair[1]); + categoryTreeJson.put(namePair[0], node); + if(!node.containsKey("children")) + node.put("children", new JSONArray()); + + node.getJSONArray("children").add(childNode); + constructCategoryTreeJson(categoryTree.getJSONObject(key), categoryTreeJson, namePair[0]); + } + } + + + /** + * 将某个condition设为初始问题 + * 将某个condition改成active, 将之前active的condition改成waiting + */ + public void changeActive(JSONObject parameters){ + Boolean flag = true; + int botId = parameters.getInteger("botId"); + int activeConditionId = parameters.getInteger("activeConditionId"); + List conditionList = new ArrayList(); + + Condition oldActiveCondition = helper.queryActiveCondition(botId); + + if(oldActiveCondition != null){ + + oldActiveCondition.setActionText(oldActiveCondition.getActionText().replace("status=active", "status=waiting")); + oldActiveCondition.setConditionJsonText(oldActiveCondition.getConditionJsonText().replace("\"active\": true", "\"active\": false")); + oldActiveCondition.setActive("0"); + conditionList.add(oldActiveCondition); + } + + Condition newActiveCondition = helper.queryConditionByConditionId(botId, activeConditionId); + newActiveCondition.setActive("1"); + newActiveCondition.setActionText(newActiveCondition.getActionText().replace("status=waiting","status=active")); + newActiveCondition.setConditionJsonText(newActiveCondition.getConditionJsonText().replace( "\"active\": false", "\"active\": true")); + conditionList.add(newActiveCondition); + + flag = helper.batchUpdateCondition(botId, conditionList); + + } + + + + public void appendCondition(String conditionName, StringBuffer actionText, JSONObject condition){ + int count = 0; + String relationHead = "", relationName = "", relationTail; + String iteration = "1", finalText; + JSONObject questionElem = null, repeatElem = null; + StringBuffer questionText = new StringBuffer(), repeatText = new StringBuffer(), processText = new StringBuffer(); + + + String conditionPattern = "condition=%s:%s:%s|%s,%s,%s|%s|%s\r\n"; + + relationHead = condition.getString("relationHead"); + if(relationHead.equals("")) + relationHead = "#visitorname"; + relationTail = condition.getString("relationTail"); + if(relationTail.equals("")) + relationTail = "#visitorname"; + relationName = condition.getString("relationName"); + + //condition的属性 number、string、location + String dataType = condition.getString("dataType"); + + if(dataType != null && ! dataType.equals("")) + dataType = dataType; + else + dataType = ""; + + //解析问题的开始轮次等 + JSONArray questionList = condition.getJSONArray("questionList"); + count = questionList.size(); + for(int i = 0;i < count;i++){ + + if(i != 0) + questionText.append("~"); + + questionElem = questionList.getJSONObject(i); + questionText.append(questionElem.getString("que_start_time")).append(":").append(questionElem.getString("que_stop_time")); + questionText.append(":").append(questionElem.getString("que_sen")); + //添加base问题 + if(questionElem.getInteger("base") == 1){ + questionText.append(":base"); + } + } + + //添加复述列表 + JSONArray repeatList = condition.getJSONArray("repeatList"); + count = repeatList.size(); + for(int i = 0;i < count;i++) { + if(i != 0) + repeatText.append("~"); + + + repeatElem = repeatList.getJSONObject(i); + if(!repeatElem.getString("repeatKeywords").startsWith("+")) + repeatElem.put("repeatKeywords", "+" + repeatElem.getString("repeatKeywords")); + + repeatText.append(repeatElem.getString("repeatString")).append("=").append(repeatElem.getString("repeatKeywords")); + processText.append("process=").append(conditionName).append("=").append(repeatElem.getString("repeatKeywords").split("-")[0]).append("|pivot_httppost=active|\r\n"); + } + processText.append("process=").append(conditionName).append("=unknown|pivot_httppost=active|\r\n"); + processText.append("process=completed=true|pivot_httppost=active|\r\n"); + finalText = String.format(conditionPattern, conditionName, dataType, iteration, + relationHead, relationName, relationTail, questionText.toString(), repeatText.toString()); + + actionText.append(finalText); + actionText.append(processText.toString()); + + } + + + /** + * 更新rule并且监测condition模板中的base问题和style是否发生变化 + * @param parameters + */ + public void updateRelation(JSONObject parameters){ + int botId = parameters.getInteger("botId"), len, baseIdx1 = 0, baseIdx2 = 0, originConditionId; + Boolean updateFlag = false; + JSONObject conditionJson = new JSONObject(), patternConditionJson, questionDict; + String relation = ""; + List conditionList = helper.queryConditionAll(botId); + List conditionRelationList = new ArrayList(); + List conditionJsonList = new ArrayList(); + + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); + + if(intervalStatus.getStatus() == 1) { + for (Condition condition : conditionList) { + conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + conditionJson.put("conditionId", condition.getConditionId()); + relation = conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); + conditionRelationList.add(relation); + conditionJsonList.add(conditionJson); + } + + Map patternTextMap = engine.queryConditionPatternText(botId, conditionRelationList); + + + for (JSONObject condtiionJson : conditionJsonList) { + originConditionId = conditionJson.getInteger("originConditionId"); + updateFlag = false; + + if (patternTextMap.get(originConditionId) != null && intervalStatus.getStatus() == 1) { + + patternConditionJson = ActionParser.parse(patternTextMap.get(originConditionId)); + + //分别找到condition的base问题 + len = conditionJson.getJSONArray("questionList").size(); + for (int i = 0; i < len; i++) { + questionDict = conditionJson.getJSONArray("questionList").getJSONObject(i); + if (questionDict.getInteger("base") == 1) { + baseIdx1 = i; + break; + } + + } + + len = patternConditionJson.getJSONArray("questionList").size(); + for (int i = 0; i < len; i++) { + questionDict = patternConditionJson.getJSONArray("questionList").getJSONObject(i); + if (questionDict.getInteger("base") == 1) { + baseIdx2 = i; + break; + } + + } + + //如果关于base问题的两个json数据不一样,就更新数据 + if (!conditionJson.getJSONArray("questionList").getJSONObject(baseIdx1).equals(patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2))) { + conditionJson.getJSONArray("questionList").set(baseIdx1, patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2)); + updateFlag = true; + } + + //如果关于style的json数据不一致,就更新styleList + if (!conditionJson.getJSONArray("styleList").equals(patternConditionJson.getJSONArray("styleList"))) { + conditionJson.put("styleList", patternConditionJson.getJSONArray("styleList")); + updateFlag = true; + } + + if (updateFlag) { + parameters.put("conditionData", conditionJson); + intervalStatus = updateCondition(parameters); + } + } + } + } + + } + + + + /** + * 更新关键词单元, + * @param botId + * @param extraKeyword 额外需要更新的关键词 + * @param appendMacro 在宏定义中添加关键词 + * @param POS + */ + public IntervalStatus updateKnowledgeUnit(int botId, Map extraKeyword, Map appendMacro, String POS){ + StringBuffer newKeywords = new StringBuffer(); + IntervalStatus intervalStatus = null; + Boolean flag; + String keywordUnitText = engine.queryKeywordUnitText(botId), keywordPair[]; + + for(String line:keywordUnitText.split("\r\n")){ + if (line.startsWith("options|") || line.trim().equals("") || line.startsWith("idlelimit")) + continue; + + newKeywords.append(line); + if(line.startsWith("++")){ + keywordPair = line.split("\\|"); + if(appendMacro != null && appendMacro.containsKey(keywordPair[0])){ + newKeywords.append("+").append(appendMacro.get(keywordPair[0]).toString()); + } + } + newKeywords.append("\r\n"); + } + + if(extraKeyword != null) { + for (String key : extraKeyword.keySet()) { + newKeywords.append(key).append("|").append(extraKeyword.get(key)); + + if (key.equals("options")) { + BotInfo botInfo = helper.queryBotInfo(botId); + //是否将用户回答传给后台 + if (botInfo.getQueryTextTransfer().equals("1")) + newKeywords.append(",query_text_transfer"); + } + newKeywords.append("\r\n"); + } + } + + if(POS != null){ + newKeywords.append(POS); + } + + flag = engine.updateKeywordUnitText(botId, newKeywords.toString()); + + + if(flag || keywordUnitText.equals(newKeywords.toString())) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, UPDATE_KEYWORD_ERROR); + + return intervalStatus; + + } + + public void createBot(JSONObject data, String authorization){ + //新建bot + ActionPostElem ape = new ActionPostElem("", -1, data.getString("botName_yhm"), data.getString("catName"), authorization, data.getString("botType")); + + + postAction(ape); + + if(intervalStatus.getStatus() == 1){ + ((JSONObject)intervalStatus.getExtraData()).put("botId", ape.getBotId()); + ((JSONObject)intervalStatus.getExtraData()).put("botAccount", engine.queryBotAccountByBotId(ape.getBotId())); + BotInfo botInfo = new BotInfo(ape.getBotId(), "", "", "", "", "1", "1"); + helper.insertBotInfo(botInfo); + } + + } + + + public void queryBotInfo(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + BotInfo botInfo = helper.queryBotInfo(botId); + JSONArray returnList = new JSONArray(); + + if(botInfo != null) { + //List returnList = new ArrayList(); + returnList.add(new JSONArray(){{ + add("bothValue"); + add("将三元组两边的值都传给后台"); + add(botInfo.getBothValue()); + }}); + + returnList.add(new JSONArray(){{ + add("queryTextTransfer"); + add("将问句传给后台"); + add(botInfo.getQueryTextTransfer()); + }}); + + intervalStatus = new IntervalStatus(1, "", returnList); + }else{ + intervalStatus = new IntervalStatus(0, "查询失败"); + } + + + + } + + public IntervalStatus deleteCondition(JSONObject data, String authorization){ + int conditionId = data.getInteger("conditionId"); + int botId = data.getInteger("botId"); + IntervalStatus intervalStatus = null; + + Condition condition = helper.queryConditionByConditionId(botId, conditionId); + JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + Boolean flag = helper.deleteConditionBy2Id(botId, conditionId); + + if(flag){ + deleteIdElemIfExist(conditionJson.getInteger("originConditionId")); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, "删除失败"); + } + + return intervalStatus; + } + + public IntervalStatus updateCondition(JSONObject parameters){ + IntervalStatus intervalStatus = null; + Integer botId = parameters.getInteger("botId"), conditionId, displayOrder; + String categoryStr, actionText, conditionName, conditionJsonText, active; + Boolean flag; + + + JSONObject conditionData = parameters.getJSONObject("conditionData"); + + conditionId = conditionData.getInteger("conditionId"); + conditionName = conditionData.getString("conditionName"); + categoryStr = conditionData.getString("conditionCategory"); + displayOrder = conditionData.getInteger("displayOrder"); + active = conditionData.getBoolean("active") ? "1":"0"; + + conditionJsonText = conditionData.toJSONString(); + + + actionText = generateSingleActionText(conditionName, conditionData); + + Condition condition = new Condition(botId, conditionId, conditionJsonText, actionText, categoryStr, active, displayOrder); + flag = helper.updateConditionById(condition); + + if(!flag){ + condition = helper.queryConditionByConditionId(botId, conditionId); + if(condition != null && condition.getConditionJsonText().equals(conditionJsonText)){ + flag = true; + } + } + + + if(flag){ + intervalStatus = new IntervalStatus(1, "success"); + }else{ + intervalStatus = new IntervalStatus(0, "修改失败"); + } + + return intervalStatus; + } + + + + /** + * 将生成的action文本提交到周志宇处 + * @param ape + * @return + */ + public void postAction(ActionPostElem ape){ + String url = CONDITION_BACKEND_URL + "/post/actions"; + JSONObject retData = null; + Integer statusCode = 0; + + + JSONObject postData = new JSONObject(); + postData.put("botname", ape.getBotName()); + postData.put("actions", ape.getActionText()); + postData.put("catName", ape.getCategoryName()); + postData.put("cdt_name_ls", ape.getConditionIdPair()); + postData.put("id", ape.getBotId()); + + + //新建bot时不传botId + if(ape.getBotId() == -1){ + postData.remove("id"); + } + if(!ape.getBotType().equals("")) + postData.put("project", ape.getBotType()); + + + try { + retData = SimpleUtil.postJSON(url, postData, ape.getAuthorization()); + }catch (UnsupportedEncodingException e){ + retData = new JSONObject(){ + { + put("status_code", -1); + } + }; + } + //System.out.println(retData.toJSONString()); + + switch(retData.getInteger("status_code")){ + case 200: + switch(retData.getString("status")){ + case "Success": + ape.setBotId(retData.getInteger("id")); + intervalStatus = new IntervalStatus(1, "", new JSONObject()); + break; + case "Fail": + intervalStatus = new IntervalStatus(0, retData.getString("reason")); + break; + } + break; + case 401: + intervalStatus = new IntervalStatus(0, TOKEN_TIME_OUT); + break; + default: + intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR); + } + + } + + + public void gamePlotInit(String botName, int botId, String auth, JSONObject parameters, String startCondition, Map> conditionExtraKeywords){ + Boolean flag = true; + String elem[], postfix, conditionName, keywordPosition, actionText, relationName, finalText, activeFlag; + PlatformUtils platformUtils = null; + JSONObject patternConditionJson = null, conditionJson = null; + List idList = new ArrayList(); + List actionTextList = new ArrayList(); + List conditionList = new ArrayList(); + JSONArray conditionData = new JSONArray(), conditionPostPair = new JSONArray(); + Map id2unit = null; + Map macroMap = null, macroAppendMap = new HashMap(); + + try{ + platformUtils = new PlatformUtils(); + + helper.deleteUserData(botId); + + idList = platformUtils.queryConditionIdByTypetreeId(parameters.getJSONArray("conditionCategories")); + + id2unit = engine.queryUnitsByIdList(idList); + + for(Integer id:id2unit.keySet()){ + + patternConditionJson = ActionParser.parse(id2unit.get(id).getActions()); + patternConditionJson.put("originConditionId", id); + patternConditionJson.put("active", false); + patternConditionJson.put("conditionCategory", "0:默认"); + relationName = patternConditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); + + for(int i = 1;i < 10;i++){ + //给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样 + if(i == 1) + postfix = ""; + else + postfix = String.valueOf(i); + + activeFlag = "0"; + + conditionJson = (JSONObject) patternConditionJson.clone(); + conditionName = conditionJson.getString("conditionName") + postfix; + + if(!conditionExtraKeywords.containsKey(conditionName + "_tail")){ //如果没有用到这个condition,就跳过 + break; + } + + conditionJson.put("conditionName", conditionName); + + if(conditionJson.getString("relationHead").equals("?")) + keywordPosition = "left"; + else + keywordPosition = "right"; + + + + flag = conditionAppendKeyword(conditionName, conditionJson, conditionExtraKeywords, macroAppendMap); + + if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition)) + conditionJson.put("active", false); + + + actionText = generateSingleActionText(conditionName, conditionJson); + if(startCondition.equals(conditionName)) { + conditionJson.put("active", true); + actionText = actionText.replace("status=waiting", "status=active"); + activeFlag = "1"; + } + + conditionList.add(new Condition(botId, conditionJson.toJSONString(), actionText, conditionJson.getString("conditionCategory"), activeFlag)); + + actionTextList.add(actionText); + conditionData.add(conditionJson); + + String finalRelationName = relationName; + conditionPostPair.add(new JSONArray(){ + { + add(id); + add(finalRelationName); + } + }); + } + } + parameters.put("conditionData", conditionData); + finalText = generateCompleteActionText(parameters, actionTextList); + ape = new ActionPostElem(botId, botName, finalText, auth, "", conditionPostPair); + postAction(ape); + + if(intervalStatus.getStatus() == 1) { + helper.batchInsertCondition(conditionList); + //insertCondition(parameters); + + + if (intervalStatus.getStatus() == 1) { + engine.updateWelcomeText(botId, parameters.getString("welcome")); + updateKnowledgeUnit(botId, new HashMap() {{ + put("options", OPTIONS); + put("idlelimit", IDLE_LIMIT); + }}, macroAppendMap, parameters.getString("POS")); + } + } + + platformUtils.destroy(); + + + }catch (SQLException e){ + intervalStatus = new IntervalStatus(0, ACTION_TEXT_GENERATE_ERROR); + System.out.println(e.getMessage()); + } + + } + + public void getBotConditionInfo(int botId, String botName, String auth){ + String url = CONDITION_BACKEND_URL + "/get/actions/" + String.valueOf(botId); + Integer statusCode; + JSONObject receiveData = SimpleUtil.getMethod(url, auth); + IntervalStatus intervalStatus = null; + ape = new ActionPostElem(botId, botName, auth); + + statusCode = receiveData.getInteger("status_code"); + //System.out.println(receiveData.toJSONString()); + + switch(statusCode){ + case 200: + ape.setCategoryName(receiveData.getString("catName")); + ape.setConditionIdPair(receiveData.getJSONArray("cdt_name_ls")); + intervalStatus = new IntervalStatus(1, ""); + break; + case 401: + intervalStatus = new IntervalStatus(0,"token过期了"); + break; + default: + intervalStatus = new IntervalStatus(0, "condition后台报错"); + break; + } + } + + public Boolean conditionAppendKeyword(String conditionName, JSONObject conditionJson, Map> conditionExtraKeywords, Map macroAppendMap ){ + + String relationHead = conditionJson.getString("relationHead"); + String repeatKeywords = conditionJson.getJSONArray("repeatList").getJSONObject(0).getString("repeatKeywords").split("-")[0]; + + String extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_head")); + if(relationHead.startsWith("++")){ + if(macroAppendMap.containsKey(relationHead)){ + macroAppendMap.get(relationHead).append(extraKeywords); + }else{ + macroAppendMap.put(relationHead, new StringBuffer(extraKeywords)); + } + } + conditionJson.put("relationHead", extraKeywords); + + + extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_tail")); + if(repeatKeywords.startsWith("++")){ + if(macroAppendMap.containsKey(repeatKeywords)){ + macroAppendMap.get(repeatKeywords).append(extraKeywords); + }else{ + macroAppendMap.put(repeatKeywords, new StringBuffer(extraKeywords)); + } + } + conditionJson.getJSONArray("repeatList").getJSONObject(0).put("repeatKeywords", extraKeywords); + + + return true; + } + + public Set getConditionNameSet(List conditionList){ + String elements[]; + String conditionName; + Set conditionNameSet = new HashSet(); + for(Condition condition:conditionList){ + + for(String line:condition.getActionText().split("\r\n")){ + if(line.startsWith("condition")){ + + elements = line.trim().split("\\|"); + + conditionName = elements[0].split("=")[1].split(":")[0]; + conditionNameSet.add(conditionName); + break; + } + } + } + + return conditionNameSet; + } + public String getConditionName(Condition condition){ + String elements[]; + String conditionName = ""; + + for(String line:condition.getActionText().split("\r\n")){ + if(line.startsWith("condition")){ + + elements = line.trim().split("\\|"); + + conditionName = elements[0].split("=")[1].split(":")[0]; + break; + } + } + + + return conditionName; + } + + + /** + * 更新condition的名字 + * @param parameters + * @return + */ + public String updateConditionName(JSONObject parameters){ + + + int botId = parameters.getInteger("botId"); + int conditioId = parameters.getInteger("conditionId"); + Boolean flag = true; + String conditionName = parameters.getString("conditionName"), actionText = ""; + + Condition condition = helper.queryConditionByConditionId(botId, conditioId); + JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); + List conditionList = helper.queryConditionAll(botId); + Set conditionNameSet = getConditionNameSet(conditionList); + + + if(conditionNameSet.contains(conditionName)){ + intervalStatus = new IntervalStatus(0, CONDITION_NAME_DUMPLICATE); + }else{ + conditionJson.put("conditionName", conditionName); + actionText = generateSingleActionText(conditionName, conditionJson); + condition.setActionText(actionText); + condition.setConditionJsonText(conditionJson.toJSONString()); + flag = helper.updateConditionById(condition); + + if(!flag){ + intervalStatus = new IntervalStatus(0, CONDITION_NAME_UPDATE_ERROR); + }else{ + intervalStatus = new IntervalStatus(1, ""); + } + + } + + return ""; + } + + + public void updateGoodbye(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + String goodbyeText = parameters.getString("sayGoodBye"); + + + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);put("sayGoodbye", goodbyeText);}}, null, null); + + } + + /** + * 修改conditiond的显示顺序 + * @param parameters + */ + public void updateConditionDisplayOrder(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + int conditioId = parameters.getInteger("conditionId"); + int order = parameters.getInteger("order"); + Boolean flag = true; + + Condition condition = helper.queryConditionByConditionId(botId, conditioId); + + condition.setDisplayOrder(order); + if(helper.updateConditionById(condition)){ + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, CONDITION_UPDATE_ERROR); + } + + + } + + public void updateBotInfo(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + Boolean updateFlag = true; + + String option = parameters.getString("option"); + String value = parameters.getString("value"); + + BotInfo botInfo = helper.queryBotInfo(botId); + + if(botInfo != null) { + + switch (option) { + case "welcomeText": + botInfo.setWelcomeText(value); + break; + case "postURL": + botInfo.setPostURL(value); + break; + case "bothValue": + botInfo.setBothValue(value); + break; + case "queryTextTransfer": + botInfo.setQueryTextTransfer(value); + break; + } + updateFlag = helper.updateBotInfo(botInfo); + if(updateFlag){ + intervalStatus = updateKnowledgeUnit(botId, new HashMap(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, UPDATE_ERROR); + } + }else{ + intervalStatus = new IntervalStatus(0, BOT_INFO_NOT_EXIST); + } + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java new file mode 100644 index 0000000..9207e17 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/CategoryUtils.java @@ -0,0 +1,206 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.entity.BotInfo; +import com.qiwu.chatbotbackend.actiongenerate.entity.Category; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.db.SqlHelper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class CategoryUtils { + SqlHelper helper = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public CategoryUtils(SqlHelper helper){ + this.helper = helper; + } + + public void insertCategory(JSONObject parameters){ + int id = 0; + Category category = new Category(parameters.getInteger("botId"), parameters.getInteger("categoryParentId"), parameters.getString("categoryName")); + + id = helper.insertCategoryByBotId(category); + + if(id != 0) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, CATEGORY_INSERT_ERROR); + + } + + public void updateCategory(JSONObject parameters){ + Boolean updateFlag = true; + List childIds = null; + Category category = new Category(parameters.getInteger("botId"), parameters.getInteger("categoryId"), + parameters.getInteger("newParentId"), parameters.getString("newCategoryName")); + + childIds = findChildCategoryIds(category.getBotId(), category.getCategoryId()); + + + if(childIds.contains(category.getParentId())){ + intervalStatus = new IntervalStatus(0, CATEGORY_UPDATE_CONFLICT); + }else{ + updateFlag = helper.updateCategory(category); + if(updateFlag) + intervalStatus = new IntervalStatus(1, ""); + else + intervalStatus = new IntervalStatus(0, CATEGORY_UPDATE_ERROR); + } + + } + + public List findChildCategoryIds(int botId, int rootId){ + List categories = helper.queryCategoryAll(botId); + List idList = new ArrayList(){ + { + add(rootId); + } + }; + + if(rootId == -1) //0和-1表示所有类别 + idList.add(0); + + for(Category category:categories){ + if(idList.contains(category.getParentId())){ + idList.add(category.getCategoryId()); + } + + } + + return idList; + } + + + public List findChildCategoryIds(int botId, int rootId, List childCategories){ + List categories = helper.queryCategoryAll(botId); + List idList = new ArrayList(){ + { + add(rootId); + } + }; + + if(rootId == -1) //0和-1表示所有类别 + idList.add(0); + + for(Category category:categories){ + if(idList.contains(category.getParentId())){ + idList.add(category.getCategoryId()); + } + if(idList.contains(category.getCategoryId())){ + childCategories.add(category); + } + } + + return idList; + } + + + public void queryCategory(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + String categoryId, parentId, defaultCategoryName = "默认"; + List defaultCategoryPath = new ArrayList(); + + List categories = helper.queryCategoryAll(botId); + Map categoryMap = new HashMap(); + BotInfo botInfo = helper.queryBotInfo(botId); + JSONObject finalJson = new JSONObject(); + + /** + * 结构是 + * { + * |--- -1 (根目录) + * | |----0 默认类别 + * | |----其他用户新建类别 + * } + */ + JSONObject categoryTree = new JSONObject(); + categoryTree.put("0", new JSONObject(){{ + put("value", 0); + put("label", "默认"); + put("children", new JSONArray()); + }} + ); + categoryTree.put("-1", new JSONObject(){{ + put("value", -1); + put("label", "root"); + put("children", new JSONArray()); + }} + ); + categoryTree.getJSONObject("-1").getJSONArray("children").add(categoryTree.getJSONObject("0")); + + + for(Category category:categories){ + categoryMap.put(category.getBotId(), category); + } + + + //默认类别路径格式:"[一级类别,二级类别, 三级类别..]" + if(botInfo.getDefaultConfigCategory().equals("") || !botInfo.getDefaultConfigCategory().startsWith("[")){ + //默认路径是从0开始 + defaultCategoryPath.add(0); + }else{ + defaultCategoryPath = JSONArray.parseArray(botInfo.getDefaultConfigCategory(), Integer.class); + } + + + for(Category category:categories){ + categoryId = String.valueOf(category.getCategoryId()); + parentId = String.valueOf(category.getParentId()); + + categoryTree.put(categoryId, new JSONObject(){ + { + put("value", category.getCategoryId()); + put("label", category.getName()); + } + }); + + categoryTree.putIfAbsent(parentId, new JSONObject()); + if(categoryTree.getJSONObject(parentId).getJSONArray("children") == null){ + categoryTree.getJSONObject(parentId).put("children", new JSONArray()); + } + + //将当年类别id的引用放在父id下 + categoryTree.getJSONObject(parentId).getJSONArray("children").add(categoryTree.getJSONObject(categoryId)); + + if(category.getCategoryId() == defaultCategoryPath.get(defaultCategoryPath.size()-1)){ + defaultCategoryName = category.getName(); + } + + } + + finalJson.put("category", categoryTree.getJSONObject("-1").getJSONArray("children")); + finalJson.put("defaultId", JSONArray.parseArray(JSON.toJSONString(defaultCategoryPath))); + finalJson.put("defaultIdName", defaultCategoryName); + + intervalStatus = new IntervalStatus(1, "", finalJson); + + + } + + public void deleteCategory(JSONObject parameters){ + + Boolean flag1, flag2; + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + + ListidList = findChildCategoryIds(botId, categoryId); + flag1 = helper.deleteCategoryByCategoryIds(botId, idList); + if(flag1) { + helper.deleteConfigByCategories(botId, idList); + intervalStatus = new IntervalStatus(1, ""); + }else{ + intervalStatus = new IntervalStatus(0, CATEGORY_DELETE_ERROR); + } + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java new file mode 100644 index 0000000..ccc932e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/ConfigTermUtils.java @@ -0,0 +1,324 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.ConfigTerm; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.Premise; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.CONFIG_INSERT_ERROR; + + + +public class ConfigTermUtils { + + SqlHelper helper = null; + String botAccount = ""; + ServletContext context = null; + UserInfo userInfo = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + public ConfigTermUtils(String botAccount, SqlHelper helper, ServletContext context) throws IOException, SQLException { + this.helper = helper; + this.context = context; + this.botAccount = botAccount; + + UserInfoController uiController = new UserInfoController(); + this.userInfo = uiController.userInfoQuery(botAccount, context); + } + + public ConfigTermUtils(SqlHelper helper){ + this.helper = helper; + } + + + public void insertConfigTerm(JSONObject parameters) throws IOException { + Boolean insertFlag = true; + List configList = new ArrayList(); + List idList = new ArrayList(); + + + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + + + //处理特殊字符 + ConfigTermText configText = configPreprocessing(parameters.getJSONObject("configData")); + configList.add(parameters.getJSONObject("configData")); + + insertFlag = helper.batchInsertConfigByBotId(botId, configList, idList, categoryId); + + + //generateSingleConfigText(); + if(insertFlag){ + UserInfoController.insertConfig(botAccount, String.valueOf(idList.get(0)), configText.toString() + idList.get(0), context); + UserInfoController.writeConfigText(botAccount, userInfo); + intervalStatus = new IntervalStatus(1,""); + }else{ + intervalStatus = new IntervalStatus(0, CONFIG_INSERT_ERROR); + } + + } + + + /** + * 数据预处理 + * @param configJson + */ + public ConfigTermText configPreprocessing(JSONObject configJson){ + int premiseNum = 0, knowledgeNum = 0, nextStepNum; + Premise premise = null; + String reply, auxiliaryPriority = "0", nextStepStatus, configName; + StringBuffer nextStepText = new StringBuffer(), featureText = new StringBuffer(); + JSONObject premiseJson = null, knowledgeJson = null, nextStep; + + ConfigTermText configTermText = null; + + List curPremiseList = new ArrayList(); + List hisPremiseList = new ArrayList(); + Map updateKnowledge = new HashMap(); + Map punctReplaceMap = new HashMap(){ + { + put(",", ","); + put("|", ""); + put("\r\n", ""); + put("\n", ""); + put("\t", ""); + } + }; + + + //解析当前信息的前置条件 + premiseNum = configJson.getJSONArray("currentPremiseList").size(); + for(int i = 0;i < premiseNum;i++){ + premiseJson = configJson.getJSONArray("currentPremiseList").getJSONObject(i); + premise = new Premise(premiseJson.getString("actionName"), premiseJson.getString("cmpType"), + premiseJson.getString("operator"), premiseJson.getString("keywords")); + + if(!premise.getConditionName().equals("") || !premise.getKeyword().equals("")){ + + premise.setKeyword(textReplace(premise.getKeyword(), punctReplaceMap)); + curPremiseList.add(premise); + + } + premiseJson.put("keywords", textReplace(premiseJson.getString("keywords"), punctReplaceMap)); + } + + //解析已知信息的前置条件 + premiseNum = configJson.getJSONArray("historyPremiseList").size(); + for(int i = 0;i < premiseNum;i++){ + premiseJson = configJson.getJSONArray("historyPremiseList").getJSONObject(i); + premise = new Premise(premiseJson.getString("actionName"), premiseJson.getString("cmpType"), + premiseJson.getString("operator"), premiseJson.getString("keywords")); + + if(!premise.getConditionName().equals("") || !premise.getKeyword().equals("")){ + + premise.setKeyword(textReplace(premise.getKeyword(), punctReplaceMap)); + hisPremiseList.add(premise); + } + premiseJson.put("keywords", textReplace(premiseJson.getString("keywords"), punctReplaceMap)); + } + + //获得辅助优先级 + if(configJson.get("auxiliaryPriority") != null){ + auxiliaryPriority = String.valueOf(configJson.getInteger("auxiliaryPriority")); + } + + //获得回答 + reply = textReplace(configJson.getString("reply"), punctReplaceMap); + configJson.put("reply", textReplace(configJson.getString("reply"), punctReplaceMap)); + + //获得更新知识单元 + if(configJson.getJSONArray("updateKnowledge") != null) { + knowledgeNum = configJson.getJSONArray("updateKnowledge").size(); + for (int i = 0; i < knowledgeNum; i++) { + knowledgeJson = configJson.getJSONArray("updateKnowledge").getJSONObject(i); + + updateKnowledge.put(knowledgeJson.getString("variableName"), textReplace(knowledgeJson.getString("keyword"), punctReplaceMap)); + knowledgeJson.put("keyword", textReplace(knowledgeJson.getString("keyword"), punctReplaceMap)); + } + } + + //多个下一步激活问题的处理 + + if(configJson.get("nextStepList") != null){ + nextStepNum = configJson.getJSONArray("nextStepList").size(); + + for(int i = 0;i < nextStepNum;i++){ + if(i != 0) + nextStepText.append(","); + nextStep = configJson.getJSONArray("nextStepList").getJSONObject(i); + nextStepText.append(nextStep.getString("nextStep")); + if(nextStep.get("except") != null && nextStep.getJSONArray("except").size() != 0){ + nextStepText.append(":").append(Joiner.on("-").join(nextStep.getJSONArray("except"))); + } + + } + } + + if(curPremiseList.size() != 0 || hisPremiseList.size() != 0) + //match表示需要条件匹配 + featureText.append("match"); + + //是否提交表单 + if(configJson.getBoolean("doPost")){ + featureText.append("post::").append(configJson.getString("postType")); + featureText.append("(").append(configJson.getString("postURL")).append(")"); + + } + + //判断下一步是选择新的问题,还是留在原来的问题,或是返回上一个问题 + if(!configJson.containsKey("nextStepStatus")) + featureText.append(",return-0"); + else{ + nextStepStatus = configJson.getString("nextStepStatus"); + switch(nextStepStatus){ + case "stay": + featureText.append(",return-0"); + break; + case "back": + featureText.append(",return-1"); + break; + case "return": + case "jump": + //存在多个下一步 + if(configJson.get("nextStepList") != null && configJson.getJSONArray("nextStepList").size() > 1){ + featureText.append(",newNext"); + } + break; + case "activate": + //下一步激活,且激活不为空 + if(configJson.get("nextStepList") != null && !configJson.getJSONArray("nextStepList").getJSONObject(0).getString("nextStep").equals("")){ + featureText.append(",activate"); + } + break; + } + } + + configTermText = new ConfigTermText(curPremiseList, hisPremiseList, updateKnowledge, "", "", "", featureText.toString(), reply, nextStepText.toString(), auxiliaryPriority); + + configName = configJson.getString("configName"); + if(configName != null && !configName.equals("")) { + configTermText.setConfigName(configName, false); + } + + return configTermText; + + + + } + + public void deleteConfig(JSONObject parameters) throws IOException { + Boolean deleteFlag = true; + int botId = parameters.getInteger("botId"); + int configId = parameters.getInteger("configId"); + + deleteFlag = helper.deleteConfigByConfigId(botId, configId); + + if(deleteFlag){ + UserInfoController.deleteConfig(botAccount, String.valueOf(configId), "", context); + UserInfoController.writeConfigText(botAccount, userInfo); + } + + } + + public void updateConfig(JSONObject parameters) throws IOException { + Boolean updateFlag = true; + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + int configId = parameters.getInteger("configId"); + + ConfigTermText configText = configPreprocessing(parameters.getJSONObject("configData")); + + ConfigTerm configTerm = helper.queryConfigByConfigId(botId, configId); + + updateFlag = helper.updateConfig(new ConfigTerm(botId, configId, categoryId, parameters.getJSONObject("configData"))); + if(!updateFlag){ + if(parameters.getJSONObject("configData").toJSONString().equals(configTerm.getConfigJsonText())){ + updateFlag = true; + } + } + + if(updateFlag){ + //更新配置条目 + UserInfoController.deleteConfig(botAccount, String.valueOf(configId), "", context); + UserInfoController.insertConfig(botAccount, String.valueOf(configId), configText.toString() + configId, context); + UserInfoController.writeConfigText(botAccount, userInfo); + } + + } + + + public void queryConfig(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + int categoryId = parameters.getInteger("categoryId"); + JSONArray configDataList = new JSONArray(); + JSONObject configJson = null; + + List configTermList = helper.queryConfigByCategoryId(botId, categoryId); + + for(ConfigTerm configTerm:configTermList){ + configJson = JSONObject.parseObject(configTerm.getConfigJsonText()); + configJson.put("configId", configTerm.getConfigId()); + configJson.put("categoryId", configTerm.getCategoryId()); + + configDataList.add(configJson); + } + + intervalStatus = new IntervalStatus(1, "", configDataList); + } + + public void querySleepingConfig(JSONObject parameters){ + + int botId = parameters.getInteger("botId"); + JSONArray sleepingConfigs = new JSONArray(); + JSONObject configJson = null; + + List configTermList = helper.querySleepingConfig(botId); + + for(ConfigTerm configTerm:configTermList){ + sleepingConfigs.add(new JSONArray(){ + { + add(configTerm.getConfigId()); + add(configTerm.getConfigName()); + } + }); + } + + intervalStatus = new IntervalStatus(1, "", sleepingConfigs); + } + + /** + * 将文本中的一些特殊字符过滤掉 + * @param text + * @param replaceMap + * @return + */ + public String textReplace(String text, Map replaceMap){ + for(String key:replaceMap.keySet()){ + text = text.replace(key, replaceMap.get(key)); + } + + return text; + } + + public void generateSingleConfigText(JSONObject configJson){ + + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java new file mode 100644 index 0000000..36b8686 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/MacroUtils.java @@ -0,0 +1,4 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +public class MacroUtils { +} diff --git a/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java new file mode 100644 index 0000000..259e624 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/actiongenerate/utils/VariableUtils.java @@ -0,0 +1,159 @@ +package com.qiwu.chatbotbackend.actiongenerate.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.entity.Variable; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class VariableUtils { + SqlHelper helper = null; + public IntervalStatus intervalStatus = new IntervalStatus(1, ""); + String botAccount = ""; + ServletContext context = null; + UserInfo userInfo = null; + + public VariableUtils(String botAccount, SqlHelper helper, ServletContext context) throws IOException, SQLException { + this.helper = helper; + this.context = context; + this.botAccount = botAccount; + + UserInfoController uiController = new UserInfoController(); + this.userInfo = uiController.userInfoQuery(botAccount, context); + } + + + + + public VariableUtils(SqlHelper helper) { + this.helper = helper; + } + + public void queryVariable(JSONObject parameters){ + int botId = parameters.getInteger("botId"); + List variables = null; + JSONArray varList = new JSONArray(); + + variables = helper.queryVariableAll(botId); + + for(Variable variable:variables){ + varList.add(new JSONObject(){ + { + put("id", variable.getVariableId()); + put("categoryId", variable.getCategoryId()); + put("name", variable.getName()); + put("description", variable.getDescription()); + put("default", variable.getValue()); + } + }); + } + + intervalStatus = new IntervalStatus(1, "", varList); + + } + + public void insertVariable(JSONObject parameters) throws IOException { + int botId = parameters.getInteger("botId"); + int variableId = 0; + + Variable variable = new Variable(parameters.getInteger("botId"), parameters.getInteger("categoryId"), + parameters.getString("varName"), parameters.getString("varDescription"), + parameters.getString("varDefaultValue")); + + if(helper.queryVariableByName(variable.getBotId(), variable.getName()) != null){ + intervalStatus = new IntervalStatus(0, VARIABLE_NAME_DUMPLICATE); + }else{ + variableId = helper.insertVariable(variable); + + if(variableId != 0){ + + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + //修改配置文件 + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_INSERT_ERROR); + } + + + } + } + + public void deleteVairiable(JSONObject parameters) throws IOException { + int botId = parameters.getInteger("botId"); + int variableId = parameters.getInteger("varId"); + Boolean deleteFalg = true; + + //从delete + //deleteFalg = + Variable variable = helper.queryVariableByVariableId(botId, variableId); + + if(deleteFalg) { + deleteFalg = helper.deleteVariable(botId, variableId); + + System.out.println("deleteFlag" + deleteFalg); + + if(deleteFalg){ + intervalStatus = new IntervalStatus(1, ""); + UserInfoController.deleteVariable(botAccount, "", variable.getName(), context); + UserInfoController.writeConfigText(botAccount, userInfo); + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_SQL_DELETE_ERROR); + } + }else{ + intervalStatus = new IntervalStatus(0, VARIABLE_DELETE_ERROR); + } + } + + public void updateVariable(JSONObject parameters) throws IOException { + Boolean updateFlag = true; + Variable variable = new Variable(parameters.getInteger("botId"), parameters.getInteger("varId"), + parameters.getInteger("categoryId"), parameters.getString("varName"), + parameters.getString("varDescription"), parameters.getString("varDefaultValue")); + + Variable variable2 = helper.queryVariableByName(variable.getBotId(), variable.getName()); + + if(variable2 != null && variable.getVariableId() == variable2.getVariableId()){ + intervalStatus = new IntervalStatus(0, VARIABLE_NAME_DUMPLICATE); + }else{ + updateFlag = helper.updateVariable(variable); + + if(updateFlag){ + intervalStatus = new IntervalStatus(1, ""); + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + }else{ + + if(variable.getCategoryId() == variable2.getCategoryId() && variable.getBotId() == variable2.getBotId() + && variable.getValue().equals(variable2.getValue()) && variable.getName().equals(variable2.getValue()) + && variable.getDescription().equals(variable2.getDescription())){ + UserInfoController.updateVariable(botAccount, "", String.format(VARIABLE_UPDATE_FORMAT, variable.getName(), variable.getValue()), context); + UserInfoController.writeConfigText(botAccount, userInfo); + intervalStatus = new IntervalStatus(1, ""); + }else { + intervalStatus = new IntervalStatus(0, VARIABLE_UPDATE_ERROR); + } + } + } + + } + + public Set getVariableNameSet(List variableList){ + Set variableNameSet = new HashSet(); + for(Variable variable:variableList){ + variableNameSet.add(variable.getName()); + } + + return variableNameSet; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java b/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java new file mode 100644 index 0000000..8e3df58 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/controller/BackupController.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.controller; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ResourceLoader; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import static com.qiwu.chatbotbackend.Config.Config.BOT_BACKUP_DIR; + +@RestController +@ResponseBody +public class BackupController { + + @Autowired + ResourceLoader loader; + + + @GetMapping("/sayhi2") + public ResponseEntity getFile(@PathVariable("name") String name){ + System.out.println("---" + name); + String filePath = BOT_BACKUP_DIR + name; + byte[] body = null; + + try { + body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream()); + }catch (Exception e){ + e.printStackTrace(); + } + + + String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length()); + HttpHeaders headers=new HttpHeaders(); + headers.add("Content-Disposition", "attachment;filename="+fileName); + + return new ResponseEntity(body, headers, HttpStatus.OK); + } + + @RequestMapping("/sayhi1") + public ResponseEntity getFile2(){ + System.out.println("---"); + String filePath = BOT_BACKUP_DIR; + byte[] body = null; + + try { + body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream()); + }catch (Exception e){ + e.printStackTrace(); + } + + + String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length()); + HttpHeaders headers=new HttpHeaders(); + headers.add("Content-Disposition", "attachment;filename="+fileName); + + return new ResponseEntity(body, headers, HttpStatus.OK); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java b/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java new file mode 100644 index 0000000..555f8e4 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/controller/Hello.java @@ -0,0 +1,13 @@ +package com.qiwu.chatbotbackend.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Hello { + + @RequestMapping("/sayhi") + public String sayHi() { + return "hello: "; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java new file mode 100644 index 0000000..cc630ea --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/C3p0Utils.java @@ -0,0 +1,82 @@ +package com.qiwu.chatbotbackend.db; + + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import org.apache.log4j.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class C3p0Utils { + static Logger logger = Logger.getLogger(C3p0Utils.class.getName()); + + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("engine"); + static ComboPooledDataSource dataSource3 = new ComboPooledDataSource("platform"); + + //从连接池中取用一个连接 + public static Connection getConnection() throws SQLException { + try { + return dataSource.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //从连接池中取用一个连接 + public static Connection getEngineConnection() throws SQLException { + try { + return dataSource2.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //从连接池中取用一个连接 + public static Connection getPlatformConnection() throws SQLException { + try { + return dataSource3.getConnection(); + + } catch (Exception e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + //释放连接回连接池 + public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + if (pst != null) { + try { + pst.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + logger.error("Exception in C3p0Utils!", e); + throw e; + } + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/DB.java b/src/main/java/com/qiwu/chatbotbackend/db/DB.java new file mode 100644 index 0000000..2a0a658 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/DB.java @@ -0,0 +1,24 @@ +package com.qiwu.chatbotbackend.db; + +import java.sql.Connection; +import java.sql.DriverManager; + +public class DB { + private static String driver = "com.mysql.jdbc.Driver"; + private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN"; + private static String user = "root"; + private static String pwd = "admin"; + + public static Connection getConnection() { + Connection conn = null; + try { + Class.forName(driver); + conn = DriverManager.getConnection(url, user, pwd); + + } catch (Exception e) { + e.printStackTrace(); + } + + return conn; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java new file mode 100644 index 0000000..9ec475d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/db/SqlHelper.java @@ -0,0 +1,1575 @@ +package com.qiwu.chatbotbackend.db; + +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Joiner; +import com.qiwu.chatbotbackend.actiongenerate.entity.*; +import com.qiwu.chatbotbackend.entity.ArchiveInfo; +import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; + +import java.sql.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class SqlHelper { + private Connection conn = null; + /* + public SqlHelper(){ + conn = DB.getConnection(); + } + */ + + public SqlHelper() throws SQLException { + conn = C3p0Utils.getConnection(); + } + + + public void destroy() { + if (conn != null) { + try { + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + + + //---------------------------------------变量的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + public List queryVariableAll(int botId){ + String sql = "select * from chatbot_variable where botId= ?"; + List variables = new ArrayList(); + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + variables.add(variable); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variables; + } + + public Variable queryVariableByName(int botId, String name){ + String sql = "select * from chatbot_variable where botId= ? and name= ?"; + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setString(2, name); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variable; + } + + + public Variable queryVariableByVariableId(int botId, int variableId){ + String sql = "select * from chatbot_variable where botId= ? and variableId= ?"; + Variable variable = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, variableId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + variable = new Variable(rs.getInt("botId"), rs.getInt("variableId"), rs.getInt("categoryId"), + rs.getString("name"), rs.getString("description"), rs.getString("defaultValue")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return variable; + } + + public Integer insertVariable(Variable variable) { + String sql = "insert into chatbot_variable (botId, categoryId, name, description, defaultValue) VALUES (?, ?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + int id = 0; + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setInt(1, variable.getBotId()); + ps.setInt(2, variable.getCategoryId()); + ps.setString(3, variable.getName()); + ps.setString(4, variable.getDescription()); + ps.setString(5, variable.getValue()); + + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + public Integer insertBotInfo(BotInfo botInfo) { + String sql = "insert into bot_info (botId, defaultConfigCategory, welcomeText, goodbyeText, postURL, queryTextTransfer) VALUES (?, ?, ?, ?, ?, 1)"; + String userName = ""; + String result = "empty"; + int id = 0; + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setInt(1, botInfo.getBotId()); + ps.setString(2, botInfo.getDefaultConfigCategory()); + ps.setString(3, botInfo.getWelcomeText()); + ps.setString(4, botInfo.getGoodbyeText()); + ps.setString(5, botInfo.getPostURL()); + + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + public boolean deleteVariable(int botId, int variableId) { + String sql = "delete from chatbot_variable where botId= ? and variableId = ?"; + String userName = ""; + String result = "empty"; + boolean b = false; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setInt(2, variableId); + + b = ps.executeUpdate() == 1; + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + + + public Boolean updateVariable(Variable variable){ + boolean b = false; + + try { + String sql = "update chatbot_variable set categoryId = ?, name = ?, description = ?, defaultValue = ? where botId = ? and variableId = ?"; + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, variable.getCategoryId()); + ps.setString(2, variable.getName()); + ps.setString(3, variable.getDescription()); + ps.setString(4, variable.getValue()); + ps.setInt(5, variable.getBotId()); + ps.setInt(6, variable.getVariableId()); + + b = ps.executeUpdate() == 1; + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + //----------------------------------------配置条目类别的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + + public boolean deleteCategoryByCategoryIds(int botId, List idList) { + String sql = "delete from config_categories where botId= ? and categoryId in (?)"; + + boolean b = false; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setString(2, Joiner.on(",").join(idList)); + b = ps.executeUpdate() == 1; + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CATEGORY_ERROR); + e.printStackTrace(); + return false; + } + } + + + public Integer insertCategoryByBotId(Category category) { + String sql = "INSERT INTO config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + boolean b = false; + int id = 0; + try { + conn.setAutoCommit(false); + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setInt(1, category.getBotId()); + ps.setInt(2, category.getParentId()); + ps.setString(3, category.getName()); + ps.setString(4, category.getStatus()); + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return id; + + } + + + + public List queryCategoryAll(int botId){ + String sql = "select * from config_categories where botId= ?"; + List categories = new ArrayList(); + Category category = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + category = new Category(rs.getInt("botId"), rs.getInt("categoryId"), + rs.getInt("categoryParentId"), rs.getString("categoryName")); + categories.add(category); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return categories; + } + + public Boolean updateCategory(Category category){ + boolean b = false; + + try { + String sql = "update config_categories set categoryName = ?, categoryParentId = ? where botId = ? and categoryId = ?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1,category.getName()); + ps1.setInt(2, category.getParentId()); + ps1.setInt(3, category.getBotId()); + ps1.setInt(4, category.getCategoryId()); + + b = ps1.executeUpdate() ==1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + //----------------------------------------配置条目的操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + public boolean deleteConfigByCategories(int botId, List idList) { + boolean b = false; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ? and categoryId in (?)"); + ps1.setInt(1, botId); + ps1.setString(2, Joiner.on(",").join(idList)); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + public boolean deleteConfigByConfigId(int botId, int configId) { + boolean b = false; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ? and configId = ?"); + ps1.setInt(1, botId); + ps1.setInt(2, configId); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + public List queryConfigByCategoryId(int botId, int configId){ + String sql = "select * from chatbot_config where botId= ? and categoryId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, configId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + + public List querySleepingConfig(int botId){ + String sql = "select * from chatbot_config where configName != '' and botId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + + public List queryConfigByCategoryIdList(int botId, List categoryIdList){ + String sql = "select * from chatbot_config where botId= ? and categoryId in (" + Joiner.on(",").join(categoryIdList) + ")"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + //ps.setString(2, Joiner.on(",").join(categoryIdList)); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), + rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTermList; + } + + public ConfigTerm queryConfigByConfigId(int botId, int configId){ + String sql = "select * from chatbot_config where botId= ? and configId = ?"; + List configTermList = new ArrayList(); + ConfigTerm configTerm = null; + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ps.setInt(2, configId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + configTerm = new ConfigTerm(rs.getInt("botId"), rs.getInt("configId"), rs.getInt("categoryId"), rs.getString("configData"), rs.getString("configName")); + //actionTextList.add(rs.getString("actionText")); + //configTermList.add(configTerm); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return configTerm; + } + + public int insertConfig(int botId, JSONObject configData, int categoryId) { + boolean insertFlag = true; + Boolean b = false; + int id = 0; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, configData.toJSONString()); + ps.setString(4, (String)configData.get("configName")); + + + b = ps.executeUpdate() == 1; + ResultSet rs = ps.getGeneratedKeys(); + + if(rs.next()){ + id = rs.getInt(1); + } + conn.commit(); + rs.close(); + ps.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + return id; + } + + public Boolean updateConfig(ConfigTerm configTerm){ + boolean b = false; + + try { + String sql = "update chatbot_config set configData = ? ,categoryId = ?, configName = ? where botId=? and configId=?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, configTerm.getConfigJsonText()); + ps1.setInt(2, configTerm.getCategoryId()); + ps1.setString(3, configTerm.getConfigName()); + ps1.setInt(4, configTerm.getBotId()); + ps1.setInt(5, configTerm.getConfigId()); + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + + + + //----------------------------------------condition操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + public Boolean deleteUserData(int botId){ + + String sql1 = "delete from chatbot_config where botId = ?"; + String sql2 = "delete from chatbot_condition where botId = ?"; + String sql3 = "delete from config_categories where botId = ?"; + String sql4 = "delete from chatbot_variable where botId = ?"; + Boolean b1, b2, b3, b4; + + try{ + PreparedStatement ps1 = conn.prepareStatement(sql1); + ps1.setInt(1, botId); + b1 = ps1.execute(); + ps1.close(); + + PreparedStatement ps2 = conn.prepareStatement(sql2); + ps2.setInt(1, botId); + b2 = ps2.execute(); + ps2.close(); + + PreparedStatement ps3 = conn.prepareStatement(sql3); + ps3.setInt(1, botId); + b3 = ps3.execute(); + ps3.close(); + + PreparedStatement ps4 = conn.prepareStatement(sql4); + ps4.setInt(1, botId); + b4 = ps4.execute(); + ps4.close(); + + } catch (SQLException e) { + System.out.println(DELETE_USER_DATA_ERROR); + e.printStackTrace(); + return false; + } + return b1&&b2&&b3&&b4; + + } + + public Boolean batchInsertCondition(List conditionList){ + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)"; + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for(Condition condition:conditionList){ + ps.setInt(1, condition.getBotId()); + ps.setString(2, condition.getConditionJsonText()); + ps.setString(3, condition.getCategory()); + ps.setString(4, condition.getActionText()); + ps.setString(5, condition.getActive()); + ps.addBatch(); + } + + count = ps.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + ps.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + } + + public List queryActionTextList(int botId){ + String sql = "select actionText from chatbot_condition where botId= ?"; + String pre_name = ""; + List actionTextList = new ArrayList(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + actionTextList.add(rs.getString("actionText")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return actionTextList; + } + + public Condition queryActiveCondition(int botId){ + Condition condition = null; + + String sql = "select * from chatbot_condition where active= 1 and botId = ?"; + String pre_name = ""; + List actionTextList = new ArrayList(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), + rs.getString("conditionData"), rs.getString("actionText"), + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return condition; + + } + public boolean deleteConditionBy2Id(int botId, int conditionId) { + boolean b; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_condition where botId= ? and conditionId=?"); + ps1.setInt(1, botId); + ps1.setInt(2, conditionId); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + public List queryConditionCategoriesById(int botId){ + String sql = "select categoryInfo from chatbot_condition where botId= ?"; + String pre_name = ""; + List categoryList = new ArrayList(); + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + categoryList.add(rs.getString("categoryInfo")); + } + + ps.close(); + rs.close(); + + + + }catch(Exception e){ + e.printStackTrace(); + } + return categoryList; + } + + + + public BotInfo queryBotInfo(int botId){ + String sql = "select * from bot_info where botId = ?"; + BotInfo botInfo = null; + + try{ + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + botInfo = new BotInfo(rs.getInt("botId"), rs.getString("welcomeText"), rs.getString("goodbyeText"), rs.getString("postURL"), rs.getString("defaultConfigCategory"), + rs.getString("bothValue"), rs.getString("queryTextTransfer")); + } + + ps.close(); + rs.close(); + + + }catch(Exception e){ + e.printStackTrace(); + } + return botInfo; + } + + public Boolean updateBotInfo(BotInfo botInfo){ + boolean b; + + try { + String sql = "update bot_info set welcomeText = ?, goodbyeText = ?, postURL = ?, defaultConfigCategory = ?, bothValue = ?, queryTextTransfer = ? where botId = ?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, botInfo.getWelcomeText()); + ps1.setString(2, botInfo.getGoodbyeText()); + ps1.setString(3, botInfo.getPostURL()); + ps1.setString(4, botInfo.getDefaultConfigCategory()); + ps1.setString(5, botInfo.getBothValue()); + ps1.setString(6, botInfo.getQueryTextTransfer()); + ps1.setInt(7, botInfo.getBotId()); + + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + + + public Boolean updateConditionById(Condition condition){ + boolean b; + + try { + String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?"; + PreparedStatement ps1 = conn.prepareStatement(sql); + ps1.setString(1, condition.getConditionJsonText()); + ps1.setString(2, condition.getActionText()); + ps1.setString(3, condition.getCategory()); + ps1.setString(4, condition.getActive()); + ps1.setInt(5, condition.getBotId()); + ps1.setInt(6, condition.getConditionId()); + + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + + public boolean batchUpdateCondition(int botId, List conditionList) { + + int count[]; + boolean insertFlag = true; + + + try { + conn.setAutoCommit(false); + + + String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?"; + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + + for(Condition condition:conditionList){ + ps.setString(1, condition.getConditionJsonText()); + ps.setString(2, condition.getActionText()); + ps.setString(3, condition.getCategory()); + ps.setString(4, condition.getActive()); + ps.setInt(5, condition.getBotId()); + ps.setInt(6, condition.getConditionId()); + ps.addBatch(); + } + + count = ps.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + ps.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + + + public List queryConditionByCategory(int botId, String category){ + boolean b; + List conditionList = new ArrayList(); + Condition condition = null; + + try { + String sql = "select * from chatbot_condition wher botId = ? and categoryInfo = ? order by displayOrder asc"; + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setString(2, category); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), + rs.getString("conditionData"), rs.getString("actionText"), + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); + conditionList.add(condition); + } + ps.close(); + rs.close(); + + + return conditionList; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return conditionList; + } + } + + public Condition queryConditionByConditionId(int botId, int conditionId){ + boolean b; + List conditionList = new ArrayList(); + Condition condition = null; + + try { + String sql = "select * from chatbot_condition where botId = ? and conditionId = ?"; + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ps.setInt(2, conditionId); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), + rs.getString("conditionData"), rs.getString("actionText"), + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); + } + ps.close(); + rs.close(); + + + return condition; + + } catch (SQLException e) { + System.out.println(CONFIG_DELETE_ERROR); + e.printStackTrace(); + return condition; + } + } + + + public List queryConditionAll(int botId){ + boolean b; + List conditionList = new ArrayList(); + Condition condition = null; + + try { + String sql = "select * from chatbot_condition where botId = ? order by displayOrder asc"; + PreparedStatement ps = conn.prepareStatement(sql); + ps.setInt(1, botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"), + rs.getString("conditionData"), rs.getString("actionText"), + rs.getString("categoryInfo"), rs.getString("active"), rs.getInt("displayOrder")); + conditionList.add(condition); + } + ps.close(); + rs.close(); + + + return conditionList; + + } catch (SQLException e) { + System.out.println(CONFIG_DELETE_ERROR); + e.printStackTrace(); + return conditionList; + } + } + + + + //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ + + private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException { + C3p0Utils.close(_conn, _st, _rs); + } + + public String queryUsernameByKey(String chat_key) { + String sql = "select * from chats where chat_key = ?"; + String userName = ""; + String result = "empty"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, chat_key); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("bot"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + public boolean deleteConfigByIdGroup(int botId, List idGroup) throws SQLException { + + StringBuilder inClause = new StringBuilder(); + boolean firstValue = true; + int batchSize = idGroup.size(); + + for (int i = 0; i < batchSize; i++) { + inClause.append('?'); + if (firstValue) { + firstValue = false; + } else { + inClause.append(','); + } + } + + String sql = "delete from chatbot_config where botId = ? and configId in (" + inClause.toString() + ')'; + String userName = ""; + boolean b = true; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.execute(); + + ps.close(); + + return b; + } catch (Exception e) { + e.printStackTrace(); + } + return b; + } + + public boolean deleteConfigByBotId(int botId) { + boolean b; + + try { + PreparedStatement ps1 = conn.prepareStatement("delete from chatbot_config where botId= ?"); + ps1.setString(1, String.valueOf(botId)); + b = ps1.executeUpdate() == 1; + ps1.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); + e.printStackTrace(); + return false; + } + } + + public boolean deleteVariableByBotId(int botId) { + String sql = "delete from chatbot_variable where botId= ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.executeUpdate() == 1; + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_VARIABLE_ERROR); + e.printStackTrace(); + return false; + } + } + + + public boolean deleteCategoryByBotId(int botId) { + String sql = "delete from config_categories where botId= ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botId)); + b = ps.executeUpdate() == 1; + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println(DELETE_OLD_CATEGORY_ERROR); + e.printStackTrace(); + return false; + } + } + + public boolean batchInsertVariableByBotId(int botId, ElementConstructor constructor) { + + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; + PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + Iterator iit = constructor.getVarInitialMap().keySet().iterator(); + while (iit.hasNext()) { + varName = iit.next(); + varValue = constructor.getVarInitialMap().get(varName); + if (constructor.getConditionDescription().get(varName) == null) + description = ""; + else + description = constructor.getConditionDescription().get(varName); + + ps2.setString(1, String.valueOf(botId)); + ps2.setString(2, varName); + ps2.setString(3, description); + ps2.setString(4, varValue); + ps2.addBatch(); + } + + count = ps2.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + ps2.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + public boolean batchInsertVariable(int botId, List variableList) { + + int count[]; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + + + try { + conn.setAutoCommit(false); + + + sql = "insert into chatbot_variable (botId, name, categoryId, description, defaultValue) VALUES (?, ?, 0, ?, ?)"; + PreparedStatement ps2 = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for(Variable variable:variableList){ + ps2.setInt(1, botId); + ps2.setString(2, variable.getName()); + ps2.setString(3, variable.getDescription()); + ps2.setString(4, variable.getValue()); + ps2.addBatch(); + } + + count = ps2.executeBatch(); + + conn.commit(); + ps2.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + public boolean batchInsertConfigByBotId(int botId, List jsonList, List idList, int categoryId) { + int count[]; + boolean insertFlag = true; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for (JSONObject json : jsonList) { + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, json.toJSONString()); + ps.setString(4, (String)json.get("configName")); + + ps.addBatch(); + } + + count = ps.executeBatch(); + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + + ResultSet rs = ps.getGeneratedKeys(); + while (rs.next()) + idList.add(rs.getInt(1)); + + + ps.close(); + rs.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + } + + public boolean batchInsertConfig(int botId, List configTermList) { + int count[]; + boolean insertFlag = true; + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + + + try { + conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交 + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + for (ConfigTerm configTerm : configTermList) { + ps.setInt(1, botId); + ps.setInt(2, configTerm.getCategoryId()); + ps.setString(3, configTerm.getConfigJsonText()); + ps.setString(4, configTerm.getConfigName()); + + ps.addBatch(); + } + + count = ps.executeBatch(); + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + ps.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + } + + + public boolean batchInsertCategoryByBotId(int botId, Map categoryMap) { + + int count[], iterNum = 0, id; + boolean insertFlag = true; + String sql = "", varName, varValue, description; + ArrayList nameList = new ArrayList(); + + + try { + conn.setAutoCommit(false); + + + sql = "insert into config_categories (botId, categoryParentId, categoryName, categoryStatus) VALUES (?, -1, ?, 'avaliable')"; + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + + Iterator iit = categoryMap.keySet().iterator(); + while (iit.hasNext()) { + varName = iit.next(); + + nameList.add(varName); + ps.setString(1, String.valueOf(botId)); + ps.setString(2, varName); + ps.addBatch(); + } + + count = ps.executeBatch(); + + conn.commit(); + + for (int i : count) { + if (i == 0) { + conn.rollback(); + System.out.println("======出现异常,回滚========="); + insertFlag = false; + } + } + + + + ResultSet rs = ps.getGeneratedKeys(); + while (rs.next()){ + id = rs.getInt(1); + categoryMap.put(nameList.get(iterNum), id); + iterNum++; + } + + + ps.close(); + rs.close(); + + } catch (SQLException e) { + try { + conn.rollback(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + System.out.println("------出现异常,回滚----------"); + e.printStackTrace(); + } + + return insertFlag; + + } + + + public JSONObject queryGameElementsByBotId(int id) { + String sql = "select * from generate_json_tb where project_id = ?"; + String userName = ""; + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("json_text"); + + ps.close(); + rs.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return JSONObject.parseObject(result); + + } + + public static String queryEnvJsonByBotName(String botName) throws SQLException { + String sql = "select * from generate_json_tb where bot_name = ?"; + Connection conn = C3p0Utils.getConnection(); + String result = "{}"; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(botName)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + result = rs.getString("env_json_text"); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + public boolean insertVariableByBotId(int id, String variableName, String description, String defaultValue) { + String sql = "insert into chatbot_variable (botId, name, description, defaultValue) VALUES (?, ?, ?, ?)"; + String userName = ""; + String result = "empty"; + boolean b = true; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(id)); + ps.setString(2, variableName); + ps.setString(3, description); + ps.setString(4, defaultValue); + b = ps.executeUpdate() == 1; + + ps.close(); + conn.commit(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + + public boolean insertConfigByBotId(int botId, JSONObject json, List idList, int categoryId) { + String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)"; + int id = 0; + boolean b = true; + int bNum = 0; + try { + PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setString(1, String.valueOf(botId)); + ps.setString(2, String.valueOf(categoryId)); + ps.setString(3, json.toJSONString()); + ps.setString(4, (String)json.get("configName")); + + System.out.println(ps.toString()); + + bNum = ps.executeUpdate(); + ResultSet rs = ps.getGeneratedKeys(); + if(rs.next()){ + id = rs.getInt(1); + idList.add(id); + } + ps.close(); + rs.close(); + conn.commit(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return b; + + } + + + public Boolean insertArchiveInfo(String archiveName, String userKey, String site){ + String sql = "insert into game_archive (archive_id, user_key, site, plot) VALUES (?, ?, ?, '')"; + int id = 0; + boolean b = true; + int bNum = 0; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(archiveName)); + ps.setString(2, String.valueOf(userKey)); + ps.setString(3, String.valueOf(site)); + + + System.out.println(ps.toString()); + + bNum = ps.executeUpdate(); + ps.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return bNum == 1; + } + + public ArchiveInfo queryUserLastGameArchive(String userKey){ + String sql = "select * from game_archive where user_key = ? order by update_time desc"; + String result = "{}"; + ArchiveInfo archiveInfo = null; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, String.valueOf(userKey)); + ResultSet rs = ps.executeQuery(); + if (rs.next()) + archiveInfo = new ArchiveInfo(rs.getString("archive_id"),rs.getString("user_key"), + rs.getString("site"),rs.getString("update_time"),rs.getString("plot")); + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return archiveInfo; + } + + + public ArchiveInfo queryUserLastGameArchiveBySite(String userKey, String site){ + String sql = "select * from game_archive where user_key = ? and site = ? order by update_time desc"; + String result = "{}"; + ArchiveInfo archiveInfo = null; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, userKey); + ps.setString(2, site); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"), + rs.getString("site"), rs.getString("update_time"), rs.getString("plot")); + } + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return archiveInfo; + } + + + public boolean deleteArchiveByBotAccount(String botAccount) { + String sql = "delete from game_archive where user_key like ?"; + boolean b; + + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, "%" + botAccount); + b = ps.execute(); + + ps.close(); + + return b; + + } catch (SQLException e) { + System.out.println("删除游戏存档失败"); + e.printStackTrace(); + return false; + } + } + + public List queryArchiveByUserKey(String userKey){ + String sql = "select * from game_archive where user_key = ? order by update_time desc"; + List archiveList = new ArrayList(); + ArchiveInfo archiveInfo = null; + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setString(1, userKey); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"), + rs.getString("site"), rs.getString("update_time"), rs.getString("plot")); + archiveList.add(archiveInfo); + } + + ps.close(); + rs.close(); + conn.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return archiveList; + } + + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Action.java b/src/main/java/com/qiwu/chatbotbackend/entity/Action.java new file mode 100644 index 0000000..a4ca8be --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Action.java @@ -0,0 +1,173 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; + + +/** + * 保存配置文件每一行(单行)解析后的信息的实体类。 + * 独立于引擎的另一种condition + */ +public class Action { + private int priority = -1; + //public int activePriority = 0; //如果本condition被其他condition激活 + private int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 + private HashSet keywordSet = new HashSet(); + private HashMap> historyPremise = new HashMap>(); + private HashMap> currentPremise = new HashMap>(); + private HashMap updateKnowledge = new LinkedHashMap(); + private String[] answer = {"",}; + private String nextStep = ""; + private HashMap featureMap = new HashMap(); + private String indexName = ""; + private int id = 0; + private String configName = ""; + private String status = "waiting"; + //public ArrayList indexName = new ArrayList(); + + public Action(int priority) { + this.priority = priority; + //this.activePriority = priority; + } + + + /** + * + * @param originAction 这个action的初始状态 + * @param basePriority 激活originAction的action的条件数量 + * @param baseAuxiliaryPriority 激活originAction的action的辅助优先级 + */ + public Action(Action originAction, int basePriority, int baseAuxiliaryPriority) { + this.priority = originAction.priority; + this.keywordSet = originAction.keywordSet; + this.historyPremise = originAction.historyPremise; + this.currentPremise = originAction.currentPremise; + this.answer = originAction.answer; + this.nextStep = originAction.nextStep; + this.featureMap = originAction.featureMap; + this.updateKnowledge = originAction.updateKnowledge; + this.indexName = originAction.indexName; + this.id = originAction.id; + this.configName = originAction.configName; + this.status = originAction.status; + this.priority = originAction.priority + basePriority + 1; //如果激活的配置没有条件 + + + this.auxiliaryPriority = originAction.auxiliaryPriority + baseAuxiliaryPriority; //优先级为两者之和 +// //如果激活originAction的action,它的辅助优先级高于originAction,那么。。 +// if(baseAuxiliaryPriority > originAction.auxiliaryPriority) +// this.auxiliaryPriority = baseAuxiliaryPriority; +// else +// this.auxiliaryPriority = originAction.auxiliaryPriority; +// +// this.auxiliaryPriority = this.getAuxiliaryPriority() + 1; + } + + public Action() { + } + + public int getPriority() { + return priority; + } + + public int getAuxiliaryPriority() { + return auxiliaryPriority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + public void setAuxiliaryPriority(int auxiliaryPriority) { + this.auxiliaryPriority = auxiliaryPriority; + } + + public HashSet getKeywordSet() { + return keywordSet; + } + + public HashMap> getHistoryPremise() { + return historyPremise; + } + + public HashMap> getCurrentPremise() { + return currentPremise; + } + + public HashMap getUpdateKnowledge() { + return updateKnowledge; + } + + public String[] getAnswer() { + return answer; + } + + public String getNextStep() { + return nextStep; + } + + public HashMap getFeatureMap() { + return featureMap; + } + + public String getIndexName() { + return indexName; + } + + public int getId() { + return id; + } + + public String getConfigName() { + return configName; + } + + public String getStatus() { + return status; + } + + public void setKeywordSet(HashSet keywordSet) { + this.keywordSet = keywordSet; + } + + public void setHistoryPremise(HashMap> historyPremise) { + this.historyPremise = historyPremise; + } + + public void setCurrentPremise(HashMap> currentPremise) { + this.currentPremise = currentPremise; + } + + public void setUpdateKnowledge(HashMap updateKnowledge) { + this.updateKnowledge = updateKnowledge; + } + + public void setAnswer(String[] answer) { + this.answer = answer; + } + + public void setNextStep(String nextStep) { + this.nextStep = nextStep; + } + + public void setFeatureMap(HashMap featureMap) { + this.featureMap = featureMap; + } + + public void setIndexName(String indexName) { + this.indexName = indexName; + } + + public void setId(int id) { + this.id = id; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + public void setStatus(String status) { + this.status = status; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java b/src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java new file mode 100644 index 0000000..068a3e9 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/ArchiveInfo.java @@ -0,0 +1,57 @@ +package com.qiwu.chatbotbackend.entity; + +public class ArchiveInfo { + String archiveId; + String userKey; + String site; + String updateTime; + String plot; + + public String getArchiveId() { + return archiveId; + } + + public void setArchiveId(String archiveId) { + this.archiveId = archiveId; + } + + public String getUserKey() { + return userKey; + } + + public void setUserKey(String userKey) { + this.userKey = userKey; + } + + public String getSite() { + return site; + } + + public void setSite(String site) { + this.site = site; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getPlot() { + return plot; + } + + public void setPlot(String plot) { + this.plot = plot; + } + + public ArchiveInfo(String archiveId, String userKey, String site, String updateTime, String plot) { + this.archiveId = archiveId; + this.userKey = userKey; + this.site = site; + this.updateTime = updateTime; + this.plot = plot; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java b/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java new file mode 100644 index 0000000..0bb4e75 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/ChatCache.java @@ -0,0 +1,127 @@ +package com.qiwu.chatbotbackend.entity; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import org.springframework.beans.factory.DisposableBean; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class ChatCache implements DisposableBean { + + + public String ENV_ERROR = "游戏平台初始化失败"; +// private String chatKey = "不知道"; + private String userKey = ""; + private String randKey = ""; + private String botAccount = ""; + + private Map infoPoint = null; + private GameEnv gameEnv = null; + private Boolean gameStart = false; + private Boolean reload = false; + + + public String getBotAccount() { + return botAccount; + } + + public void setBotAccount(String botAccount) { + this.botAccount = botAccount; + } + + + public String getUserKey() { + return userKey; + } + + public void setUserKey(String userKey) { + this.userKey = userKey; + } + + public String getRandKey() { + return randKey; + } + + public void setRandKey(String randKey) { + this.randKey = randKey; + } + + public Map getInfoPoint() { + return infoPoint; + } + + public void setInfoPoint(Map infoPoint) { + this.infoPoint = infoPoint; + } + + public boolean isGameStart() { + return gameStart; + } + + public void setGameStart(boolean gameStart) { + this.gameStart = gameStart; + } + + public Boolean getReload() { + return reload; + } + + public void setReload(Boolean reload) { + this.reload = reload; + } + + public GameEnv getGameEnv() { + return gameEnv; + } + + public void setGameEnv(GameEnv gameEnv) { + this.gameEnv = gameEnv; + } + + public ChatCache(String userKey, String randKey, GameEnv gameEnv, Map infoPoint) { + this.userKey = userKey; + this.randKey = randKey; + this.gameEnv = gameEnv; + this.infoPoint = infoPoint; + } + + + @Override + public void destroy() throws IOException { + } + + public ChatCache(UserInfo userInfo, String userKey, String randKey, String botType) throws Exception { + + if(botType.equals("game")) { + try { + this.gameEnv = new GameEnv(userInfo.botAccount); + System.out.println("初始化时:" + this.gameEnv); + } catch (Exception e) { + System.out.println(ENV_ERROR); + + this.infoPoint.put("error_message", ENV_ERROR); + e.printStackTrace(); + } + } + + String k; + this.botAccount = userInfo.botAccount; + this.infoPoint = new HashMap(); + Iterator iit = userInfo.varInitialMap.keySet().iterator(); + while (iit.hasNext()) { + k = iit.next(); + this.infoPoint.put(k, userInfo.varInitialMap.get(k)); + } + this.infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + this.randKey = randKey; + this.userKey = userKey; + + } + + public ChatCache(String userKey, String randKey) { + this.userKey = userKey; + this.randKey = randKey; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java b/src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java new file mode 100644 index 0000000..6abebde --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/ConfigTermText.java @@ -0,0 +1,467 @@ +package com.qiwu.chatbotbackend.entity; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class ConfigTermText implements Cloneable{ + + public static ThreadLocal iterNum=new ThreadLocal() { + protected Integer initialValue() { + return 0; + } + }; + + private int id = 0; + + private String curPremise = ""; + private String hisPremise = ""; + private String feature = ""; + private String reply = ""; + private String nextStep = ""; + private String updateKnowledge = ""; + private String nextStepStatus = "return"; + private String configName = ""; + private String auxiliaryPriority = "1"; + private String status = "waiting"; + + static HashMap StatusMap = new HashMap(){ + { + put("waiting", 0); + put("sleeping", 1); + } + }; + + + public String getFeature() { + return feature; + } + + public void setFeature(String feature) { + this.feature = feature; + } + + public String getCurPremise() { + return curPremise; + } + + public String getNextStep() { + return nextStep; + } + + public void setNextStep(String nextStep) { + this.nextStep = nextStep; + } + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName, Boolean append) { + + if(append) { + + iterNum.set(iterNum.get() + 1); + + this.configName = configName + "_" + iterNum.get(); + }else{ + this.configName = configName; + } + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + + public void setCurPremise(String curPremise) { + this.curPremise = curPremise; + } + + public String getHisPremise() { + return hisPremise; + } + + public void setHisPremise(String hisPremise) { + this.hisPremise = hisPremise; + } + + public String getReply() { + return reply; + } + + public void setReply(String reply) { + this.reply = reply; + } + + public String getAuxiliaryPriority() { + return auxiliaryPriority; + } + + public String getStatus() { + return status; + } + + public String getNextStepStatus() { + return nextStepStatus; + } + + public String getUpdateKnowledge() { + return updateKnowledge; + } + + public void setUpdateKnowledge(String updateKnowledge) { + this.updateKnowledge = updateKnowledge; + } + + + static Map statusMap = new HashMap() { + { + put("return", "return"); + put("return-1", "back"); + put("return-0", "stay"); + put("activate", "activate"); + put("activate:after", "activate:after"); + } + }; + + public void setStatus(String status) { + this.status = status; + } + public void setAuxiliaryPriority(String auxiliaryPriority) { + this.auxiliaryPriority = auxiliaryPriority; + } + + public void setNextStepStatus(String nextStepStatus) { + this.nextStepStatus = nextStepStatus; + } + + public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { + this.curPremise = curPremise; + this.hisPremise = hisPremise; + this.feature = feature; + if (!updateKnowledge.equals("")) + this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; + + this.reply = reply; + this.nextStep = nextStep; + } + + public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { + this.curPremise = curPremise; + this.hisPremise = hisPremise; + this.feature = feature; + this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); + //if (!updateKnowledge.equals("")) + // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; + + this.reply = reply; + this.nextStep = nextStep; + } + + + public ConfigTermText(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { + this.curPremise = appendPremiseStr(curPremise, extraCP); + this.hisPremise = appendPremiseStr(hisPremise, extraHP); + this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); + this.feature = feature; + this.reply = reply; + this.nextStep = nextStep; + this.auxiliaryPriority = auxiliaryPriority; + } + + public String appendPremiseStr(List premises, String extraPremise) { + StringBuffer sb = new StringBuffer(); + String premiseStr = "", conditionName; + Map nameCount = new HashMap(); + + for (Premise premise : premises){ + //设置初始值 + //System.out.println("nameCount" + nameCount); + conditionName = premise.getConditionName(); + + nameCount.putIfAbsent(conditionName, 0); + + //nameCount加一 + nameCount.put(conditionName, nameCount.get(conditionName) + 1); + + //在conditionName后添加count + if(nameCount.get(conditionName) > 1) { + premise.setConditionName(conditionName + nameCount.get(conditionName)); + } + + + + sb.append(","); + sb.append(premise.getConditionName()); + sb.append("::"); + sb.append(premise.getCmpType()); + sb.append("-"); + sb.append(premise.getOperator()); + sb.append("="); + sb.append(premise.getKeyword()); + } + if (sb.length() > 0) + sb.deleteCharAt(0); //删除第一个逗号 + + + if (!extraPremise.equals("")) { + if (sb.length() == 0) + sb.append(extraPremise); + else + sb.append("," + extraPremise); + } else if (sb.length() == 0) { + sb.append(" "); + } + premiseStr = sb.toString(); + + return premiseStr; + } + + public String appendKnowledgeStr(Map knowledge, String extraKL) { + StringBuffer sb = new StringBuffer(); + String varName = "", varValue = "", knowledgeStr; + Iterator iit = knowledge.keySet().iterator(); + Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 + String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; + + while (iit.hasNext()) { + varName = iit.next(); + varValue = knowledge.get(varName); + + if(varValue.startsWith("updateFollowerLocation")){ + delayUpdateFollowerLocation = true; + delayUpdateFollowerLocationKey = varName; + delayUpdateFollowerLocationValue = varValue; + continue; + } + sb.append("-<-").append(varName).append(":").append(varValue); + + } + if (!extraKL.equals("")) { + sb.append("-<-" + extraKL); + } + + if(delayUpdateFollowerLocation){ + sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); + } + + if (sb.length() > 0) + knowledgeStr = "updateKnowledge" + sb.toString(); + else + knowledgeStr = ""; + + return knowledgeStr; + } + + + public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { + //System.out.println(premise); + + String pair1[] = premise.split("=", 2); + String key = pair1[0]; + + String keywords = pair1[1]; + String pair2[] = key.split("::"); + String conditionName = pair2[0]; + String pair3[] = pair2[1].split("-"); + String cmpType = pair3[0]; + String operator = ""; + if (pair3.length > 1) + operator = pair3[1]; + + String question = ""; + if (conditionDescription.get(conditionName) != null) + question = conditionDescription.get(conditionName); + + JSONObject premiseJ = new JSONObject(); + premiseJ.put("keywords", keywords); + premiseJ.put("actionName", conditionName); + premiseJ.put("cmpType", cmpType); + premiseJ.put("question", question); + premiseJ.put("operator", operator); + + premiseList.add(premiseJ); + + } + + public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { + String pair[] = knowledge.split(":", 2); + + if (knowledge.equals("") || pair.length < 2) + return; + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + JSONObject knowledgeJ = new JSONObject(); + knowledgeJ.put("variableName", pair[0]); + knowledgeJ.put("keyword", pair[1]); + + knowledgeList.add(knowledgeJ); + } + + public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { + String pair[] = next.split("-"); + JSONObject nextStepJ = new JSONObject(); + JSONArray exceptJ = new JSONArray(); + + for (int i = 1; i < pair.length; i++) + exceptJ.add(pair[i]); + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + nextStepJ.put("nextStep", pair[0]); + nextStepJ.put("except", exceptJ); + nextStepJ.put("nextStepText", question); + nextStepList.add(nextStepJ); + } + + public JSONObject toJson(Map conditionDescription) { + JSONObject data = new JSONObject(); + JSONArray curPremiseList = new JSONArray(); + JSONArray hisPremiseList = new JSONArray(); + + //添加当前对话内容 + for (String premise : curPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(curPremiseList, premise, conditionDescription); + } + data.put("currentPremiseList", curPremiseList); + + //添加已知信息的内容 + for (String premise : hisPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(hisPremiseList, premise, conditionDescription); + } + data.put("historyPremiseList", hisPremiseList); + + //添加下一步状态 + + + //添加configName + data.put("configName", configName); + + //添加config状态 + data.put("configStatus", statusMap.get(status)); + + + boolean doPost = false; + String postURL = "", postType = "all", pair[]; + + for (String feat : feature.split(",")) { + if (feat.startsWith("post")) { + doPost = true; + pair = feat.substring(0, feat.length() - 1).split("\\(", 2); + postURL = pair[1]; + postType = pair[0].split("::")[1]; + }else if(feat.equals("return-0")){ + nextStepStatus = "return-0"; + }else if(feat.equals("activate")){ + nextStepStatus = "activate"; + }else if(feat.equals("activate:after")){ + nextStepStatus = "activate:after"; + } + } + + + data.put("nextStepStatus", statusMap.get(nextStepStatus)); + //添加post参数 + data.put("doPost", doPost); + data.put("postURL", postURL); + data.put("postType", postType); + + //添加回答 + data.put("reply", reply); + + //添加config类别id + data.put("categoryId", 0); + + //添加辅助优先级 + data.put("auxiliaryPriority", auxiliaryPriority); + + //添加更新答案处的信息 + JSONArray knowledgeList = new JSONArray(); + if (!updateKnowledge.equals("")) { + for (String knowledge : updateKnowledge.split("-<-")) { + appendJKnowledge(knowledgeList, knowledge, conditionDescription); + } + } + data.put("updateKnowledge", knowledgeList); + + //添加下一步 + JSONArray nextStepList = new JSONArray(); + for (String next : nextStep.split(",")) { + appendJNextStep(nextStepList, next, conditionDescription); + } + data.put("nextStepList", nextStepList); + + return data; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append(curPremise).append("|"); + sb.append(hisPremise); + sb.append("|").append(feature).append(","); + sb.append(updateKnowledge).append(","); + sb.append(nextStepStatus).append( "|"); + sb.append("auxiliaryPriority="); + sb.append(auxiliaryPriority).append("|").append("configName="); + sb.append(configName); + sb.append("|=>|").append(reply); + sb.append("|").append("nextStep="); + sb.append(nextStep).append("|"); + sb.append("status=").append(status); + sb.append("|").append("configId="); + + return sb.toString(); + } + + public Object clone() { + Object o=null; + try{ + o= super.clone(); + }catch(CloneNotSupportedException e){ + System.out.println(e.toString()); + } + return o; + } + + + public static void activateCopy(ConfigTermText configTermText, List configTermTextList, String name){ + + configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}"); + + + ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone(); + + if(configTermText2.getUpdateKnowledge().equals("")) + configTermText2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); + else + configTermText2.setUpdateKnowledge(configTermText2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); + configTermText2.setConfigName(name, true); + + configTermTextList.add(configTermText2); + + } + + + public ConfigTermText simpleCopy(ConfigTermText configTermText){ + + ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone(); + + return configTermText2; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java b/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java new file mode 100644 index 0000000..4f334de --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Macro.java @@ -0,0 +1,53 @@ +package com.qiwu.chatbotbackend.entity; + +public class Macro { + int botId; + int macroId; + String name; + String value; + + public Macro(int botId, int macroId, String name, String value) { + this.botId = botId; + this.macroId = macroId; + this.name = name; + this.value = value; + } + + public Macro(int botId, String name, String value) { + this.botId = botId; + this.name = name; + this.value = value; + } + + public int getBotId() { + return botId; + } + + public void setBotId(int botId) { + this.botId = botId; + } + + public int getMacroId() { + return macroId; + } + + public void setMacroId(int macroId) { + this.macroId = macroId; + } + + 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; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Premise.java b/src/main/java/com/qiwu/chatbotbackend/entity/Premise.java new file mode 100644 index 0000000..864c854 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Premise.java @@ -0,0 +1,63 @@ +package com.qiwu.chatbotbackend.entity; + +public class Premise { + private String conditionName = ""; + private String cmpType = ""; + private String operator = ""; + private String keyword = ""; + + public Premise(String conditionName, String cmpType, String operator, String keyword) { + + this.conditionName = conditionName; + this.cmpType = cmpType; + this.operator = operator; + this.keyword = keyword; + + if(cmpType == null){ + this.cmpType = "match"; + }else{ + this.cmpType = cmpType; + } + + if(operator == null){ + this.operator = "Include"; + }else{ + this.operator = operator; + } + if(cmpType.equals("any")){ + this.operator = "Include"; + } + } + + public String getConditionName() { + return conditionName; + } + + public void setConditionName(String conditionName) { + this.conditionName = conditionName; + } + + public String getCmpType() { + return cmpType; + } + + public void setCmpType(String cmpType) { + this.cmpType = cmpType; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getKeyword() { + return keyword; + } + + public void setKeyword(String keyword) { + this.keyword = keyword; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java b/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java new file mode 100644 index 0000000..3435ea3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/Solution.java @@ -0,0 +1,45 @@ +package com.qiwu.chatbotbackend.entity; + + +/** + * 包含后台返回数据的实体类。 + */ +public class Solution { + private int status = 0; + private String answer; + private String next; + + public String getAnswer() { + return answer; + } + + public int getStatus() { + return status; + } + + + public void setAnswer(String answer) { + this.answer = answer; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + public Solution(int status, String answers, String next) { + this.answer = answers; + this.next = next; + this.status = status; + } + + public Solution() { + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java b/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java new file mode 100644 index 0000000..cfe6ada --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/entity/UserInfo.java @@ -0,0 +1,36 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.List; + +/** + * 本地读取的用户配置文件(整个)和提交的用户配置文件的信息经过解析后保存在这里 + */ +public class UserInfo { + public UserInfo(String botAccount) { + this.conditionTable = new HashMap>(); + this.configStr = ""; + this.botAccount = botAccount; + this.extraInfo = new HashMap() { + { + put("activeAction", " "); + } + }; + this.id2config = new HashMap(); + this.id2condition = new HashMap(); + this.varInitialMap = new HashMap(); + this.name2condition = new HashMap(); + } + + public HashMap> conditionTable; + public String configStr; + public String botAccount; + public HashMap extraInfo; + public HashMap id2config; + public HashMap id2condition; + public HashMap name2condition; + //存储需要初始化的变量 + public HashMap varInitialMap; + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java new file mode 100644 index 0000000..178b608 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/CharacterConstructor.java @@ -0,0 +1,170 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class CharacterConstructor extends ElementConstructor { + + public CharacterConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { + String category, name, className, description, attrValue,botName = (String)gameElements.get("botName"); + + try { + + //FIND_NPC_LOCATION + String pattern; + StringBuffer onlineModeTalkers = new StringBuffer(","); + + + JSONArray allNPC = gameElements.getJSONArray("npc"); + Map attribute = null; + HashSet classSet = new HashSet(); + List replaceList = new ArrayList(); + + + + copyPattern("HOW_FIND_NPC"); + copyPattern("NPC_LOCATION"); + copyPattern("AOURND_NPC_CLASS"); + copyPattern("NPC_ATTR"); + copyPattern("WHO_YOU_ARE"); + + + + + + for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { + replaceList.clear(); + + + name = character.getString("name"); + + replaceList.add(new String[]{"name", name}); + + + + //找到所有处于离线模式的npc + if(character.getBoolean("offline")!= null && !character.getBoolean("offline")){ + onlineModeTalkers.append(name).append(","); + } + List nameList = new ArrayList(); + nameList.add(name); + + //添加词性 + className = (String) character.get("class"); + appendPOS(POS, name, "人名"); + appendPOS(POS, className, "人名"); + + + appendReplacedKeyword("NPC_LOCATION", replaceList); + appendReplacedKeyword("HOW_FIND_NPC", replaceList); + + //添加别名 + if(character.containsKey("nickname")){ + for(String nickname:JSONArray.parseArray(character.getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + appendPOS(POS, nickname, "人名"); + nameList.add(nickname); + + replaceList.get(0)[1] = nickname; + appendReplacedKeyword("NPC_LOCATION", replaceList); + appendReplacedKeyword("HOW_FIND_NPC", replaceList); + } + } + } + + + + //添加类名称 + if (!classSet.contains(className)) { + classSet.add(className); + //替换后的名字改为类名 + replaceList.get(0)[1] = className; + appendReplacedKeyword("AOURND_NPC_CLASS", replaceList); + + } + + + attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); + + //替换后的名字改为npc名 + replaceList.get(0)[1] = name; + replaceList.add(new String[]{"attrName", ""}); + + for(String attrName:attribute.keySet()){ + + replaceList.get(1)[1] = attrName; + + appendPOS(POS, attrName, "名词"); + + for(String NPCName:nameList) { + appendReplacedKeyword("NPC_ATTR", replaceList); + } + + } + + } + + replaceList.add(new String[]{"botName", botName}); + appendReplacedKeyword("WHO_YOU_ARE", replaceList); + + + keywordMap.put("onlineModeTalkers", onlineModeTalkers); + varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); + conditionDescription.put("onlineModeTalkers", "所有在线npc"); + + + + //同时识别zainali和wenzainali + configTermText = new ConfigTermText( + "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," + + "wenzainali::match-Keyword=" + keywordMap.get("NPC_LOCATION_wenzainali").toString(), " ", + "match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:wenzainali" + ); + ConfigTermText.activateCopy(configTermText, configTermTextList, "npc"); + + //根据根据NPC的名字查询地点 + queryTypeConfigTermGenerate(keywordMap, "NPC_LOCATION", "npc", "queryLocationByConditionName"); + + //根据根据NPC名字和属性查询属性值 + queryTypeConfigTermGenerate(keywordMap, "NPC_ATTR", "npc", "queryAttrByNPCName"); + + //根据根据NPC类别和地点属性查询所有NPC实例 + + queryTypeConfigTermGenerate(keywordMap, "AOURND_NPC_CLASS", "npc", "queryAroundNpcByClassName"); + + + //根据类名查询周围所有实例 + + queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_NPC", "npc", "queryFindNPCWay"); + + //查询说话的人 + //WHO_YOU_ARE + queryTypeConfigTermGenerate(keywordMap, "WHO_YOU_ARE", "npc", "queryLastTalker"); + + }catch (Exception e){ + operationStatus = 0; + message = "NPC接口处理出现异常"; + e.printStackTrace(); + return; + } + + + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java new file mode 100644 index 0000000..753f4b3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ElementConstructor.java @@ -0,0 +1,259 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class ElementConstructor { + + + int botId = 0; + + + + int operationStatus = 1; + Map keywordMap = null; + SqlHelper helper = null; + HashSet exceptRelation = null; + ConfigTermText configTermText = null; + String botAccount; + + + + String message = ""; + + + List configDataList = new ArrayList(); + List configTermTextList = new ArrayList(); + StringBuffer configText = new StringBuffer(); + Map varInitialMap = new HashMap(); + Map conditionDescription = new HashMap(); + StringBuffer POS = new StringBuffer(); + + + public String getMessage() { return message; } + + public int getOperationStatus() { return operationStatus; } + + public Map getVarInitialMap() { + return varInitialMap; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { } + + public List getConfigTermTextList() { + return configTermTextList; + } + + public Map getConditionDescription() { + return conditionDescription; + } + + public List getConfigDataList() { + return configDataList; + } + + public void ElementConstructor(String userName) { + this.botAccount = botAccount; + } + + public String getConfigText() { + return configText.toString(); + } + + //生成完整的后台配置文件 + public void generateConfigText(List idList) { + int id, length = idList.size(); + String varValue; + ConfigTermText configTermText = null; + for (int i = 0; i < length; i++) { + configTermText = configTermTextList.get(i); + id = idList.get(i); + + configText.append(configTermText.toString() + id + "\n"); + } + + //变量 + for (String varName : varInitialMap.keySet()) { + varValue = varInitialMap.get(varName); + configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); + } + + } + + + /** + * 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition + * @param config + * @param relationKeywords + * @param exceptRelation + * @param botName + */ + public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation, String botName){ + String conditionName, pair[]; + for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ + conditionName = (String) premise.get("actionName"); + + + + if(!exceptRelation.contains(conditionName)) { + + //初始化 + if(!relationKeywords.containsKey(conditionName + "_head")) { + relationKeywords.put(conditionName + "_head", new HashSet()); + relationKeywords.put(conditionName + "_tail", new HashSet()); + } + + //visitorname和bot的替换 + premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); + + for (String keyword : ((String) premise.get("keywords")).split("\\+")) { + + if(keyword.equals("")){ + continue; + + + } else if(keyword.contains(":")){ + //有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域 + pair = keyword.split(":",2); + + if(pair[1].equals("")) + continue; + + + relationKeywords.get(conditionName + "_head").add(pair[0]); + relationKeywords.get(conditionName + "_tail").add(pair[1]); + + } else { + relationKeywords.get(conditionName + "_tail").add(keyword); + } + + } + } + + } + for(Map premise:JSONArray.parseArray(config.getJSONArray("historyPremiseList").toJSONString(), Map.class)){ + conditionName = (String) premise.get("actionName"); + + if(conditionName.startsWith("npc_") || conditionName.startsWith("goods_")) + continue; + + + + if(!exceptRelation.contains(conditionName)) { + + + if(!relationKeywords.containsKey(conditionName + "_head")) { + relationKeywords.put(conditionName + "_head", new HashSet()); + relationKeywords.put(conditionName + "_tail", new HashSet()); + } + + premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); + + for (String keyword : ((String) premise.get("keywords")).split("\\+")) { + + if(keyword.equals("")){ + continue; + + + } else if(keyword.contains(":")){ + pair = keyword.split(":",2); + + if(pair[1].equals("")) + continue; + + + relationKeywords.get(conditionName + "_head").add(pair[0]); + relationKeywords.get(conditionName + "_tail").add(pair[1]); + + } else { + relationKeywords.get(conditionName + "_tail").add(keyword); + } + } + } + } + } + + + /** + * 根据插入的数据做后处理 + * @param idList + */ + public void postProcessing(List idList, int categoryId){} + + /** + * 构造参数配置文件的json版 + */ + public void buildJconfig() { + + } + + + public void appendPOS(StringBuffer POS, String name, String tag){ + if(!name.equals("")) { + POS.append("="); + POS.append(name); + POS.append("|"); + POS.append(tag); + POS.append("\n"); + } + } + + + public void queryTypeConfigTermGenerate(Map keywordMap, String intent, String module, String queryMethod){ + + String conditionKeywords = ""; + String conditionNameList[] = keywordMap.get(intent).toString().split(","); + for (String conditionName : conditionNameList) { + conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString(); + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", + "", + " ", + module + "_query:" + queryMethod + ":" + conditionName + ); + //ConfigTermText.activateCopy(configTermText, configTermTextList, module); + + + //查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面 + configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}"); + + + configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); + configTermText.setConfigName(module, true); + + configTermTextList.add(configTermText); + } + } + + /** + * 将condition的关键词复制一份,然后清空原来关键词 + * @param intent + */ + public void copyPattern(String intent){ + for(String conditionName:keywordMap.get(intent).toString().split(",")){ + keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName))); + keywordMap.get(intent + "_" + conditionName).setLength(0); + } + } + + + public void appendReplacedKeyword(String intent, List replaceList){ + String pattern, replaceText; + for(String conditionName:keywordMap.get(intent).toString().split(",")){ + pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString(); + for(String[] replacePair: replaceList){ + pattern = pattern.replace(replacePair[0], replacePair[1]); + } + keywordMap.get(intent + "_" + conditionName).append(pattern); + } + + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java new file mode 100644 index 0000000..b28d28d --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/Floyd.java @@ -0,0 +1,106 @@ +package com.qiwu.chatbotbackend.gameDesign; + +/** + * 弗洛伊德算法,用于构造地图时求最短路径 + */ +public class Floyd { + + + /** + * 表示正无穷 + */ + int MAX_WEIGHT = Integer.MAX_VALUE; + /** + * 路径矩阵 + */ + int[][] pathMatirx; + /** + * 前驱表 + */ + int[][] preTable; + + + public void findShortestPath(int[][] matrix, int length) { + //路径矩阵(D),表示顶点到顶点的最短路径权值之和的矩阵,初始时,就是图的邻接矩阵。 + pathMatirx = new int[length][length]; + //前驱表(P),P[m][n] 的值为 m到n的最短路径的前驱顶点,如果是直连,值为n。也就是初始值 + preTable = new int[length][length]; + + /* + System.out.println("matrix"); + for (int i = 0; i < length; i++){ + for(int j = 0; j < length; j++){ + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + */ + + //初始化D,P + for (int i = 0; i < length; i++) { + for (int j = 0; j < length; j++) { + pathMatirx[i][j] = matrix[i][j]; + preTable[i][j] = j; + } + } + + //循环 中间经过顶点 + for (int k = 0; k < length; k++) { + //循环所有路径 + for (int m = 0; m < length; m++) { + + for (int n = 0; n < length; n++) { + + int mn = pathMatirx[m][n]; + int mk = pathMatirx[m][k]; + int kn = pathMatirx[k][n]; + int addedPath = (mk == MAX_WEIGHT || kn == MAX_WEIGHT) ? MAX_WEIGHT : mk + kn; + + if (mn > addedPath) { + //如果经过k顶点路径比原两点路径更短,将两点间权值设为更小的一个 + pathMatirx[m][n] = addedPath; + //前驱设置为经过下标为k的顶点 + preTable[m][n] = preTable[m][k]; + } + + } + } + } + + /* + System.out.println("pathMatrix"); + for (int i = 0; i < length; i++){ + for(int j = 0; j < length; j++){ + System.out.print(pathMatirx[i][j] + " "); + } + System.out.println(); + } + */ + } + + /** + * 打印 所有最短路径 + */ + public void printPath(int[][] matrix, int length) { + + + for (int m = 0; m < length; m++) { + for (int n = m + 1; n < length; n++) { + + int k = preTable[m][n]; + System.out.print("(" + m + "," + n + ")" + pathMatirx[m][n] + ": "); + System.out.print(m); + while (k != n) { + System.out.print("->" + k); + k = preTable[k][n]; + } + + System.out.println("->" + n); + } + System.out.println(); + } + + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java new file mode 100644 index 0000000..07a793a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/GlobalVariableConstructor.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.CC_URL; + +public class GlobalVariableConstructor extends ElementConstructor { + + public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + public void construct(JSONObject gameElements, UserInfo userinfo) { + + try { + String category, name, description, attrValue; + JSONObject globalVariable = gameElements.getJSONObject("globalVariable"); + Map attribute = null; + Iterator attrIter = null; + + + + + for(String attrName:globalVariable.keySet()) { + attrValue = (String)globalVariable.get(attrName); + varInitialMap.put("globalVariable_" + attrName, attrValue); + } + + + varInitialMap.put("botType", "game"); + varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); + varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); + varInitialMap.put("CC_URL", CC_URL); + + + JSONObject script = gameElements.getJSONObject("speechcraft"); + for(String key:script.keySet()){ + attrValue = (String)script.get(key); + varInitialMap.put(key, attrValue); + } + }catch (Exception e){ + operationStatus = 0; + message = "全局变量处理出现异常"; + e.printStackTrace(); + return; + } + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java new file mode 100644 index 0000000..b5a01ba --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ItemConstructor.java @@ -0,0 +1,131 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +public class ItemConstructor extends ElementConstructor { + + + + public ItemConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + + public void construct(JSONObject gameElements, UserInfo userinfo) { + try { + + String pattern; + String category, name, className, description, attrValue; + JSONArray goods = gameElements.getJSONArray("goods"); + Map attribute = null; + Iterator attrIter = null; + HashSet classSet = new HashSet(); + + + copyPattern("HOW_FIND_ITEM"); + copyPattern("ITEM_LOCATION"); + copyPattern("AROUND_ITEM_CLASS"); + copyPattern("ITEM_ATTR"); + + List replaceList = new ArrayList(); + + for (JSONObject good : goods.toJavaList(JSONObject.class)) { + name = (String) good.get("name"); + + replaceList.clear(); + replaceList.add(new String[]{"name", name}); + + List nameList = new ArrayList(); + nameList.add(name); + + //添加词性 + className = (String) good.get("class"); + appendPOS(POS, name, "名词"); + appendPOS(POS, className, "名词"); + + appendReplacedKeyword("ITEM_LOCATION", replaceList); + appendReplacedKeyword("HOW_FIND_ITEM", replaceList); + + if(good.containsKey("nickname")){ + for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + appendPOS(POS, nickname, "名词"); + nameList.add(nickname); + replaceList.get(0)[1] = nickname; + appendReplacedKeyword("ITEM_LOCATION", replaceList); + appendReplacedKeyword("HOW_FIND_ITEM", replaceList); + } + } + } + + //添加类名称 + if (!classSet.contains(className)) { + classSet.add(className); + replaceList.get(0)[1] = className; + appendReplacedKeyword("AROUND_ITEM_CLASS", replaceList); + } + + + attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); + + replaceList.get(0)[1] = name; + replaceList.add(new String[]{"attrName", ""}); + for(String attrName: attribute.keySet()){ + replaceList.get(1)[1] = attrName; + + appendPOS(POS, attrName, "名词"); + + +// for(String itemName:nameList) { +// for(String conditionName:keywordMap.get("ITEM_ATTR").toString().split(",")){ +// //pattern = keywordMap.get("NPC_ATTR_" + conditionName + "_pattern").toString(); +// keywordMap.get("ITEM_ATTR_" + conditionName).append("+").append(itemName).append(":").append(attrName); +// } +// } + appendReplacedKeyword("ITEM_ATTR", replaceList); + + } + } + + + configTermText = new ConfigTermText( + "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," + + "wenzainali::match-Keyword=" + keywordMap.get("ITEM_LOCATION_wenzainali").toString(), " ", + "match,return-0", "", "yaobuyao", "goods_query:queryLocationByConditionName:wenzainali" + ); + ConfigTermText.activateCopy(configTermText, configTermTextList, "item"); + + + queryTypeConfigTermGenerate(keywordMap, "ITEM_LOCATION", "goods", "queryLocationByConditionName"); + + //根据根据物品名字和属性查询属性值 + queryTypeConfigTermGenerate(keywordMap, "ITEM_ATTR", "goods", "queryAttrByGoodsName"); + + //根据类名查询周围所有实例 + queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM_CLASS", "goods", "queryAroundGoodsByClassName"); + //根据类名查询周围所有实例 + queryTypeConfigTermGenerate(keywordMap, "WHAT_ITEM_I_HAVE", "goods", "queryPlayerItems"); + + queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_ITEM", "goods", "queryFindItemWay"); + + } catch(Exception e){ + operationStatus = 0; + message = "物品处理出现异常"; + e.printStackTrace(); + return; + } + + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java new file mode 100644 index 0000000..99cba08 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/ListeningConstructor.java @@ -0,0 +1,124 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.Premise; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class ListeningConstructor extends ElementConstructor{ + + public ListeningConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + public void construct(JSONObject jsonObject, UserInfo userinfo) { + + + + + } + + public static void cc(String botAccount, JSONObject gameELments, HashMap plotIndex, List configTermTextList){ + int size = 0; + String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; + String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; + Boolean autoJump = false; + List curPremiseList = new ArrayList(); + List hisPremiseList = new ArrayList(); + JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); + JSONObject plotNode = null; + + if(listeningActions == null) + return; + + size = listeningActions.size(); + JSONObject config = null; + + for(int i = 0; i < size;i++){ + plotNode = null; + autoJump = false; + priority = "2"; + feature = "match"; + config = listeningActions.getJSONObject(i); + curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), Premise.class); + hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), Premise.class); + Map updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); + nextPlotId = config.getString("nextPlotId"); + + if(nextPlotId != null){ + plotNode = plotIndex.get(nextPlotId); + } + + + if(plotNode != null){ + reply = plotNode.getString("plotText"); + nextCondition = plotNode.getString("conditionName"); + nextLocation = plotNode.getString("place"); + autoJump = plotNode.getBoolean("autoJump"); + + + if(nextCondition == null || nextCondition.equals("")){ + nextCondition = DEFAULT_CONDITION; + } + + if(autoJump){ + feature = "match,activate:after"; + updateKnowledge.put("plot_jump_text", "str+" + reply); + nextCondition = "plot_" + nextPlotId; + reply = ""; + }else{ + feature = "match"; + + } + + if(config.getString("priority") != null) + priority = config.getString("priority"); + + updateKnowledge.put(nextLocation + "_activate_by", ""); + updateKnowledge.put(nextLocation + "_activate_ready", "0"); + updateKnowledge.put("site", nextLocation); + + + nTaskLineName = String.format(TASK_LINE, nextLocation); + //任务线最后一个condition + lastTaskCondition = String.format(TASK_CONDITION, nextLocation); + lastTaskReply = String.format(TASK_REPLY, nextLocation); + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextPlotId); + + + + updateKnowledge.put(lastTaskCondition, nextCondition); + updateKnowledge.put(lastTaskReply, reply); + updateKnowledge.put(nextPlotId, "1"); //下一步设为1 + updateKnowledge.put(nTaskLineName, nextGameStep); + updateKnowledge.put("game_step", nextGameStep); + }else{ + feature = "match,return-0"; + } + + ConfigTermText configTermText = new ConfigTermText( + curPremiseList, + hisPremiseList, + updateKnowledge, + "", "", "", feature, reply, nextCondition, priority + ); + + System.out.println("生成:" + curPremiseList.get(0)); + configTermTextList.add(configTermText); + } + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java new file mode 100644 index 0000000..b610e65 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/MapConstructor.java @@ -0,0 +1,382 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.TASK_CONDITION; +import static com.qiwu.chatbotbackend.Config.Config.TASK_LINE; +import static com.qiwu.chatbotbackend.Config.Config.TASK_REPLY; + +public class MapConstructor extends ElementConstructor { + + int[][] matrix; + int locationNum; + HashMap id2j = new HashMap(); + Map question2keyword = new HashMap(); + Map> name2nickname = new HashMap>(); + JSONArray locations = null; + + Map script = null; //话术模板 + + + + public MapConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + + public void constructGreph(JSONArray locations) { + + JSONObject jobj = null; + int locationId, index; + String locationName, taskLineName = ""; + + locationNum = locations.size(); + StringBuffer nameSet = null; + keywordMap.putIfAbsent("site_list", new StringBuffer()); + + for (int i = 0; i < locationNum; i++) { + jobj = locations.getJSONObject(i); + jobj.put("index", i); + locationName = (String) jobj.get("name"); + keywordMap.get("site_list").append("+").append(locationName); + + + taskLineName = String.format(TASK_LINE, locationName); + + + if (!varInitialMap.containsKey(taskLineName)) { + conditionDescription.put(taskLineName, taskLineName); + varInitialMap.put(taskLineName, ""); + } + + nameSet = new StringBuffer(); + nameSet.append(locationName); + name2nickname.putIfAbsent(locationName, new ArrayList<>()); + POS.append("=" + locationName + "|地名\r\n"); + if(jobj.containsKey("nickname")){ + + for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + nameSet.append("+").append(nickname); + POS.append("=").append(nickname).append("|地名\r\n"); + name2nickname.get(locationName).add(nickname); + } + } + } + jobj.put("nameSet", nameSet.toString()); + + locationId = (Integer) jobj.get("id"); + id2j.put(locationId, jobj); + } + + //邻接矩阵初始化 + matrix = new int[locationNum][locationNum]; + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { + matrix[i][j] = Integer.MAX_VALUE; + } + } + + for (int i = 0; i < locationNum; i++) { + List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); + for (int neighbourId : neighbours) { + JSONObject neighbourObject = id2j.get(neighbourId); + //System.out.println(neighbourObject); + index = (Integer) neighbourObject.get("index"); + matrix[i][index] = 1; + matrix[index][i] = 1; + } + } + } + + + public void construct(JSONObject gameElements, UserInfo userinfo) { + + try { + + conditionDescription.put("site", "当前地点"); + + JSONObject map = gameElements.getJSONObject("map"); + Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); + script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); + + + + + + if(script == null){ + throw new Exception("话术不存在"); + } + JSONArray locations = map.getJSONArray("locations"); + String userName = (String) gameElements.get("userName"); + this.locations = locations; + this.question2keyword = question2keyword; + //通过邻接表构造邻接矩阵 + constructGreph(locations); + + //用弗洛伊德算法求最短路径 + //Floyd floyd = new Floyd(); + //floyd.findShortestPath(matrix, locationNum); + //floyd.printPath(matrix, locationNum); + generateWantToThere(gameElements, keywordMap); + generateHowToThere(gameElements, keywordMap); + + //查询类型配置条目的生成 + queryTypeConfigTermGenerate(keywordMap, "WHERE_I_AM", "map", "queryWhereIam"); + queryTypeConfigTermGenerate(keywordMap, "WHERE_CAN_I_GO", "map", "queryCanGoBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_NPC", "map", "queryAroundNpcBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM", "map", "queryAroundGoodsBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_THINGS", "map", "queryAroundAllBySite"); + + queryTypeConfigTermGenerate(keywordMap, "AROUND_PLACE", "map", "queryAroundPlace"); + queryTypeConfigTermGenerate(keywordMap, "WHO_IN_THERE", "map", "queryInnerNpcBySite"); + queryTypeConfigTermGenerate(keywordMap, "TASK_IS_WHAT", "map", "queryTaskDescription"); + queryTypeConfigTermGenerate(keywordMap, "WHAT_THINGS_IN_LOCATION", "map", "queryItemsInPlace"); + + + + } catch(Exception e){ + operationStatus = 0; + e.printStackTrace(); + message = "地图处理出现异常:"; + return; + } + + } + + + /** + * 生成‘怎么去哪里’所需要的配置文件 + */ + public void generateHowToThere(JSONObject gameElements, Map keywordMap) { + //String conditionName = "want_know_zenmezuo"; + String intent = "HOW_TO_THERE", placeA, keywordPattern, gotoSite; + String conditionNameList[] = keywordMap.get(intent).toString().split(","); + StringBuffer placeKeywords = new StringBuffer(); + + String nameSet; + + + for(String conditionName:conditionNameList) { + placeKeywords.setLength(0); + + keywordPattern = keywordMap.get(intent + "_" + conditionName).toString(); + + + + + + //提取关键词 + //conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString(); + + for (int i = 0; i < locationNum; i++) { + + placeA = (String) locations.getJSONObject(i).get("name"); + gotoSite = keywordPattern.replace("name", placeA); + //toAllSiteskeywords.append(gotoSite); + //toSitekeywords.append(gotoSite); + placeKeywords.append(gotoSite); + for (String nickname : name2nickname.get(placeA)) { + gotoSite = keywordPattern.replace("name", nickname); + placeKeywords.append(gotoSite); + //toSitekeywords.append(gotoSite); + } + + + //nameSet = (String) locations.getJSONObject(i).get("nameSet"); + //placeKeywords.append("+").append(nameSet); + } + + + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:" + conditionName + "::match-Include=0", + " ", + "match,return-0", + "", + " ", + "map_query:queryPathAt:" + ); + configTermText.setNextStepStatus("return-0"); + configTermText.setAuxiliaryPriority("1"); + ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); + + + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", + " ", + "match,return-0", + "", + " ", + "map_query:queryPathAdjoin:" + ); + configTermText.setNextStepStatus("return-0"); + configTermText.setAuxiliaryPriority("1"); + ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); + + + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:" + conditionName + "::match-Include=2", + " ", + "match,return-0", + "", + " ", + "map_query:queryHowToPathBySite:" + conditionName + ); + configTermText.setNextStepStatus("return-0"); + configTermText.setAuxiliaryPriority("1"); + ConfigTermText.activateCopy(configTermText, configTermTextList, "map"); + + } + + + } + + + + /** + * 生成‘我要去那里’所需要的配置文件 + */ + public void generateWantToThere(JSONObject gameElements, Map keywordMap) { + String placeA, lastTaskCondition, lastTaskReply, taskLine; + String intent = "GO_TO", keywordPattern; + String conditionName = keywordMap.get(intent).toString().split(",")[0]; + + keywordPattern = keywordMap.get(intent + "_" + conditionName).toString(); + + //包含去xx的所有地点的关键词集合 + StringBuffer toAllSiteskeywords = new StringBuffer(); + + //包含去xx这个特定地点的关键词的集合(包含别名) + StringBuffer toSitekeywords = new StringBuffer(); + + + String gotoSite = ""; + + + for (int i = 0; i < locationNum; i++) { + toSitekeywords.setLength(0); + placeA = (String) locations.getJSONObject(i).get("name"); + gotoSite = keywordPattern.replace("name", placeA); + toAllSiteskeywords.append(gotoSite); + toSitekeywords.append(gotoSite); + for (String nickname : name2nickname.get(placeA)) { + gotoSite = keywordPattern.replace("name", nickname); + toAllSiteskeywords.append(gotoSite); + toSitekeywords.append(gotoSite); + } + + lastTaskCondition = String.format(TASK_CONDITION, placeA); + lastTaskReply = String.format(TASK_REPLY, placeA); + taskLine = String.format(TASK_LINE, placeA); + + + //地点任务和地点回答的初始化 + if (!varInitialMap.containsKey(lastTaskCondition)) { + varInitialMap.put(lastTaskCondition, conditionName); + varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); + conditionDescription.put(lastTaskCondition, lastTaskCondition); + conditionDescription.put(lastTaskReply, lastTaskReply); + } + + + /** + * 要去某个地方,并且该地点相邻或者可以直接到达 + */ + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", + + " ", + "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" + + ); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); + + + //上一个配置文件激活时的默认选项(兜底),上一条一定会激活下一条,下一条是没有条件的,如果没有找到其他可以激活的配置条目,则激活下一条 + configTermText = new ConfigTermText( + " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA + + "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("plot_" + placeA + "_doudi", false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + //上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step + configTermText = new ConfigTermText( + lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA + + "-<-npc_update:updateFollowerLocation:" + placeA + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("plot_" + placeA + "_doudi2", false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + } + + /** + * 要去的地方就在当前地点 + */ + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + toAllSiteskeywords + + ",isNeighbour:" + conditionName + "::match-Include=0", + " ", + "match,return-0", + "", + " ", + "map_query:queryPathAt:" + ); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); + + + /** + * 要去的地方要经过几个地点才能到达 + */ + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + toAllSiteskeywords + + ",isNeighbour:" + conditionName + "::match-Include=2", + " ", + "match,return-0", + "", + " ", + "map_query:queryToDoPathBySite:" + conditionName + ); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); + + /** + * 要去的地方不可到达 + */ + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + toAllSiteskeywords + + ",isNeighbour:" + conditionName + "::match-Include=5", + " ", + "match,return-0", + "", + " ", + "map_query:queryPathNotExist:" + ); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); + + } +} \ No newline at end of file diff --git a/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java new file mode 100644 index 0000000..557d929 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/gameDesign/PlotConstructor2.java @@ -0,0 +1,886 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.Premise; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.io.*; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.qiwu.chatbotbackend.Config.Config.*; + + +public class PlotConstructor2 extends ElementConstructor { + + + JSONArray plots = null; + HashMap> adjList = new HashMap>(); + HashMap> revAdjList = new HashMap>(); + private HashMap plotIndex = new HashMap(); + HashMap visited = new HashMap(); + + public HashMap getPlotIndex() { + return plotIndex; + } + + + public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + public void construct(JSONObject jsonObject, UserInfo userinfo) { + + try { + addGameStartPlot(jsonObject, keywordMap); + + JSONArray plots = jsonObject.getJSONArray("plots"); + String start = (String) jsonObject.get("start"), startCondition; + JSONObject returnMessage = null; + + + + this.plots = plots; + constructAdjList(plots); + + if (plotIndex.containsKey(start)) { + //String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; + String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place")); + conditionDescription.put(taskLineName, taskLineName); + + if(jsonObject.get("firstUnknownText") == null) + varInitialMap.put("unknownText", "你说啥?"); + else + varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); + + + varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); + conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION); + conditionDescription.put("game_step", GAME_STEP_DESCRIPTION); + + BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); + + varInitialMap.put(start, "1"); + ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList); + + + } else { + System.out.println(START_PLOT_NOT_EXIST); + operationStatus = 0; + message = START_PLOT_NOT_EXIST; + return; + } + } catch(Exception e){ + operationStatus = 0; + message = PLOT_GENERATION_ERROR; + e.printStackTrace(); + return; + } + } + + + /** + * 根据id构造邻接表 + * @param plots + */ + public void constructAdjList(JSONArray plots) { + int length = plots.size(), branchSize; + String id = "", nextPlotId = "", nextPlotText; + JSONObject plot = null; + JSONArray branch = null; + + for (int i = 0; i < length; i++) { + plot = plots.getJSONObject(i); + id = (String) plot.get("id"); + plot.put("index", i); + + if (adjList.get(id) == null) { + adjList.put(id, new ArrayList<>()); + } + + varSlotFilt(plot, keywordMap); + + //添加branch中的下一个plot + branch = plot.getJSONArray("branch"); + branchSize = branch.size(); + for (int j = 0; j < branchSize; j++) { + nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); + + branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise"))); + branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise"))); + + + //将剧情和相应文本相对应 + //plotTextIndex.put(nextPlotId, nextPlotText); + + if (revAdjList.get(nextPlotId) == null) { + revAdjList.put(nextPlotId, new ArrayList<>()); + } + + adjList.get(id).add(nextPlotId); + revAdjList.get(nextPlotId).add(id); + + } + plotIndex.put(id, plot); + } + } + + + /** + * 将条件文本中的一些特殊字符过滤调 + * @param premiseList 条件列表 + * @return + */ + JSONArray premiseTextFilt(JSONArray premiseList){ + JSONObject premise = null; + int size = premiseList.size(); + for(int i = 0;i < size;i++){ + premise = premiseList.getJSONObject(i); + premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", "")); + premiseList.set(i, premise); + } + + return premiseList; + } + + /** + * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 + * @param plot + */ + public static void varSlotFilt(JSONObject plot, Map keywordMap){ + + String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 + //System.out.println(plot.getString("id")); + Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); + Matcher m = replacePattern.matcher(plot.getString("plotText")); + while (m.find()) { + npcName = m.group(1); + //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 + //System.out.println("npcName" + npcName); + //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); + if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { + varSlot = m.group(3); + middleText = m.group(2); + plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); + } + + } + } + + + + /** + * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 + * 加上剧情计数器, null时未激活,大于等于1时表示已激活 + * @param root + * @param userinfo + */ + public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { + String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION, + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; + String hint, gameStep, nextGameStep; + JSONObject node = null, branchNode = null; + Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false; + StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer(); + JSONArray branch = null; + + + int branchSize; + + List curPremiseList, historyPremiseList; + + root.put("nextUnknownText", varInitialMap.get("unknownText")); + root.put("parentId", "null"); + root.put("autoJump", false); + root.put("prevAutoJump", false); + jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); + + if(root.get("conditionName") != null && !root.get("conditionName").equals("")) + conditionName = (String)root.get("conditionName"); + else{ + conditionName = DEFAULT_CONDITION; + root.put("conditionName", conditionName); + } + + + + String startPlace = ((String)root.get("place")).split("\\+")[0]; + String startTaskLine = String.format(TASK_LINE, startPlace); + String startTaskCondition = String.format(TASK_CONDITION, startPlace); + String startTaskReply = String.format(TASK_REPLY, startPlace); + varInitialMap.put("site", startPlace); + varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); + varInitialMap.put(startTaskCondition, ""); + varInitialMap.put(startTaskReply, ""); + conditionDescription.put(startTaskLine, startTaskLine); + conditionDescription.put(startTaskCondition,startTaskCondition); + conditionDescription.put(startTaskReply, startTaskReply); + + + + //generateStartGame(root, jsonObject, startPlace, conditionName); + Queue queue = new LinkedList(); + + queue.add(root); + //System.out.println(root.toJSONString()); + + while (!queue.isEmpty()) { + node = queue.remove(); + id = (String) node.get("id"); + location = ((String) node.get("place")).split("\\+")[0]; + conditionName = (String) node.get("conditionName"); + curAutoJump = node.getBoolean("autoJump"); + prevAutoJump = node.getBoolean("prevAutoJump"); + curUnknownText = (String) node.get("unknownText"); + taskLineName = String.format(TASK_LINE, location); + conditionDescription.put(id, String.format(PLOT_STATUS, id)); + varInitialMap.put(id ,""); + + //本任务线的最后一个condition和本任务线的最后一个回答 + + + + + branch = node.getJSONArray("branch"); + branchSize = branch.size(); + + + + for (int i = 0; i < branchSize; i++) { + + skipText.setLength(0); + + branchNode = branch.getJSONObject(i); + //reply = branchNode.getString("reply"); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + + + + nextId = branchNode.getString("nextPlotId"); + moveWithPlot = branchNode.getBoolean("moveWithPlot"); + if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ + nextId = id + "_end"; + createEndNode(node, id, nextId, curUnknownText); + } + + if(moveWithPlot == null || curAutoJump) + moveWithPlot = true; + + + + nextUnknownText = plotIndex.get(nextId).getString("unknownText"); + nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump"); + reply = plotIndex.get(nextId).getString("plotText"); + + + + if(reply.equals("")) + reply = curUnknownText; + + + + //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 + nextCondition = plotIndex.get(nextId).getString("conditionName"); + if(nextCondition.equals("")) + nextCondition = DEFAULT_CONDITION; + + nextLocation = plotIndex.get(nextId).getString("place"); + + //任务线 + nTaskLineName = String.format(TASK_LINE, nextLocation); + //任务线最后一个condition + lastTaskCondition = String.format(TASK_CONDITION, nextLocation); + lastTaskReply = String.format(TASK_REPLY, nextLocation); + +// if(nextId.endsWith("_end")) +// nextGameStep = id; +// else +// nextGameStep = nextId; + + + gameStep = String.format(GAME_STEP_FORMAT, botAccount, id); + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId); + + + + /** + * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 + * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: + * 1: 将剧情停留在最后一步剧情 + * 2. 设一个专门的剧情表示剧情的结尾 + */ + + //现在暂时放开下一步剧情未发生过的限制条件 + //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + appendPremise(extraHP, taskLineName, "match", "Include", gameStep); + appendPremise(extraHP, "site", "match", "Include", location); + appendPremise(extraHP, id, "match", "Include", "1"); + + + appendKnowledge(extraUK, lastTaskCondition, nextCondition); + appendKnowledge(extraUK, lastTaskReply, reply); + appendKnowledge(extraUK, id, "+1"); //当前剧情状态加一 + appendKnowledge(extraUK, nextId, "1"); //下一步设为1 + appendKnowledge(extraUK, nTaskLineName, nextGameStep); + + + + + //如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end + if(nextId.endsWith("_end")) { + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id); + } + + + //System.out.println(id); + + appendFeature(extraFT, "match"); + //下一步为自动跳转且地点相同,则将回答放在plot_jump_text + if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ + appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); + } + + + + /** + * 1. 主角是否随剧情移动 + * 如果随剧情移动,则更新地点和game_step + * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 + * + * 2. 当前条件是否为空 + * 如果当前条件为空,则提交qa激活并进入下一步剧情 + * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 + * + * 3. 下一部剧情是否为空 + * + * + * 4. 有没有说去XX + * + * 主角不随剧情移动+当前条件为空+去沙滩 + * 1、沙滩无剧情 + * 2、沙滩有剧情 + * + * 5. 地点变化 + * 1. 当前所处地点 + * 2. 下一步剧情所处地点(包含自动跳转的情况) + * 3. 自动跳转完成后的地点 + */ + + /** + * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) + * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) + * 2. 自动跳转剧情文本保存到beforeJumpTaskReply + * 3. 当前剧情和下一步剧情更新状态 + */ + + + if(branchNode.containsKey("activateExtraPlot")) { + //激活除了下一步剧情以外的剧情 + extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot")); + } + + + //如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新 + if(moveWithPlot || location.equals(nextLocation)) { + appendKnowledge(extraUK, "site", nextLocation); + appendKnowledge(extraUK, "game_step", nextGameStep); + appendKnowledge(extraUK,"unknownText", nextUnknownText); + //extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep; + //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 + //只有到达下一步剧情所在地时才会更新 + + + + } else { + + //任务线最后一个condition + + + + + /** + * 注意,比较的是当前地点和跳转前的地点 + * 地点更新为跳转后的地点 + */ + //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 + if(!location.equals(nextLocation)){ + //System.out.println(id + "报异常" + curUnknownText); + if(curUnknownText.equals("")) { + + //如果没有unknown,就提示他到下一个地点 + hint = String.format(LOCATION_HINT, nextLocation); + //hint = "请到" + nextLocation; + //如果当前地点和下一步剧情地点不同,要提示 + }else { + //如果有unknown,就提示unknown文本 + hint = curUnknownText; + } + + + + //下一部剧情在不同地点时,为了防止到达下个地点的剧情重复执行,需要加一个标志表示下一步剧情是否已经发生过 + appendKnowledge(extraUK, nextLocation + "_activate_by", id); + appendKnowledge(extraUK, nextLocation + "_activate_ready", "1"); + + + + + arriveActivatePlot2(jsonObject, id, nextId, nextLocation); + + //如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说 + reply = hint; + + + + //必须在上一个jConfig添加完之后 + //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); + + } + } + + //System.out.println(branchNode); + + curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class); + historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class); + + + + //是否将当前识别到的数据加入到已知数据列表 + if((Boolean)branchNode.get("includeCurInfo")){ + appendFeature(extraFT, "includeCurInfo"); + } + + if(branchNode.get("extraFeature") != null){ + appendFeature(extraFT, branchNode.getString("extraFeature")); + } + + + if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ + appendFeature(extraFT, "activate:after"); + nextCondition = "plot_" + nextId; + } + + configTermText = new ConfigTermText( + curPremiseList, + historyPremiseList, + updateKnowledge, + "", extraHP.toString(), extraUK.toString(), + extraFT.toString(), reply, nextCondition, "1" + ); + configTermText.setConfigName("plot_" + id, false); + + + //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 + if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !prevAutoJump){ + Boolean activateFlag = false; + if(extraFT.indexOf("activate") != -1) + activateFlag = true; + unconditionalPlotProcess(configTermText, nextCondition, activateFlag); + } + if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) + configTermText.setAuxiliaryPriority("3"); + configTermTextList.add(configTermText); + + + + //将子结点加入队列 + adjId = nextId; + plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump); + if(branchNode.getJSONObject("activateExtraPlot") != null){ + for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){ + plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump); + } + } + + extraFT.setLength(0); + extraHP.setLength(0); + extraUK.setLength(0); + skipText.setLength(0); + arriveUK.setLength(0); + + + + + } + + + } + + + + + + /** + * ---------------------------------------------------------------------------------------------------- + * 不设剧情不设条件时的处理 + * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 + * 2. 如果qa返回小于90则只回答剧情文本 + * 3. 如果qa返回not_found则只回答剧情文本 + * 4. 无论哪种情况都会跳下一步剧情 + */ + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip1",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip2",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=not_found", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip3",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + + + /** + * ---------------------------------------------------------------------------------------------------- + * 待激活列表,用于qa问答 + */ + + //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 + configTermText = new ConfigTermText(" ", " ", "activate,post::gameQA(" + QA_URL + ")", + "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); + configTermText.setNextStepStatus("active"); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=not_found", "match,return-0", + "{unknownText-2}", " ", "" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown1",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", + UNKNOWN_TEXT, + " ", "" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown2",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", + UNKNOWN_TEXT, + " ", "" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown3",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", + "{unknownText-2}", " ", "" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown4",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + + //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", + "" ," ", "" + ); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("common_answer",false); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + //--------------------------------------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------------------------------------- + + + /** + * ---------------------------------------------------------------------------------------------------- + * 用于存档 + */ + configTermText = new ConfigTermText( + "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", + "{archiveOperation-2}" ," ", "" + ); + configTermText.setAuxiliaryPriority("4"); + configTermTextList.add(configTermText); + + + } + + + /** + * 新建一个剧情结点 + * @param node + * @param id + * @param nextId + * @param nextUnknownText + */ + public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ + + String condition = (String) node.get("conditionName"); + String location = ((String) node.get("place")).split("\\+")[0]; + + String nextCondition = condition; + String nextLocation = location; + String nTaskLineName = String.format(TASK_LINE, nextCondition); + + + JSONObject endNode = new JSONObject(); + endNode.put("place", location); + endNode.put("conditionName", condition); + endNode.put("id", nextId); + endNode.put("plotText", nextUnknownText); + endNode.put("autoJump", false); + endNode.put("includeCurInfo", true); + endNode.put("updateKnowledge", new ArrayList()); + endNode.put("unknownText", ""); + + + plotIndex.put(nextId, endNode); + visited.put(nextId, true); + + } + + + /** + * 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档 + * @param gameElements + * @param keywordMap + */ + void addGameStartPlot(JSONObject gameElements, Map keywordMap){ + + + File file = null; + FileReader fr = null; + BufferedReader br = null; + try { + file = new File("gameconfig.txt"); + fr = new FileReader(file); + + br = new BufferedReader(fr); + String jsonStr = br.readLine(); + + jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); + jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); + jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); + jsonStr = jsonStr.replace("startId", gameElements.getString("start")); + jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); + + //System.out.println("JSONSTR ------------------------------\n" + jsonStr); + JSONObject config = JSONObject.parseObject(jsonStr); + + + gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); + gameElements.put("start", "start1"); + gameElements.put("firstUnknownText", GAME_START_HINT); + + + br.close(); + fr.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + + //如果是无条件剧情,那么需要跟着一个激活操作 + public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){ + configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); + + // + //if() + if(activateFlag){ + configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); + }else { + configTermText.setNextStep("queryskip*,map*,item*,npc*"); + } + + //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition + configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); + configTermText.setNextStepStatus("active"); + } + + + /** + * 在条件文本后面添加一个条件 + * @param premiseStr + * @param conditionName + * @param cmpType + * @param operator + * @param value + */ + public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ + int strLen = premiseStr.length(); + String split_punt = ""; + + + if(premiseStr.length() != 0) + split_punt = ","; + + premiseStr.append(split_punt); + premiseStr.append(conditionName); + premiseStr.append("::"); + premiseStr.append(cmpType); + premiseStr.append("-"); + premiseStr.append(operator); + premiseStr.append("="); + premiseStr.append(value); + + } + + public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ + knowledgeStr.append("-<-"); + knowledgeStr.append(key); + knowledgeStr.append(":"); + knowledgeStr.append(value); + } + + public void appendFeature(StringBuffer featureStr, String key){ + featureStr.append(","); + featureStr.append(key); + } + + + /** + * 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B + * @param updateKnowledge + * @param nextPlotLocation + * @param activateExtraPlot 激活id列表 + */ + public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ + JSONObject plot = null; + String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; + StringBuffer newUK = updateKnowledge; + + Iterator plotIter = activateExtraPlot.keySet().iterator(); + + while(plotIter.hasNext()){ + plotId = plotIter.next(); + plotText = (String)activateExtraPlot.get(plotId); + + plot = plotIndex.get(plotId); + conditionName = plot.getString("conditionName"); + + if(conditionName == null || conditionName.equals("")){ + conditionName = DEFAULT_CONDITION; + } + location = plot.getString("place"); + + lastTaskCondition = String.format(TASK_CONDITION, location); + lastTaskReply = String.format(TASK_REPLY, location); + taskLine = String.format(TASK_LINE, location); + + + appendKnowledge(newUK, lastTaskCondition, conditionName); + appendKnowledge(newUK, lastTaskReply, plotText); + appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); + appendKnowledge(newUK, plotId, "1"); + + + } + } + + + + void plotEnQueue(Queue queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){ + JSONObject adjNode; + if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { + visited.put(adjId, true); + adjNode = plotIndex.get(adjId); + + adjNode.put("parentId", parentId); + adjNode.put("prevAutoJump", thisAutoJump); + queue.add(adjNode); + } else { + conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId)); + varInitialMap.put(adjId, ""); + } + } + + + /** + * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况,将这块处理当做listening模块的一个剧情处理 + */ + void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ + + JSONObject updateKnowledge = new JSONObject(); + JSONArray curPremiseList = new JSONArray(); + //curPremiseList.add(curPremise.toString()); + + JSONArray hisPremiseList = new JSONArray(); + //hisPremiseList.add(hisPremise.toString()); + + + + //激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达 + // 2.3 两个条件是特意加的 + curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation)); + hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); + hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); + hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4")); + + + + JSONObject listeningConfig = new JSONObject(); + listeningConfig.put("curPremise", curPremiseList); + listeningConfig.put("hisPremise", hisPremiseList); + listeningConfig.put("updateKnowledge", updateKnowledge); + listeningConfig.put("nextPlotId", nextId); + listeningConfig.put("priority", "1"); + + if(gameElements.getJSONArray("listeningActions") == null) + gameElements.put("listeningActions", new JSONArray()); + + gameElements.getJSONArray("listeningActions").add(listeningConfig); + + } + + Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) { + + return nextAutoJump && (location.equals(nextLocation) || moveWithPlot); + } + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java b/src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java new file mode 100644 index 0000000..17339d5 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ActionMatcher.java @@ -0,0 +1,1128 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.http.message.BasicNameValuePair; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.text.ParseException; +import java.util.*; + + +public class ActionMatcher { + + Map activatedMap = new HashMap(); + + + static String POST_DATA_ERROR = "post数据有误"; + static String POST_ERROR = "数据post时出错了"; + static String API_ERROR = "api处理过程中出错了"; + + + public LogWriter logWriter = null; + public UserInfo userinfo = null; + public ServletContext context = null; + public GameEnv gameEnv = null; + public Map curInfoPoint = null; + public Map historyInfoPoint = null; + public WorldController worldController = null; + BasicBotUtil botUtil = null; + + public ActionMatcher(Map curInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, BasicBotUtil botUtil) { + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = botUtil.getChatCache().getInfoPoint(); + this.logWriter = logWriter; + this.userinfo = userinfo; + this.context = context; + + this.worldController = new WorldController(logWriter, userinfo); + this.botUtil = botUtil; + if(botUtil.botType.equals("game")) { + this.gameEnv = botUtil.getChatCache().getGameEnv(); + } + } + + + public ActionMatcher(){ + + } + + + + /** + * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch + * + * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 + * @return bestMatch 状态表中满足条件最多的一条 + */ + public Action getBestMatch(HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { + + Integer configId = 0; + List actionList = null; + Action bestMatch = new Action(-1), iterCon; + Iterator it = curInfoPoint.keySet().iterator(); + Queue activatedQueue = new LinkedList(); + Queue activatedAction = new LinkedList(); + + + + while (it.hasNext()) { + String conditionName = it.next(); + String keywords = curInfoPoint.get(conditionName); + String keyword = null; + Boolean activateFlag = false; + Boolean replaceFlag = false; + Boolean satisfyFlag = false; + + if (keywords != null && !keywords.equals("")) + keyword = keywords; + + + if (keyword != null && conditionTable.get(conditionName) != null) { + actionList = conditionTable.get(conditionName); + + + for (Action action : actionList) { + activateFlag = false; + satisfyFlag = false; + replaceFlag = false; + if (action.getStatus().equals("waiting")){ + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(action.getId()), 1); + + //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 + if (action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) { + activateFlag = true; + } + + if(higherPriority(action, bestMatch)){ + replaceFlag = true; + } + + + + //没有激活,优先级不够高,直接跳过 + if(!activateFlag && !replaceFlag){ + logWriter.record("-----------------------------------优先级不足,跳过", 0); + continue; + } + + if(conditionSatisfy(action)){ + satisfyFlag = true; + } + + + if(satisfyFlag){ + if(activateFlag){ + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); + } + if(replaceFlag){ + bestMatch = action; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); + logWriter.writeln(); + } + } + + } + } + } + + } + logWriter.record("----------------------匹配结束", 2); + + bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); + + + return bestMatch; + } + + /** + * 在激活列表中选择满足匹配且优先级最高的一条配置条目 + * @param bestMatch + * @param activatedQueue + * @param context + * @return + * @throws IOException + */ + public Action activatedQueueMatching(Action bestMatch, Queue activatedQueue, ServletContext context) throws IOException { + Action action; + Boolean activateFlag = false; + Boolean replaceFlag = false; + Boolean satisfyFlag = false; + Boolean parentFlag = false; + + //待激活配置条目被激活后的匹配 + while (!activatedQueue.isEmpty()) { + activateFlag = false; + replaceFlag = false; + satisfyFlag = false; + parentFlag = false; + + action = activatedQueue.remove(); + activatedMap.remove(action.getId()); + + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(action.getId()), 1); + + + if(higherPriority(action, bestMatch)) + replaceFlag = true; + + if(action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) + activateFlag = true; + + if(bestMatch.getNextStep().contains(String.valueOf(action.getId()))) + //现在的condition是被bestMatch这个condition激活的 + parentFlag = true; + + + //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 + if(!activateFlag && !replaceFlag && !parentFlag) { + logWriter.record("-----------------------------------优先级不足,跳过", 0); + //logWriter.record(userinfo.id2config.get(action.getId()), 1); + continue; + } + + if(conditionSatisfy(action)){ + if(activateFlag) { + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); + } + if(replaceFlag){ + bestMatch = action; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); + logWriter.writeln(); + } + } + + + + + } + + return bestMatch; + + } + + /** + * 根据当前信息点,历史信息点,判断是否满足该action的条件,match关键字指引擎识别的关键字包含在action相应的关键词列表中,这里可以根据特征添加其他操作。 + * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 + * + * @param action 配置文件(状态表)的一行 + * @return 满足条件就为True, 不满足就为False + */ + public boolean conditionSatisfy(Action action) { + boolean flag = true; + String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; + HashSet keywordSet = null; + + + + if (action.getFeatureMap().containsKey("match")) { + Iterator it = action.getCurrentPremise().keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + actionName = comparePair[0]; + cmpType = comparePair[1]; + keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + keywordSet = action.getCurrentPremise().get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + + it = action.getHistoryPremise().keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + cmpType = comparePair[1]; + actionName = comparePair[0]; + //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 + keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.getFeatureMap().containsKey("includeCurInfo"), actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + + + keywordSet = action.getHistoryPremise().get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + } + + + return flag; + + } + + + /** + * 单个条件的匹配,判断是否满足条件 + * 比较类型分为 match、number、time、variable, + * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 + * + * @param variableValue 变量的值或者condition识别到的关键字 + * @param cmpType 比较类型 + * @param keywordSet 限定值域 + * @return 返回匹配或者不匹配 + */ + public boolean premiseSatisfy(String variableValue, String cmpType, HashSet keywordSet) { + boolean flag = true; + String operator = ""; + + try { + String splitPair[] = cmpType.split("-", 2); + if (splitPair.length > 1) { + operator = splitPair[1]; + cmpType = splitPair[0]; + } + + + if (cmpType.equals("match")) { + if(operator.equals("Keyword") || operator.equals("Include")) { //识别到的关键词 属于预先设定的值域 + if (!keywordSet.contains(variableValue)) { + flag = false; + } + if (flag == false && variableValue.contains(":")) { + String ks[] = variableValue.split(":"); + for (String k : ks) { + if (keywordSet.contains(k)) + flag = true; + } + } + } else if(operator.equals("Exclude")) { + if(variableValue.contains(":")){ + String ks[] = variableValue.split(":", 2); + if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) + flag = false; + }else { + if (keywordSet.contains(variableValue)) { + flag = false; + } + } + }else if(operator.equals("Have")) { //变量的值包含了某些关键词 + for (String key : keywordSet) { + if (key.equals("")) + continue; + if (!variableValue.contains(key)) { + flag = false; + break; + } + } + + }else if(operator.equals("NotHave")){ + for(String key:keywordSet){ + if(key.equals("")) + continue; + if(variableValue.contains(key)){ + flag = false; + break; + } + } + }else if(operator.equals("Any")){ + + if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + flag = false; + }else{ + flag = false; + } + + + } else if (cmpType.equals("number") && !variableValue.equals("")) { + int candidateA = 0; + int candidateB = 0; + + if (variableValue.contains(":")) { + String ks[] = variableValue.split(":"); + for (String k : ks) { + if(StringUtils.isNumeric(k)) + variableValue = k; + + } + } + + if(!StringUtils.isNumeric(variableValue)){ + return false; + + } + + candidateA = Integer.parseInt(variableValue); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if (cmpType.equals("time")) { + + long candidateA, candidateB = 0; + + if (variableValue.contains(":")) { + String ks[] = variableValue.split(":"); + for (String k : ks) { + if(k.contains("年") && k.contains("月") && k.contains("日")) + variableValue = k; + + } + } + + candidateA = SimpleUtil.transferToMillisecond(variableValue); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = SimpleUtil.transferToMillisecond(k); + break; + } + } + if (operator.equals("Early")) + flag = candidateA < candidateB; + else if (operator.equals("Later")) + flag = candidateA > candidateB; + + } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { + String conditionName2 = "", conditionValue2 = ""; + for (String k : keywordSet) { + if (!k.equals("")) { + conditionName2 = k; + break; + } + } + + if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { + conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); + }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ + conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); + }else { + flag = false; + } + + + if(flag ){ + /** + * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true + */ + flag = false; + if(operator.equals("Equal")){ + flag = variableValue.equals(conditionValue2); + + }else if(variableValue.contains(":") && conditionValue2.contains(":")){ + String relPair1[] = variableValue.split(":", 2), keyword1 = ""; + String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; + boolean similar = false; + + if(relPair1[0].equals(relPair2[0])){ + similar = true; + keyword1 = relPair1[1]; + keyword2 = relPair2[1]; + }else if (relPair1[1].equals(relPair2[1])){ + similar = true; + keyword1 = relPair1[0]; + keyword2 = relPair2[0]; + } + + if(similar){ + if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ + int candidateA = Integer.parseInt(keyword1); + int candidateB = Integer.parseInt(keyword2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") + && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ + long candidateA = SimpleUtil.transferToMillisecond(keyword1); + long candidateB = SimpleUtil.transferToMillisecond(keyword2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + }else if(!variableValue.contains(":") && !conditionValue2.contains(":")){ + if(StringUtils.isNumeric(variableValue) && StringUtils.isNumeric(conditionValue2)){ + int candidateA = Integer.parseInt(variableValue); + int candidateB = Integer.parseInt(conditionValue2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(variableValue.contains("年") && variableValue.contains("月") && variableValue.contains("日") + && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ + long candidateA = SimpleUtil.transferToMillisecond(variableValue); + long candidateB = SimpleUtil.transferToMillisecond(conditionValue2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + } + + + + } else if (cmpType.equals("any")) { + if (variableValue.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + flag = false; + + } else { + flag = false; + } + } catch (IndexOutOfBoundsException e) { + System.out.println("配置文件格式有误"); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + + flag = false; + } catch (ParseException e) { + System.out.println("时间解析错误"); + historyInfoPoint.put("error_message", "解析出错:variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + flag = false; + } catch (Exception e) { + System.out.println("操作符有误"); + logWriter.record(e.getCause() + "\n条件比较时,keyword:" + variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); + System.out.println(e.getCause() + "\n条件比较时,variableName:" +variableValue + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); + flag = false; + } + + return flag; + } + + /** + * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 + * + * @return 返回给引擎的数据 + */ + public Solution getSolution(Action ansAction, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, reply, variable; + Solution ans = new Solution(0, "", ""); + + + //如果一条配置文件有多个答案,则随 + // 机选择一个答案 + + //System.out.println(ans.getAnswer()); + + //post关键字 + if (ansAction.getFeatureMap().containsKey("post")) { + logWriter.record("---------------------进入表单结束",1); + ans = postToServer(ans, ansAction); + logWriter.record("---------------------提交表单结束",1); + + //nextNext关键字 + } + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + //updateKnowledge关键字 + if (ansAction.getFeatureMap().containsKey("updateKnowledge")) { + logWriter.record("---------------------进入更新答案【略】",1); + updateKnowledge(ansAction); + logWriter.record("---------------------更新答案结束",1); + } + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ansAction.getFeatureMap().containsKey("newNext")) { + logWriter.record("---------------------进入判断下一步【略】",1); + ans = findNewNext(ans, ansAction); + logWriter.record("---------------------判断下一步结束",1); + //上一步 + } else if (ansAction.getFeatureMap().containsKey("return-1")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + //停留 + } else if (ansAction.getFeatureMap().containsKey("return-0")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if(activeList.length > 0) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else + ans.setNext("nextStep= "); + //激活 + } else if (ansAction.getFeatureMap().containsKey("activate") || ansAction.getFeatureMap().containsKey("activate:after")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + } + + + + + + try { + + reply = SimpleUtil.randStr(ansAction.getAnswer()); + reply = botUtil.varSlotReplace(reply); + + ans.setAnswer(reply); + + + botUtil.extraOperation(ansAction, ans); + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ans.getNext().equals("")) { + ans.setNext("nextStep=" + ansAction.getNextStep()); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return ans; + } + + /** + * 请求处理结束后台将当前信息的信息点转移到已知信息 + * @param ans + * @param context + * @param debugFlag + */ + public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { + //将当前信息点更新至历史信息点 + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, lastReply; + String next = ans.getNext().split("=", 2)[1]; + + //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx + historyInfoPoint.put("currentAction", next); + historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); + + logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + + try { + String keyword1, keyword2; + while (it.hasNext()) { + actionName = it.next(); + + if(skipSet.contains(actionName)) + continue; + + keyword1 = curInfoPoint.get(actionName); + keyword2 = historyInfoPoint.get(actionName); + if (keyword2 == null) { + historyInfoPoint.put(actionName, keyword1); + }else if (historyInfoPoint.get(actionName).equals("do_reset")){ + historyInfoPoint.put(actionName, ""); + }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) + historyInfoPoint.put(actionName, keyword1); + } + historyInfoPoint.put("临时变量reply", ""); + historyInfoPoint.put("临时变量condition", ""); + historyInfoPoint.put("临时变量3", ""); + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 如果接收到的表单中包含debug_mode这个参数, 后台会将存储的变量值返回给前段,用于调试 + * + * @param ans 最终返回的数据 + * @param context + */ + public void appendDebugInfo(Solution ans, ServletContext context) { + Iterator it = null; + String key, values, value; + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("bot_name"); + add("action_name"); + add("lastReply"); + add("unknownTextList"); + add("finalUnknownText"); + add("unknownText"); + add("randKey"); + add("userKey"); + } + }; + + it = curInfoPoint.keySet().iterator(); + String debugInfo = ""; + debugInfo += "(识别:"; + + while (it.hasNext()) { + key = it.next(); + values = curInfoPoint.get(key); + if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { + if (key.endsWith("_backup")) { + key = key.substring(0, key.length() - 7); + } + debugInfo += (" " + key + ":\'" + values + "\' "); + } + } + + debugInfo += ")"; + if(curInfoPoint.containsKey("debug_mode")) { + debugInfo = debugInfo.replace("-)", ""); + debugInfo += "(已知:"; + it = historyInfoPoint.keySet().iterator(); + while (it.hasNext()) { + + key = it.next(); + value = historyInfoPoint.get(key); + if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition")) + debugInfo += (" " + key + ":\'" + value + "\' "); + + } + } + ans.setAnswer(debugInfo + ")" + ans.getAnswer()); + } + + + /** + * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) + * + * @param ans 返回给用户的数据 + * @param ansAction 满足条件最多的condition(配置文件的某一行) + */ + public Solution postToServer(Solution ans, Action ansAction) throws IOException { + String url = null, elem[], subElem[], key,keys, postType = "all"; + Map infoMap = new HashMap(); + List pairList = new ArrayList(); + Iterator k_iter = null; + FormsPoster poster = new FormsPoster(logWriter); + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("lastReply"); + } + }; + + elem = ansAction.getFeatureMap().get("post").split("\\|"); + url = elem[0]; + postType = elem[1]; + + + if(postType.equals("all")){ + poster.postAll(curInfoPoint, historyInfoPoint, ans, url); + }else if(postType.equals("term")){ + poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); + }else if(postType.equals("gameQA")){ + System.out.println("提交表单" + gameEnv); + poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); + } + + return ans; + + } + + public Solution findNewNext(Solution ans, Action ansAction) { + String nextOptions[] = ansAction.getNextStep().split(","); + String conditionName, premises[], cpPair[]; + boolean flag = true; + + String activeList = historyInfoPoint.get("activeList"); + + for (String option : nextOptions) { + flag = true; + cpPair = option.split(":"); + conditionName = cpPair[0]; + if (cpPair.length == 1) { + ans.setNext("nextStep=" + conditionName); + break; + } + premises = cpPair[1].split("-"); + for (String premise : premises) { + if (premise.equals("known")) { + //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 + boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); + boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); + + //只有前两者都为假时,conditionExist才为真 + boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); + + if (conditionExist) + flag = false; + } + + if (premise.equals("active")) { + boolean isActive = activeList.contains(conditionName); + if (isActive) + flag = false; + } + } + + if (flag) { + ans.setNext("nextStep=" + conditionName); + break; + } + + } + return ans; + + } + + + public void updateKnowledge(Action action) throws ParseException { + String keyword, variableName, updateValue, returnStr = "1"; + + + + Iterator iit = action.getUpdateKnowledge().keySet().iterator(); + while (iit.hasNext()) { + + variableName = iit.next(); + + keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); + updateValue = botUtil.knowledgeProcess(variableName, action.getUpdateKnowledge().get(variableName)); + + + try { + //做数字加法 + if (updateValue.startsWith("+")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = SimpleUtil.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("-")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = SimpleUtil.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(4); + //做字符串删除 + } else if (updateValue.startsWith("str-")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(4), ""); + + } else if (updateValue.startsWith("int+=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = SimpleUtil.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("int-=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = SimpleUtil.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(5); + //做字符串删除 + } else if (updateValue.startsWith("str-=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(5), ""); + + + //变量提取 + } else if (updateValue.startsWith("var=")) { + String conditionName = updateValue.substring(5, updateValue.length() - 3); + if (updateValue.endsWith("-1}")) { + if (curInfoPoint.get(conditionName) != null) { + updateValue = curInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("-2}")) { + if (historyInfoPoint.get(conditionName) != null) { + updateValue = historyInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + + //提取配置条目的下一步 + } else if (updateValue.endsWith("nextStep-3}")) { + updateValue = action.getNextStep(); + //提取配置条目的回答 + } else if (updateValue.endsWith("reply-3}")) { + updateValue = SimpleUtil.randStr(action.getAnswer()); + } + //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue + if (variableName.startsWith("process-nextStep")) { + action.setNextStep(updateValue); + updateValue = ""; + } + + } + + + } catch (Exception e) { + logWriter.record(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue, 0); + System.out.println(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue); + //e.printStackTrace(); + continue; + } + + + + if(updateValue.equals("")) { + curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 + // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 + curInfoPoint.put(variableName, ""); + } + + botUtil.putKeyword(variableName, updateValue); + + + } + + } + + + public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority, String activateList, ServletContext context) throws IOException { + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + String configStr = ""; + Integer configId; + Action newAction, originAction; + List originActionList = new ArrayList(); + + for (String configIdStr : activateList.split(",")) { + logWriter.record("------激活-------" + configIdStr + "-------
", 0); + try { + if (StringUtils.isNumeric(configIdStr)) { + configId = Integer.parseInt(configIdStr); + configStr = userinfo.id2config.get(configId); + originAction = userinfo.id2condition.get(configId); + originActionList.add(originAction); + } else { + if (configIdStr.endsWith("*")) { + String prefix = configIdStr.substring(0, configIdStr.length()-1); + for(String name:userinfo.name2condition.keySet()){ + if (name.startsWith(prefix)){ + originActionList.add(userinfo.name2condition.get(name)); + } + } + + } else { + originActionList.add(userinfo.name2condition.get(configIdStr)); + } + + + } + } catch (Exception e) { + e.printStackTrace(); + logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); + } + } + + for (Action action : originActionList){ + originAction = action; + try { + + configId = originAction.getId(); + newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); + + + + //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 + if (activatedMap.containsKey(configId)) { + if(higherPriority(newAction, activatedMap.get(configId))) + activatedMap.put(configId, newAction); + + } else if (!activatedMap.containsKey(configId)) { + activatedMap.put(configId, newAction); + activatedQueue.add(newAction); + } + }catch (Exception e) { + e.printStackTrace(); + logWriter.record("----------激活失败:" + action.getConfigName(), 5); + } + + } + + + } + + /** + * 一个提交表单后在激活的操作 + * @param ansAction + * @param context + * @param userinfo + * @return + * @throws IOException + * @throws ParseException + */ + public Solution postActivate(Action ansAction, Solution oldBestMatch, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + Queue activatedQueue = new LinkedList(); + Solution bestMatch = oldBestMatch; + Action newAction1 = ansAction, newAction2; + + + + while ((newAction1.getFeatureMap().containsKey("activate") && newAction1.getFeatureMap().containsKey("post")) || newAction1.getFeatureMap().containsKey("activate:after")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + activateCondition(activatedQueue, userinfo.botAccount, newAction1.getPriority(), newAction1.getAuxiliaryPriority(), newAction1.getNextStep(), context); + newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); + + + + if(newAction1 == newAction2) + break; + + bestMatch = getSolution(newAction2, context, userinfo); + newAction1 = newAction2; + } + + return bestMatch; + + + + + } + + public Boolean higherPriority(Action action1, Action action2){ + return ((action1.getAuxiliaryPriority() > action2.getAuxiliaryPriority()) || (action1.getAuxiliaryPriority() == action2.getAuxiliaryPriority() && action1.getPriority() > action2.getPriority())); + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java new file mode 100644 index 0000000..7d84210 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/ChatCacheController.java @@ -0,0 +1,291 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSON; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ArchiveInfo; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.FileFinder; + +import javax.servlet.ServletContext; +import java.io.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class ChatCacheController { + + public static long TIME_OUT = 300000; + + + public static String CHAT_CACHE_DIR = "ChatCache/"; + + private static String ARCHIVE_NAME = "%s-%s-%s"; + private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; + private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; + private static String ENV_POSTFIX = "-env.data"; + private static String INFO_POSTFIX = "-info.data"; + + public static String COMBINE_PUNC1 = "@@@"; //chatKey的连接符 chatKey格式为 用户名@@@bot账号@@@@随机码 + public static String COMBINE_PUNC2 = "@@@@"; + + + + /** + * 通过chat_key获得后台保存的历史信息点 + * chatCache:存储了chatKye相对应的对话记录(历史信息点) + * + * @return 历史信息点,对话过程中引擎提取的用户信息 + */ + public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception { + Map chatCacheMap = null; + ChatCache chatCache = null; + + if (context.getAttribute("chatCache") == null) { + chatCacheMap = new HashMap(); + context.setAttribute("chatCache", chatCacheMap); + } else { + chatCacheMap = (Map) context.getAttribute("chatCache"); + } + + + + chatCache = chatCacheMap.get(userKey); + + + //如果用户之前没有玩过或者有一段时间没有玩 + if(chatCache == null){ + chatCache = new ChatCache(userinfo, userKey, randKey, botType); + chatCacheMap.put(userKey, chatCache); + //用户几分钟前还在玩 + } else { + if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 + //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { + ChatCacheController.saveChatCache(chatCache, null); + } + chatCache = new ChatCache(userinfo, userKey, randKey, botType); + chatCacheMap.put(userKey, chatCache); + } + } + System.out.println(chatCache.getGameEnv()); + + return chatCache; + } + + + + public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); + String nowTime = now .format(format), userId, botAccount, keyElem[]; + Boolean opFlag, destroy = false; + + if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey())) + return true; + + + System.out.println("游戏存档中"); + + String userKey = chatCache.getUserKey(); + String site = chatCache.getInfoPoint().get("site"); + String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); + + try { + + if(helper == null){ + helper = new SqlHelper(); + destroy = true; + } + + File dir = new File(CHAT_CACHE_DIR); + if (!dir.exists()) + dir.mkdir(); + + + + + + ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); + + + File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); + FileWriter fw = new FileWriter(file); + + String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); + fw.write(jsonString); + fw.close(); + + + opFlag = helper.insertArchiveInfo(archiveName, userKey, site); + + if(destroy) + helper.destroy(); + + } catch (Exception e) { + System.out.println("游戏存档时发生异常"); + opFlag = false; + } + + return opFlag; + } + + + + public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { + ChatCache chatCache = null; + GameEnv gameEnv = null; + Map infoPoint = null; + System.out.println(archiveInfo.getArchiveId()); + String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); + keys[1] = keys[1].split("-")[0]; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + Map infoPoints = new HashMap(); + + File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + if (file.exists()){ + gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); + }else{ + throw new IOException("环境存档不存在"); + } + + + file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String jsonStr = br.readLine(); + infoPoint = (Map)JSON.parseObject(jsonStr); + + chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); + chatCache.setGameStart(true); + + br.close(); + fr.close(); + + + return chatCache; + } + + + + /** + * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 + */ + public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo){ + String sessionKey; + ChatCache chatCache = null; + SqlHelper helper = null; + long lastChatTime, now; + Map history = new HashMap(); + Map chatCacheMap = (Map) context.getAttribute("chatCache"); + + try { + helper = new SqlHelper(); + + Iterator it = chatCacheMap.keySet().iterator(); + while (it.hasNext()) { + sessionKey = it.next(); + if (sessionKey.equals(userKey)) { +// saveChatCache(chatCacheMap.get(sessionKey),null); + continue; + } + history = chatCacheMap.get(sessionKey).getInfoPoint(); + lastChatTime = Long.valueOf(history.get("lastUpdateTime")); + now = System.currentTimeMillis(); + if (now - lastChatTime > ChatCacheController.TIME_OUT) { + chatCache = chatCacheMap.get(sessionKey); + + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { + saveChatCache(chatCache, helper); + } + System.out.println("移除" + sessionKey); + it.remove(); + } + } + }catch (Exception e){ + e.printStackTrace(); + }finally { + helper.destroy(); + } + context.setAttribute("chatCache", chatCacheMap); + } + + /** + * 根据chatKey更新chatCache的数据,并修改最后更新时间 + */ + public static synchronized void updateChatCache4Insert(Map curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) { + chatCache.getInfoPoint().put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + Map keyCacheMap = (Map) context.getAttribute("chatCache"); + keyCacheMap.put(chatCache.getUserKey(), chatCache); + //ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); + //chatCache.setInfoPoint(historyInfoPoint); + //chatCache.setGameEnv(gameEnv); + context.setAttribute("chatCache", keyCacheMap); + } + + + public static synchronized boolean findChatCache(String userKey, ServletContext context) throws Exception { + ArchiveInfo archiveInfo = null; + Map chatCacheMap = null; + ChatCache chatCache = null; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + Boolean findFlag = false; + SqlHelper helper; + Map infoPoints = new HashMap(); + try { + helper = new SqlHelper(); + + if (context.getAttribute("chatCache") != null) { + chatCacheMap = (HashMap)context.getAttribute("chatCache"); + if (chatCacheMap.containsKey(userKey)) { + chatCache = chatCacheMap.get(userKey); + + + // //保存到本地,并从chatCacheMap中删除 + if(!chatCache.getUserKey().endsWith(chatCache.getRandKey()) && chatCache.isGameStart()){ + findFlag = true; + saveChatCache(chatCache, helper); + chatCacheMap.remove(userKey); + } + + + } + + } + + if (!findFlag) { + + + archiveInfo = helper.queryUserLastGameArchive(userKey); + + helper.destroy(); + findFlag = (archiveInfo != null); + } + + + } catch (Exception e) { + e.printStackTrace(); + findFlag = false; + } + + return findFlag; + } + + + public static Boolean deleteChatCache(SqlHelper helper, String botAccount){ + + Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount); + Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount); + + return sqlDeleteFlag && fileDeleteFlag; + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java b/src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java new file mode 100644 index 0000000..21b52be --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/FormsPoster.java @@ -0,0 +1,262 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; +import org.apache.http.message.BasicNameValuePair; +import org.springframework.beans.factory.annotation.Value; + +import java.io.UnsupportedEncodingException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class FormsPoster { + + + LogWriter logWriter; + + public static String TALKER = "【(.*?)@.*?】"; + + @Value("${qa.url}") + public String QA_URL; + + + public void setQaUrl(String qaUrl) { + QA_URL = qaUrl; + } + + public FormsPoster(LogWriter logWriter) { + this.logWriter = logWriter; + } + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("lastReply"); + } + }; + + + + /** + * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器,还有回答 + * @param curInfoPoint + * @param historyInfoPoint + * @param ans + * @param URL + * @throws UnsupportedEncodingException + */ + public void postAll(Map curInfoPoint, Map historyInfoPoint, Solution ans, String URL) throws UnsupportedEncodingException { + String key, keyName; + Iterator k_iter = null; + List pairList = new ArrayList(); + + k_iter = curInfoPoint.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next(); + if (curInfoPoint.get(key) != null && !curInfoPoint.get(key).equals("")) + //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); + } + + k_iter = historyInfoPoint.keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next(); + + if(historyInfoPoint.get(key) != null && !historyInfoPoint.get(key).equals("")) { + if (skipSet.contains(key)) + continue; + if (curInfoPoint.get(key) == null || curInfoPoint.equals("")) { + pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); + } else { + pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); + } + } + } + + pairList.add(new BasicNameValuePair("reply", ans.getAnswer())); + + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); + + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); + logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); + if((Integer)jobj.get("post_status") == 1){ + Iterator kit = jobj.keySet().iterator(); + + while (kit.hasNext()) { + keyName = kit.next(); + if (keyName.equals("process")) { + ans.setNext((String) jobj.get(keyName)); + historyInfoPoint.put("process", (String) jobj.get(keyName)); + } else if (keyName.equals("solution")) { + ans.setAnswer((String) jobj.get(keyName)); + } else if (keyName.equals("status") || keyName.equals("qa_candidates")){ + continue; + } else{ + historyInfoPoint.put(keyName, jobj.getString(keyName)); + } + } + }else { + if(URL.equals(QA_URL)) + ans.setAnswer("qa_threshold, game_step, query_text 看看少了哪个"); + else + ans.setAnswer("提交表单出现异常"); + } + + + + + } + + /** + * 提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 + * @param curInfoPoint + * @param historyInfoPoint + * @param ans + * @param ansAction + * @param URL + * @throws UnsupportedEncodingException + */ + public void postTerm(Map curInfoPoint, Map historyInfoPoint, Solution ans, Action ansAction, String URL) throws UnsupportedEncodingException { + String key, keyName; + Iterator k_iter = null; + List pairList = new ArrayList(); + + pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); + pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); + pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); + k_iter = ansAction.getCurrentPremise().keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next().split("::")[0]; + if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) + pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); + } + + k_iter = ansAction.getHistoryPremise().keySet().iterator(); + while (k_iter.hasNext()) { + key = k_iter.next().split("::")[0]; + if(!historyInfoPoint.get(key).equals("")) { + if (curInfoPoint.get(key) == null || curInfoPoint.equals("")) { + pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); + } else { + pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); + } + } + } + + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); + + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); + logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); + if((Integer)jobj.get("post_status") == 1){ + Iterator kit = jobj.keySet().iterator(); + + while (kit.hasNext()) { + keyName = kit.next(); + if (keyName.equals("process")) { + ans.setNext((String) jobj.get(keyName)); + historyInfoPoint.put("process", (String) jobj.get(keyName)); + } else if (keyName.equals("solution")) { + ans.setAnswer((String) jobj.get(keyName)); + } else if (keyName.equals("status")){ + continue; + } else{ + historyInfoPoint.put(keyName, jobj.getString(keyName)); + } + } + }else { + ans.setAnswer("提交表单出现异常"); + } + + } + + + /** + * 游戏专用提交表单 + * @param curInfoPoint + * @param historyInfoPoint + * @param ans + * @param gameEnv + * @param worldController + * @param URL + * @throws UnsupportedEncodingException + */ + public void postGameQA1(String gameStep, Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { + String key, keyName; + Iterator k_iter = null; + List pairList = new ArrayList(); + String threshold = "50"; + + if (historyInfoPoint.get("qa_threshold") != null) + threshold = historyInfoPoint.get("qa_threshold"); + + pairList.add(new BasicNameValuePair("game_step", gameStep)); + pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); + pairList.add(new BasicNameValuePair("qa_threshold", threshold)); + + + //设置初始值 + historyInfoPoint.put("common_answer", ""); + historyInfoPoint.put("qa_score", "0"); + historyInfoPoint.put("qa_status", "OK"); + + logWriter.record("提交表单的数据:
" + pairList.toString(), 2); + + JSONObject jobj = SimpleUtil.postFORM(URL, pairList); + + logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); + + String text,score, site = historyInfoPoint.get("site"), npc; + System.out.println(jobj.toJSONString()); + if((Integer)jobj.get("post_status") == 1){ + if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){ + + List candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); + + for(JSONArray pair:candidates){ + List textscore = JSON.toJavaObject(pair, List.class); + + + Pattern findTalker = Pattern.compile(TALKER); + + + if((Integer)textscore.get(1) > 90) { + Matcher m = findTalker.matcher((String)textscore.get(0)); + if (m.find()) { + npc = m.group(1); + + if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, historyInfoPoint.get("site"), logWriter) == 1)) { + historyInfoPoint.put("common_answer", (String)textscore.get(0)); + historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); + break; + } + } + } + } + } + }else { + historyInfoPoint.put("error_message", jobj.getString("error_message")); + } + + } + public void postGameQA(Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { + postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo); + + if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){ + postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo); + } +// historyInfoPoint.put("common_answer", "【旁白@%正常】QA暂时关闭"); +// historyInfoPoint.put("qa_score", "99"); +// historyInfoPoint.put("qa_status", "OK"); + + } + + } diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java b/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java new file mode 100644 index 0000000..c6a7b85 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/LogWriter.java @@ -0,0 +1,81 @@ +package com.qiwu.chatbotbackend.processing; + +import java.io.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; + + +public class LogWriter { + private PrintWriter recorder = null; + DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"); + LocalDateTime ldt = null; + + + String filePath; + String fileName; + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + String PRINT_PATTERN = "[%s] %s" + + "----------------------------------------------------------------------------
"; + Map colorMap = new HashMap(){ + { + put(0, "black"); + put(1, "gray"); + put(2, "green"); + put(3, "yellow"); + put(4, "green"); + put(5, "red"); + } + }; + public LogWriter(String filePath, String fileName) throws IOException { + File file = new File(filePath + "/" + fileName + ".html"); + + System.out.println(file.getAbsolutePath()); + + if (!file.exists()) { + file.createNewFile(); + } + file.setReadable(true,false); + + FileWriter fw = new FileWriter(file, true); + + + BufferedWriter bw = new BufferedWriter(fw); + recorder = new PrintWriter(bw); + recorder.println("\n" + + "\n" + + "\n" + + " \n" + + " log\n" + + ""); + } + + public void record(String text, int level){ + ldt = LocalDateTime.now(); + recorder.println(String.format(PRINT_PATTERN, colorMap.get(level), ldt.format(dtf), text)); + } + public void writeln(){ + recorder.println("
"); + } + + public void close(){ + recorder.close(); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java b/src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java new file mode 100644 index 0000000..d1cfc67 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/SimpleUtil.java @@ -0,0 +1,270 @@ +package com.qiwu.chatbotbackend.processing; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.entity.Solution; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + + +public class SimpleUtil { + + /** + * 将后台返回的数据转成json格式 + */ + public static String toJson(Solution ans) { + JSONObject jobj = new JSONObject(); + jobj.put("solution", ans.getAnswer()); + jobj.put("status", ans.getStatus()); + jobj.put("process", ans.getNext()); + return jobj.toString(); + } + + public static String toJson(String returnStr) { + JSONObject jobj = new JSONObject(); + jobj.put("returnString", returnStr); + return jobj.toString(); + } + + /** + * 当请求中的数据是json格式时,该函数用于提取request中的json数据 + * + * @param request + * @return json字符串 + */ + public static String readJSONString(HttpServletRequest request) { + StringBuffer json = new StringBuffer(); + String line = null; + + try { + BufferedReader reader = request.getReader(); + while ((line = reader.readLine()) != null) { + json.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + + return json.toString(); + } + + + public static JSONObject getMethod(String url, String auth){ + CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse resp = null; + String respContent = null; + String keyName = null; + JSONObject jobj = new JSONObject(); + + + try { + HttpGet httpGet = new HttpGet(url); + + if(auth != null){ + httpGet.setHeader("Authorization", auth); + } + resp = client.execute(httpGet); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + jobj.put("get_status", 1); + jobj.put("status_code", 200); + + } else { + jobj.put("get_status", 0); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); + jobj.put("parameter", "接收请求的程序出现异常"); + } + } catch (Exception e) { + e.printStackTrace(); + jobj.put("status_code", 0); + jobj.put("get_status", 0); + + }finally { + try { + if (resp != null) { + resp.close(); + } + if (client != null) { + client.close(); + } + }catch(IOException e){ + e.printStackTrace(); + } + } + + return jobj; + } + + + + /** + * 通过get方法传递参数时需要对参数的编码进行转换 + */ + public static String convert2Utf8(String s) { + if (s == null) return null; + try { + s = new String(s.getBytes("iso-8859-1"), "utf-8"); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return s; + } + + public static long transferToMillisecond(String keyword) throws ParseException { + long time; + + System.out.println(keyword); + + String timeSeries[] = {"时", "分", "秒"}; + for (String f : timeSeries) { + if (!keyword.contains(f)) + keyword += "0" + f; + } + + SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); + time = format.parse(keyword).getTime(); + + return time; + } + + public static String transferToStandardTime(long time) throws ParseException { + + SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); + + Date date = new Date(time); + return format.format(date); + + } + + public static boolean isInteger(String str){ + return true; + } + + + + public static JSONObject postJSON(String url, JSON data, String auth) 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); + + if(auth != null){ + httpPost.setHeader("Authorization", auth); + } + + try { + HttpResponse resp = client.execute(httpPost); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + jobj.put("post_status", 1); + jobj.put("status_code", 200); + } else { + jobj.put("post_status", 0); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); + jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); + } + + } catch (Exception e) { + jobj.put("status_code", 0); + jobj.put("post_status", 0); + e.printStackTrace(); + } + + return jobj; + + } + + + + + + public static JSONObject postFORM(String url, List pairList) throws UnsupportedEncodingException { + + + HttpPost httpPost = new HttpPost(url); + CloseableHttpClient client = HttpClients.createDefault(); + String respContent = null; + String keyName = null; + + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); + entity.setContentType("application/x-www-form-urlencoded"); + httpPost.setEntity(entity); + JSONObject jobj = new JSONObject(); + + try { + System.out.println("url为:" + url); + HttpResponse resp = client.execute(httpPost); + if (resp.getStatusLine().getStatusCode() == 200) { + HttpEntity he = resp.getEntity(); + respContent = EntityUtils.toString(he, "UTF-8"); + jobj = JSONObject.parseObject(respContent); + jobj.put("post_status", 1); + + } else { + jobj.put("post_status", 0); + jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); + } + } catch (Exception e) { + jobj.put("error_message", "提交表单时出错:" + e.getMessage()); + jobj.put("post_status", 0); + } + + return jobj; + + } + + public static String randStr(String strList[]){ + String reply; + int randNum = (int) (Math.random() * strList.length); + reply = strList[randNum]; + + return reply; + } + + public static String randStr(List strList){ + String reply; + + int randNum = (int) (Math.random() * strList.size()); + reply = strList.get(randNum); + + return reply; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java new file mode 100644 index 0000000..afb1f05 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/UserInfoController.java @@ -0,0 +1,507 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import javax.servlet.ServletContext; +import java.io.*; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.CONFIG_DIR; +import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; + +public class UserInfoController { + + + + + /** + * 根据本地配置文件生成用户信息 + */ + public static void configInit(ServletContext context) throws IOException { + + String line; + + + File dir = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR); + if (!dir.exists()) + dir.mkdir(); + for (File configFile : dir.listFiles()) { + + FileReader reader = new FileReader(configFile); + BufferedReader br = new BufferedReader(reader); + String fileName = configFile.getName(); + UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); + + userinfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + + reader.close(); + br.close(); + } + + } + + public static UserInfo userConfigInit(String botAccount, ServletContext context) throws IOException { + String line; + UserInfo userInfo = null; + File userFile = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR + botAccount + ".txt"); + + + + System.out.println("配置文件地址:" + userFile.getAbsolutePath()); + if (!userFile.exists()) { + BufferedReader br = new BufferedReader(new StringReader("")); + userInfo = new UserInfo(botAccount); + + userInfo = buildUserInfo(br, userInfo, true); + context.setAttribute(userInfo.botAccount, userInfo); + + } else { + FileReader reader = new FileReader(userFile); + BufferedReader br = new BufferedReader(reader); + UserInfo userinfo = new UserInfo(botAccount); + + userInfo = buildUserInfo(br, userinfo, true); + context.setAttribute(userinfo.botAccount, userinfo); + + + + reader.close(); + br.close(); + + + } + return userInfo; + } + + + /** + * 解析一行配置文件 + * @param action + * @param line + * @return + */ + public static Action buildCondition(Action action, String line) { + String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; + + + try { + + element = line.replace("\n", "").split("\\|=\\>\\|"); + premises = element[0].split("\\|"); + feature = premises[2]; + cur_premises = premises[0].split(","); + history_premises = premises[1].split(","); + + + action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); + //action.setConfigName(premises[4].split("=", 2)[1]); + + + next = element[1].split("\\|"); + if (next.length < 4) + return action; + + if(premises.length < 5) + action.setConfigName(""); + else + action.setConfigName(premises[4].split("=", 2)[1]); + + + + //回答可以有多个,然后可随机选择一个 + action.setAnswer(next[0].split("~")); + //第二处 + action.setNextStep(next[1].split("=", 2)[1]); + action.setId(Integer.parseInt(next[3].split("=")[1])); + action.setStatus(next[2].split("=")[1]); + + + //featureMap的构建 + features = feature.split(","); + for (String feat : features) { + if (feat.equals("") || feat.equals(" ")) { + continue; + } else if (feat.startsWith("updateKnowledge")) { + String[] knowledge = feat.split("-<-"); + int length = knowledge.length; + action.getFeatureMap().put("updateKnowledge", ""); + for (int i = 1; i < length; i++) { + if (knowledge[i].equals("") || knowledge[i].equals(" ")) + continue; + + pair = knowledge[i].split(":", 2); + action.getUpdateKnowledge().put(pair[0], pair[1]); + } + } else if (feat.startsWith("post")) { + pair = feat.split("\\(", 2); + url = pair[1]; + url = url.substring(0, url.length() - 1); + pair = pair[0].split("::"); + action.getFeatureMap().put("post", url + "|" + pair[1]); + } else { + action.getFeatureMap().put(feat, ""); + } + } + + + insertPremise(action.getCurrentPremise(), cur_premises); + insertPremise(action.getHistoryPremise(), history_premises); + //满足条件越多,优先级越大 + action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); + + + firstCnditionName = cur_premises[0]; + if (firstCnditionName.equals(" ")) + action.setIndexName("emptySet"); + else + action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]); + } catch (IndexOutOfBoundsException e) { + e.printStackTrace(); + System.out.println(line); + System.out.println(TEXT_PARSE_ERROR); + } + return action; + } + + + /** + * @param br + * @param userinfo + * @param overRide 覆盖之前的状态表 + * @return + * @throws IOException + */ + public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide){ + String line = "", infoName, extraElements[]; + HashMap> conditionTable = null; + + //是否覆盖原有的数据 + if (overRide) { + conditionTable = new HashMap>(); + userinfo.id2condition.clear(); + userinfo.id2config.clear(); + userinfo.configStr = ""; + userinfo.varInitialMap.clear(); + userinfo.name2condition.clear(); + + } else { + conditionTable = userinfo.conditionTable; + } + + List actionList = null; + + + try{ + while ((line = br.readLine()) != null) { + if (line.trim().equals("")) + continue; + line = line.replace("\n", ""); + + //在用户信息中添加额外信息,如设为active的action + if (line.contains("extraInfo")) { + extraElements = line.split("\\|", -1); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + } else if (line.contains("varInitial")) { + extraElements = line.split("\\|", -1); + userinfo.varInitialMap.put(extraElements[1], extraElements[2]); + } else { + Action action = new Action(); + action = buildCondition(action, line); + actionList = conditionTable.get(action.getIndexName()); + if (actionList == null) + actionList = new ArrayList(); + actionList.add(action); + conditionTable.put(action.getIndexName(), actionList); + if (action.getId() != 0) { + if (!action.getConfigName().equals("")) { + userinfo.name2condition.put(action.getConfigName(), action); + } + userinfo.id2config.put(action.getId(), line); + userinfo.id2condition.put(action.getId(), action); + } + + } + } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(TEXT_PARSE_ERROR); + + //e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + System.out.println(line); + } + + + userinfo.conditionTable = conditionTable; + + return userinfo; + } + + /** + * 通过split方法解析配置文件中的条件部分(如:xihuan::match-Include=+dota+英雄联盟) + * + * @param premiseMap 前提条件哈希表 + */ + public static void insertPremise(HashMap> premiseMap, String[] premisesString) { + String pair[]; + HashSet keyWordSet = null; + for (String premise : premisesString) { + // System.out.println(premise); + if (premise.equals("") || premise.equals(" ")) + continue; + pair = premise.split("=", 2); + keyWordSet = new HashSet(); + for (String keyword : pair[1].split("\\+")) + //为了处理条件不满足(为空)时的特殊情况, + if (keyword.equals("null")) keyWordSet.add(""); + else if (!keyword.equals("")) keyWordSet.add(keyword); + premiseMap.put(pair[0], keyWordSet); + } + } + + + /** + * 原为通过用户chat_key从数据库中获得用户名 + * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) + * 如果context中没有,就重新加载本地配置文件(即初始化) + * 初始化后还是没有就创建一个userinfo + * ------------- + * 修改后直接从request获得用户名,并从context根据用户名获得userinfo + * + * @param bot_name 用户名 + * @return 用户信息 + */ + public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException { + + String botAccount = bot_name; + UserInfo userinfo = null; + if (context.getAttribute(botAccount) == null) { + userinfo = userConfigInit(botAccount, context); + } else { + userinfo = (UserInfo) context.getAttribute(botAccount); + } + + return userinfo; + } + + + public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { + int id = Integer.parseInt(configId); + Action action = new Action(); + UserInfoController userInfoController = new UserInfoController(); + + String conditionNameList[] = data.split(","); + String conditionName = ""; + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userInfo = (UserInfo) context.getAttribute(userName); + + if (userInfo.id2config.containsKey(id)) { + Action oldAction = userInfo.id2condition.get(id); + //------------------- + conditionName = oldAction.getIndexName(); + + + + if (userInfo.conditionTable.get(conditionName) != null) { + List actionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Action c = condIter.next(); + if (c.getId() == id) { + condIter.remove(); + } + } + } + + userInfo.name2condition.remove(oldAction.getConfigName()); + userInfo.id2config.remove(id); + userInfo.id2condition.remove(id); + } else { + System.out.println("未找到要删除的configId"); + } + + return true; + } + + public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { + String conditionName = ""; + + for (int configId : idGroup) { + if (userInfo.id2config.containsKey(configId)) { + Action oldAction = userInfo.id2condition.get(configId); + + conditionName = oldAction.getIndexName(); + + + + if (userInfo.conditionTable.get(conditionName) != null) { + List actionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Action c = condIter.next(); + if (c.getId() == configId) { + condIter.remove(); + } + } + } + + userInfo.name2condition.remove(oldAction.getConfigName()); + userInfo.id2config.remove(configId); + userInfo.id2condition.remove(configId); + } else { + System.out.println("未找到要删除的configId:" + configId); + } + } + + + return true; + } + + + public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { + Action action = new Action(); + String dataPair[] = data.split("---"); + String configLine = dataPair[0]; + UserInfoController userInfoController = new UserInfoController(); + int id = Integer.parseInt(configId); + + + + action = userInfoController.buildCondition(action, configLine); + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + if (userinfo.conditionTable.get(action.getIndexName()) == null) { + List actionList = new ArrayList(); + userinfo.conditionTable.put(action.getIndexName(), actionList); + } + + if(!action.getConfigName().equals("")){ + userinfo.name2condition.put(action.getConfigName(), action); + } + userinfo.conditionTable.get(action.getIndexName()).add(action); + userinfo.id2config.put(id, configLine); + userinfo.id2condition.put(id, action); + + return true; + + } + + public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { + Action action = new Action(); + //data=configLine+"---"+conditionNameList + String dataPair[] = data.split("---", -1); + String name = dataPair[0], value = dataPair[1]; + + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.put(name, value); + + + return true; + + } + + public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { + //data=configLine+"---"+conditionNameList + String name = data; + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.remove(name); + + + return true; + + } + + + public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + String extraElements[] = data.split("\\|"); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + + return true; + } + + + public static String writeConfigText(String userName, UserInfo userinfo){ + + String path = System.getProperty("user.dir") + "/" + CONFIG_DIR + userName + ".txt"; + String returnMessage = "success"; + FileWriter fw = null; + BufferedWriter bw = null; + + try { + File file = new File(path); + File dir = new File(System.getProperty("user.dir") + "/" + CONFIG_DIR); + + + + if (!dir.exists()) + dir.mkdir(); + if (!file.exists()) { + file.createNewFile(); + } + + fw = new FileWriter(file); + bw = new BufferedWriter(fw); + + Iterator keyIter = userinfo.extraInfo.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + if (!userinfo.extraInfo.get(info).equals("")) + bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); + } + + keyIter = userinfo.varInitialMap.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); + } + + Iterator idIter = userinfo.id2config.keySet().iterator(); + while (idIter.hasNext()) { + int id = idIter.next(); + bw.write(userinfo.id2config.get(id) + "\n"); + } + bw.write("\n"); + } catch (Exception e) { + e.printStackTrace(); + returnMessage = "config file write error"; + } finally { + try { + bw.close(); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return returnMessage; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java b/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java new file mode 100644 index 0000000..31ab377 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/processing/WorldController.java @@ -0,0 +1,472 @@ +package com.qiwu.chatbotbackend.processing; + + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; + +import static com.qiwu.chatbotbackend.Config.Config.*; + +public class WorldController { + public LogWriter logWriter = null; + public UserInfo userInfo = null; + + public WorldController(LogWriter logWriter, UserInfo userInfo) { + this.logWriter = logWriter; + this.userInfo = userInfo; + } + + public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ + String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr="", owner; + String namePair[] = varName.split("_"); + boolean operationFlag = true; + List textList = null; + String subValuePair[] = null; + + logWriter.record(String.format("---------------------key:%s, value:%s", varName, varValue), 0); + + String location = "", value = ""; + if(valuePair[0].startsWith("query")){ //查询专用 + String ItemName = ""; + String currentLocation; + + if(varName.startsWith("goods_")) { + currentLocation = historyInfoPoint.get("site"); + switch (valuePair[0]) { + case "queryGoodsIntro": + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]); + if(returnStr == null ) + returnStr = DONT_FOUND; + break; + + case "queryAttrByGoodsName": + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); + + if(returnStr == null) { + returnStr = DONT_FOUND; + }else{ + returnStr = userInfo.varInitialMap.get("GET_ITEM_ATTR").replace(ITEM_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value); + + } + break; + case "queryAllAttrByGoodsName": + textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); + if(textList == null || textList.size() == 0) + returnStr = DONT_FOUND; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + case "queryAroundGoodsByClassName": + textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); + if(textList == null || textList.size() == 0) + returnStr = DONT_FOUND; + else { + for (String site : textList) + returnStr += "、" + site; + returnStr = returnStr.substring(1); + } + break; + + case "queryLocationByConditionName": + // + ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName); + returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = ATTRIBUTE_HIDDEN; + } else if(returnStr.equals("是")){ + location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); + if(location == null){ + returnStr = DONT_FOUND; + }else{ + owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "owner"); + //logWriter.record(ItemName + "-owner:" + owner, 0); + + if(owner != null && !owner.equals("")){ + //如果物品的所属角色是玩家,那么回答物品在你身上 + if(owner.equals("玩家")){ + returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS"); + }else { + //不然回答物品在某个人身上 + if(userInfo.varInitialMap.get("FIND_ITEM_OWNER") == null) + userInfo.varInitialMap.put("FIND_ITEM_OWNER", FIND_ITEM_OWNER); + System.out.println("pattern:" + userInfo.varInitialMap.get("FIND_ITEM_OWNER") + ", ItemName:" + ItemName + ", owner:" + owner); + returnStr = userInfo.varInitialMap.get("FIND_ITEM_OWNER").replace(ITEM_NAME_SLOT, ItemName).replace(NPC_NAME_SLOT, owner); + } + }else { + //没有所属角色就回答物品在某个地点 + returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location); + } + } + } + break; + case "queryPlayerItems": + String player = gameEnv.queryPlayerName(); + textList = gameEnv.queryGoodsByNpcName(player); + if(textList == null || textList.size() == 0) + returnStr = NOTHING_FOUND; + else { + for (String site : textList) + returnStr += "、" + site; + + returnStr = userInfo.varInitialMap.get("WE_HAVE").replace(ITEM_LIST_SLOT, returnStr.substring(1)); + } + + break; + + + case "queryFindItemWay": + // + ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = DONT_FOUND; + } else if(returnStr.equals("是")){ + location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); + if(location == null){ + returnStr = DONT_FOUND; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_ITEM_WAY").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location); + } + } + + break; + default: + } + }else if(varName.startsWith("npc_")) { + String NPCName = ""; + switch(valuePair[0]){ + case "queryNpcIntro": + //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); + if(returnStr == null) + returnStr = DONT_FOUND; + + break; + case "queryAttrByNPCName": + //根据condition的名字,从当前信息点中获取npc的名字 + subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); + subValuePair[0] = subValuePair[0].replace("哪里", "location"); + value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); + if(value == null) { + returnStr = DONT_FOUND; + }else{ + + returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace(NPC_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value); + + } + break; + + case "queryLocationByNPCName": + // + + location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); + if(location == null){ + returnStr = DONT_FOUND; + }else{ + returnStr = location; + } + + break; + case "queryLocationByConditionName": + // + NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + NPCName = gameEnv.getNpcNameByNickname(historyInfoPoint.get("site"), NPCName); + + System.out.println(NPCName); + returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = DONT_FOUND; + } else if(returnStr.equals("是")){ + + + location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); + if(location == null){ + returnStr = DONT_FOUND; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_NPC_LOCATION").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location); + } + } + break; + + case "queryFindNPCWay": + + // + NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = DONT_FOUND; + } else if(returnStr.equals("是")){ + location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); + if(location == null){ + returnStr = DONT_FOUND; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_NPC_WAY").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location); + } + } + + break; + + case "queryLastTalker": + String lastTalker = "没找到npc名字"; + Matcher m = GameBotUtil.findTalker(historyInfoPoint.get("lastReply")); + while(m.find()){ + lastTalker = m.group(1); + } + + returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace(NPC_NAME_SLOT, lastTalker); + break; + + + + default: + } + }else if (varName.startsWith("map_")) { + String format = ""; + String start = historyInfoPoint.get("site"); + String destination = ""; + List sites = new ArrayList<>(); + + switch (valuePair[0]) { + case "queryAroundAllBySite": + format = userInfo.varInitialMap.get("AROUND_THINGS"); + + + + sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) + returnStr = NOTHING_FOUND; + else { + + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + + returnStr = format.replace(NPC_ITEM_LIST_SLOT, text.substring(1)); + } + break; + case "queryAroundNpcBySite": + format = userInfo.varInitialMap.get("AROUND_PEOPLE"); + + + sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) + returnStr = NOTHING_FOUND; + else { + + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + + returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); + } + break; + case "queryAroundGoodsBySite": + + format = userInfo.varInitialMap.get("AROUND_ITEMS"); + + sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) + returnStr = NOTHING_FOUND; + else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace(ITEM_LIST_SLOT, text.substring(1)); + } + } + break; + case "queryCanGoBySite": + + format = userInfo.varInitialMap.get("CAN_GO_SITES"); + + sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); + if(sites == null) { + returnStr = userInfo.varInitialMap.get("CAN_GO_NOWHERE"); + } + else if(sites.size() == 0){ + returnStr = userInfo.varInitialMap.get("CAN_GO_NOWHERE"); + } else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace(CAN_GO_SITE_SLOT, text.substring(1)); + } + } + break; + + case "queryHowToPathBySite": + format = userInfo.varInitialMap.get("PATH_EXIST"); + + if(!currentInfoPoint.containsKey(valuePair[1])) { + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); + break; + } + destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; + destination = gameEnv.getPlaceNameByNickname(start, destination); + + sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), destination); + if(sites == null) { + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; + } + else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); + } + } + break; + + case "queryToDoPathBySite": + format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT"); + + destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; + destination = gameEnv.getPlaceNameByNickname(start, destination); + + if(!currentInfoPoint.containsKey(valuePair[1])) { + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; + break; + } + + sites = gameEnv.queryPathBySite(start, destination); + if(sites == null) { + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; + } else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); + } + } + break; + + case "queryPathNotExist": + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; + break; + case "queryAroundPlace": + + format = userInfo.varInitialMap.get("AROUND_PLACE"); + + + sites = gameEnv.queryCanGoBySite(start); + if(sites == null || sites.size() == 0) { + returnStr = NOWHERE_CAN_GO; + } else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace(SITE_LIST_SLOT, text.substring(1)); + } + } + break; + case "queryInnerNpcBySite": + format = userInfo.varInitialMap.get("INNER_PEOPLE"); + + + sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) + returnStr = NOTHING_FOUND; + else { + + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + + returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); + } + break; + + case "queryTaskDescription": + format = userInfo.varInitialMap.get("TASK_DESCRIPTION"); + + + returnStr = format.replace(TASK_DESCRIPTION_SLOT, userInfo.varInitialMap.get(TASK_DESCRIPTION)); + + break; + case "queryWhereIam": + returnStr = userInfo.varInitialMap.get("WHERE_I_AM").replace(SITE_SLOT, historyInfoPoint.get("site")); + break; + case "queryPathAt": + returnStr = userInfo.varInitialMap.get("PATH_AT").replace(SITE_SLOT, historyInfoPoint.get("site")); + break; + case "queryPathAdjoin": + returnStr = userInfo.varInitialMap.get("PATH_ADJOINT"); + break; + case "queryItemsInPlace": + break; + case "queryNPCInPlace": + break; + case "queryThingsInPlace": + break; + + } + + } + }else if(valuePair[0].startsWith("updateFollowerLocation")){ + Boolean flag = true; + switch (valuePair[0]) { + case "updateFollowerLocation": + flag = gameEnv.updateFollowerLocation(valuePair[1]); + + } + + if(flag){ + returnStr = "更新成功"; + }else + returnStr = "更新失败"; + + }else{ //增删改统一使用 + logWriter.record("更新环境--varName:" + varName + "valuePair:" + valuePair[0] + ":" + valuePair[1], 1); + try { + gameEnv.CUD(varName, valuePair[0], valuePair[1]); + } catch (Exception e){ + System.out.println("更新环境出现异常--varName:" + varName + "valuePair:" + valuePair[0] + ":" + valuePair[1]); + } + } + + + logWriter.record("---------------------return:" + returnStr, 0); + return returnStr; + } + + public static String findLocationName(GameEnv gameEnv, String locationName, String site){ + return gameEnv.getPlaceNameByNickname(site, locationName); + } + + + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java new file mode 100644 index 0000000..e261b5a --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/FindCacheServlet.java @@ -0,0 +1,55 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(name = "FindCacheServlet", urlPatterns = {"/findChatCache"}) +public class FindCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ServletContext context = this.getServletContext(); + + request.setCharacterEncoding("UTF-8"); + + String userKey = request.getParameter("client_id"); + String botAccount = request.getParameter("aipioneer_username"); + Boolean exist = false; + + try { + + exist = ChatCacheController.findChatCache(userKey, context); + } catch (Exception e) { + e.printStackTrace(); + } + + JSONObject responseJSONObject = new JSONObject(); + responseJSONObject.put("exist", exist); + responseJSONObject.put("aipioneer_username", botAccount); + responseJSONObject.put("client_id", userKey); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + response.setHeader("Access-Control-Allow-Origin", "*"); + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java new file mode 100644 index 0000000..2b0e3c2 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GameDesignServlet.java @@ -0,0 +1,377 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; +import com.qiwu.chatbotbackend.actiongenerate.entity.IntervalStatus; +import com.qiwu.chatbotbackend.actiongenerate.utils.ActionUtils; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTermText; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.gameDesign.*; +import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.SimpleUtil; +import com.qiwu.chatbotbackend.processing.UserInfoController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +import static com.qiwu.chatbotbackend.Config.Config.GAME_CONDITION_CATEGORY; +import static com.qiwu.chatbotbackend.Config.Config.GAME_WELCOME_TEXT; + + +@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) +public class GameDesignServlet extends HttpServlet { + + String POST_URL = "http://localhost:1111/conditionProcess"; + String KEYWORD_DIR = "keywords.txt"; + //分组及其相应的id,id初始化为0, 新建分组成功后id会更新。 + HashMap categoryMap = new HashMap(){ + { + put("地图", 0); + put("剧情", 0); + put("物品", 0); + put("NPC", 0); + put("全局变量", 0); + } + }; + + + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS"); + StringBuffer timeUsedDetect = new StringBuffer(); + LocalDateTime ldt = LocalDateTime.now(); + String now = ldt.format(dtf); + timeUsedDetect.append("接收请求的时间:").append(now); + + //所有需要修改的词性 + StringBuffer POS = new StringBuffer(); + + //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等,格式为: "conditionName_tail/head":"keywords" + HashMap> additionalKeywords = new HashMap>(); + + //预先定义好的所有condition相关的关键词,格式为 "conditionName_标签":"keywords" + Map keywordMap = new HashMap(); + + //特定的relation的三元组不会被添加到relationKeywords + HashSet exceptRelation = new HashSet(); + + + Integer botId, projectId, dataId, returnStatus = 1; + String botAccount = null, userName, botName, moduleName2, returnMessage = "Success"; + ServletContext context = this.getServletContext(); + JSONObject json = null, root = null; + Boolean flag; + SqlHelper helper = null; + List idList = new ArrayList<>(); + ElementConstructor constructor = new ElementConstructor(); + + try { + helper = new SqlHelper(); + + + //读取并解析json数据 + String jsonStr = SimpleUtil.readJSONString(request); + + + if (jsonStr != null && !jsonStr.equals("")) { + JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); + dataId = (Integer) receiveParaneters.get("id"); + + JSONObject gameElements = helper.queryGameElementsByBotId(dataId); + + gameElements.put("auth", request.getHeader("authorization")); + //System.out.println(gameElements.toJSONString()); + botId = (Integer)gameElements.get("botId"); + botAccount = (String) gameElements.get("botAccount"); + userName = (String)gameElements.get("userName"); + botName = (String)gameElements.get("botName"); + + + //假设重建用户信息 + if (context.getAttribute(botAccount) == null) { + UserInfoController.userConfigInit(botAccount, context); + } + + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + + + //清空之前生成的配置条目 + flag = botInit(botId, botAccount, userinfo, helper); + + + StringBuffer mergedConfigText = new StringBuffer(); + int skipCount = 0; + + + //从文件中读取condition相关的关键词 + readKeywords(keywordMap, KEYWORD_DIR); + + + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n,预处理之后:").append(now); + String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; + for(String moduleName: moduleList){ + + switch (moduleName) { + case "map": + moduleName2 = "地图"; + constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "plots": + moduleName2 = "剧情"; + constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + + root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); + break; + case "goods": + moduleName2 = "物品"; + constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "globalVariable": + moduleName2 = "全局变量"; + constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + case "npc": + moduleName2 = "NPC"; + constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); + break; + default: + continue; + + } + + if (constructor.getOperationStatus() == 1) { + + //先清空再插入 + idList.clear(); + helper.batchInsertVariableByBotId(botId, constructor); + + List jsonList = new ArrayList(); + for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ + json = configTermText.toJson(constructor.getConditionDescription()); + constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); + jsonList.add(json); + } + + + helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); + constructor.postProcessing(idList, categoryMap.get(moduleName2)); + constructor.generateConfigText(idList); + + mergedConfigText.append(constructor.getConfigText()); + }else { + returnStatus = 0; + returnMessage = constructor.getMessage(); + break; + } + + ldt = LocalDateTime.now(); + now = ldt.format(dtf); + timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); + + } + + if(returnStatus == 1) { + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求预处理:").append(now); + StringReader sr = new StringReader(mergedConfigText.toString()); + BufferedReader br = new BufferedReader(sr); + //System.out.println(mergedConfigText.toString()); + UserInfoController.buildUserInfo(br, userinfo, true); + context.setAttribute(botAccount, userinfo); + UserInfoController.writeConfigText(botAccount, userinfo); + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求前:").append(now); + IntervalStatus generateResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS, helper); + + // ldt = LocalDateTime.now(); + // now = ldt.format(dtf); + // timeUsedDetect.append("\n发送post请求后:").append(now); + + if(generateResult.getStatus() != 1){ + returnStatus = 0; + returnMessage = generateResult.getMessage(); + } + } + + helper.destroy(); + + + + + }else { + returnStatus = 0; + returnMessage = "请求解析失败"; + } + } catch (SQLException e) { + e.printStackTrace(); + } + + + + System.out.println(timeUsedDetect.toString()); + + + JSONObject responseJSONObject = new JSONObject(); + responseJSONObject.put("status", returnStatus); + responseJSONObject.put("message", returnMessage); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + } + + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + OutputStream out = response.getOutputStream(); + out.write("ssss".getBytes()); + out.flush(); + } + + public boolean botInit(int botId, String botAccount, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { + boolean deleteConfigFlag = helper.deleteConfigByBotId(botId); + boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); + boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); + boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); + boolean deleteArchiveFlag = ChatCacheController.deleteChatCache(helper, botAccount); + + + return deleteConfigFlag && deleteVariableFlag; + } + + + /** + * 重新生成action文本 + * @param root + * @param gameElements + * @param userInfo + * @param additionalKeywords + * @param exceptRelation + * @param POS + * @return + */ + public IntervalStatus actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS, SqlHelper helper){ + String startCondition, POS2 = "", botName = gameElements.getString("botName"); + System.out.println(botName); + JSONObject returnMessage = null; + EngineUtils engine = null; + IntervalStatus intervalStatus = new IntervalStatus(1, ""); + + JSONObject actionPostData = new JSONObject(); + + startCondition = (String)root.get("conditionName"); + actionPostData.put("startCondition", "start_options"); + actionPostData.put("welcome", String.format(GAME_WELCOME_TEXT, gameElements.getString("botName"))); + actionPostData.put("relationKeywords", additionalKeywords); + actionPostData.put("botId", gameElements.getInteger("botId")); + + if(gameElements.getJSONArray("conditionCategoryIdList") != null){ + actionPostData.put("conditionCategories", gameElements.getJSONArray("conditionCategoryIdList")); + }else{ + actionPostData.put("conditionCategories", new JSONArray(){ + { + add(GAME_CONDITION_CATEGORY); + } + }); + } + + + + if (gameElements.containsKey("POS")) + POS2 = (String)gameElements.get("POS"); + actionPostData.put("POS", POS.toString() + POS2); + + System.out.println(actionPostData.toJSONString()); + + try { + engine = new EngineUtils(); + ActionUtils actionUtils = new ActionUtils(engine, helper); + actionUtils.gamePlotInit(botName, gameElements.getInteger("botId"), gameElements.getString("auth"), actionPostData, startCondition, additionalKeywords); + intervalStatus = actionUtils.intervalStatus; + }catch(Exception e){ + e.printStackTrace(); + intervalStatus = new IntervalStatus(0, "action生成失败"); + }finally { + engine.destroy(); + } + + userInfo.extraInfo.put("activeAction", startCondition); + + return intervalStatus; + + } + + + //从配置文件中读取生成状态表所需要的关键词 + public void readKeywords(Map keywordsMap, String path){ + + File file = new File(path); + String line, elem[]; + + if(file.exists()){ + FileReader reader = null; + try { + reader = new FileReader(file); + BufferedReader br = new BufferedReader(reader); + + + while ((line = br.readLine()) != null) { + if(!line.equals("") && !line.startsWith("#")) { + elem = line.split("\\|", 3); + + //查看意图是否已经存在相关的condition,如果已经存在就append,如果不存在就初始化 + if (!elem[1].equals("pattern")) { + if (keywordsMap.get(elem[0]) == null) { + keywordsMap.put(elem[0], new StringBuffer(elem[1])); + } else { + keywordsMap.get(elem[0]).append(",").append(elem[1]); + } + } + + //根据意图和condition名字添加关键字 + keywordsMap.put(elem[0] + "_" + elem[1], new StringBuffer(elem[2])); + + } + + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + } + + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java new file mode 100644 index 0000000..58d9609 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GetAnswerServlet.java @@ -0,0 +1,208 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.*; +import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; + +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.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import static com.qiwu.chatbotbackend.Config.Config.*; +import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2; + + +@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) +public class GetAnswerServlet extends HttpServlet { + /** + * GetAnswerServlet就是处理post请求并返回答案的入口 + */ + + + //String LOG_PATH = "/home/hxw/source/logs/"; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + Map receiveParamters = new HashMap<>(request.getParameterMap()); + Map curInfoPoint = new HashMap(); + + Solution bestMatch = null; + BasicBotUtil botUtil = null; + Action ansAction = null; + boolean debugFlag = false; + String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; + String botName = receiveParamters.get("bot_name")[0]; + + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); + + //如果有client_id,会用@分隔 + chatKey = receiveParamters.get("chat_key")[0]; + String chatKeys[] = receiveParamters.get("chat_key")[0].split(COMBINE_PUNC2); + if(chatKeys.length == 1){ + userKey = chatKeys[0]; + randKey = chatKeys[0]; + }else{ + userKey = chatKeys[0]; + randKey = chatKeys[1]; + } + + receiveParamters.put("userKey", new String[]{userKey}); + receiveParamters.put("randKey", new String[]{randKey}); + + + + try { + LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); + + + UserInfo userinfo = null; + UserInfoController uiController = new UserInfoController(); + + userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); + + + if (userinfo != null) { + //获得用户历史信息 + ChatCache chatCache = null; + Boolean loadCacheStatus = Boolean.valueOf(false); + + if (userinfo.varInitialMap.get("botType") != null) + botType = userinfo.varInitialMap.get("botType"); + + + chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); + + if (chatCache == null) { + throw (new Exception("chatCache初始化失败")); + } + + + /** + * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) + * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 + */ + + //historyInfoPoint = chatCache.getInfoPoint(); + + + switch (botType) { + case "game": + WorldController worldController = new WorldController(logWriter, userinfo); + botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController); + break; + default: + botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); + break; + } + + //针对不同游戏类型对信息点做预处理 + debugFlag = botUtil.preprocessing(receiveParamters, context); + + + //信息点预处理 + ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil); + + + /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/ + ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); + if (state.equals("") && ansAction.getPriority() == -1) + state = INTENT_NOT_UNDERSTAND; + if (state.equals("")) { + try { + bestMatch = matcher.getSolution(ansAction, context, userinfo); + + + if (!botUtil.getChatCache().getReload()) { + //读档成功不应该再激活 + //if(matcher.) + if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); + } + } else { + //跳过 + botUtil.getChatCache().setReload(false); //清楚标识 + } + + } catch (ParseException e) { + e.printStackTrace(); + } + } else { + bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction")); + } + + + //针对不同bot类型做后处理 + botUtil.postprocessing(chatKey, context, bestMatch); + + botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); + if (debugFlag) { + matcher.appendDebugInfo(bestMatch, context); + } + + + //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) + matcher.infoTransfer(bestMatch, context, debugFlag); + + + ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); + //清理超时的用户数据 + if (context.getAttribute("cacheUpdateTime") == null) + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { + ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + } + + + ansJ = SimpleUtil.toJson(bestMatch); + } else { + ansJ = CONFIG_FILE_NOT_FOUND; + } + out.write(ansJ.getBytes()); + + logWriter.writeln(); + logWriter.writeln(); + logWriter.record("-----------------------------------------对话处理结束", 0); + logWriter.writeln(); + logWriter.writeln(); + logWriter.close(); + }catch (Exception e){ + JSONObject errorData = new JSONObject(){ + { + put("solution", PROGRAM_ERROR); + put("status", 1); + } + }; + e.printStackTrace(); + out.write(errorData.toJSONString().getBytes()); + + } + + + + System.out.println(ansJ); + + out.flush(); + + } + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + System.out.println("do get method"); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java new file mode 100644 index 0000000..72639e3 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/GetConfigServlet.java @@ -0,0 +1,44 @@ +package com.qiwu.chatbotbackend.servlet; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; + +@WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"}) +public class GetConfigServlet extends HttpServlet { + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String userName = request.getParameter("userName"); + + String path = "config/" + userName + ".txt"; + File file = new File(path); + OutputStream out = response.getOutputStream(); + + + if (file.exists()) { + + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + String line; + while ((line = br.readLine()) != null) { + line = line + "\n"; + out.write(line.getBytes()); + } + + + fr.close(); + br.close(); + } else { + out.write("查无此bot".getBytes()); + } + out.flush(); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java b/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java new file mode 100644 index 0000000..d74a2da --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/servlet/SaveChatCacheServlet.java @@ -0,0 +1,61 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Map; + +@WebServlet(name = "SaveChatCacheServlet", urlPatterns = {"/saveChatCache"}) +public class SaveChatCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + String chatKey = request.getParameter("chatKey"), message = ""; + ServletContext context = this.getServletContext(); + chatKey = chatKey.split("@@@@")[0]; + Boolean flag = false; + + Map chatCacheMap = (Map)context.getAttribute("chatCache"); + ChatCache chatCache = chatCacheMap.get(chatKey); + + + if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { + flag = ChatCacheController.saveChatCache(chatCache, null); + chatCacheMap.remove(chatKey); + } + + System.out.println("调用接口删除" + chatKey); + + + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + PrintWriter out = response.getWriter(); + + JSONObject retData = new JSONObject(); + retData.put("status", flag); + System.out.println("xx:" + retData.toJSONString()); + out.append(retData.toJSONString()); + out.flush(); + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + doPost(request, response); + } + +} + + diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java new file mode 100644 index 0000000..0578adc --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/BasicBotUtil.java @@ -0,0 +1,226 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.LogWriter; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class BasicBotUtil { + Map curInfoPoint = null; + UserInfo userinfo = null; + LogWriter logWriter = null; + ChatCache chatCache = null; + + public String botType = "basic"; + + + public ChatCache getChatCache() { + return chatCache; + } + + public BasicBotUtil(){}; + public BasicBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter){ + this.curInfoPoint = curInfoPoint; + this.userinfo = userinfo; + this.logWriter = logWriter; + this.chatCache = chatCache; + } + + public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { + return infoPointPreprocessing(receiveParameters, context, true); + + + } + + //在接收到请求后对数据做处理,转化为系统可以处理的数据 + + /** + * + * @param receiveParameters + * @param context + * @param setUnknown 如果什么都没识别到就将上一个激活的condition设为unknown + * @return + * @throws IOException + */ + public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context, Boolean setUnknown) throws IOException { + + String return_str = "", k, botType = ""; + String receiveParameterStr = ""; + boolean debugFlag = false; + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("randKey"); + add("userKey"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + + //输出所有actionName的值 + Iterator iit = receiveParameters.keySet().iterator(); + receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; + while (iit.hasNext()) { + k = iit.next(); + // + receiveParameterStr += k + ": "; + curInfoPoint.put(k, receiveParameters.get(k)[0]); + + if (k.equals("debug_mode") || k.equals("debug_rule")) + debugFlag = true; + + String values[] = receiveParameters.get(k); + + receiveParameterStr += values[0] + " " + "
"; + + if (values[0].equals(":")) { + curInfoPoint.put(k, ""); + } + } + logWriter.record(receiveParameterStr, 0); + System.out.println(receiveParameterStr.toString()); + + //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown + iit = curInfoPoint.keySet().iterator(); + boolean unknown_flag = setUnknown; + while (iit.hasNext()) { + k = iit.next(); + String values = curInfoPoint.get(k); + if (skipSet.contains(k)) + continue; + if (!values.equals("")) { + unknown_flag = false; + break; + } + } + + String currentAction = ""; + if (chatCache.getInfoPoint().containsKey("currentAction")) + currentAction = chatCache.getInfoPoint().get("currentAction"); + else if (userinfo.extraInfo.containsKey("activeAction")) { + currentAction = userinfo.extraInfo.get("activeAction"); + chatCache.getInfoPoint().put("currentAction", currentAction); + } else + currentAction = " "; + + + curInfoPoint.put("emptySet", " "); + if (chatCache.getInfoPoint().get("activeList") == null) { + chatCache.getInfoPoint().put("activeList", currentAction); + } + + if (unknown_flag && !currentAction.equals("")) { + String i = "unknown"; + curInfoPoint.put(currentAction, i); + } + + logWriter.record("historyInfoPoint:" + chatCache.getInfoPoint().toString(), 1); + + + + return debugFlag; + } + + public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + if(chatCache.getInfoPoint().get("error_message") != null && chatCache.getInfoPoint().get("error_message") != ""){ + bestMatch.setAnswer(bestMatch.getAnswer() + chatCache.getInfoPoint().get("error_message")); + } + + + return true; + } + + + /** + * 从当前信息点或者已知信息点中提取关键词 + * @param infoPoint + * @param infoPoint2 + * @param chooseLater + * @param actionName + * @return + */ + public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ + String keyword = ""; + String nameSeries[] = actionName.split("_"); + + /** + * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 + */ + if(chooseLater){ + keyword = infoPoint2.get(actionName); + if(keyword != null && !keyword.equals("")) + return keyword; + } + keyword = infoPoint.get(actionName); + + + return keyword; + }; + + /** + * 更新历史信息点中的某一个键值对 + * @param variableName + * @param updateValue + */ + public void putKeyword(String variableName, String updateValue){ + chatCache.getInfoPoint().put(variableName, updateValue); + } + + public String knowledgeProcess(String variableName, String updateValue){ + return updateValue; + + } + + /** + * 额外的更新操作 + */ + public void extraOperation(Action ansAction, Solution solution) throws IOException { + + } + + //将文本中存在的变量槽位{npc_xxx}替换成变量值 + public String varSlotReplace(String text){ + + String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 + String keyword, variable,reply = text; + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1).substring(1, m.group(1).length() - 3); + if (m.group(1).endsWith("-1}")) { + if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) { + keyword = curInfoPoint.get(variable); + + + if(keyword.contains(":")) + keyword = keyword.split(":")[1]; + + reply = reply.replace("{" + variable + "-1}", keyword); + } + } else if (m.group(1).endsWith("-2}")) { + if (chatCache.getInfoPoint().get(variable) != null) + if(chatCache.getInfoPoint().get(variable).equals("do_reset")){ + reply = reply.replace("{" + variable + "-2}", ""); + }else + reply = reply.replace("{" + variable + "-2}", chatCache.getInfoPoint().get(variable)); + } + } + + return reply; + } +} diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java new file mode 100644 index 0000000..5471da6 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextDestroyListener.java @@ -0,0 +1,58 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; +import java.io.IOException; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Map; + +@WebListener +public class ContextDestroyListener implements ServletContextListener { + + public void contextDestroyed(ServletContextEvent sce) { + System.out.println("destory context...."); + /** + * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 + */ + + String chatKey; + ServletContext servletContext = sce.getServletContext(); + Object obj = servletContext.getAttribute("chatCache"); + ChatCache cache = null; + SqlHelper helper = null; + + if(obj != null){ + Map chatCacheMap = (Map)obj; + + Iterator cacheIter = chatCacheMap.keySet().iterator(); + try { + helper = new SqlHelper(); + while (cacheIter.hasNext()) { + chatKey = cacheIter.next(); + cache = chatCacheMap.get(chatKey); + + //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 + if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { + System.out.println(String.format("saving %s", chatKey)); + ChatCacheController.saveChatCache(cache, helper); + } + } + cacheIter.remove(); + helper.destroy(); + + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java new file mode 100644 index 0000000..f4f93c5 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/ContextInitialListener.java @@ -0,0 +1,30 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.qiwu.chatbotbackend.Config.ConfigInitializer; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class ContextInitialListener implements ServletContextListener { + String CONFIG_DIR = "config.txt"; + + /** + * 在程序初始化时,从配置文件中加载数据 + * @param sce + */ + public void contextInitialized(ServletContextEvent sce) { + System.out.println("Initial context...."); + + //Config config = new Config(); + ConfigInitializer.init(); + + + + + + + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java new file mode 100644 index 0000000..91bfd1e --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/DataDeliver.java @@ -0,0 +1,34 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.processing.SimpleUtil; + +import java.io.UnsupportedEncodingException; + +import static com.qiwu.chatbotbackend.Config.Config.CC_URL; + +public class DataDeliver extends Thread { + + JSONObject data = null; + String url = CC_URL; + + public void setData(JSONObject data) { + this.data = data; + } + + + + + public void run() + { + System.out.println("线程开始"); + System.out.println(url); + try { + SimpleUtil.postJSON(CC_URL, data, null); + System.out.println("线程完成"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java new file mode 100644 index 0000000..db2c1ef --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/FileFinder.java @@ -0,0 +1,123 @@ +package com.qiwu.chatbotbackend.task.utils; + + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC1; + +/** + * 实现一个支持通配符的基于广度优先算法的文件查找器 + */ +public class FileFinder { + + /** + * 查找文件。 + * @param baseDirName 待查找的目录 + * @param targetFileName 目标文件名,支持通配符形式 + * @return 满足查询条件的文件名列表 + */ + public static List findFiles(String baseDirName, String targetFileName) { + + String tempName; + List fileList = new ArrayList(); + //判断目录是否存在 + File baseDir = new File(baseDirName); + if (!baseDir.exists() || !baseDir.isDirectory()){ + System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); + return fileList; + } + + File[] files = baseDir.listFiles(); + for (int i = 0; i < files.length; i++) { + //如果是目录则放进队列 + if (files[i].isDirectory()) { + continue; + } else { + //如果是文件则根据文件名与目标文件名进行匹配 + tempName = files[i].getName(); + if (FileFinder.wildcardMatch(targetFileName, tempName)) { + //匹配成功,将文件名添加到结果集 + fileList.add(files[i]); + } + } + } + + return fileList; + } + /** + * 通配符匹配 + * @param pattern 通配符模式 + * @param str 待匹配的字符串 + * @return 匹配成功则返回true,否则返回false + */ + private static boolean wildcardMatch(String pattern, String str) { + int patternLength = pattern.length(); + int strLength = str.length(); + int strIndex = 0; + char ch; + for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) { + ch = pattern.charAt(patternIndex); + if (ch == '*') { + //通配符星号*表示可以匹配任意多个字符 + while (strIndex < strLength) { + if (wildcardMatch(pattern.substring(patternIndex + 1), + str.substring(strIndex))) { + return true; + } + strIndex++; + } + } else if (ch == '?') { + //通配符问号?表示匹配任意一个字符 + strIndex++; + if (strIndex > strLength) { + //表示str中已经没有字符匹配?了。 + return false; + } + } else { + if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) { + return false; + } + strIndex++; + } + } + return (strIndex == strLength); + } + + public static boolean deleteGameArchive(String baseDirName, String botAccount){ + + String tempName; + String regEx = ".*" + COMBINE_PUNC1 + botAccount + "-.*"; + List fileList = new ArrayList(); + Pattern pattern = Pattern.compile(regEx); + Matcher matcher = null; + //判断目录是否存在 + File baseDir = new File(baseDirName); + if (!baseDir.exists() || !baseDir.isDirectory()){ + System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); + return false; + } + + File[] files = baseDir.listFiles(); + for (int i = 0; i < files.length; i++) { + //如果是目录则放进队列 + if (files[i].isDirectory()) { + continue; + } else { + //如果是文件则根据文件名与目标文件名进行匹配 + tempName = files[i].getName(); + matcher = pattern.matcher(tempName); + if (matcher.find()) { + //匹配成功,将文件名添加到结果集 + files[i].delete(); + } + } + } + + return true; + } + +} diff --git a/src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java b/src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java new file mode 100644 index 0000000..81ed988 --- /dev/null +++ b/src/main/java/com/qiwu/chatbotbackend/task/utils/GameBotUtil.java @@ -0,0 +1,705 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.*; +import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.SimpleUtil; +import com.qiwu.chatbotbackend.processing.WorldController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.sql.SQLException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.qiwu.chatbotbackend.Config.Config.*; +import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; + +public class GameBotUtil extends BasicBotUtil{ + + WorldController worldController = null; + public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; + public static String LOAD_BY_LAST = "load_last"; + + + + + public GameBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){ + super(curInfoPoint, chatCache, userinfo, logWriter); + this.worldController = worldController; + this.botType = "game"; + + } + + + + @Override + public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { + Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); + + //将要去的地点的别名替换为真名 +// String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; +// +// for(String conditionName: conditionList) { +// +// if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { +// String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName); +// String destination = info.split(":")[1]; +// String site = historyInfoPoint.get("site"); +// try { +// newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); +// }catch(Exception e){ +// e.printStackTrace(); +// } +// +// logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); +// curInfoPoint.put(conditionName, newInfo); +// } +// } + +// historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); + + String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|"); + if(activeList.length == 0){ + chatCache.getInfoPoint().put("临时变量condition", "yaobuyao"); + }else { + chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]); + } + + + return debugFlag; + + } + + @Override + public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + + + StringBuffer finalText = new StringBuffer(); + String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~")); + //将自动跳转文本、qa文本、查询文本拼接 + String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"}; + String queryResult; + Set keepNoSpeaker = new HashSet(){ + { + add("sendData:archiveList"); + add(GAME_START_HINT); + } + }; + + chatCache.getInfoPoint().put("plot_text", plotText); + + //整合qa问答、地图、npc查询文本和剧情文本 + for(String queryName:queryList){ + queryResult = chatCache.getInfoPoint().get(queryName); + if(queryResult != null){ + if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 + //剧情可以为空,其他不行 + continue; + } + + switch (queryName){ + case "common_answer": + if(!queryResult.equals("no answer")) + finalText.append(queryResult); + break; + case "plot_jump_text": + finalText.append(queryResult); + break; + case "map_query": + case "goods_query": + case "npc_query": + case "error_message": + queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv()); + finalText.append(queryResult); + break; + case "plot_text": + if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪 + finalText.setLength(0); + finalText.append(plotText); + } + //文本为空跳过 + else if(plotText.equals("") && finalText.length() != 0){ + continue; + }else { + + //对剧情文本做处理,或者说对unknown文本做处理 + finalText.append(plotTextFilt(plotText)); + } + + break; + + + } + chatCache.getInfoPoint().put(queryName, ""); + + } + } + bestMatch.setAnswer(finalText.toString()); + + + return true; + } + + @Override + public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ + String keyword = ""; + String nameSeries[] = actionName.split("_"); + + + //变量名以npc_开头,就从游戏环境中查询相应的值 + if(actionName.startsWith("npc_")){ + if(nameSeries.length == 4){ + keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); + }else if (nameSeries.length == 3){ + if(nameSeries[1].equals("玩家") && nameSeries[2].equals("物品栏")) { + StringBuffer sb = new StringBuffer(); + List goods = chatCache.getGameEnv().queryGoodsByNpcName("玩家"); + for (String good : goods) { + sb.append("+").append(good); + } + keyword = sb.toString(); + }else{ + keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); + } + } + + }else if (actionName.startsWith("goods_")) { + if(nameSeries.length == 3) { + nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); + keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); + } + //System.out.println("return" + keyword); + + + }else if(actionName.startsWith("isNeighbour")){ + String opPair[] = actionName.split(":"); + if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ + keyword = "not_exist"; + }else { + logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); + keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); + logWriter.record("返回:" + keyword, 1); + } + }else { + + /** + * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 + */ + if(chooseLater){ + keyword = infoPoint2.get(actionName); + if(keyword != null && !keyword.equals("")) + return keyword; + } + keyword = infoPoint.get(actionName); + + } + + if(keyword == null) + keyword = ""; + + + return keyword; + }; + + @Override + public void putKeyword(String variableName, String updateValue){ + + String namePair[] = variableName.split("_"); + + + //如果变量名开头为NPC或者item,就专门交给游戏环境处理 + if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { + try { + if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { + updateValue = "update:" + updateValue; + } + variableName = variableName.replace("所属玩家", "owner"); + String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint()); + updateValue = returnStr; + } catch (Exception e) { + e.printStackTrace(); + updateValue = GAME_MODULE_ERROR; + } + } + + chatCache.getInfoPoint().put(variableName, updateValue); + } + + + public String knowledgeProcess(String variableName, String updateValue){ + String values[] = updateValue.split(":",2), returnValue; + if(values.length > 1 && values[0].equals("update")) + returnValue = values[1]; + else + returnValue = updateValue; + + return returnValue; + } + + + /** + * 主要用于游戏存档和读档 + * @param ansAction + * @param solution + * @throws IOException + */ + @Override + public void extraOperation(Action ansAction, Solution solution) throws IOException { + Boolean flag = true; + String userKey = curInfoPoint.get("userKey"); + String randKey = curInfoPoint.get("randKey"); + String keyword = "", site; + SqlHelper helper = null; + ChatCache chatCache = null; + + + try { + helper = new SqlHelper(); + + //未登录用户没有存取档的操作 + if(userKey.equals(randKey)) + return; + + if(ansAction.getFeatureMap().containsKey("newGame")) { + System.out.println("newGame"); + this.chatCache.setGameStart(true); + + + }else if (ansAction.getFeatureMap().containsKey("gameBackup")) { + + System.out.println("gameBackup"); + chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint()); + flag = ChatCacheController.saveChatCache(chatCache, null); + if(flag) + solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); + else + solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); + + } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { + + System.out.println("loadLastArchive"); + ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); + if(archiveInfo != null){ + System.out.println("存档Id" + archiveInfo.getArchiveId()); + }else{ + System.out.println("没有找到存档"); + } + loading(archiveInfo, solution); + this.chatCache.setGameStart(true); + + } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) { + + System.out.println("loadArchiveBySite"); + if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { + site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; + System.out.println("要读取的存档的地点是:" + site); + ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site); + loading(archiveInfo, solution); + this.chatCache.setGameStart(true); + }else{ + System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); + } + } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){ + + System.out.println("sendArchiveList"); + DataDeliver dataDeliver = new DataDeliver(); + JSONObject data = new JSONObject(); + List archiveList = helper.queryArchiveByUserKey(userKey); + data.put("data", JSONObject.toJSON(archiveList)); + data.put("dataType", "archiveList"); + data.put("userKey", userKey); + dataDeliver.setData(data); + dataDeliver.start(); + + solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个 + } + + } catch (SQLException e) { + + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } finally{ + helper.destroy(); + } + + } + + private void loading(ArchiveInfo archiveInfo, Solution solution) throws Exception { + String keyword = "", site; + ChatCache loadCache = null; + + + + + if (archiveInfo != null) { + + //如果存在读档,就要将自动跳转和qa的临时数据清空 + chatCache.getInfoPoint().put("plot_jump_text", ""); + chatCache.getInfoPoint().put("common_answer", ""); + + + loadCache = ChatCacheController.loadChatCache(archiveInfo); + + + //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); + this.chatCache.setInfoPoint(loadCache.getInfoPoint()); + this.chatCache.setGameEnv(loadCache.getGameEnv()); + + + System.out.println("----------读档中------------"); + site = loadCache.getInfoPoint().get("site"); + + String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site)); + String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site)); + solution.setAnswer(reply); + solution.setNext("nextStep=" + nextStep); + this.chatCache.setReload(true); + + }else{ + System.out.println("没有找到该存档"); + } + } + + + //将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版 + //@Override + public String varSlotReplace2(String text){ + String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}"; + Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); + + String varElements[] = {}, result = ""; + String keyword, variable, variableSlot, reply = text; + Matcher m = replacePattern.matcher(reply); + while (m.find()) { + variable = m.group(1); + varElements = variable.split("_"); + variableSlot = "${" + variable + "}"; + + switch (varElements[0]){ + //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 + case "globalVariable": + reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); + + case "npc": + result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]); + reply = reply.replace(variableSlot, result); + + case "goods": + result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]); + reply = reply.replace(variableSlot, result); + + case "map": + System.out.println("地图替换还没写"); + + default: + if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ + reply = reply.replace(variableSlot, curInfoPoint.get(variable)); + }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){ + reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); + } + + } + } + + return reply; + } + + + + + + public static Matcher findTalker(String reply){ + Pattern findTalker = Pattern.compile(TALKER); + Matcher m = findTalker.matcher(reply); + + return m; + } + static String findFirstTalker(String reply){ + String npc = ""; + Pattern findTalker = Pattern.compile(TALKER); + Matcher m = findTalker.matcher(reply); + + if(m.find()) { + npc = m.group(1); + } + + return npc; + } + + /** + * 查看回答文本的说话这是否在当前地点 + * 0:没有说话者 + * 1:说话者在当前地点 + * 2:说话者不在当前地点或者不能说话 + * @param reply + * @param curInfoPoint + * @param historyInfoPoint + * @param gameEnv + * @param site + * @param logWriter + * @return + */ + public static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){ + String npc, location; + + Matcher m = findTalker(reply); + int flag = 1; + if(m.find()) { + npc = m.group(1); + + location = gameEnv.queryNpcAttrByNpcName(npc, "location"); + System.out.println("location:" + location + ", npc:" + npc); + if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ + if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ + flag = 1; + logWriter.record("\"" + reply + "\":匹配", 1); + }else { + flag = 2; + logWriter.record(npc + "不能说话", 1); + } + + }else { + logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); + flag = 2; + } + }else{ + logWriter.record("\"" + reply + "\":没有npc名",1 ); + flag = 0; + } + return flag; + + } + + + /** + * 查看回答文本的说话这是否在当前地点 + * 0:没有说话者 + * 1:说话者在当前地点 + * 2:说话者不在当前地点或者不能说话 + * @param npc + * @param site + * @param onlineDetect npc是在线类型才可以通过 + * @return + */ + public Boolean canTalk(String npc, String site, Boolean onlineDetect){ + String location; + + Boolean flag = false; + location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location"); + if( location == null){ + return false; + } + if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ + if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ + + + + if(onlineDetect){ + if(isOnlineMode(npc, chatCache.getInfoPoint())){ + logWriter.record("\"" + npc + "\":匹配", 1); + flag = true; + } + }else { + flag = true; + } + }else { + logWriter.record(npc + "不能说话", 1); + } + }else { + logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 ); + } + + return flag; + + } + + + public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv){ + + return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text; + + } + + + String plotTextFilt(String reply){ + String textType, returnText = "plot text filt error", plotLastTalker; + String site = chatCache.getInfoPoint().get("site"); + + + textType = textTypeDetect(reply, site); + System.out.println("textType:" + textType); + + switch(textType){ + case "direct_return": + returnText = reply; + break; + case "less_talker": + return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv()); + case "to_unknown": + Set candidates = new HashSet(); + Map> npcTextMap = null; + String unknownList = "", foundNPC; + String fieldList[] = {"unknownTextList", "finalUnknownText"}; + String lastReply = chatCache.getInfoPoint().get("lastReply"); + + plotLastTalker = findTextLastTalker(lastReply, site); + + for(String unknownField:fieldList){ + candidates.clear(); + + if(userinfo.varInitialMap.get(unknownField) != null) { + unknownList = userinfo.varInitialMap.get(unknownField); + npcTextMap = unknownTextClassify(unknownList); + + if(!plotLastTalker.equals("")) { + candidates.add(plotLastTalker); + } + + //先找剧情相关的npc + foundNPC = foundCandidateText(candidates, npcTextMap); + if(!foundNPC.equals("")){ + returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); + break; + }else{ + //再找地点相关的npc + candidates.addAll(findRelateTalkers(true)); + foundNPC = foundCandidateText(candidates, npcTextMap); + if(!foundNPC.equals("")){ + returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); + break; + } + } + } + + } + + break; + } + + + return returnText; + + } + + public String textTypeDetect(String text, String site){ + int code = 0; + String textType = "to_unknown", npc; + + + Boolean flag = true; + + npc = findFirstTalker(text); + + if(text.equals("")){ + textType = "to_unknown"; + }else if(npc.equals("")) { + textType = "less_talker"; + }else if(canTalk(npc, site, false)){ + textType = "direct_return"; + }else{ + textType = "to_unknown"; + } + + + + + return textType; + } + + + + private static Boolean isOnlineMode(String npc, Map historyInfoPoint){ + return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); + } + + + private String findTextLastTalker(String text, String site){ + Matcher m = findTalker(text); + String npc, lastTalker = ""; + while(m.find()) { + //回答unknown文本的npc必须处于在线模式 + npc = m.group(1); + //处于离线模式 可以说话 相同地点 + if(canTalk(npc, site, true)) { + //找到最后一个说话且处于离线模式的npc + lastTalker = npc; + }else{ + System.out.println(npc + "是离线模式"); + } + } + + return lastTalker; + } + + /** + * 找到用来说话的人 + * includeSiteNPC 是否包含当前地点的npc + */ + private List findRelateTalkers(Boolean includeSiteNPC){ + String site = chatCache.getInfoPoint().get("site"); + String lastReply = chatCache.getInfoPoint().get("lastReply"); + + List talkers = new ArrayList(); + + + if(lastReply == null) lastReply = ""; + + String plotLastTalker = findTextLastTalker(lastReply, site); + if(!plotLastTalker.equals("")){ + talkers.add(plotLastTalker); + } + + if(includeSiteNPC){ + List npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site")); + for(String npc:npcList){ + if(canTalk(npc, site, true)){ + talkers.add(npc); + } + } + } + + if(talkers.size() == 0){ + talkers.add(chatCache.getInfoPoint().get(ASSISTANT)); + } + + return talkers; + } + + + + + //从unknown文本中提取npc名字 + private Map> unknownTextClassify(String unknownText){ + String talker; + Map> npcTextMap = new HashMap>(); + + for(String ans:unknownText.split("~")){ + talker = findFirstTalker(ans); + npcTextMap.putIfAbsent(talker, new ArrayList()); + npcTextMap.get(talker).add(ans); + } + + return npcTextMap; + + } + + private String foundCandidateText(Set candidates, Map> npcTextMap){ + String foundNPC = ""; + for(String npc:candidates) { + //先看剧情中最后说话的人有没有unknown文本,如果有就。。。 + if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) { + foundNPC = npc; + break; + } + } + + return foundNPC; + } + +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties new file mode 100644 index 0000000..454e52a --- /dev/null +++ b/src/main/resources/application-dev.properties @@ -0,0 +1,11 @@ +server.port=8081 +server.servlet.context-path=/bot +#启用shutdown +# management.endpoints.web.exposure.include=info, health, shutdown +# management.endpoint.shutdown.enabled=true +# spring.security.user.name=hxw +# spring.security.user.password=123 +qa.url2=http://192.168.1.87:59100/game +qa.url=http://aliyun-hz1.chewrobot.com:59100/game +test.var=111122223333 +TEST_VAR=11111 diff --git a/src/main/resources/application-pro.properties b/src/main/resources/application-pro.properties new file mode 100644 index 0000000..f266626 --- /dev/null +++ b/src/main/resources/application-pro.properties @@ -0,0 +1,8 @@ +server.port=8081 +server.servlet.context-path=/bot +#启用shutdown +# management.endpoints.web.exposure.include=info, health, shutdown +# management.endpoint.shutdown.enabled=true +# spring.security.user.name=hxw +# spring.security.user.password=123 +qa.url=http://aliyun-hz1.chewrobot.com:59100/game \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..4ad66bd --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.profiles.active=@profiles.active@ +test.var=111122223333 +TEST_VAR=11111 \ No newline at end of file diff --git a/src/main/resources/dev/c3p0-config.xml b/src/main/resources/dev/c3p0-config.xml new file mode 100644 index 0000000..4d32655 --- /dev/null +++ b/src/main/resources/dev/c3p0-config.xml @@ -0,0 +1,63 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/chatCN?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/platform?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 2 + 30 + 8 + 2 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/dev/log4j.properties b/src/main/resources/dev/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/dev/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/resources/pro/c3p0-config.xml b/src/main/resources/pro/c3p0-config.xml new file mode 100644 index 0000000..f6916a5 --- /dev/null +++ b/src/main/resources/pro/c3p0-config.xml @@ -0,0 +1,65 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/chatCN?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://localhost:3306/platform?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 3 + 30 + 10 + 3 + 200 + + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/pro/log4j.properties b/src/main/resources/pro/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/pro/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/main/resources/static/js/jquery-3.3.1.min.js b/src/main/resources/static/js/jquery-3.3.1.min.js new file mode 100644 index 0000000..4d9b3a2 --- /dev/null +++ b/src/main/resources/static/js/jquery-3.3.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w(" + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

+
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/templates/index.jsp b/src/main/resources/templates/index.jsp new file mode 100644 index 0000000..330092e --- /dev/null +++ b/src/main/resources/templates/index.jsp @@ -0,0 +1,16 @@ +<%-- + Created by IntelliJ IDEA. + User: hxw + Date: 18-5-8 + Time: 下午1:47 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + $Title$ + + +$END$ + + diff --git a/src/main/resources/templates/update.html b/src/main/resources/templates/update.html new file mode 100644 index 0000000..e102286 --- /dev/null +++ b/src/main/resources/templates/update.html @@ -0,0 +1,97 @@ + + + + 配置文件 v2.2.4 + + + + + + + +
+ +
+

用户名:

+

内 容:

+

 

+

 

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

用户名:

+

内 容:

+

关键词替换:

+

 

+ +
+ + +
+
+
+
+ + + + + + + + + diff --git a/src/main/resources/test/c3p0-config.xml b/src/main/resources/test/c3p0-config.xml new file mode 100644 index 0000000..39d0885 --- /dev/null +++ b/src/main/resources/test/c3p0-config.xml @@ -0,0 +1,33 @@ + + + + + 10 + 30 + 50 + 10 + 200 + + + + + com.mysql.jdbc.Driver + + jdbc:mysql://192.168.1.82:3306/SimplifiedBot?useUnicode=true&characterEncoding=UTF8 + + root + 3g9^pWQs#ft7 + 10 + 30 + 50 + 10 + 200 + + + + ...... + + ...... + + ...... + \ No newline at end of file diff --git a/src/main/resources/test/log4j.properties b/src/main/resources/test/log4j.properties new file mode 100644 index 0000000..6e86266 --- /dev/null +++ b/src/main/resources/test/log4j.properties @@ -0,0 +1,22 @@ +### 设置### +log4j.rootLogger=debug,stdout,D,E +### 输出信息到控制抬 ### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.Threshold=INFO +log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n +### 输出DEBUG 级别以上的日志文件设置 ### +log4j.appender.D=org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File=vincent_player_debug.log +log4j.appender.D.Append=true +log4j.appender.D.Threshold=DEBUG +log4j.appender.D.layout=org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n +### 输出ERROR 级别以上的日志文件设置 ### +log4j.appender.E=org.apache.log4j.DailyRollingFileAppender +log4j.appender.E.File=vincent_player_error.log +log4j.appender.E.Append=true +log4j.appender.E.Threshold=ERROR +log4j.appender.E.layout=org.apache.log4j.PatternLayout +log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/src/processing/ActionMatcher.java b/src/processing/ActionMatcher.java deleted file mode 100644 index bcd031f..0000000 --- a/src/processing/ActionMatcher.java +++ /dev/null @@ -1,1177 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.http.message.BasicNameValuePair; - -import javax.servlet.ServletContext; -import java.io.IOException; -import java.text.ParseException; -import java.util.*; - - -public class ActionMatcher { - - Map activatedMap = new HashMap(); - - - static String POST_DATA_ERROR = "post数据有误"; - static String POST_ERROR = "数据post时出错了"; - static String API_ERROR = "api处理过程中出错了"; - - - public LogWriter logWriter = null; - public UserInfo userinfo = null; - public ServletContext context = null; - public GameEnv gameEnv = null; - public Map curInfoPoint = null; - public Map historyInfoPoint = null; - public WorldController worldController = null; - BasicBotUtil botUtil = null; - - public ActionMatcher(Map curInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, BasicBotUtil botUtil) { - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = botUtil.getChatCache().getInfoPoint(); - this.logWriter = logWriter; - this.userinfo = userinfo; - this.context = context; - - this.worldController = new WorldController(logWriter, userinfo); - this.botUtil = botUtil; - if(botUtil.botType.equals("game")) { - this.gameEnv = botUtil.getChatCache().getGameEnv(); - } - } - - - public ActionMatcher(){ - - } - - - - /** - * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch - * - * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 - * @return bestMatch 状态表中满足条件最多的一条 - */ - public Action getBestMatch(HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { - - Integer configId = 0; - List actionList = null; - Action bestMatch = new Action(-1), iterCon; - Iterator it = curInfoPoint.keySet().iterator(); - Queue activatedQueue = new LinkedList(); - Queue activatedAction = new LinkedList(); - - - - while (it.hasNext()) { - String conditionName = it.next(); - String keywords = curInfoPoint.get(conditionName); - String keyword = null; - Boolean activateFlag = false; - Boolean replaceFlag = false; - Boolean satisfyFlag = false; - - if (keywords != null && !keywords.equals("")) - keyword = keywords; - - - if (keyword != null && conditionTable.get(conditionName) != null) { - actionList = conditionTable.get(conditionName); - - - for (Action action : actionList) { - activateFlag = false; - satisfyFlag = false; - replaceFlag = false; - if (action.getStatus().equals("waiting")){ - - logWriter.record("-----------------------------------检索到配置条目", 0); - logWriter.record(userinfo.id2config.get(action.getId()), 1); - - //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 - if (action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) { - activateFlag = true; - } - - if(higherPriority(action, bestMatch)){ - replaceFlag = true; - } - - - - //没有激活,优先级不够高,直接跳过 - if(!activateFlag && !replaceFlag){ - logWriter.record("-----------------------------------优先级不足,跳过", 0); - continue; - } - - if(conditionSatisfy(action)){ - satisfyFlag = true; - } - - - if(satisfyFlag){ - if(activateFlag){ - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); - } - if(replaceFlag){ - bestMatch = action; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); - logWriter.writeln(); - } - } - - - -// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) -// || action.featureMap.get("activate") != null){ -// if(conditionSatisfy(action)){ -// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { -// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 -// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); -// } -// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { -// bestMatch = action; -// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); -// logWriter.writeln(); -// } -// -// -// } -// -// }else { -// logWriter.record("-----------------------------------优先级不足,跳过", 0); -// logWriter.record(userinfo.id2config.get(action.id), 1); -// } -// } -// -// -// -// -// -// if (action.status.equals("waiting")){ -// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) -// || action.featureMap.get("activate") != null){ -// if(conditionSatisfy(action)){ -// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { -// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 -// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); -// } -// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { -// bestMatch = action; -// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); -// logWriter.writeln(); -// } -// -// -// } -// -// }else { -// logWriter.record("-----------------------------------优先级不足,跳过", 0); -// logWriter.record(userinfo.id2config.get(action.id), 1); -// } - } - } - } - - } - logWriter.record("----------------------匹配结束", 2); - - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); - - - return bestMatch; - } - - /** - * 在激活列表中选择满足匹配且优先级最高的一条配置条目 - * @param bestMatch - * @param activatedQueue - * @param context - * @return - * @throws IOException - */ - public Action activatedQueueMatching(Action bestMatch, Queue activatedQueue, ServletContext context) throws IOException { - Action action; - Boolean activateFlag = false; - Boolean replaceFlag = false; - Boolean satisfyFlag = false; - Boolean parentFlag = false; - - //待激活配置条目被激活后的匹配 - while (!activatedQueue.isEmpty()) { - activateFlag = false; - replaceFlag = false; - satisfyFlag = false; - parentFlag = false; - - action = activatedQueue.remove(); - activatedMap.remove(action.getId()); - - - logWriter.record("-----------------------------------检索到配置条目", 0); - logWriter.record(userinfo.id2config.get(action.getId()), 1); - - - if(higherPriority(action, bestMatch)) - replaceFlag = true; - - if(action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) - activateFlag = true; - - if(bestMatch.getNextStep().contains(String.valueOf(action.getId()))) - //现在的condition是被bestMatch这个condition激活的 - parentFlag = true; - - - //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 - if(!activateFlag && !replaceFlag && !parentFlag) { - logWriter.record("-----------------------------------优先级不足,跳过", 0); - //logWriter.record(userinfo.id2config.get(action.getId()), 1); - continue; - } - - if(conditionSatisfy(action)){ - if(activateFlag) { - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context); - } - if(replaceFlag){ - bestMatch = action; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2); - logWriter.writeln(); - } - } - - - - - } - - return bestMatch; - - } - - /** - * 根据当前信息点,历史信息点,判断是否满足该action的条件,match关键字指引擎识别的关键字包含在action相应的关键词列表中,这里可以根据特征添加其他操作。 - * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 - * - * @param action 配置文件(状态表)的一行 - * @return 满足条件就为True, 不满足就为False - */ - public boolean conditionSatisfy(Action action) { - boolean flag = true; - String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; - HashSet keywordSet = null; - - - - if (action.getFeatureMap().containsKey("match")) { - Iterator it = action.getCurrentPremise().keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - cmpType = comparePair[1]; - keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - keywordSet = action.getCurrentPremise().get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - - it = action.getHistoryPremise().keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - cmpType = comparePair[1]; - actionName = comparePair[0]; - //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.getFeatureMap().containsKey("includeCurInfo"), actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - - - keywordSet = action.getHistoryPremise().get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5); - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - } - - - return flag; - - } - - - - - /** - * 单个条件的匹配,判断是否满足条件 - * 比较类型分为 match、number、time、variable, - * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 - * - * @param keyword - * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 - * @return 返回匹配或者不匹配 - */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { - boolean flag = true; - String operator = ""; - - try { - String splitPair[] = cmpType.split("-", 2); - if (splitPair.length > 1) { - operator = splitPair[1]; - cmpType = splitPair[0]; - } - - - if (cmpType.equals("match")) { - if(operator.equals("Keyword") || operator.equals("Include")) { - if (!keywordSet.contains(keyword)) { - flag = false; - } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if (keywordSet.contains(k)) - flag = true; - } - } - } else if(operator.equals("Exclude")) { - if(keyword.contains(":")){ - String ks[] = keyword.split(":", 2); - if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) - flag = false; - }else { - if (keywordSet.contains(keyword)) { - flag = false; - } - } - }else if(operator.equals("Have")){ - for(String key:keywordSet){ - if(key.equals("")) - continue; - if(!keyword.contains(key)){ - flag = false; - break; - } - } - }else{ - flag = false; - } - - - } else if (cmpType.equals("number") && !keyword.equals("")) { - int candidateA = 0; - int candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(StringUtils.isNumeric(k)) - keyword = k; - - } - } - - if(!StringUtils.isNumeric(keyword)){ - return false; - - } - - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if (cmpType.equals("time")) { - - long candidateA, candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(k.contains("年") && k.contains("月") && k.contains("日")) - keyword = k; - - } - } - - candidateA = SimpleUtil.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = SimpleUtil.transferToMillisecond(k); - break; - } - } - if (operator.equals("Early")) - flag = candidateA < candidateB; - else if (operator.equals("Later")) - flag = candidateA > candidateB; - - } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { - String conditionName2 = "", conditionValue2 = ""; - for (String k : keywordSet) { - if (!k.equals("")) { - conditionName2 = k; - break; - } - } - - if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { - conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); - }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ - conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); - }else { - flag = false; - } - - - if(flag ){ - /** - * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true - */ - flag = false; - if(operator.equals("Equal")){ - flag = keyword.equals(conditionValue2); - - }else if(keyword.contains(":") && conditionValue2.contains(":")){ - String relPair1[] = keyword.split(":", 2), keyword1 = ""; - String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; - boolean similar = false; - - if(relPair1[0].equals(relPair2[0])){ - similar = true; - keyword1 = relPair1[1]; - keyword2 = relPair2[1]; - }else if (relPair1[1].equals(relPair2[1])){ - similar = true; - keyword1 = relPair1[0]; - keyword2 = relPair2[0]; - } - - if(similar){ - if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ - int candidateA = Integer.parseInt(keyword1); - int candidateB = Integer.parseInt(keyword2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") - && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ - long candidateA = SimpleUtil.transferToMillisecond(keyword1); - long candidateB = SimpleUtil.transferToMillisecond(keyword2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ - if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ - int candidateA = Integer.parseInt(keyword); - int candidateB = Integer.parseInt(conditionValue2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") - && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ - long candidateA = SimpleUtil.transferToMillisecond(keyword); - long candidateB = SimpleUtil.transferToMillisecond(conditionValue2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - } - - - - } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 - flag = false; - - } else { - flag = false; - } - } catch (IndexOutOfBoundsException e) { - System.out.println("配置文件格式有误"); - logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); - - flag = false; - e.printStackTrace(); - } catch (ParseException e) { - System.out.println("时间解析错误"); - historyInfoPoint.put("error_message", "解析出错:" + keyword); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); - e.printStackTrace(); - flag = false; - } catch (Exception e) { - System.out.println("操作符有误"); - logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0); - System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString()); - e.printStackTrace(); - flag = false; - } - - return flag; - } - - /** - * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 - * - * @return 返回给引擎的数据 - */ - public Solution getSolution(Action ansAction, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, reply, variable; - Solution ans = new Solution(0, "", ""); - - - //如果一条配置文件有多个答案,则随 - // 机选择一个答案 - - //System.out.println(ans.getAnswer()); - - //post关键字 - if (ansAction.getFeatureMap().containsKey("post")) { - logWriter.record("---------------------进入表单结束",1); - ans = postToServer(ans, ansAction); - logWriter.record("---------------------提交表单结束",1); - - //nextNext关键字 - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - //updateKnowledge关键字 - if (ansAction.getFeatureMap().containsKey("updateKnowledge")) { - logWriter.record("---------------------进入更新答案【略】",1); - updateKnowledge(ansAction); - logWriter.record("---------------------更新答案结束",1); - } - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ansAction.getFeatureMap().containsKey("newNext")) { - logWriter.record("---------------------进入判断下一步【略】",1); - ans = findNewNext(ans, ansAction); - logWriter.record("---------------------判断下一步结束",1); - //上一步 - } else if (ansAction.getFeatureMap().containsKey("return-1")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - //停留 - } else if (ansAction.getFeatureMap().containsKey("return-0")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if(activeList.length > 0) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else - ans.setNext("nextStep= "); - //激活 - } else if (ansAction.getFeatureMap().containsKey("activate") || ansAction.getFeatureMap().containsKey("activate:after")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - } - - - - - - try { - - reply = SimpleUtil.randStr(ansAction.getAnswer()); - reply = botUtil.varSlotReplace(reply); - - ans.setAnswer(reply); - - - botUtil.extraOperation(ansAction, ans); - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ans.getNext().equals("")) { - ans.setNext("nextStep=" + ansAction.getNextStep()); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return ans; - } - - /** - * 请求处理结束后台将当前信息的信息点转移到已知信息 - * @param ans - * @param context - * @param debugFlag - */ - public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { - //将当前信息点更新至历史信息点 - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, lastReply; - String next = ans.getNext().split("=", 2)[1]; - - //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx - historyInfoPoint.put("currentAction", next); - historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); - - logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); - - HashSet skipSet = new HashSet() { - { - add("chat_key"); - add("action_name"); - add("bot_name"); - add("emptySet"); - add("query_text"); - } - }; - - - try { - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - - if(skipSet.contains(actionName)) - continue; - - keyword1 = curInfoPoint.get(actionName); - keyword2 = historyInfoPoint.get(actionName); - if (keyword2 == null) { - historyInfoPoint.put(actionName, keyword1); - }else if (historyInfoPoint.get(actionName).equals("do_reset")){ - historyInfoPoint.put(actionName, ""); - }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) - historyInfoPoint.put(actionName, keyword1); - } - historyInfoPoint.put("临时变量reply", ""); - historyInfoPoint.put("临时变量condition", ""); - historyInfoPoint.put("临时变量3", ""); - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 如果接收到的表单中包含debug_mode这个参数, 后台会将存储的变量值返回给前段,用于调试 - * - * @param ans 最终返回的数据 - * @param context - */ - public void appendDebugInfo(Solution ans, ServletContext context) { - Iterator it = null; - String key, values, value; - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("bot_name"); - add("action_name"); - add("lastReply"); - add("unknownTextList"); - add("finalUnknownText"); - add("unknownText"); - add("randKey"); - add("userKey"); - } - }; - - it = curInfoPoint.keySet().iterator(); - String debugInfo = ""; - debugInfo += "(识别:"; - - while (it.hasNext()) { - key = it.next(); - values = curInfoPoint.get(key); - if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { - if (key.endsWith("_backup")) { - key = key.substring(0, key.length() - 7); - } - debugInfo += (" " + key + ":\'" + values + "\' "); - } - } - - debugInfo += ")"; - if(curInfoPoint.containsKey("debug_mode")) { - debugInfo = debugInfo.replace("-)", ""); - debugInfo += "(已知:"; - it = historyInfoPoint.keySet().iterator(); - while (it.hasNext()) { - - key = it.next(); - value = historyInfoPoint.get(key); - if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition")) - debugInfo += (" " + key + ":\'" + value + "\' "); - - } - } - ans.setAnswer(debugInfo + ")" + ans.getAnswer()); - } - - - /** - * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) - * - * @param ans 返回给用户的数据 - * @param ansAction 满足条件最多的condition(配置文件的某一行) - */ - public Solution postToServer(Solution ans, Action ansAction) throws IOException { - String url = null, elem[], subElem[], key,keys, postType = "all"; - Map infoMap = new HashMap(); - List pairList = new ArrayList(); - Iterator k_iter = null; - FormsPoster poster = new FormsPoster(logWriter); - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("lastReply"); - } - }; - - elem = ansAction.getFeatureMap().get("post").split("\\|"); - url = elem[0]; - postType = elem[1]; - - - if(postType.equals("all")){ - poster.postAll(curInfoPoint, historyInfoPoint, ans, url); - }else if(postType.equals("term")){ - poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); - }else if(postType.equals("gameQA")){ - System.out.println("提交表单" + gameEnv); - poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); - } - - return ans; - - } - - public Solution findNewNext(Solution ans, Action ansAction) { - String nextOptions[] = ansAction.getNextStep().split(","); - String conditionName, premises[], cpPair[]; - boolean flag = true; - - String activeList = historyInfoPoint.get("activeList"); - - for (String option : nextOptions) { - flag = true; - cpPair = option.split(":"); - conditionName = cpPair[0]; - if (cpPair.length == 1) { - ans.setNext("nextStep=" + conditionName); - break; - } - premises = cpPair[1].split("-"); - for (String premise : premises) { - if (premise.equals("known")) { - //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 - boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); - boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); - - //只有前两者都为假时,conditionExist才为真 - boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); - - if (conditionExist) - flag = false; - } - - if (premise.equals("active")) { - boolean isActive = activeList.contains(conditionName); - if (isActive) - flag = false; - } - } - - if (flag) { - ans.setNext("nextStep=" + conditionName); - break; - } - - } - return ans; - - } - - - public void updateKnowledge(Action action) throws ParseException { - String keyword, variableName, updateValue, returnStr = "1"; - - - - Iterator iit = action.getUpdateKnowledge().keySet().iterator(); - while (iit.hasNext()) { - - variableName = iit.next(); - - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); - updateValue = botUtil.knowledgeProcess(variableName, action.getUpdateKnowledge().get(variableName)); - - - try { - //做数字加法 - if (updateValue.startsWith("+")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = SimpleUtil.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("-")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = SimpleUtil.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(4); - //做字符串删除 - } else if (updateValue.startsWith("str-")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(4), ""); - - } else if (updateValue.startsWith("int+=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = SimpleUtil.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("int-=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = SimpleUtil.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(5); - //做字符串删除 - } else if (updateValue.startsWith("str-=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(5), ""); - - - //变量提取 - } else if (updateValue.startsWith("var=")) { - String conditionName = updateValue.substring(5, updateValue.length() - 3); - if (updateValue.endsWith("-1}")) { - if (curInfoPoint.get(conditionName) != null) { - updateValue = curInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - } else if (updateValue.endsWith("-2}")) { - if (historyInfoPoint.get(conditionName) != null) { - updateValue = historyInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - - //提取配置条目的下一步 - } else if (updateValue.endsWith("nextStep-3}")) { - updateValue = action.getNextStep(); - //提取配置条目的回答 - } else if (updateValue.endsWith("reply-3}")) { - updateValue = SimpleUtil.randStr(action.getAnswer()); - } - //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue - if (variableName.startsWith("process-nextStep")) { - action.setNextStep(updateValue); - updateValue = ""; - } - - } - - - } catch (Exception e) { - logWriter.record(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue, 0); - System.out.println(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue); - //e.printStackTrace(); - continue; - } - - - - if(updateValue.equals("")) { - curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 - // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 - curInfoPoint.put(variableName, ""); - } - - botUtil.putKeyword(variableName, updateValue); - - - } - - } - - - public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority, String activateList, ServletContext context) throws IOException { - UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - String configStr = ""; - Integer configId; - Action newAction, originAction; - List originActionList = new ArrayList(); - - for (String configIdStr : activateList.split(",")) { - logWriter.record("------激活-------" + configIdStr + "-------
", 0); - try { - if (StringUtils.isNumeric(configIdStr)) { - configId = Integer.parseInt(configIdStr); - configStr = userinfo.id2config.get(configId); - originAction = userinfo.id2condition.get(configId); - originActionList.add(originAction); - } else { - if (configIdStr.endsWith("*")) { - String prefix = configIdStr.substring(0, configIdStr.length()-1); - for(String name:userinfo.name2condition.keySet()){ - if (name.startsWith(prefix)){ - originActionList.add(userinfo.name2condition.get(name)); - } - } - - } else { - originActionList.add(userinfo.name2condition.get(configIdStr)); - } - - - } - } catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); - } - } - - for (Action action : originActionList){ - originAction = action; - try { - - configId = originAction.getId(); - - newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); - //action = ActionMatcher.buildCondition(action, configStr); - - - - //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 - if (activatedMap.containsKey(configId)) { - if(higherPriority(newAction, activatedMap.get(configId))) - activatedMap.put(configId, newAction); -// if(newAction.getAuxiliaryPriority() > activatedMap.get(configId).getAuxiliaryPriority()) -// activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; -// if(newAction.priority > activatedMap.get(configId).priority) -// activatedMap.get(configId).priority = newAction.priority; - } else if (!activatedMap.containsKey(configId)) { - activatedMap.put(configId, newAction); - activatedQueue.add(newAction); - } - }catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------激活失败:" + action.getConfigName(), 5); - } - - } - - - } - - /** - * 一个提交表单后在激活的操作 - * @param ansAction - * @param context - * @param userinfo - * @return - * @throws IOException - * @throws ParseException - */ - public Solution postActivate(Action ansAction, Solution oldBestMatch, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - Queue activatedQueue = new LinkedList(); - Solution bestMatch = oldBestMatch; - Action newAction1 = ansAction, newAction2; -// activateCondition(activatedQueue, userinfo.botAccount, ansAction.priority, ansAction.auxiliaryPriority, ansAction.nextStep, context); -// ansAction = activatedQueueMatching(ansAction, activatedQueue, context); -// -// bestMatch = getSolution(ansAction, context, userinfo); - - - - while ((newAction1.getFeatureMap().containsKey("activate") && newAction1.getFeatureMap().containsKey("post")) || newAction1.getFeatureMap().containsKey("activate:after")) { - //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - activateCondition(activatedQueue, userinfo.botAccount, newAction1.getPriority(), newAction1.getAuxiliaryPriority(), newAction1.getNextStep(), context); - newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); - - - - if(newAction1 == newAction2) - break; - - bestMatch = getSolution(newAction2, context, userinfo); - newAction1 = newAction2; - } - - return bestMatch; - - - - - } - - public Boolean higherPriority(Action action1, Action action2){ - return ((action1.getAuxiliaryPriority() > action2.getAuxiliaryPriority()) || (action1.getAuxiliaryPriority() == action2.getAuxiliaryPriority() && action1.getPriority() > action2.getPriority())); - } - - -} diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java deleted file mode 100644 index 56e83b2..0000000 --- a/src/processing/ChatCacheController.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ArchiveInfo; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.FileFinder; - -import javax.servlet.ServletContext; -import java.io.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class ChatCacheController { - - public static long TIME_OUT = 300000; - - - public static String CHAT_CACHE_DIR = "ChatCache/"; - - private static String ARCHIVE_NAME = "%s-%s-%s"; - private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; - private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; - private static String ENV_POSTFIX = "-env.data"; - private static String INFO_POSTFIX = "-info.data"; - - public static String COMBINE_PUNC1 = "@@@"; //chatKey的连接符 chatKey格式为 用户名@@@bot账号@@@@随机码 - public static String COMBINE_PUNC2 = "@@@@"; - - - - /** - * 通过chat_key获得后台保存的历史信息点 - * chatCache:存储了chatKye相对应的对话记录(历史信息点) - * - * @return 历史信息点,对话过程中引擎提取的用户信息 - */ - public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception { - Map chatCacheMap = null; - ChatCache chatCache = null; - - if (context.getAttribute("chatCache") == null) { - chatCacheMap = new HashMap(); - context.setAttribute("chatCache", chatCacheMap); - } else { - chatCacheMap = (Map) context.getAttribute("chatCache"); - } - - - - try { - chatCache = chatCacheMap.get(userKey); - - - //如果用户之前没有玩过或者有一段时间没有玩 - if(chatCache == null){ - chatCache = new ChatCache(userinfo, userKey, randKey, botType); - chatCacheMap.put(userKey, chatCache); - //用户几分钟前还在玩 - } else { - if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { - ChatCacheController.saveChatCache(chatCache, null); - } - chatCache = new ChatCache(userinfo, userKey, randKey, botType); - chatCacheMap.put(userKey, chatCache); - } - } - //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - } catch (Exception e) { - //可整合 - e.printStackTrace(); - - //chatCache = new ChatCache(userinfo, userKey, randKey); - //chatCacheMap.put(userKey, chatCache); - - } - System.out.println(chatCache.getGameEnv()); - - return chatCache; - } - - - - public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); - String nowTime = now .format(format), userId, botAccount, keyElem[]; - Boolean opFlag, destroy = false; - - if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey())) - return true; - - - System.out.println("游戏存档中"); - - String userKey = chatCache.getUserKey(); - String site = chatCache.getInfoPoint().get("site"); - String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); - - try { - - if(helper == null){ - helper = new SqlHelper(); - destroy = true; - } - - File dir = new File(CHAT_CACHE_DIR); - if (!dir.exists()) - dir.mkdir(); - - - - - - ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); - - - File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); - FileWriter fw = new FileWriter(file); - - String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); - fw.write(jsonString); - fw.close(); - - - opFlag = helper.insertArchiveInfo(archiveName, userKey, site); - - if(destroy) - helper.destroy(); - - } catch (Exception e) { - System.out.println("游戏存档时发生异常"); - e.printStackTrace(); - opFlag = false; - } - - return opFlag; - } - - - - public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; - Map infoPoint = null; - System.out.println(archiveInfo.getArchiveId()); - String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); - keys[1] = keys[1].split("-")[0]; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; - Map infoPoints = new HashMap(); - try { - File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - if (file.exists()){ - gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - }else{ - throw new IOException("环境存档不存在"); - } - - - file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); - FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - String jsonStr = br.readLine(); - infoPoint = (Map)JSON.parseObject(jsonStr); - - chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); - chatCache.setGameStart(true); - - br.close(); - fr.close(); - - - - - } catch (IOException e) { - System.out.println(e.toString()); - } - - return chatCache; - } - - - - /** - * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 - */ - public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { - String sessionKey; - ChatCache chatCache = null; - SqlHelper helper = null; - long lastChatTime, now; - Map history = new HashMap(); - Map chatCacheMap = (Map) context.getAttribute("chatCache"); - - try { - helper = new SqlHelper(); - - Iterator it = chatCacheMap.keySet().iterator(); - while (it.hasNext()) { - sessionKey = it.next(); - if (sessionKey.equals(userKey)) { -// saveChatCache(chatCacheMap.get(sessionKey),null); - continue; - } - history = chatCacheMap.get(sessionKey).getInfoPoint(); - lastChatTime = Long.valueOf(history.get("lastUpdateTime")); - now = System.currentTimeMillis(); - if (now - lastChatTime > ChatCacheController.TIME_OUT) { - chatCache = chatCacheMap.get(sessionKey); - - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { - saveChatCache(chatCache, helper); - } - System.out.println("移除" + sessionKey); - it.remove(); - } - } - }catch (Exception e){ - e.printStackTrace(); - }finally { - helper.destroy(); - } - context.setAttribute("chatCache", chatCacheMap); - } - - /** - * 根据chatKey更新chatCache的数据,并修改最后更新时间 - */ - public static synchronized void updateChatCache4Insert(Map curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) { - chatCache.getInfoPoint().put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - Map keyCacheMap = (Map) context.getAttribute("chatCache"); - keyCacheMap.put(chatCache.getUserKey(), chatCache); - //ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); - //chatCache.setInfoPoint(historyInfoPoint); - //chatCache.setGameEnv(gameEnv); - context.setAttribute("chatCache", keyCacheMap); - } - - - public static synchronized boolean findChatCache(String userKey, ServletContext context) throws Exception { - ArchiveInfo archiveInfo = null; - Map chatCacheMap = null; - ChatCache chatCache = null; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - Boolean findFlag = false; - SqlHelper helper; - Map infoPoints = new HashMap(); - try { - helper = new SqlHelper(); - - if (context.getAttribute("chatCache") != null) { - chatCacheMap = (HashMap)context.getAttribute("chatCache"); - if (chatCacheMap.containsKey(userKey)) { - chatCache = chatCacheMap.get(userKey); - - - // //保存到本地,并从chatCacheMap中删除 - if(!chatCache.getUserKey().endsWith(chatCache.getRandKey()) && chatCache.isGameStart()){ - findFlag = true; - saveChatCache(chatCache, helper); - chatCacheMap.remove(userKey); - } - - - } - - } - - if (!findFlag) { - - - archiveInfo = helper.queryUserLastGameArchive(userKey); - - helper.destroy(); - findFlag = (archiveInfo != null); - } - - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - - return findFlag; - } - - - public static Boolean deleteChatCache(SqlHelper helper, String botAccount){ - - Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount); - Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount); - - return sqlDeleteFlag && fileDeleteFlag; - } - - -} diff --git a/src/processing/ChatCacheController2.java b/src/processing/ChatCacheController2.java deleted file mode 100644 index 860cfed..0000000 --- a/src/processing/ChatCacheController2.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ArchiveInfo; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import javax.servlet.ServletContext; -import java.io.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class ChatCacheController2 { - - public static long TIME_OUT = 300000; - - - private static String CHAT_CACHE_DIR = "ChatCache/"; - - private static String ARCHIVE_NAME = "%s-%s-%s"; - private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; - private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; - private static String ENV_POSTFIX = "-env.data"; - private static String INFO_POSTFIX = "-info.data"; - - public static String COMBINE_PUNC1 = "@@@"; - public static String COMBINE_PUNC2 = "@@@@"; - - - - /** - * 通过chat_key获得后台保存的历史信息点 - * chatCache:存储了chatKye相对应的对话记录(历史信息点) - * - * @return 历史信息点,对话过程中引擎提取的用户信息 - */ - public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { - Map chatCacheMap = null; - ChatCache chatCache = null; - - if (context.getAttribute("chatCache") == null) { - chatCacheMap = new HashMap(); - //chatCacheMap.put(chatKey, new ChatCache(userinfo)); - context.setAttribute("chatCache", chatCacheMap); - } else { - chatCacheMap = (Map) context.getAttribute("chatCache"); - } - - - - try { - chatCache = chatCacheMap.get(userKey); - - - //如果用户之前没有玩过或者有一段时间没有玩 - if(chatCache == null){ - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - //用户几分钟前还在玩 - } else { - if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 - saveChatCache(chatCache, null); - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - } - } - //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); - } catch (Exception e) { - //可整合 - e.printStackTrace(); - chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); - - } - - return chatCache; - } - - - - public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); - String nowTime = now .format(format); - Boolean opFlag; - - - String userKey = chatCache.getUserKey(); - String site = chatCache.getInfoPoint().get("site"); - String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); - - try { - - if(helper == null){ - helper = new SqlHelper(); - } - - File dir = new File(CHAT_CACHE_DIR); - if (!dir.exists()) - dir.mkdir(); - - - - - - ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); - - - File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); - FileWriter fw = new FileWriter(file); - - String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); - fw.write(jsonString); - fw.close(); - - - opFlag = helper.insertArchiveInfo(archiveName, userKey, site); - - } catch (Exception e) { - System.out.println("游戏存档时发生异常"); - e.printStackTrace(); - opFlag = false; - } - - return opFlag; - } - - - - public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; - Map infoPoint = null; - String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); - keys[1] = keys[1].split("-")[0]; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; - Map infoPoints = new HashMap(); - try { - File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - if (file.exists()){ - gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); - }else{ - throw new IOException("环境存档不存在"); - } - - - file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); - FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - String jsonStr = br.readLine(); - infoPoint = (Map)JSON.parseObject(jsonStr); - - chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); - chatCache.setReloading(true); - - br.close(); - fr.close(); - - - - - } catch (IOException e) { - System.out.println(e.toString()); - } - - return chatCache; - } - - - - /** - * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 - */ - public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { - String sessionKey; - ChatCache chatCache = null; - SqlHelper helper = null; - long lastChatTime, now; - Map history = new HashMap(); - Map chatCacheMap = (Map) context.getAttribute("chatCache"); - - try { - - Iterator it = chatCacheMap.keySet().iterator(); - while (it.hasNext()) { - sessionKey = it.next(); - if (sessionKey.equals(userKey)) { - saveChatCache(chatCacheMap.get(sessionKey),null); - continue; - } - history = chatCacheMap.get(sessionKey).getInfoPoint(); - lastChatTime = Long.valueOf(history.get("lastUpdateTime")); - now = System.currentTimeMillis(); - if (now - lastChatTime > ChatCacheController2.TIME_OUT) { - chatCache = chatCacheMap.get(sessionKey); - - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { - saveChatCache(chatCache, null); - } - System.out.println("移除" + sessionKey); - it.remove(); - } - } - }catch (Exception e){ - e.printStackTrace(); - } - context.setAttribute("chatCache", chatCacheMap); - } - - /** - * 根据chatKey更新chatCache的数据,并修改最后更新时间 - */ - public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { - historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); - Map keyCacheMap = (Map) context.getAttribute("chatCache"); - ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); - chatCache.setInfoPoint(historyInfoPoint); - chatCache.setGameEnv(gameEnv); - context.setAttribute("chatCache", keyCacheMap); - } - - - public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception { - ChatCache chatCache = null; - GameEnv gameEnv = null; - ArchiveInfo archiveInfo = null; - Map infoPoint = null; - - String fileDir = System.getProperty("user.dir") + "/ChatCache"; - String line, pair[]; - SqlHelper helper; - Map infoPoints = new HashMap(); - try { - - helper = new SqlHelper(); - archiveInfo = helper.queryUserLastGameArchive(userKey); - - - } catch(Exception e){ - e.printStackTrace(); - return false; - } - - return archiveInfo != null; - } - - - public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { - try { - System.out.println("移除----------------------------"); - HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); - chatCacheHashMap.remove(chatKey); - - } catch(Exception e){ - e.printStackTrace(); - return false; - } - - return true; - } - - - - - - - - - -} diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java deleted file mode 100644 index 21b52be..0000000 --- a/src/processing/FormsPoster.java +++ /dev/null @@ -1,262 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.GameBotUtil; -import org.apache.http.message.BasicNameValuePair; -import org.springframework.beans.factory.annotation.Value; - -import java.io.UnsupportedEncodingException; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class FormsPoster { - - - LogWriter logWriter; - - public static String TALKER = "【(.*?)@.*?】"; - - @Value("${qa.url}") - public String QA_URL; - - - public void setQaUrl(String qaUrl) { - QA_URL = qaUrl; - } - - public FormsPoster(LogWriter logWriter) { - this.logWriter = logWriter; - } - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("lastReply"); - } - }; - - - - /** - * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器,还有回答 - * @param curInfoPoint - * @param historyInfoPoint - * @param ans - * @param URL - * @throws UnsupportedEncodingException - */ - public void postAll(Map curInfoPoint, Map historyInfoPoint, Solution ans, String URL) throws UnsupportedEncodingException { - String key, keyName; - Iterator k_iter = null; - List pairList = new ArrayList(); - - k_iter = curInfoPoint.keySet().iterator(); - while (k_iter.hasNext()) { - key = k_iter.next(); - if (curInfoPoint.get(key) != null && !curInfoPoint.get(key).equals("")) - //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); - pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); - } - - k_iter = historyInfoPoint.keySet().iterator(); - while (k_iter.hasNext()) { - key = k_iter.next(); - - if(historyInfoPoint.get(key) != null && !historyInfoPoint.get(key).equals("")) { - if (skipSet.contains(key)) - continue; - if (curInfoPoint.get(key) == null || curInfoPoint.equals("")) { - pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); - } else { - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - } - } - } - - pairList.add(new BasicNameValuePair("reply", ans.getAnswer())); - - logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - - JSONObject jobj = SimpleUtil.postFORM(URL, pairList); - logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); - if((Integer)jobj.get("post_status") == 1){ - Iterator kit = jobj.keySet().iterator(); - - while (kit.hasNext()) { - keyName = kit.next(); - if (keyName.equals("process")) { - ans.setNext((String) jobj.get(keyName)); - historyInfoPoint.put("process", (String) jobj.get(keyName)); - } else if (keyName.equals("solution")) { - ans.setAnswer((String) jobj.get(keyName)); - } else if (keyName.equals("status") || keyName.equals("qa_candidates")){ - continue; - } else{ - historyInfoPoint.put(keyName, jobj.getString(keyName)); - } - } - }else { - if(URL.equals(QA_URL)) - ans.setAnswer("qa_threshold, game_step, query_text 看看少了哪个"); - else - ans.setAnswer("提交表单出现异常"); - } - - - - - } - - /** - * 提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 - * @param curInfoPoint - * @param historyInfoPoint - * @param ans - * @param ansAction - * @param URL - * @throws UnsupportedEncodingException - */ - public void postTerm(Map curInfoPoint, Map historyInfoPoint, Solution ans, Action ansAction, String URL) throws UnsupportedEncodingException { - String key, keyName; - Iterator k_iter = null; - List pairList = new ArrayList(); - - pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); - pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); - pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); - k_iter = ansAction.getCurrentPremise().keySet().iterator(); - while (k_iter.hasNext()) { - key = k_iter.next().split("::")[0]; - if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) - pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); - } - - k_iter = ansAction.getHistoryPremise().keySet().iterator(); - while (k_iter.hasNext()) { - key = k_iter.next().split("::")[0]; - if(!historyInfoPoint.get(key).equals("")) { - if (curInfoPoint.get(key) == null || curInfoPoint.equals("")) { - pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); - } else { - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - } - } - } - - logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - - JSONObject jobj = SimpleUtil.postFORM(URL, pairList); - logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); - if((Integer)jobj.get("post_status") == 1){ - Iterator kit = jobj.keySet().iterator(); - - while (kit.hasNext()) { - keyName = kit.next(); - if (keyName.equals("process")) { - ans.setNext((String) jobj.get(keyName)); - historyInfoPoint.put("process", (String) jobj.get(keyName)); - } else if (keyName.equals("solution")) { - ans.setAnswer((String) jobj.get(keyName)); - } else if (keyName.equals("status")){ - continue; - } else{ - historyInfoPoint.put(keyName, jobj.getString(keyName)); - } - } - }else { - ans.setAnswer("提交表单出现异常"); - } - - } - - - /** - * 游戏专用提交表单 - * @param curInfoPoint - * @param historyInfoPoint - * @param ans - * @param gameEnv - * @param worldController - * @param URL - * @throws UnsupportedEncodingException - */ - public void postGameQA1(String gameStep, Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { - String key, keyName; - Iterator k_iter = null; - List pairList = new ArrayList(); - String threshold = "50"; - - if (historyInfoPoint.get("qa_threshold") != null) - threshold = historyInfoPoint.get("qa_threshold"); - - pairList.add(new BasicNameValuePair("game_step", gameStep)); - pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); - pairList.add(new BasicNameValuePair("qa_threshold", threshold)); - - - //设置初始值 - historyInfoPoint.put("common_answer", ""); - historyInfoPoint.put("qa_score", "0"); - historyInfoPoint.put("qa_status", "OK"); - - logWriter.record("提交表单的数据:
" + pairList.toString(), 2); - - JSONObject jobj = SimpleUtil.postFORM(URL, pairList); - - logWriter.record("提交表单接收到的数据:
" + jobj.toJSONString(), 2); - - String text,score, site = historyInfoPoint.get("site"), npc; - System.out.println(jobj.toJSONString()); - if((Integer)jobj.get("post_status") == 1){ - if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){ - - List candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); - - for(JSONArray pair:candidates){ - List textscore = JSON.toJavaObject(pair, List.class); - - - Pattern findTalker = Pattern.compile(TALKER); - - - if((Integer)textscore.get(1) > 90) { - Matcher m = findTalker.matcher((String)textscore.get(0)); - if (m.find()) { - npc = m.group(1); - - if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, historyInfoPoint.get("site"), logWriter) == 1)) { - historyInfoPoint.put("common_answer", (String)textscore.get(0)); - historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); - break; - } - } - } - } - } - }else { - historyInfoPoint.put("error_message", jobj.getString("error_message")); - } - - } - public void postGameQA(Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { - postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo); - - if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){ - postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo); - } -// historyInfoPoint.put("common_answer", "【旁白@%正常】QA暂时关闭"); -// historyInfoPoint.put("qa_score", "99"); -// historyInfoPoint.put("qa_status", "OK"); - - } - - } diff --git a/src/processing/LogWriter.java b/src/processing/LogWriter.java deleted file mode 100644 index c6a7b85..0000000 --- a/src/processing/LogWriter.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import java.io.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Map; - - -public class LogWriter { - private PrintWriter recorder = null; - DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"); - LocalDateTime ldt = null; - - - String filePath; - String fileName; - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - String PRINT_PATTERN = "[%s] %s" + - "----------------------------------------------------------------------------
"; - Map colorMap = new HashMap(){ - { - put(0, "black"); - put(1, "gray"); - put(2, "green"); - put(3, "yellow"); - put(4, "green"); - put(5, "red"); - } - }; - public LogWriter(String filePath, String fileName) throws IOException { - File file = new File(filePath + "/" + fileName + ".html"); - - System.out.println(file.getAbsolutePath()); - - if (!file.exists()) { - file.createNewFile(); - } - file.setReadable(true,false); - - FileWriter fw = new FileWriter(file, true); - - - BufferedWriter bw = new BufferedWriter(fw); - recorder = new PrintWriter(bw); - recorder.println("\n" + - "\n" + - "\n" + - " \n" + - " log\n" + - ""); - } - - public void record(String text, int level){ - ldt = LocalDateTime.now(); - recorder.println(String.format(PRINT_PATTERN, colorMap.get(level), ldt.format(dtf), text)); - } - public void writeln(){ - recorder.println("
"); - } - - public void close(){ - recorder.close(); - } -} diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java deleted file mode 100644 index bb0e51d..0000000 --- a/src/processing/MyFunc.java +++ /dev/null @@ -1,214 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.entity.Solution; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - - -public class MyFunc { - - /** - * 将后台返回的数据转成json格式 - */ - public static String toJson(Solution ans) { - JSONObject jobj = new JSONObject(); - jobj.put("solution", ans.getAnswer()); - jobj.put("status", ans.getStatus()); - jobj.put("process", ans.getNext()); - return jobj.toString(); - } - - public static String toJson(String returnStr) { - JSONObject jobj = new JSONObject(); - jobj.put("returnString", returnStr); - return jobj.toString(); - } - - /** - * 当请求中的数据是json格式时,该函数用于提取request中的json数据 - * - * @param request - * @return json字符串 - */ - public static String readJSONString(HttpServletRequest request) { - StringBuffer json = new StringBuffer(); - String line = null; - - try { - BufferedReader reader = request.getReader(); - while ((line = reader.readLine()) != null) { - json.append(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return json.toString(); - } - - /** - * 通过get方法传递参数时需要对参数的编码进行转换 - */ - public static String convert2Utf8(String s) { - if (s == null) return null; - try { - s = new String(s.getBytes("iso-8859-1"), "utf-8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return s; - } - - public static long transferToMillisecond(String keyword) throws ParseException { - long time; - - System.out.println(keyword); - - String timeSeries[] = {"时", "分", "秒"}; - for (String f : timeSeries) { - if (!keyword.contains(f)) - keyword += "0" + f; - } - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - time = format.parse(keyword).getTime(); - - return time; - } - - public static String transferToStandardTime(long time) throws ParseException { - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - - Date date = new Date(time); - return format.format(date); - - } - - public static boolean isInteger(String str){ - return true; - } - - - - public static JSONObject postJSON(String url, JSON data, String auth) 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); - - if(auth != null){ - httpPost.setHeader("Authorization", auth); - } - - 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); - jobj.put("post_status", 1); - - } else { - jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常"); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return jobj; - - } - - - - - - public static JSONObject postFORM(String url, List pairList) throws UnsupportedEncodingException { - - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); - entity.setContentType("application/x-www-form-urlencoded"); - httpPost.setEntity(entity); - JSONObject jobj = new JSONObject(); - - try { - System.out.println("url为:" + url); - HttpResponse resp = client.execute(httpPost); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - jobj = JSONObject.parseObject(respContent); - jobj.put("post_status", 1); - - } else { - jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常"); - } - } catch (Exception e) { - e.printStackTrace(); - jobj.put("post_status", 0); - - } - - return jobj; - - } - - public static String randStr(String strList[]){ - String reply; - int randNum = (int) (Math.random() * strList.length); - reply = strList[randNum]; - - return reply; - } - - public static String randStr(List strList){ - String reply; - - int randNum = (int) (Math.random() * strList.size()); - reply = strList.get(randNum); - - return reply; - } - - -} \ No newline at end of file diff --git a/src/processing/ProcessQuestion.java b/src/processing/ProcessQuestion.java deleted file mode 100644 index 9c4a77a..0000000 --- a/src/processing/ProcessQuestion.java +++ /dev/null @@ -1,852 +0,0 @@ -package processing; - -import entity.Solution; -import entity.Condition; -import entity.UserInfo; -import net.sf.json.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import javax.servlet.ServletContext; -import java.io.*; -import java.sql.SQLException; -import java.text.ParseException; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class ProcessQuestion { - - static Map activatedMap = new HashMap(); - - - - static String POST_DATA_ERROR = "post数据有误"; - static String POST_ERROR = "数据post时出错了"; - static String API_ERROR = "api处理过程中出错了"; - static String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; - Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); - -/* - public void updateDB(QuestionKeyWord qkw) throws SQLException { - SqlHelper helper = new SqlHelper(); - String result = helper.queryActionByKey(qkw.getChatKey()); - if(result != "empty") - //待添加 - //qkw.setActionName(result+"+"+qkw.getActionName()); - helper.updateAction(qkw); - else - helper.insertAction(qkw); - helper.destroy(); - } -*/ - - - - - public boolean infoPointPreprocessing(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, StringBuffer curInfoRecord){ - - String return_str = "", k ; - boolean debugFlag = false; - - - - //输出所有actionName的值 - Iterator iit = curInfoPoint.keySet().iterator(); - while(iit.hasNext()){ - k = iit.next(); - // - System.out.print(k+": "); - - if(k.equals("debug_mode")) - debugFlag = true; - - String values[] = curInfoPoint.get(k); - - for(String v:values) { - System.out.print(v + " "); - } - System.out.println(); - if(values[0].equals(":")){ - values[0] = ""; - curInfoPoint.put(k, values); - } - - } - - //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown - iit = curInfoPoint.keySet().iterator(); - boolean unknown_flag = true; - while(iit.hasNext()){ - k = iit.next(); - String values[] = curInfoPoint.get(k); - if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name") || k.equals("emptySet")) - continue; - if(values != null && !values[0].equals("")) { - unknown_flag = false; - break; - } - } - - String currentAction = ""; - if(historyInfoPoint.containsKey("currentAction")) - currentAction = historyInfoPoint.get("currentAction"); - else if(userinfo.extraInfo.containsKey("activeAction")) { - currentAction = userinfo.extraInfo.get("activeAction"); - historyInfoPoint.put("currentAction", currentAction); - }else - currentAction = " "; - - - curInfoPoint.put("emptySet", new String[]{" ",}); - if(historyInfoPoint.get("activeList") == null){ - historyInfoPoint.put("activeList", currentAction); - } - - if(unknown_flag && !currentAction.equals("")){ - String i[] = {"unknown",}; - curInfoPoint.put(currentAction,i); - } - - return debugFlag; - } - - - /** - * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 - * @return bestMatch 状态表中满足条件最多的一条 - */ - public Condition getBestMatch(Map curInfoPoint,Map historyInfoPoint,HashMap> conditionTable, ServletContext context) throws IOException { - - Integer configId = 0; - List conditionList = null; - Condition bestMatch = new Condition(-1),iterCon; - Iterator it = curInfoPoint.keySet().iterator(); - Queue activatedQueue = new LinkedList(); - Queue activatedCondition = new LinkedList(); - - - while (it.hasNext()) { - String conditionName = it.next(); - String[] keywords = curInfoPoint.get(conditionName); - String keyword = null; - - if (keywords != null && !keywords[0].equals("")) - keyword = keywords[0]; - - if (keyword != null && conditionTable.get(conditionName) != null) { - conditionList = conditionTable.get(conditionName); - for (Condition condition : conditionList) { - if(condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ - - if(condition.featureMap.get("instantPost") != null){ - - - } - //Post后还是可以激活 - - if(condition.featureMap.get("activate") != null){ - bestMatch = condition; - - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); - } else if((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) - bestMatch = condition; - } - } - } - } - - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context); - - - - return bestMatch; - } - - public Condition activatedQueueMatching(Condition bestMatch,Queue activatedQueue, Map curInfoPoint,Map historyInfoPoint, ServletContext context){ - Condition condition; - //待激活配置条目被激活后的匹配 - while(!activatedQueue.isEmpty()){ - condition = activatedQueue.remove(); - activatedMap.remove(condition.id); - - if(conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ - if(condition.featureMap.containsKey("activate")){ - bestMatch = condition; - activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context); - } else if((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)){ - bestMatch = condition; - } - } - - } - - return bestMatch; - - } - - /** - * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 - * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @param condition 配置文件(状态表)的一行 - * @return 满足条件就为True,不满足就为False - */ - public boolean conditionSatisfy(Map curInfoPoint,Map historyInfoPoint,Condition condition){ - boolean flag = true; - String actionName,keywords[],keyword,comparePair[],cmpType,premiseStr; - HashSet keywordSet = null; - - if(condition.featureMap.containsKey("match")){ - Iterator it = condition.currentPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - keywords = curInfoPoint.get(actionName); - if (keywords == null) { - flag = false; - break; - } - keyword = keywords[0]; - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; - - keywordSet = condition.currentPremise.get(premiseStr); - if(!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - } - - it = condition.historyPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - keyword = historyInfoPoint.get(actionName); - - if(keyword == null){ - flag = false; - break; - } - - if (comparePair.length == 1) - cmpType = "match"; - else - cmpType = comparePair[1]; - - keywordSet = condition.historyPremise.get(premiseStr); - if(!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - } - } - - return flag; - - } - - /** - * 单个条件的匹配,判断是否满足条件 判断(keyword in keywordSet) - * @param keyword - * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 - * @return 返回匹配或者不匹配 - */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet){ - boolean flag = true; - String operator = ""; - - try { - String splitPair[] = cmpType.split("-"); - if (splitPair.length > 1) { - operator = splitPair[1]; - cmpType = splitPair[0]; - } - - - if (cmpType.equals("match")) { - if (!keywordSet.contains(keyword)) { - flag = false; - } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if (keywordSet.contains(k)) - flag = true; - } - } - - } else if (cmpType.equals("number") && !keyword.equals("") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - - } else if (cmpType.equals("time")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - if (operator.equals("Early")) - flag = candidateA < candidateB; - else if (operator.equals("Later")) - flag = candidateA > candidateB; - - - } - //-------------------------------------------------------------------- - //为兼容旧数据 - else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA > candidateB; - - } else if (cmpType.equals("numberBiggerOrEqual") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA >= candidateB; - - } else if (cmpType.equals("numberSmaller") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA < candidateB; - - } else if (cmpType.equals("numberSmallerOrEqual") && StringUtils.isNumeric(keyword)) { - int candidateA = 0; - int candidateB = 0; - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - flag = candidateA <= candidateB; - - } else if (cmpType.equals("timeEarly")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - flag = candidateA < candidateB; - - } else if (cmpType.equals("timeLater")) { - long candidateA, candidateB = 0; - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - flag = candidateA > candidateB; - - } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 - flag = false; - - } else { - flag = false; - } - } catch (IndexOutOfBoundsException e){ - System.out.println("配置文件格式有误"); - e.printStackTrace(); - }catch (Exception e){ - System.out.println("操作符有误"); - e.printStackTrace(); - flag = false; - } - - return flag; - } - - /** - * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 - * @param curInfoPoint 当前信息点,即引擎识别的conditionName和关键字 - * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 - * @return 返回给引擎的数据 - */ - public Solution getSolution(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, reply, variable; - Solution ans = new Solution(0, "", ""); - - - - //如果一条配置文件有多个答案,则随 - // 机选择一个答案 - int randNum = (int) (Math.random() * ansCondition.answer.length); - ans.setAnswer(ansCondition.answer[randNum]); - //System.out.println(ans.getAnswer()); - - //post关键字 - if(ansCondition.featureMap.containsKey("post")){ - ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); - - //nextNext关键字 - }else if(ansCondition.featureMap.containsKey("newNext")){ - ans = findNewNext(ans, ansCondition, curInfoPoint, historyInfoPoint); - //上一步 - }else if (ansCondition.featureMap.containsKey("return-1")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - //停留 - }else if (ansCondition.featureMap.containsKey("return-0")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - //激活 - }else if (ansCondition.featureMap.containsKey("activate")){ - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - } - - //updateKnowledge关键字 - if (ansCondition.featureMap.containsKey("updateKnowledge")){ - updateKnowledge(ansCondition, historyInfoPoint); - } - - if(ans.getNext().equals("")){ - ans.setNext("nextStep=" + ansCondition.nextStep); - } - - - 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}替换成后台存储的变量值 - reply = ans.getAnswer(); - Matcher m = replacePattern.matcher(reply); - while(m.find()){ - variable = m.group(1).substring(1, m.group(1).length()-3); - if(m.group(1).endsWith("-1}")){ - if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable)[0].equals("")) - reply = reply.replace("{" + variable + "-1}", curInfoPoint.get(variable)[0]); - }else if(m.group(1).endsWith("-2}")){ - if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")) - reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); - } - } - ans.setAnswer(reply); - - }catch(Exception e){ - e.printStackTrace(); - } - - return ans; - } - - public void infoTransition(Map curInfoPoint, Map historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag){ - //将当前信息点更新至历史信息点 - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, lastReply; - String next = ans.getNext().split("=")[1]; - - //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx - historyInfoPoint.put("currentAction",next); - historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); - - if(debugFlag) - lastReply = ans.getAnswer().split(")")[2]; - else - lastReply = ans.getAnswer(); - historyInfoPoint.put("lastReply", lastReply); - - try { - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - keyword1 = curInfoPoint.get(actionName)[0]; - keyword2 = historyInfoPoint.get(actionName); - if (keyword2 == null) - historyInfoPoint.put(actionName, keyword1); - else if (keyword2 != null && !keyword1.equals("")) - historyInfoPoint.put(actionName, keyword1); - } - - - ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); - //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); - - - }catch(Exception e){ - e.printStackTrace(); - } - } - - - /** - * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 - * @param ans 最终返回的数据 - * @param curInfoPoint 当前对话识别到的信息点 - * @param historyInfoPoint 在当前对话之前采集到的所有用户信息点 - * @param context - */ - public void appendDebugInfo(Solution ans, Map curInfoPoint, Map historyInfoPoint, ServletContext context) { - Iterator it = null; - String key, values[], value; - - HashSet skipSet = new HashSet(){ - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("bot_name"); - add("action_name"); - add("chat_key"); - add("lastReply"); - } - }; - - it = curInfoPoint.keySet().iterator(); - String debugInfo = ""; - debugInfo += "(识别:"; - - while(it.hasNext()) { - key = it.next(); - values = curInfoPoint.get(key); - if (values != null && !values[0].equals(" ") && !values[0].equals("") && !skipSet.contains(key)) - debugInfo += (" " + key + ":\'" + values[0] + "\' "); - } - - debugInfo += ")(已知:"; - it = historyInfoPoint.keySet().iterator(); - while(it.hasNext()){ - - key = it.next(); - value = historyInfoPoint.get(key); - if(value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key)) - debugInfo += (" " + key + ":\'" + value + "\' "); - - } - ans.setAnswer( debugInfo + ")" + ans.getAnswer()); - } - - - /** - * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) - * @param ans 返回给用户的数据 - * @param ansCondition 满足条件最多的condition(配置文件的某一行) - */ - public Solution postToServer(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint) throws IOException { - String url = null,elem[], subElem[], key, postType = "all"; - Map infoMap = new HashMap(); - List pairList = new ArrayList(); - Iterator k_iter = null; - - elem = ansCondition.featureMap.get("post").split("\\|"); - url = elem[0]; - postType = elem[1]; - - //提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 - if(postType.equals("all")){ - k_iter = curInfoPoint.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next(); - if(curInfoPoint.get(key)[0] != "") - //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); - pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); - } - - k_iter = historyInfoPoint.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next(); - if(historyInfoPoint.get(key) != "") - //infoMap.put(key + "_his", historyInfoPoint.get(key)); - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - } - - //提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值 - }else if(postType.equals("term")){ - k_iter = ansCondition.currentPremise.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next().split("::")[0]; - if(curInfoPoint.get(key)[0] != "") - pairList.add(new BasicNameValuePair(key , curInfoPoint.get(key)[0])); - } - - k_iter = ansCondition.historyPremise.keySet().iterator(); - while(k_iter.hasNext()){ - key = k_iter.next().split("::")[0]; - if(historyInfoPoint.get(key) != "") - pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); - //infoMap.put(key + "_his", historyInfoPoint.get(key)); - } - } - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); - entity.setContentType("application/x-www-form-urlencoded"); - httpPost.setEntity(entity); - - try { - HttpResponse resp = client.execute(httpPost); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - JSONObject jobj = JSONObject.fromString(respContent); - Iterator kit = jobj.keys(); - while (kit.hasNext()) { - keyName = kit.next(); - if (keyName.equals("process")) { - ans.setNext((String)jobj.get(keyName)); - historyInfoPoint.put("process", (String)jobj.get(keyName)); - } else if (keyName.equals("solution")) { - ans.setAnswer((String) jobj.get(keyName)); - } else { - historyInfoPoint.put(keyName, jobj.getString(keyName)); - } - } - } else { - ans.setAnswer(API_ERROR); - } - }catch (Exception e){ - e.printStackTrace(); - - ans.setNext(POST_ERROR + url); - } - - return ans; - - } - - public Solution findNewNext(Solution ans, Condition ansCondition, Map curInfoPoint, Map historyInfoPoint){ - String nextOptions[] = ansCondition.nextStep.split(","); - String conditionName,premises[],cpPair[]; - boolean flag = true; - - String activeList = historyInfoPoint.get("activeList"); - - for(String option: nextOptions){ - flag = true; - cpPair = option.split(":"); - conditionName = cpPair[0]; - if(cpPair.length == 1){ - ans.setNext("nextStep="+conditionName); - break; - } - premises = cpPair[1].split("-"); - for(String premise:premises) { - if(premise.equals("known")) { - //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 - boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName)[0].equals("") && !curInfoPoint.get(conditionName)[0].equals("unknown"); - boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown"); - - //只有前两者都为假时,conditionExist才为真 - boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); - - if (conditionExist) - flag = false; - } - - if(premise.equals("active")){ - boolean isActive = activeList.contains(conditionName); - if (isActive) - flag = false; - } - } - - if(flag){ - ans.setNext("nextStep="+conditionName); - break; - } - - } - return ans; - - } - - public void updateKnowledge(Condition condition, Map historyInfoPoint) throws ParseException { - String keyword, variableName, updateValue; - - Iterator iit = condition.updateKnowledge.keySet().iterator(); - while(iit.hasNext()){ - - variableName = iit.next(); - updateValue = condition.updateKnowledge.get(variableName); - keyword = historyInfoPoint.get(variableName); - - try { - //做数字加法 - if (updateValue.startsWith("+")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("-")) { - if(keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - }else if (StringUtils.isNumeric(keyword)){ - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(4); - //做字符串删除 - } else if (updateValue.startsWith("str-")) { - if(keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(4), ""); - } - }catch (Exception e){ - e.printStackTrace(); - continue; - } - historyInfoPoint.put(variableName, updateValue); - } - - - - } - - - public void activateCondition(Queue activatedQueue, String userName, int basePriority, String activateList, ServletContext context){ - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - String configStr = ""; - Integer configId; - Condition newCondition, originCondition; - - for(String configIdStr:activateList.split(",")){ - if (!StringUtils.isNumeric(configIdStr)) - continue; - configId = Integer.parseInt(configIdStr); - - configStr = userinfo.id2config.get(configId); - if(configStr != null) { - originCondition = userinfo.id2condition.get(configId); - newCondition = new Condition(originCondition, basePriority); - //condition = ProcessQuestion.buildCondition(condition, configStr); - - if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { - activatedMap.get(configId).activePriority = newCondition.activePriority; - } else if (!activatedMap.containsKey(configId)) { - activatedMap.put(configId, newCondition); - activatedQueue.add(newCondition); - } - } - } - - - } - - public Solution postActivate(Condition ansCondition, Map curInfoPoint, Map historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - Queue activatedQueue = new LinkedList(); - Solution bestMatch = null; - activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context); - ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context); - - bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); - - return bestMatch; - - - } - - - - -} diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java deleted file mode 100644 index 6211686..0000000 --- a/src/processing/QuestionMatcher.java +++ /dev/null @@ -1,1056 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Condition; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.http.message.BasicNameValuePair; - -import javax.servlet.ServletContext; -import java.io.IOException; -import java.text.ParseException; -import java.util.*; - - -public class QuestionMatcher { - - Map activatedMap = new HashMap(); - - - static String POST_DATA_ERROR = "post数据有误"; - static String POST_ERROR = "数据post时出错了"; - static String API_ERROR = "api处理过程中出错了"; - - - - - public LogWriter logWriter = null; - public UserInfo userinfo = null; - public ServletContext context = null; - public GameEnv gameEnv = null; - public Map curInfoPoint = null; - public Map historyInfoPoint = null; - public WorldController worldController = null; - BasicBotUtil botUtil = null; - - public QuestionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; - this.logWriter = logWriter; - this.userinfo = userinfo; - this.context = context; - this.gameEnv = gameEnv; - this.worldController = new WorldController(logWriter, userinfo); - this.botUtil = botUtil; - } - - - public QuestionMatcher(){ - - } - - - - - /** - * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch - * - * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 - * @return bestMatch 状态表中满足条件最多的一条 - */ - public Condition getBestMatch( HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { - - Integer configId = 0; - List conditionList = null; - Condition bestMatch = new Condition(-1), iterCon; - Iterator it = curInfoPoint.keySet().iterator(); - Queue activatedQueue = new LinkedList(); - Queue activatedCondition = new LinkedList(); - - - - while (it.hasNext()) { - String conditionName = it.next(); - String keywords = curInfoPoint.get(conditionName); - String keyword = null; - - if (keywords != null && !keywords.equals("")) - keyword = keywords; - - - if (keyword != null && conditionTable.get(conditionName) != null) { - conditionList = conditionTable.get(conditionName); - - - for (Condition condition : conditionList) { - - if (condition.status.equals("waiting")){ - if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority) - || condition.featureMap.get("activate") != null){ - if(conditionSatisfy(condition)){ - if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { - //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); - } - if((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)) { - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - } - - - } - - }else { - logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - } - } - } - } - - } - logWriter.record("----------------------匹配结束", 2); - - bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); - - - return bestMatch; - } - - /** - * 在激活列表中选择满足匹配且优先级最高的一条配置条目 - * @param bestMatch - * @param activatedQueue - * @param context - * @return - * @throws IOException - */ - public Condition activatedQueueMatching(Condition bestMatch, Queue activatedQueue, ServletContext context) throws IOException { - Condition condition; - //待激活配置条目被激活后的匹配 - while (!activatedQueue.isEmpty()) { - condition = activatedQueue.remove(); - activatedMap.remove(condition.id); - - - if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority) - || condition.featureMap.get("activate") != null - || bestMatch.nextStep.contains(String.valueOf(condition.id)) || (!condition.configName.equals("") && bestMatch.nextStep.contains(condition.configName.substring(0,3)))){ - //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 - if(conditionSatisfy(condition)){ - if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { - activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); - } - - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - - - } - - } else { - logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - } - - - - - } - - return bestMatch; - - } - - /** - * 根据当前信息点,历史信息点,判断是否满足该condition的条件,match关键字指引擎识别的关键字包含在condition相应的关键词列表中,这里可以根据特征添加其他操作。 - * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 - * - * @param condition 配置文件(状态表)的一行 - * @return 满足条件就为True, 不满足就为False - */ - public boolean conditionSatisfy(Condition condition) { - boolean flag = true; - String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; - HashSet keywordSet = null; - - logWriter.record("-----------------------------------检索到配置条目", 0); - logWriter.record(userinfo.id2config.get(condition.id), 1); - - if (condition.featureMap.containsKey("match")) { - Iterator it = condition.currentPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - actionName = comparePair[0]; - cmpType = comparePair[1]; - keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - keywordSet = condition.currentPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - - it = condition.historyPremise.keySet().iterator(); - while (flag && it.hasNext()) { - premiseStr = it.next(); - comparePair = premiseStr.split("::"); - cmpType = comparePair[1]; - actionName = comparePair[0]; - //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, condition.featureMap.containsKey("includeCurInfo"), actionName); - - if (keyword == null) { - flag = false; - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - break; - } - - - - keywordSet = condition.historyPremise.get(premiseStr); - if (!premiseSatisfy(keyword, cmpType, keywordSet)) - flag = false; - - if(flag == false){ - logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); - } - } - } - - - return flag; - - } - - - - - /** - * 单个条件的匹配,判断是否满足条件 - * 比较类型分为 match、number、time、variable, - * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 - * - * @param keyword - * @param cmpType 比较类型 - * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 - * @return 返回匹配或者不匹配 - */ - public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { - boolean flag = true; - String operator = ""; - - try { - String splitPair[] = cmpType.split("-", 2); - if (splitPair.length > 1) { - operator = splitPair[1]; - cmpType = splitPair[0]; - } - - - if (cmpType.equals("match")) { - if(operator.equals("Keyword") || operator.equals("Include")) { - if (!keywordSet.contains(keyword)) { - flag = false; - } - if (flag == false && keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if (keywordSet.contains(k)) - flag = true; - } - } - } else if(operator.equals("Exclude")) { - if(keyword.contains(":")){ - String ks[] = keyword.split(":", 2); - if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) - flag = false; - }else { - if (keywordSet.contains(keyword)) { - flag = false; - } - } - }else if(operator.equals("Have")){ - for(String key:keywordSet){ - if(key.equals("")) - continue; - if(!keyword.contains(key)){ - flag = false; - break; - } - } - }else{ - flag = false; - } - - - } else if (cmpType.equals("number") && !keyword.equals("")) { - int candidateA = 0; - int candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(StringUtils.isNumeric(k)) - keyword = k; - - } - } - - if(!StringUtils.isNumeric(keyword)){ - return false; - - } - - candidateA = Integer.parseInt(keyword); - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = Integer.parseInt(k); - break; - } - } - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if (cmpType.equals("time")) { - - long candidateA, candidateB = 0; - - if (keyword.contains(":")) { - String ks[] = keyword.split(":"); - for (String k : ks) { - if(k.contains("年") && k.contains("月") && k.contains("日")) - keyword = k; - - } - } - - candidateA = MyFunc.transferToMillisecond(keyword); - - for (String k : keywordSet) { - if (!k.equals("")) { - candidateB = MyFunc.transferToMillisecond(k); - break; - } - } - if (operator.equals("Early")) - flag = candidateA < candidateB; - else if (operator.equals("Later")) - flag = candidateA > candidateB; - - } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { - String conditionName2 = "", conditionValue2 = ""; - for (String k : keywordSet) { - if (!k.equals("")) { - conditionName2 = k; - break; - } - } - - if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { - conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); - }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ - conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); - }else { - flag = false; - } - - - if(flag ){ - /** - * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true - */ - flag = false; - if(operator.equals("Equal")){ - flag = keyword.equals(conditionValue2); - - }else if(keyword.contains(":") && conditionValue2.contains(":")){ - String relPair1[] = keyword.split(":", 2), keyword1 = ""; - String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; - boolean similar = false; - - if(relPair1[0].equals(relPair2[0])){ - similar = true; - keyword1 = relPair1[1]; - keyword2 = relPair2[1]; - }else if (relPair1[1].equals(relPair2[1])){ - similar = true; - keyword1 = relPair1[0]; - keyword2 = relPair2[0]; - } - - if(similar){ - if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ - int candidateA = Integer.parseInt(keyword1); - int candidateB = Integer.parseInt(keyword2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") - && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword1); - long candidateB = MyFunc.transferToMillisecond(keyword2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ - if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ - int candidateA = Integer.parseInt(keyword); - int candidateB = Integer.parseInt(conditionValue2); - - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") - && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ - long candidateA = MyFunc.transferToMillisecond(keyword); - long candidateB = MyFunc.transferToMillisecond(conditionValue2); - - if (operator.equals("Bigger")) - flag = candidateA > candidateB; - else if (operator.equals("BiggerOrEqual")) - flag = candidateA >= candidateB; - else if (operator.equals("Smaller")) - flag = candidateA < candidateB; - else if (operator.equals("SmallerOrEqual")) - flag = candidateA <= candidateB; - else if (operator.equals("Equal")) - flag = candidateA == candidateB; - else if (operator.equals("NotEqual")) - flag = candidateA != candidateB; - - // 操作符为等于时可以比较两个字符串是否相同 - } - } - } - - - - } else if (cmpType.equals("any")) { - if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 - flag = false; - - } else { - flag = false; - } - } catch (IndexOutOfBoundsException e) { - System.out.println("配置文件格式有误"); - flag = false; - e.printStackTrace(); - } catch (ParseException e) { - System.out.println("时间解析错误"); - e.printStackTrace(); - flag = false; - } catch (Exception e) { - System.out.println("操作符有误"); - e.printStackTrace(); - flag = false; - } - - return flag; - } - - /** - * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 - * - * @return 返回给引擎的数据 - */ - public Solution getSolution(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, reply, variable; - Solution ans = new Solution(0, "", ""); - - - //如果一条配置文件有多个答案,则随 - // 机选择一个答案 - - //System.out.println(ans.getAnswer()); - - //post关键字 - if (ansCondition.featureMap.containsKey("post")) { - logWriter.record("---------------------进入表单结束",1); - ans = postToServer(ans, ansCondition); - logWriter.record("---------------------提交表单结束",1); - - //nextNext关键字 - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - //updateKnowledge关键字 - if (ansCondition.featureMap.containsKey("updateKnowledge")) { - logWriter.record("---------------------进入更新答案【略】",1); - updateKnowledge2(ansCondition); - logWriter.record("---------------------更新答案结束",1); - } - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ansCondition.featureMap.containsKey("newNext")) { - logWriter.record("---------------------进入判断下一步【略】",1); - ans = findNewNext(ans, ansCondition); - logWriter.record("---------------------判断下一步结束",1); - //上一步 - } else if (ansCondition.featureMap.containsKey("return-1")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - //停留 - } else if (ansCondition.featureMap.containsKey("return-0")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if(activeList.length > 0) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else - ans.setNext("nextStep= "); - //激活 - } else if (ansCondition.featureMap.containsKey("activate") || ansCondition.featureMap.containsKey("activate:after")) { - String activeList[] = historyInfoPoint.get("activeList").split("\\|"); - if (activeList.length == 1) - ans.setNext("nextStep=" + activeList[activeList.length - 1]); - else { - ans.setNext("nextStep=" + activeList[activeList.length - 2]); - } - } - - - - - - try { - - reply = MyFunc.randStr(ansCondition.answer); - reply = botUtil.varSlotReplace(reply); - reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter); - - ans.setAnswer(reply); - - botUtil.extraOperation(ansCondition, ans); - - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - - - if (ans.getNext().equals("")) { - ans.setNext("nextStep=" + ansCondition.nextStep); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return ans; - } - - /** - * 请求处理结束后台将当前信息的信息点转移到已知信息 - * @param ans - * @param context - * @param debugFlag - */ - public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { - //将当前信息点更新至历史信息点 - Iterator it = curInfoPoint.keySet().iterator(); - String actionName, lastReply; - String next = ans.getNext().split("=", 2)[1]; - - //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx - historyInfoPoint.put("currentAction", next); - historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); - - logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); - - HashSet skipSet = new HashSet() { - { - add("chat_key"); - add("action_name"); - add("bot_name"); - add("emptySet"); - add("query_text"); - } - }; - - if (debugFlag) - lastReply = ans.getAnswer().split(")")[2]; - else - lastReply = ans.getAnswer(); - historyInfoPoint.put("lastReply", lastReply); - - try { - String keyword1, keyword2; - while (it.hasNext()) { - actionName = it.next(); - - if(skipSet.contains(actionName)) - continue; - - keyword1 = curInfoPoint.get(actionName); - keyword2 = historyInfoPoint.get(actionName); - if (keyword2 == null) { - historyInfoPoint.put(actionName, keyword1); - }else if (historyInfoPoint.get(actionName).equals("do_reset")){ - historyInfoPoint.put(actionName, ""); - }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) - historyInfoPoint.put(actionName, keyword1); - } - historyInfoPoint.put("临时变量reply", ""); - historyInfoPoint.put("临时变量condition", ""); - historyInfoPoint.put("临时变量3", ""); - - - - //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 - * - * @param ans 最终返回的数据 - * @param context - */ - public void appendDebugInfo(Solution ans, ServletContext context) { - Iterator it = null; - String key, values, value; - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("bot_name"); - add("action_name"); - add("lastReply"); - add("unknownTextList"); - add("finalUnknownText"); - add("unknownText"); - add("randKey"); - add("userKey"); - } - }; - - it = curInfoPoint.keySet().iterator(); - String debugInfo = ""; - debugInfo += "(识别:"; - - while (it.hasNext()) { - key = it.next(); - values = curInfoPoint.get(key); - if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { - if (key.endsWith("_backup")) { - key = key.substring(0, key.length() - 7); - } - debugInfo += (" " + key + ":\'" + values + "\' "); - } - } - - debugInfo += ")"; - if(curInfoPoint.containsKey("debug_mode")) { - debugInfo = debugInfo.replace("-)", ""); - debugInfo += "(已知:"; - it = historyInfoPoint.keySet().iterator(); - while (it.hasNext()) { - - key = it.next(); - value = historyInfoPoint.get(key); - if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition") && !key.startsWith("临时变量")) - debugInfo += (" " + key + ":\'" + value + "\' "); - - } - } - ans.setAnswer(debugInfo + ")" + ans.getAnswer()); - } - - - /** - * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) - * - * @param ans 返回给用户的数据 - * @param ansCondition 满足条件最多的condition(配置文件的某一行) - */ - public Solution postToServer(Solution ans, Condition ansCondition) throws IOException { - String url = null, elem[], subElem[], key,keys, postType = "all"; - Map infoMap = new HashMap(); - List pairList = new ArrayList(); - Iterator k_iter = null; - FormsPoster poster = new FormsPoster(logWriter); - - HashSet skipSet = new HashSet() { - { - add("activeList"); - add("currentAction"); - add("lastUpdateTime"); - add("lastReply"); - } - }; - - elem = ansCondition.featureMap.get("post").split("\\|"); - url = elem[0]; - postType = elem[1]; - - - if(postType.equals("all")){ - poster.postAll(curInfoPoint, historyInfoPoint, ans, url); - }else if(postType.equals("term")){ - poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansCondition, url); - }else if(postType.equals("gameQA")){ - poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); - } - - return ans; - - } - - public Solution findNewNext(Solution ans, Condition ansCondition) { - String nextOptions[] = ansCondition.nextStep.split(","); - String conditionName, premises[], cpPair[]; - boolean flag = true; - - String activeList = historyInfoPoint.get("activeList"); - - for (String option : nextOptions) { - flag = true; - cpPair = option.split(":"); - conditionName = cpPair[0]; - if (cpPair.length == 1) { - ans.setNext("nextStep=" + conditionName); - break; - } - premises = cpPair[1].split("-"); - for (String premise : premises) { - if (premise.equals("known")) { - //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 - boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); - boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); - - //只有前两者都为假时,conditionExist才为真 - boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); - - if (conditionExist) - flag = false; - } - - if (premise.equals("active")) { - boolean isActive = activeList.contains(conditionName); - if (isActive) - flag = false; - } - } - - if (flag) { - ans.setNext("nextStep=" + conditionName); - break; - } - - } - return ans; - - } - - - public void updateKnowledge2(Condition condition) throws ParseException { - String keyword, variableName, updateValue, returnStr = "1"; - - - - Iterator iit = condition.updateKnowledge.keySet().iterator(); - while (iit.hasNext()) { - - variableName = iit.next(); - - keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); - updateValue = botUtil.knowledgeProcess(variableName, condition.updateKnowledge.get(variableName)); - - - try { - //做数字加法 - if (updateValue.startsWith("+")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("-")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(4); - //做字符串删除 - } else if (updateValue.startsWith("str-")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(4), ""); - - } else if (updateValue.startsWith("int+=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = String.valueOf(number + offset); - } - //做数字减法 - } else if (updateValue.startsWith("int-=")) { - if (keyword == null || keyword.equals("")) - keyword = "0"; - if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { - long time = MyFunc.transferToMillisecond(keyword); - int offset = Integer.parseInt(updateValue.substring(5)); - updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); - } else if (StringUtils.isNumeric(keyword)) { - int number = Integer.parseInt(keyword); - int offset = Integer.parseInt(updateValue.substring(1)); - updateValue = String.valueOf(number - offset); - } - //做字符串累加 - } else if (updateValue.startsWith("str+=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword + updateValue.substring(5); - //做字符串删除 - } else if (updateValue.startsWith("str-=")) { - if (keyword == null || keyword.equals("")) - keyword = ""; - updateValue = keyword.replace(updateValue.substring(5), ""); - - - //变量提取 - } else if (updateValue.startsWith("var=")) { - String conditionName = updateValue.substring(5, updateValue.length() - 3); - - if (updateValue.endsWith("-1}")) { - if (curInfoPoint.get(conditionName) != null) { - updateValue = curInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - } else if (updateValue.endsWith("-2}")) { - if (historyInfoPoint.get(conditionName) != null) { - updateValue = historyInfoPoint.get(conditionName); - } else { - updateValue = ""; - } - - //提取配置条目的下一步 - } else if (updateValue.endsWith("nextStep-3}")) { - updateValue = condition.nextStep; - //提取配置条目的回答 - } else if (updateValue.endsWith("reply-3}")) { - updateValue = MyFunc.randStr(condition.answer); - } - //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue - if (variableName.startsWith("process-nextStep")) { - condition.nextStep = updateValue; - updateValue = ""; - } - - } - - - } catch (Exception e) { - e.printStackTrace(); - continue; - } - - - - if(updateValue.equals("")) { - curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 - // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 - curInfoPoint.put(variableName, ""); - } - - botUtil.putKeyword(variableName, updateValue); - - - } - - } - - - public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException { - UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - String configStr = ""; - Integer configId; - Condition newCondition, originCondition; - List originConditionList = new ArrayList(); - - for (String configIdStr : activateList.split(",")) { - logWriter.record("------激活-------" + configIdStr + "-------
", 0); - try { - if (StringUtils.isNumeric(configIdStr)) { - configId = Integer.parseInt(configIdStr); - configStr = userinfo.id2config.get(configId); - originCondition = userinfo.id2condition.get(configId); - originConditionList.add(originCondition); - } else { - if (configIdStr.endsWith("*")) { - String prefix = configIdStr.substring(0, configIdStr.length()-1); - for(String name:userinfo.name2condition.keySet()){ - if (name.startsWith(prefix)){ - originConditionList.add(userinfo.name2condition.get(name)); - } - } - - } else { - originConditionList.add(userinfo.name2condition.get(configIdStr)); - } - - - } - } catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); - } - } - - for (Condition condition: originConditionList){ - originCondition = condition; - try { - - configId = originCondition.id; - - newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); - //condition = QuestionMatcher.buildCondition(condition, configStr); - - - - if (activatedMap.containsKey(configId)) { - if(newCondition.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) - activatedMap.get(configId).auxiliaryPriority = newCondition.auxiliaryPriority; - if(newCondition.activePriority > activatedMap.get(configId).activePriority) - activatedMap.get(configId).activePriority = newCondition.activePriority; - } else if (!activatedMap.containsKey(configId)) { - activatedMap.put(configId, newCondition); - activatedQueue.add(newCondition); - } - }catch (Exception e) { - e.printStackTrace(); - logWriter.record("----------激活失败:" + condition.configName, 5); - } - - } - - - } - - /** - * 一个提交表单后在激活的操作 - * @param ansCondition - * @param context - * @param userinfo - * @return - * @throws IOException - * @throws ParseException - */ - public Solution postActivate(Condition ansCondition, ServletContext context, UserInfo userinfo) throws IOException, ParseException { - Queue activatedQueue = new LinkedList(); - Solution bestMatch = null; - activateCondition(activatedQueue, userinfo.botAccount, ansCondition.priority, ansCondition.auxiliaryPriority, ansCondition.nextStep, context); - ansCondition = activatedQueueMatching(ansCondition, activatedQueue, context); - - bestMatch = getSolution(ansCondition, context, userinfo); - - return bestMatch; - - - } - - -} diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java deleted file mode 100644 index c8d8226..0000000 --- a/src/processing/ResponseFilter.java +++ /dev/null @@ -1,208 +0,0 @@ -//package com.qiwu.chatbotbackend.processing; -// -//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -//import com.qiwu.chatbotbackend.entity.Action; -//import com.qiwu.chatbotbackend.entity.UserInfo; -//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; -// -//import java.util.*; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; -//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; -// -//public class ResponseFilter { -// -// static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, -// String reply, UserInfo userInfo, Action ansCondition, LogWriter logWriter){ -// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; -// -// -// if(botType == null || botType.equals("")){ -// return reply; -// -// }else if (botType.equals("game")){ -// -// String site = historyInfoPoint.get("site"); -// -// -// reply = SimpleUtil.randStr(reply.split("~")); -// -// if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 -// return reply; -// } -// -// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ -// return reply; -// } -// -// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ -// return appendTalker(reply, historyInfoPoint, gameEnv, worldController); -// }else if (reply.equals("") && ( -// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals("")) && !historyInfoPoint.get("common_answer").equals("no answer")) -// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) -// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) -// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) -// ){ -// return reply; -// } -// -// -// -// -// -// if(userInfo.varInitialMap.get("unknownTextList") != null){ -// List unknownList = new ArrayList(); -// -// String lastTalker = ""; -// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 -// -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { -// if(isOnlineText(ans, historyInfoPoint)) -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return SimpleUtil.randStr(unknownList); -// } -// -// } -// -// if(userInfo.varInitialMap.get("finalUnknownText") != null){ -// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); -// List finalUnknownList = new ArrayList(); -// -// -// for(String ans:finalUnknownText.split("~")){ -// if(ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// if(isOnlineText(ans, historyInfoPoint)) -// finalUnknownList.add(ans); -// //return ans; -// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ -// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if(finalUnknownList.size() > 0){ -// return SimpleUtil.randStr(finalUnknownList); -// -// } -// } -// -// } -// -// -// return "找不到匹配文本"; -// } -// -// -// -// static Matcher findTalker(String reply){ -// Pattern findTalker = Pattern.compile(TALKER); -// Matcher m = findTalker.matcher(reply); -// -// return m; -// } -// /** -// * 查看回答文本的说话这是否在当前地点 -// * 0:没有说话者 -// * 1:说话者在当前地点 -// * 2:说话者不在当前地点或者不能说话 -// * @param reply -// * @param curInfoPoint -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @param site -// * @param logWriter -// * @return -// */ -// static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ -// String npc, location; -// -// Matcher m = findTalker(reply); -// int flag = 1; -// if(m.find()) { -// npc = m.group(1); -// location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); -// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ -// if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ -// flag = 1; -// logWriter.record("\"" + reply + "\":匹配", 1); -// }else { -// flag = 2; -// logWriter.record(npc + "不能说话", 1); -// } -// -// }else { -// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); -// flag = 2; -// } -// }else{ -// logWriter.record("\"" + reply + "\":没有npc名",1 ); -// flag = 0; -// } -// return flag; -// -// } -// -// /** -// * 在头部没有【%s@%s】的文本加上【%s@%s】 -// * @param reply -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @return -// */ -// static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ -// -// List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); -// String npc = ""; -// List filtedNpcList = new ArrayList(); -// -// for(String npcName:npcList){ -// if(isOnlineMode(npcName, historyInfoPoint)) { -// filtedNpcList.add(npcName); -// }else{ -// System.out.println(npcName + "是离线模式"); -// } -// } -// if(filtedNpcList.size() != 0) -// npc = SimpleUtil.randStr(filtedNpcList); -// else -// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); -// -// -// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION) + reply; -// -// } -// -// static Boolean isOnlineMode(String npc, Map historyInfoPoint){ -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// } -// static Boolean isOnlineText(String text, Map historyInfoPoint){ -// Matcher m = findTalker(text); -// String npc = ""; -// if(m.find()) { -// npc = m.group(1); -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// }else{ -// System.out.println("竟然没找到npc"); -// return false; -// } -// } -// -//} diff --git a/src/processing/ResponseFilter3.java b/src/processing/ResponseFilter3.java deleted file mode 100644 index db46673..0000000 --- a/src/processing/ResponseFilter3.java +++ /dev/null @@ -1,260 +0,0 @@ -//package com.qiwu.chatbotbackend.processing; -// -//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -//import com.qiwu.chatbotbackend.entity.Condition; -//import com.qiwu.chatbotbackend.entity.UserInfo; -//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; -// -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; -//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; -// -//public class ResponseFilter3 { -// -// static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, -// String reply, UserInfo userInfo, Condition ansCondition, LogWriter logWriter){ -// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; -// -// -// if(botType == null || botType.equals("")){ -// return reply; -// -// }else if (botType.equals("game")){ -// -// String site = historyInfoPoint.get("site"); -// -// -// reply = MyFunc.randStr(reply.split("~")); -// -// if(reply.endsWith("开始游戏或者继续游戏")){ -// return reply; -// } -// -// -// //如果剧情跳转中包含了自动跳转的文本,那么不判断是否处于同一地点 -//// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ -//// return reply; -//// } -// -// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// return reply; -// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ -// return appendTalker(reply, historyInfoPoint, gameEnv, worldController); -// -// //如果回答为空但是有qa回答、地图物品npc查询结果则允许返回空文本,否则往下漏,取unknown文本 -// }else if (reply.equals("") && ( -// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals(""))) -// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) -// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) -// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) -// ){ -// return reply; -// } -// -// -// -// if(userInfo.varInitialMap.get("unknownTextList") != null){ -// List unknownList = new ArrayList(); -// -// String lastTalker = ""; -// Boolean onlyLastTalker = false; -// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 -// if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ -//// Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); -//// while(m.find()) { -//// //回答unknown文本的npc必须处于在线模式 -//// npc = m.group(1); -//// if(isOnlineMode(npc, historyInfoPoint)) { -//// //找到最后一个说话且处于离线模式的npc -//// lastTalker = npc; -//// }else{ -//// System.out.println(npc + "是离线模式"); -//// } -//// } -// lastTalker = findPlotLastTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)), site, historyInfoPoint, gameEnv, logWriter); -// if(!lastTalker.equals("") && userInfo.varInitialMap.get("unknownTextList").contains(lastTalker)) -// onlyLastTalker = true; -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (ans.contains(lastTalker) && onlyLastTalker) { -// -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return MyFunc.randStr(unknownList); -// } -// -// }else { -// -// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { -// if (ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { -// -// unknownList.add(ans); -// //return ans; -// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { -// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if (unknownList.size() > 0) { -// return MyFunc.randStr(unknownList); -// } -// } -// } -// -// -// //最终unknown文本 -// if(userInfo.varInitialMap.get("finalUnknownText") != null){ -// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); -// List finalUnknownList = new ArrayList(); -// -// -// for(String ans:finalUnknownText.split("~")){ -// if(ans.equals("")) -// continue; -// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ -// finalUnknownList.add(ans); -// //return ans; -// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ -// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); -// } -// } -// if(finalUnknownList.size() > 0){ -// return MyFunc.randStr(finalUnknownList); -// -// } -// } -// -// } -// -// -// return "找不到匹配文本"; -// } -// -// -// -// static Matcher findTalker(String reply){ -// Pattern findTalker = Pattern.compile(TALKER); -// Matcher m = findTalker.matcher(reply); -// -// return m; -// } -// /** -// * 查看回答文本的说话这是否在当前地点 -// * 0:没有说话者 -// * 1:说话者在当前地点 -// * 2:说话者不在当前地点 -// * @param reply -// * @param curInfoPoint -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @param site -// * @param logWriter -// * @return -// */ -// static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter, Boolean needOnline){ -// String npc, location; -// -// Matcher m = findTalker(reply); -// int flag = 1; -// if(m.find()) { -// npc = m.group(1); -// flag = npcIsSameLocation(npc, site, reply, historyInfoPoint, gameEnv, logWriter); -// }else{ -// logWriter.record("\"" + reply + "\":没有npc名",1 ); -// flag = 0; -// } -// return flag; -// -// } -// -// static Integer npcIsSameLocation(String npc, String site, String reply, Map historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){ -// Integer flag; -// String location = gameEnv.queryNpcAttrByNpcName(npc, "location"); -// //String location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); -// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ -// if((gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能"))){ -// flag = 1; -// logWriter.record("\"" + reply + "\":匹配", 1); -// }else { -// flag = 2; -// logWriter.record(npc + "不能说话或者是离线模式", 1); -// } -// -// }else { -// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); -// flag = 2; -// } -// -// return flag; -// } -// -// /** -// * 在头部没有【%s@%s】的文本加上【%s@%s】 -// * @param reply -// * @param historyInfoPoint -// * @param gameEnv -// * @param worldController -// * @return -// */ -// static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ -// -// List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); -// String npc = ""; -// List filtedNpcList = new ArrayList(); -// -// for(String npcName:npcList){ -// if(isOnlineMode(npcName, historyInfoPoint)) { -// filtedNpcList.add(npcName); -// }else{ -// System.out.println(npcName + "是离线模式"); -// } -// } -// if(filtedNpcList.size() != 0) -// npc = MyFunc.randStr(filtedNpcList); -// else -// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); -// -// -// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION); -// -// } -// -// static Boolean isOnlineMode(String npc, Map historyInfoPoint){ -// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); -// } -// -// public static String findPlotLastTalker(String text, String site, Map historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){ -// Matcher m = findTalker(text); -// String npc, lastTalker = ""; -// while(m.find()) { -// //回答unknown文本的npc必须处于在线模式 -// npc = m.group(1); -// //处于离线模式 可以说话 相同地点 -// if(isOnlineMode(npc, historyInfoPoint) && npcIsSameLocation(npc, site, npc, historyInfoPoint, gameEnv, logWriter) == 1) { -// //找到最后一个说话且处于离线模式的npc -// lastTalker = npc; -// }else{ -// System.out.println(npc + "是离线模式"); -// } -// } -// -// return lastTalker; -// } -// -//} diff --git a/src/processing/SimpleUtil.java b/src/processing/SimpleUtil.java deleted file mode 100644 index 1d9ecfa..0000000 --- a/src/processing/SimpleUtil.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.entity.Solution; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - - -public class SimpleUtil { - - /** - * 将后台返回的数据转成json格式 - */ - public static String toJson(Solution ans) { - JSONObject jobj = new JSONObject(); - jobj.put("solution", ans.getAnswer()); - jobj.put("status", ans.getStatus()); - jobj.put("process", ans.getNext()); - return jobj.toString(); - } - - public static String toJson(String returnStr) { - JSONObject jobj = new JSONObject(); - jobj.put("returnString", returnStr); - return jobj.toString(); - } - - /** - * 当请求中的数据是json格式时,该函数用于提取request中的json数据 - * - * @param request - * @return json字符串 - */ - public static String readJSONString(HttpServletRequest request) { - StringBuffer json = new StringBuffer(); - String line = null; - - try { - BufferedReader reader = request.getReader(); - while ((line = reader.readLine()) != null) { - json.append(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return json.toString(); - } - - /** - * 通过get方法传递参数时需要对参数的编码进行转换 - */ - public static String convert2Utf8(String s) { - if (s == null) return null; - try { - s = new String(s.getBytes("iso-8859-1"), "utf-8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return s; - } - - public static long transferToMillisecond(String keyword) throws ParseException { - long time; - - System.out.println(keyword); - - String timeSeries[] = {"时", "分", "秒"}; - for (String f : timeSeries) { - if (!keyword.contains(f)) - keyword += "0" + f; - } - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - time = format.parse(keyword).getTime(); - - return time; - } - - public static String transferToStandardTime(long time) throws ParseException { - - SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒"); - - Date date = new Date(time); - return format.format(date); - - } - - public static boolean isInteger(String str){ - return true; - } - - - - public static JSONObject postJSON(String url, JSON data, String auth) 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); - - if(auth != null){ - httpPost.setHeader("Authorization", auth); - } - - try { - HttpResponse resp = client.execute(httpPost); - jobj.put("status_code", resp.getStatusLine().getStatusCode()); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - jobj = JSONObject.parseObject(respContent); - jobj.put("post_status", 1); - } else { - jobj.put("post_status", 0); - jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return jobj; - - } - - - - - - public static JSONObject postFORM(String url, List pairList) throws UnsupportedEncodingException { - - - HttpPost httpPost = new HttpPost(url); - CloseableHttpClient client = HttpClients.createDefault(); - String respContent = null; - String keyName = null; - - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); - entity.setContentType("application/x-www-form-urlencoded"); - httpPost.setEntity(entity); - JSONObject jobj = new JSONObject(); - - try { - System.out.println("url为:" + url); - HttpResponse resp = client.execute(httpPost); - if (resp.getStatusLine().getStatusCode() == 200) { - HttpEntity he = resp.getEntity(); - respContent = EntityUtils.toString(he, "UTF-8"); - jobj = JSONObject.parseObject(respContent); - jobj.put("post_status", 1); - - } else { - jobj.put("post_status", 0); - jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode()); - } - } catch (Exception e) { - jobj.put("error_message", "提交表单时出错:" + e.getMessage()); - jobj.put("post_status", 0); - } - - return jobj; - - } - - public static String randStr(String strList[]){ - String reply; - int randNum = (int) (Math.random() * strList.length); - reply = strList[randNum]; - - return reply; - } - - public static String randStr(List strList){ - String reply; - - int randNum = (int) (Math.random() * strList.size()); - reply = strList.get(randNum); - - return reply; - } - - -} \ No newline at end of file diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java deleted file mode 100644 index 7f58522..0000000 --- a/src/processing/UserInfoController.java +++ /dev/null @@ -1,542 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.UserInfo; - -import javax.servlet.ServletContext; -import java.io.*; -import java.sql.SQLException; -import java.util.*; - -import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; - -public class UserInfoController { - - static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; - static String FILE_ERROR = ".txt文件有误"; - - - - /** - * 根据本地配置文件生成用户信息 - */ - public static void configInit(ServletContext context) throws IOException { - - String line; - - System.out.println("configDir"+ CONFIG_DIR); - - File dir = new File(CONFIG_DIR); - if (!dir.exists()) - dir.mkdir(); - for (File configFile : dir.listFiles()) { - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - String fileName = configFile.getName(); - UserInfo userinfo = new UserInfo(fileName.split("\\.")[0]); - - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } - - reader.close(); - br.close(); - } - - } - - public static void userConfigInit(String botAccount, ServletContext context) throws IOException { - String line; - File userFile = new File(CONFIG_DIR + "/" + botAccount + ".txt"); - - System.out.println(userFile.getAbsolutePath()); - if (!userFile.exists()) { - BufferedReader br = new BufferedReader(new StringReader("")); - UserInfo userinfo = new UserInfo(botAccount); - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } - - } else { - FileReader reader = new FileReader(userFile); - BufferedReader br = new BufferedReader(reader); - UserInfo userinfo = new UserInfo(botAccount); - - try { - userinfo = buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - System.out.println(userinfo.botAccount + FILE_ERROR); - e.printStackTrace(); - } - - reader.close(); - br.close(); - } - } - - - /** - * 解析一行配置文件 - * @param action - * @param line - * @return - */ - public static Action buildCondition(Action action, String line) { - String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; - - - try { - - text = line.split("---"); - - line = text[0]; - if(text.length > 1 && text[1].startsWith("<-")) - line += "---" + text[1]; - - element = line.replace("\n", "").split("\\|=\\>\\|"); - premises = element[0].split("\\|"); - feature = premises[2]; - cur_premises = premises[0].split(","); - history_premises = premises[1].split(","); - - - action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); - //action.setConfigName(premises[4].split("=", 2)[1]); - - - next = element[1].split("\\|"); - if (next.length < 4) - return action; - - if(premises.length < 5) - action.setConfigName(""); - else - action.setConfigName(premises[4].split("=", 2)[1]); - - - - //回答可以有多个,然后可随机选择一个 - action.setAnswer(next[0].split("~")); - //第二处 - action.setNextStep(next[1].split("=", 2)[1]); - action.setId(Integer.parseInt(next[3].split("=")[1])); - action.setStatus(next[2].split("=")[1]); - - - //featureMap的构建 - features = feature.split(","); - for (String feat : features) { - if (feat.equals("") || feat.equals(" ")) { - continue; - } else if (feat.startsWith("updateKnowledge")) { - String[] knowledge = feat.split("-<-"); - int length = knowledge.length; - action.getFeatureMap().put("updateKnowledge", ""); - for (int i = 1; i < length; i++) { - if (knowledge[i].equals("") || knowledge[i].equals(" ")) - continue; - - pair = knowledge[i].split(":", 2); - action.getUpdateKnowledge().put(pair[0], pair[1]); - } - } else if (feat.startsWith("post")) { - pair = feat.split("\\(", 2); - url = pair[1]; - url = url.substring(0, url.length() - 1); - pair = pair[0].split("::"); - action.getFeatureMap().put("post", url + "|" + pair[1]); - } else { - action.getFeatureMap().put(feat, ""); - } - } - - - insertPremise(action.getCurrentPremise(), cur_premises); - insertPremise(action.getHistoryPremise(), history_premises); - //满足条件越多,优先级越大 - action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size()); - //action.activePriority = action.priority; - /* - for(String premise:cur_premises){ - pair = premise.split("="); - action.indexName.add(pair[0]); - } - */ - firstCnditionName = cur_premises[0]; - if (firstCnditionName.equals(" ")) - action.setIndexName("emptySet"); - else - action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]); - } catch (IndexOutOfBoundsException e) { - e.printStackTrace(); - System.out.println(line); - System.out.println(TEXT_PARSE_ERROR); - } - return action; - } - - - /** - * @param br - * @param userinfo - * @param overRide 覆盖之前的状态表 - * @return - * @throws IOException - */ - public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { - String line, infoName, extraElements[]; - HashMap> conditionTable = null; - - //是否覆盖原有的数据 - if (overRide) { - conditionTable = new HashMap>(); - userinfo.id2condition.clear(); - userinfo.id2config.clear(); - userinfo.configStr = ""; - userinfo.varInitialMap.clear(); - userinfo.name2condition.clear(); - - } else { - conditionTable = userinfo.conditionTable; - } - - List actionList = null; - - - while ((line = br.readLine()) != null) { - try { - if (line.trim().equals("")) - continue; - line = line.replace("\n", ""); - - //在用户信息中添加额外信息,如设为active的action - if (line.contains("extraInfo")) { - extraElements = line.split("\\|", -1); - userinfo.extraInfo.put(extraElements[1], extraElements[2]); - } else if (line.contains("varInitial")) { - extraElements = line.split("\\|", -1); - userinfo.varInitialMap.put(extraElements[1], extraElements[2]); - } else { - Action action = new Action(); - action = buildCondition(action, line); - actionList = conditionTable.get(action.getIndexName()); - if (actionList == null) - actionList = new ArrayList(); - actionList.add(action); - conditionTable.put(action.getIndexName(), actionList); - if (action.getId() != 0) { - if(!action.getConfigName().equals("")){ - userinfo.name2condition.put(action.getConfigName(), action); - } - userinfo.id2config.put(action.getId(), line); - userinfo.id2condition.put(action.getId(), action); - } - - } - } catch (ArrayIndexOutOfBoundsException e) { - System.out.println(TEXT_PARSE_ERROR); - - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - System.out.println(line); - } - } - - userinfo.conditionTable = conditionTable; - - return userinfo; - } - - /** - * 通过split方法解析配置文件中的条件部分(如:xihuan::match-Include=+dota+英雄联盟) - * - * @param premiseMap 前提条件哈希表 - */ - public static void insertPremise(HashMap> premiseMap, String[] premisesString) { - String pair[]; - HashSet keyWordSet = null; - for (String premise : premisesString) { - // System.out.println(premise); - if (premise.equals("") || premise.equals(" ")) - continue; - pair = premise.split("=", 2); - keyWordSet = new HashSet(); - for (String keyword : pair[1].split("\\+")) - //为了处理条件不满足(为空)时的特殊情况, - if (keyword.equals("null")) keyWordSet.add(""); - else if (!keyword.equals("")) keyWordSet.add(keyword); - premiseMap.put(pair[0], keyWordSet); - } - } - - - /** - * 原为通过用户chat_key从数据库中获得用户名 - * 根据用户名从servletContext中获得用户的数据userinfo(配置文件及相应的状态表) - * 如果context中没有,就重新加载本地配置文件(即初始化) - * 初始化后还是没有就创建一个userinfo - * ------------- - * 修改后直接从request获得用户名,并从context根据用户名获得userinfo - * - * @param bot_name 用户名 - * @return 用户信息 - */ - public UserInfo userInfoQuery(String bot_name, ServletContext context) throws IOException, SQLException { - /*根据数据库得到botAccount改为直接得到 - SqlHelper helper = new SqlHelper(); - String botAccount = helper.querybotAccountByKey(chat_key); - */ - String botAccount = bot_name; - UserInfo userinfo = null; - if (context.getAttribute(botAccount) == null) { - userConfigInit(botAccount, context); - } - if (context.getAttribute(botAccount) == null) { - - return null; - //userinfo = new UserInfo(botAccount); - //userinfo.conditionTable = new HashMap>(); - } else { - userinfo = (UserInfo) context.getAttribute(botAccount); - } - //helper.destroy(); - - - return userinfo; - } - - - public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { - int id = Integer.parseInt(configId); - Action action = new Action(); - UserInfoController userInfoController = new UserInfoController(); - //data=configLine+"---"+conditionNameList - - String conditionNameList[] = data.split(","); - String conditionName = ""; - if (context.getAttribute(userName) == null) { - userInfoController.userConfigInit(userName, context); - } - UserInfo userInfo = (UserInfo) context.getAttribute(userName); - - if (userInfo.id2config.containsKey(id)) { - Action oldAction = userInfo.id2condition.get(id); - //------------------- - try { - - conditionName = oldAction.getIndexName(); - } catch (Exception e) { - e.printStackTrace(); - } - - - if (userInfo.conditionTable.get(conditionName) != null) { - List actionList = userInfo.conditionTable.get(conditionName); - Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); - while (condIter.hasNext()) { - Action c = condIter.next(); - if (c.getId() == id) { - condIter.remove(); - } - } - } - - userInfo.name2condition.remove(oldAction.getConfigName()); - userInfo.id2config.remove(id); - userInfo.id2condition.remove(id); - } else { - System.out.println("未找到要删除的configId"); - } - - return true; - } - - public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { - Action action = new Action(); - String conditionName = ""; - - for (int configId : idGroup) { - if (userInfo.id2config.containsKey(configId)) { - Action oldAction = userInfo.id2condition.get(configId); - try { - - conditionName = oldAction.getIndexName(); - } catch (Exception e) { - e.printStackTrace(); - } - - - if (userInfo.conditionTable.get(conditionName) != null) { - List actionList = userInfo.conditionTable.get(conditionName); - Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); - while (condIter.hasNext()) { - Action c = condIter.next(); - if (c.getId() == configId) { - condIter.remove(); - } - } - } - - userInfo.name2condition.remove(oldAction.getConfigName()); - userInfo.id2config.remove(configId); - userInfo.id2condition.remove(configId); - } else { - System.out.println("未找到要删除的configId:" + configId); - } - } - - - return true; - } - - - public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { - Action action = new Action(); - //data=configLine+"---"+conditionNameList - String dataPair[] = data.split("---"); - String configLine = dataPair[0]; - String conditionNameList[]; - UserInfoController userInfoController = new UserInfoController(); - int id = Integer.parseInt(configId); - - action = userInfoController.buildCondition(action, configLine); - - if (context.getAttribute(userName) == null) { - userInfoController.userConfigInit(userName, context); - } - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - - if (userinfo.conditionTable.get(action.getIndexName()) == null) { - List actionList = new ArrayList(); - userinfo.conditionTable.put(action.getIndexName(), actionList); - } - - if(!action.getConfigName().equals("")){ - userinfo.name2condition.put(action.getConfigName(), action); - } - userinfo.conditionTable.get(action.getIndexName()).add(action); - userinfo.id2config.put(id, configLine); - userinfo.id2condition.put(id, action); - - return true; - - } - - public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { - Action action = new Action(); - //data=configLine+"---"+conditionNameList - String dataPair[] = data.split("---", -1); - String name = dataPair[0], value = dataPair[1]; - - UserInfoController userInfoController = new UserInfoController(); - - - if (context.getAttribute(userName) == null) { - userInfoController.userConfigInit(userName, context); - } - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - userinfo.varInitialMap.put(name, value); - - - return true; - - } - - public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { - //data=configLine+"---"+conditionNameList - String name = data; - UserInfoController userInfoController = new UserInfoController(); - - - if (context.getAttribute(userName) == null) { - userInfoController.userConfigInit(userName, context); - } - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - userinfo.varInitialMap.remove(name); - - - return true; - - } - - - public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { - UserInfoController userInfoController = new UserInfoController(); - - - if (context.getAttribute(userName) == null) { - userInfoController.userConfigInit(userName, context); - } - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - - String extraElements[] = data.split("\\|"); - userinfo.extraInfo.put(extraElements[1], extraElements[2]); - - return true; - } - - - public static String writeConfigText(String userName, UserInfo userinfo) throws IOException { - - - String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText; - String path = CONFIG_DIR + "/" + userName + ".txt"; - - - File file = new File(path); - File dir = new File(System.getProperty("user.dir") + "/config"); - - System.out.println(userName); - System.out.println("config_dir" + dir.getAbsolutePath()); - String returnMessage = "success"; - - if (!dir.exists()) - dir.mkdir(); - if (!file.exists()) { - file.createNewFile(); - } - - FileWriter fw = new FileWriter(file); - BufferedWriter bw = new BufferedWriter(fw); - try { - Iterator keyIter = userinfo.extraInfo.keySet().iterator(); - while (keyIter.hasNext()) { - String info = keyIter.next(); - if (!userinfo.extraInfo.get(info).equals("")) - bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); - } - - keyIter = userinfo.varInitialMap.keySet().iterator(); - while (keyIter.hasNext()) { - String info = keyIter.next(); - bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); - } - - Iterator idIter = userinfo.id2config.keySet().iterator(); - while (idIter.hasNext()) { - int id = idIter.next(); - bw.write(userinfo.id2config.get(id) + "\n"); - } - bw.write("\n"); - } catch (Exception e) { - e.printStackTrace(); - returnMessage = "config file write error"; - } finally { - bw.close(); - fw.close(); - } - - return returnMessage; - } -} diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java deleted file mode 100644 index 31ab377..0000000 --- a/src/processing/WorldController.java +++ /dev/null @@ -1,472 +0,0 @@ -package com.qiwu.chatbotbackend.processing; - - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.task.utils.GameBotUtil; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; - -import static com.qiwu.chatbotbackend.Config.Config.*; - -public class WorldController { - public LogWriter logWriter = null; - public UserInfo userInfo = null; - - public WorldController(LogWriter logWriter, UserInfo userInfo) { - this.logWriter = logWriter; - this.userInfo = userInfo; - } - - public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ - String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr="", owner; - String namePair[] = varName.split("_"); - boolean operationFlag = true; - List textList = null; - String subValuePair[] = null; - - logWriter.record(String.format("---------------------key:%s, value:%s", varName, varValue), 0); - - String location = "", value = ""; - if(valuePair[0].startsWith("query")){ //查询专用 - String ItemName = ""; - String currentLocation; - - if(varName.startsWith("goods_")) { - currentLocation = historyInfoPoint.get("site"); - switch (valuePair[0]) { - case "queryGoodsIntro": - subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); - returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]); - if(returnStr == null ) - returnStr = DONT_FOUND; - break; - - case "queryAttrByGoodsName": - subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); - value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); - - if(returnStr == null) { - returnStr = DONT_FOUND; - }else{ - returnStr = userInfo.varInitialMap.get("GET_ITEM_ATTR").replace(ITEM_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value); - - } - break; - case "queryAllAttrByGoodsName": - textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); - if(textList == null || textList.size() == 0) - returnStr = DONT_FOUND; - else { - for (String site : textList) - returnStr += "、" + site; - returnStr = returnStr.substring(1); - } - break; - case "queryAroundGoodsByClassName": - textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); - if(textList == null || textList.size() == 0) - returnStr = DONT_FOUND; - else { - for (String site : textList) - returnStr += "、" + site; - returnStr = returnStr.substring(1); - } - break; - - case "queryLocationByConditionName": - // - ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; - ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName); - returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); - if(returnStr == null || returnStr.equals("否")){ - returnStr = ATTRIBUTE_HIDDEN; - } else if(returnStr.equals("是")){ - location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); - if(location == null){ - returnStr = DONT_FOUND; - }else{ - owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "owner"); - //logWriter.record(ItemName + "-owner:" + owner, 0); - - if(owner != null && !owner.equals("")){ - //如果物品的所属角色是玩家,那么回答物品在你身上 - if(owner.equals("玩家")){ - returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS"); - }else { - //不然回答物品在某个人身上 - if(userInfo.varInitialMap.get("FIND_ITEM_OWNER") == null) - userInfo.varInitialMap.put("FIND_ITEM_OWNER", FIND_ITEM_OWNER); - System.out.println("pattern:" + userInfo.varInitialMap.get("FIND_ITEM_OWNER") + ", ItemName:" + ItemName + ", owner:" + owner); - returnStr = userInfo.varInitialMap.get("FIND_ITEM_OWNER").replace(ITEM_NAME_SLOT, ItemName).replace(NPC_NAME_SLOT, owner); - } - }else { - //没有所属角色就回答物品在某个地点 - returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location); - } - } - } - break; - case "queryPlayerItems": - String player = gameEnv.queryPlayerName(); - textList = gameEnv.queryGoodsByNpcName(player); - if(textList == null || textList.size() == 0) - returnStr = NOTHING_FOUND; - else { - for (String site : textList) - returnStr += "、" + site; - - returnStr = userInfo.varInitialMap.get("WE_HAVE").replace(ITEM_LIST_SLOT, returnStr.substring(1)); - } - - break; - - - case "queryFindItemWay": - // - ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; - returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); - if(returnStr == null || returnStr.equals("否")){ - returnStr = DONT_FOUND; - } else if(returnStr.equals("是")){ - location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); - if(location == null){ - returnStr = DONT_FOUND; - }else{ - returnStr = userInfo.varInitialMap.get("FIND_ITEM_WAY").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location); - } - } - - break; - default: - } - }else if(varName.startsWith("npc_")) { - String NPCName = ""; - switch(valuePair[0]){ - case "queryNpcIntro": - //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); - subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); - returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); - if(returnStr == null) - returnStr = DONT_FOUND; - - break; - case "queryAttrByNPCName": - //根据condition的名字,从当前信息点中获取npc的名字 - subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); - subValuePair[0] = subValuePair[0].replace("哪里", "location"); - value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); - if(value == null) { - returnStr = DONT_FOUND; - }else{ - - returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace(NPC_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value); - - } - break; - - case "queryLocationByNPCName": - // - - location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); - if(location == null){ - returnStr = DONT_FOUND; - }else{ - returnStr = location; - } - - break; - case "queryLocationByConditionName": - // - NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; - NPCName = gameEnv.getNpcNameByNickname(historyInfoPoint.get("site"), NPCName); - - System.out.println(NPCName); - returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); - if(returnStr == null || returnStr.equals("否")){ - returnStr = DONT_FOUND; - } else if(returnStr.equals("是")){ - - - location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); - if(location == null){ - returnStr = DONT_FOUND; - }else{ - returnStr = userInfo.varInitialMap.get("FIND_NPC_LOCATION").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location); - } - } - break; - - case "queryFindNPCWay": - - // - NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; - returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); - if(returnStr == null || returnStr.equals("否")){ - returnStr = DONT_FOUND; - } else if(returnStr.equals("是")){ - location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); - if(location == null){ - returnStr = DONT_FOUND; - }else{ - returnStr = userInfo.varInitialMap.get("FIND_NPC_WAY").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location); - } - } - - break; - - case "queryLastTalker": - String lastTalker = "没找到npc名字"; - Matcher m = GameBotUtil.findTalker(historyInfoPoint.get("lastReply")); - while(m.find()){ - lastTalker = m.group(1); - } - - returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace(NPC_NAME_SLOT, lastTalker); - break; - - - - default: - } - }else if (varName.startsWith("map_")) { - String format = ""; - String start = historyInfoPoint.get("site"); - String destination = ""; - List sites = new ArrayList<>(); - - switch (valuePair[0]) { - case "queryAroundAllBySite": - format = userInfo.varInitialMap.get("AROUND_THINGS"); - - - - sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); - if(sites == null || sites.size() == 0) - returnStr = NOTHING_FOUND; - else { - - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - - returnStr = format.replace(NPC_ITEM_LIST_SLOT, text.substring(1)); - } - break; - case "queryAroundNpcBySite": - format = userInfo.varInitialMap.get("AROUND_PEOPLE"); - - - sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); - if(sites == null || sites.size() == 0) - returnStr = NOTHING_FOUND; - else { - - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - - returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); - } - break; - case "queryAroundGoodsBySite": - - format = userInfo.varInitialMap.get("AROUND_ITEMS"); - - sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); - if(sites == null || sites.size() == 0) - returnStr = NOTHING_FOUND; - else { - if(sites.size() > 0) { - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - returnStr = format.replace(ITEM_LIST_SLOT, text.substring(1)); - } - } - break; - case "queryCanGoBySite": - - format = userInfo.varInitialMap.get("CAN_GO_SITES"); - - sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); - if(sites == null) { - returnStr = userInfo.varInitialMap.get("CAN_GO_NOWHERE"); - } - else if(sites.size() == 0){ - returnStr = userInfo.varInitialMap.get("CAN_GO_NOWHERE"); - } else { - if(sites.size() > 0) { - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - returnStr = format.replace(CAN_GO_SITE_SLOT, text.substring(1)); - } - } - break; - - case "queryHowToPathBySite": - format = userInfo.varInitialMap.get("PATH_EXIST"); - - if(!currentInfoPoint.containsKey(valuePair[1])) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); - break; - } - destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; - destination = gameEnv.getPlaceNameByNickname(start, destination); - - sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), destination); - if(sites == null) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; - } - else { - if(sites.size() > 0) { - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); - } - } - break; - - case "queryToDoPathBySite": - format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT"); - - destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; - destination = gameEnv.getPlaceNameByNickname(start, destination); - - if(!currentInfoPoint.containsKey(valuePair[1])) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; - break; - } - - sites = gameEnv.queryPathBySite(start, destination); - if(sites == null) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; - } else { - if(sites.size() > 0) { - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); - } - } - break; - - case "queryPathNotExist": - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; - break; - case "queryAroundPlace": - - format = userInfo.varInitialMap.get("AROUND_PLACE"); - - - sites = gameEnv.queryCanGoBySite(start); - if(sites == null || sites.size() == 0) { - returnStr = NOWHERE_CAN_GO; - } else { - if(sites.size() > 0) { - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - returnStr = format.replace(SITE_LIST_SLOT, text.substring(1)); - } - } - break; - case "queryInnerNpcBySite": - format = userInfo.varInitialMap.get("INNER_PEOPLE"); - - - sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); - if(sites == null || sites.size() == 0) - returnStr = NOTHING_FOUND; - else { - - StringBuffer text = new StringBuffer(); - - for(String site:sites){ - text.append("、" + site); - } - - returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); - } - break; - - case "queryTaskDescription": - format = userInfo.varInitialMap.get("TASK_DESCRIPTION"); - - - returnStr = format.replace(TASK_DESCRIPTION_SLOT, userInfo.varInitialMap.get(TASK_DESCRIPTION)); - - break; - case "queryWhereIam": - returnStr = userInfo.varInitialMap.get("WHERE_I_AM").replace(SITE_SLOT, historyInfoPoint.get("site")); - break; - case "queryPathAt": - returnStr = userInfo.varInitialMap.get("PATH_AT").replace(SITE_SLOT, historyInfoPoint.get("site")); - break; - case "queryPathAdjoin": - returnStr = userInfo.varInitialMap.get("PATH_ADJOINT"); - break; - case "queryItemsInPlace": - break; - case "queryNPCInPlace": - break; - case "queryThingsInPlace": - break; - - } - - } - }else if(valuePair[0].startsWith("updateFollowerLocation")){ - Boolean flag = true; - switch (valuePair[0]) { - case "updateFollowerLocation": - flag = gameEnv.updateFollowerLocation(valuePair[1]); - - } - - if(flag){ - returnStr = "更新成功"; - }else - returnStr = "更新失败"; - - }else{ //增删改统一使用 - logWriter.record("更新环境--varName:" + varName + "valuePair:" + valuePair[0] + ":" + valuePair[1], 1); - try { - gameEnv.CUD(varName, valuePair[0], valuePair[1]); - } catch (Exception e){ - System.out.println("更新环境出现异常--varName:" + varName + "valuePair:" + valuePair[0] + ":" + valuePair[1]); - } - } - - - logWriter.record("---------------------return:" + returnStr, 0); - return returnStr; - } - - public static String findLocationName(GameEnv gameEnv, String locationName, String site){ - return gameEnv.getPlaceNameByNickname(site, locationName); - } - - - - -} diff --git a/src/servlet/ContextDestroyListener.java b/src/servlet/ContextDestroyListener.java deleted file mode 100644 index 92eedbf..0000000 --- a/src/servlet/ContextDestroyListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; -import java.io.IOException; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.Map; - -@WebListener -public class ContextDestroyListener implements ServletContextListener { - - public void contextDestroyed(ServletContextEvent sce) { - System.out.println("destory context...."); - /** - * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 - */ - - String chatKey; - ServletContext servletContext = sce.getServletContext(); - Object obj = servletContext.getAttribute("chatCache"); - ChatCache cache = null; - SqlHelper helper = null; - - if(obj != null){ - Map chatCacheMap = (Map)obj; - - Iterator cacheIter = chatCacheMap.keySet().iterator(); - try { - helper = new SqlHelper(); - while (cacheIter.hasNext()) { - chatKey = cacheIter.next(); - cache = chatCacheMap.get(chatKey); - - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { - System.out.println(String.format("saving %s", chatKey)); - ChatCacheController.saveChatCache(cache, helper); - } - } - cacheIter.remove(); - helper.destroy(); - - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - -} diff --git a/src/servlet/FindCacheServlet.java b/src/servlet/FindCacheServlet.java deleted file mode 100644 index e261b5a..0000000 --- a/src/servlet/FindCacheServlet.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - -@WebServlet(name = "FindCacheServlet", urlPatterns = {"/findChatCache"}) -public class FindCacheServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ServletContext context = this.getServletContext(); - - request.setCharacterEncoding("UTF-8"); - - String userKey = request.getParameter("client_id"); - String botAccount = request.getParameter("aipioneer_username"); - Boolean exist = false; - - try { - - exist = ChatCacheController.findChatCache(userKey, context); - } catch (Exception e) { - e.printStackTrace(); - } - - JSONObject responseJSONObject = new JSONObject(); - responseJSONObject.put("exist", exist); - responseJSONObject.put("aipioneer_username", botAccount); - responseJSONObject.put("client_id", userKey); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - response.setHeader("Access-Control-Allow-Origin", "*"); - - System.out.println("xx:" + responseJSONObject.toJSONString()); - - - - PrintWriter out = response.getWriter(); - out.append(responseJSONObject.toString()); - out.flush(); - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } -} diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java deleted file mode 100644 index af68997..0000000 --- a/src/servlet/GameDesignServlet.java +++ /dev/null @@ -1,362 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTermText; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.gameDesign.*; -import com.qiwu.chatbotbackend.processing.ChatCacheController; -import com.qiwu.chatbotbackend.processing.SimpleUtil; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.sql.SQLException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL; - - -@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) -public class GameDesignServlet extends HttpServlet { - - String POST_URL = "http://localhost:1111/conditionProcess"; - String KEYWORD_DIR = "keywords.txt"; - //分组及其相应的id,id初始化为0, 新建分组成功后id会更新。 - HashMap categoryMap = new HashMap(){ - { - put("地图", 0); - put("剧情", 0); - put("物品", 0); - put("NPC", 0); - put("全局变量", 0); - } - }; - - - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - DateTimeFormatter dtf=DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS"); - StringBuffer timeUsedDetect = new StringBuffer(); - LocalDateTime ldt = LocalDateTime.now(); - String now = ldt.format(dtf); - timeUsedDetect.append("接收请求的时间:").append(now); - - //所有需要修改的词性 - StringBuffer POS = new StringBuffer(); - - //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等,格式为: "conditionName_tail/head":"keywords" - HashMap> additionalKeywords = new HashMap>(); - - //预先定义好的所有condition相关的关键词,格式为 "conditionName_标签":"keywords" - Map keywordMap = new HashMap(); - - //特定的relation的三元组不会被添加到relationKeywords - HashSet exceptRelation = new HashSet(); - - - Integer botId, projectId, dataId, returnStatus = 1; - String botAccount = null, userName, botName, moduleName2, returnMessage = "Success"; - ServletContext context = this.getServletContext(); - JSONObject json = null, root = null; - Boolean flag; - SqlHelper helper = null; - List idList = new ArrayList<>(); - ElementConstructor constructor = new ElementConstructor(); - - try { - helper = new SqlHelper(); - } catch (SQLException e) { - e.printStackTrace(); - } - - //读取并解析json数据 - String jsonStr = SimpleUtil.readJSONString(request); - - - if (jsonStr != null && !jsonStr.equals("")) { - JSONObject receiveParaneters = JSONObject.parseObject(jsonStr); - dataId = (Integer) receiveParaneters.get("id"); - - JSONObject gameElements = helper.queryGameElementsByBotId(dataId); - - gameElements.put("auth", request.getHeader("authorization")); - //System.out.println(gameElements.toJSONString()); - botId = (Integer)gameElements.get("botId"); - botAccount = (String) gameElements.get("botAccount"); - userName = (String)gameElements.get("userName"); - botName = (String)gameElements.get("botName"); - - - //假设重建用户信息 - if (context.getAttribute(botAccount) == null) { - UserInfoController.userConfigInit(botAccount, context); - } - - UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - - - //清空之前生成的配置条目 - try { - flag = botInit(botId, botAccount, userinfo, helper); - } catch (SQLException e) { - System.out.println("清空旧数据失败"); - e.printStackTrace(); - } - - - StringBuffer mergedConfigText = new StringBuffer(); - int skipCount = 0; - - - //从文件中读取condition相关的关键词 - System.out.println("----------------------read-------------------------/r------------------------------------------------------"); - readKeywords(keywordMap, KEYWORD_DIR); - - - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n,预处理之后:").append(now); - String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; - for(String moduleName: moduleList){ - - switch (moduleName) { - case "map": - moduleName2 = "地图"; - constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - case "plots": - moduleName2 = "剧情"; - constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - - root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); - break; - case "goods": - moduleName2 = "物品"; - constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - case "globalVariable": - moduleName2 = "全局变量"; - constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - case "npc": - moduleName2 = "NPC"; - constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); - constructor.construct(gameElements, userinfo); - break; - default: - continue; - - } - if (constructor.getOperationStatus() == 1) { - - System.out.println(moduleName); - //先清空再插入 - idList.clear(); - helper.batchInsertVariableByBotId(botId, constructor); - - List jsonList = new ArrayList(); - for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ - json = configTermText.toJson(constructor.getConditionDescription()); - constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); - jsonList.add(json); - } - - - helper.batchInsertConfigByBotId(botId, jsonList, idList, categoryMap.get(moduleName2)); - constructor.postProcessing(idList, categoryMap.get(moduleName2)); - constructor.generateConfigText(idList); - - mergedConfigText.append(constructor.getConfigText()); - }else { - returnStatus = 0; - returnMessage = constructor.getMessage(); - break; - } - - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n,").append(moduleName2).append("模块:").append(now); - - } - - if(returnStatus == 1) { - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求预处理:").append(now); - StringReader sr = new StringReader(mergedConfigText.toString()); - BufferedReader br = new BufferedReader(sr); - //System.out.println(mergedConfigText.toString()); - UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(botAccount, userinfo); - UserInfoController.writeConfigText(botAccount, userinfo); - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求前:").append(now); - String postResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS); - - ldt = LocalDateTime.now(); - now = ldt.format(dtf); - timeUsedDetect.append("\n发送post请求后:").append(now); - - if(!postResult.equals("success")){ - returnStatus = 0; - returnMessage = postResult; - } - } - - helper.destroy(); - - - - - }else { - returnStatus = 0; - returnMessage = "请求解析失败"; - } - - - - System.out.println(timeUsedDetect.toString()); - - - JSONObject responseJSONObject = new JSONObject(); - responseJSONObject.put("status", returnStatus); - responseJSONObject.put("message", returnMessage); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - - - System.out.println("xx:" + responseJSONObject.toJSONString()); - - - - PrintWriter out = response.getWriter(); - out.append(responseJSONObject.toString()); - out.flush(); - - } - - - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - OutputStream out = response.getOutputStream(); - out.write("ssss".getBytes()); - out.flush(); - } - - public boolean botInit(int botId, String botAccount, UserInfo userInfo, SqlHelper helper) throws SQLException, IOException { - boolean deleteConfigFlag = helper.deleteConfigByBotId(botId); - boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); - boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); - boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); - boolean deleteArchiveFlag = ChatCacheController.deleteChatCache(helper, botAccount); - - - return deleteConfigFlag && deleteVariableFlag; - } - - public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS){ - String startCondition, POS2 = ""; - String botName = (String)gameElements.get("botName"); - JSONObject returnMessage = null; - - JSONObject actionPostData = new JSONObject(); - //System.out.println("root"+ root.toJSONString()); - startCondition = (String)root.get("conditionName"); - actionPostData.put("startCondition", "start_options"); - actionPostData.put("botName_yhm", (String)gameElements.get("botName")); - actionPostData.put("botName", botName); - actionPostData.put("botId", (Integer)gameElements.get("botId")); - actionPostData.put("type", "game_plot_init"); - actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始"); - actionPostData.put("relationKeywords", additionalKeywords); - actionPostData.put("auth", gameElements.get("auth")); - - - - if (gameElements.containsKey("POS")) - POS2 = (String)gameElements.get("POS"); - - actionPostData.put("POS", POS.toString() + POS2); - - System.out.println(actionPostData.toJSONString()); - - - userInfo.extraInfo.put("activeAction", startCondition); - try { - returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - if(returnMessage.getInteger("post_status") == 1 && returnMessage.getInteger("status") != null && returnMessage.getInteger("status") == 1 ) { - return "success"; - }else { - System.out.println(returnMessage.get("parameter")); - System.out.println("语义关系生成失败"); - - return (String)returnMessage.get("parameter"); - } - - } - - - //从配置文件中读取生成状态表所需要的关键词 - public void readKeywords(Map keywordsMap, String path){ - - File file = new File(path); - String line, elem[]; - - if(file.exists()){ - FileReader reader = null; - try { - reader = new FileReader(file); - BufferedReader br = new BufferedReader(reader); - - - while ((line = br.readLine()) != null) { - if(!line.equals("") && !line.startsWith("#")) { - elem = line.split("\\|", 3); - - //查看意图是否已经存在相关的condition,如果已经存在就append,如果不存在就初始化 - if (!elem[1].equals("pattern")) { - if (keywordsMap.get(elem[0]) == null) { - keywordsMap.put(elem[0], new StringBuffer(elem[1])); - } else { - keywordsMap.get(elem[0]).append(",").append(elem[1]); - } - } - - //根据意图和condition名字添加关键字 - keywordsMap.put(elem[0] + "_" + elem[1], new StringBuffer(elem[2])); - - } - - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - } - - - - - -} diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java deleted file mode 100644 index eb6abcd..0000000 --- a/src/servlet/GetAnswerServlet.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.*; -import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; -import com.qiwu.chatbotbackend.task.utils.GameBotUtil; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.OutputStream; -import java.sql.SQLException; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; - -import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2; -import static com.qiwu.chatbotbackend.Config.Config.TEST_VAR; - - -@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) -public class GetAnswerServlet extends HttpServlet { - /** - * GetAnswerServlet就是处理post请求并返回答案的入口 - */ - - String NAME_MISSING_ERROR = "没找到bot名?"; - String LOG_PATH = "/var/www/html/logs/"; - //String LOG_PATH = "/home/hxw/source/logs/"; - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - Map receiveParamters = new HashMap<>(request.getParameterMap()); - Map curInfoPoint = new HashMap(); - //Map historyInfoPoint = null; - Solution bestMatch = null; - BasicBotUtil botUtil = null; - Action ansAction = null; - boolean debugFlag = false; - String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; - String botName = receiveParamters.get("bot_name")[0]; - - OutputStream out = response.getOutputStream(); - ServletContext context = this.getServletContext(); - - //如果有client_id,会用@分隔 - chatKey = receiveParamters.get("chat_key")[0]; - String chatKeys[] = receiveParamters.get("chat_key")[0].split(COMBINE_PUNC2); - if(chatKeys.length == 1){ - userKey = chatKeys[0]; - randKey = chatKeys[0]; - }else{ - userKey = chatKeys[0]; - randKey = chatKeys[1]; - } - receiveParamters.put("userKey", new String[]{userKey}); - receiveParamters.put("randKey", new String[]{randKey}); - - - LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); - - - UserInfo userinfo = null; - UserInfoController uiController = new UserInfoController(); - try { - //userinfo = process.userInfoQuery(chatKey,context); - //从servlet根据用户名查询用户信息 - userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); - - } catch (SQLException e) { - state = NAME_MISSING_ERROR; - e.printStackTrace(); - } - - - - - if(userinfo != null) { - //获得用户历史信息 - ChatCache chatCache = null; - Boolean loadCacheStatus = Boolean.valueOf(false); - - if(userinfo.varInitialMap.get("botType") != null) - botType = userinfo.varInitialMap.get("botType"); - - - try { - chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); - - if(chatCache == null){ - throw(new Exception("chatCache初始化失败")); - } - } catch (Exception e) { - System.out.println(e.getMessage()); - //e.printStackTrace(); - } - - /** - * 如果读档成功,则返回存档前的状态(包括最后一个condition和最后的回答) - * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 - */ - - //historyInfoPoint = chatCache.getInfoPoint(); - - - - - switch(botType){ - case "game": - WorldController worldController = new WorldController(logWriter,userinfo); - botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController); - break; - default: - botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); - break; - } - - //针对不同游戏类型对信息点做预处理 - debugFlag = botUtil.preprocessing(receiveParamters, context); - - - //信息点预处理 - ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil); - - - /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/ - ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); - if (state.equals("") && ansAction.getPriority()== -1) - state = "我不理解,"; - if (state.equals("")) { - try { - bestMatch = matcher.getSolution(ansAction, context, userinfo); - - - - if(!botUtil.getChatCache().getReload()) { - //读档成功不应该再激活 - //if(matcher.) - if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { - //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); - } - }else{ - //跳过 - botUtil.getChatCache().setReload(false); //清楚标识 - } - - } catch (ParseException e) { - e.printStackTrace(); - } - } else { - bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction")); - } - - - //针对不同bot类型做后处理 - botUtil.postprocessing(chatKey, context, bestMatch); - - botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); - if (debugFlag) { - matcher.appendDebugInfo(bestMatch, context); - } - - - //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) - matcher.infoTransfer(bestMatch, context, debugFlag); - - - ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo); - //清理超时的用户数据 - if (context.getAttribute("cacheUpdateTime") == null) - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) { - ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo); - context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); - } - - - - ansJ = SimpleUtil.toJson(bestMatch); - } else { - ansJ = "找不到配置文件"; - } - - System.out.println(TEST_VAR); - - - - logWriter.writeln(); - logWriter.writeln(); - logWriter.record("-----------------------------------------对话处理结束", 0); - logWriter.writeln(); - logWriter.writeln(); - logWriter.close(); - - System.out.println(ansJ); - out.write(ansJ.getBytes()); - out.flush(); - - } - - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - System.out.println("do get method"); - } -} diff --git a/src/servlet/GetConfigServlet.java b/src/servlet/GetConfigServlet.java deleted file mode 100644 index 72639e3..0000000 --- a/src/servlet/GetConfigServlet.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - -@WebServlet(name = "GetConfigServlet", urlPatterns = {"/getConfig"}) -public class GetConfigServlet extends HttpServlet { - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - String userName = request.getParameter("userName"); - - String path = "config/" + userName + ".txt"; - File file = new File(path); - OutputStream out = response.getOutputStream(); - - - if (file.exists()) { - - FileReader fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); - String line; - while ((line = br.readLine()) != null) { - line = line + "\n"; - out.write(line.getBytes()); - } - - - fr.close(); - br.close(); - } else { - out.write("查无此bot".getBytes()); - } - out.flush(); - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } -} diff --git a/src/servlet/MyListener.java b/src/servlet/MyListener.java deleted file mode 100644 index ebe10f8..0000000 --- a/src/servlet/MyListener.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; -import java.util.Iterator; -import java.util.Map; - -@WebListener -public class MyListener implements ServletContextListener { - - public void contextDestroyed(ServletContextEvent sce) { - System.out.println("destory context...."); - /** - * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 - */ - - String chatKey; - ServletContext servletContext = sce.getServletContext(); - Object obj = servletContext.getAttribute("chatCache"); - ChatCache cache = null; - SqlHelper helper = null; - - if(obj != null){ - Map chatCacheMap = (Map)obj; - - Iterator cacheIter = chatCacheMap.keySet().iterator(); - - - while(cacheIter.hasNext()){ - chatKey = cacheIter.next(); - cache = chatCacheMap.get(chatKey); - try { - helper = new SqlHelper(); - System.out.println(String.format("saving %s", chatKey)); - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if(cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { - ChatCacheController.saveChatCache(cache, helper); - } - }catch (Exception e){ - System.out.println(String.format("保存%s时出现异常", chatKey)); - } - cacheIter.remove(); - } - } - } - -} diff --git a/src/servlet/ReloadChatCacheServlet.java b/src/servlet/ReloadChatCacheServlet.java deleted file mode 100644 index 20af7a3..0000000 --- a/src/servlet/ReloadChatCacheServlet.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@WebServlet(name = "ReloadChatCacheServlet", urlPatterns = {"/reloadChatCache"}) -public class ReloadChatCacheServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/ReloadConfig.java b/src/servlet/ReloadConfig.java deleted file mode 100644 index 1e2912f..0000000 --- a/src/servlet/ReloadConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package servlet; - -import entity.UserInfo; -import processing.MyFunc; -import processing.ProcessQuestion; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - -@WebServlet(name = "ReloadConfig") -public class ReloadConfig extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String userName = request.getParameter("userName"); - boolean flag = true; - UserInfo userinfo = new UserInfo(userName); - File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt"); - ServletContext context = this.getServletContext(); - if(!configFile.exists()) { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("文件不存在: "+userName); - - }else{ - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - - try { - userinfo = ProcessQuestion.buildUserInfo(br, userinfo); - context.setAttribute(userinfo.userName,userinfo); - }catch(Exception e){ - flag = false; - System.out.println(userinfo.userName + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - - if(!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + userName +".txt\\\n"); - - } - else{ - response.setCharacterEncoding("utf-8"); - response.setContentType( "text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新成功+ “ "); - out.flush(); - out.close(); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - - - } - - } - - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java deleted file mode 100644 index 7d6c8cb..0000000 --- a/src/servlet/ReloadConfigServlet.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; - - -/** - * 发请求从本地文件夹重新加载某用户的配置文件 - */ -@WebServlet(name = "ReloadConfigServlet", urlPatterns = {"/reload", "/reload/"}) -public class ReloadConfigServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - String botAccount = request.getParameter("botAccount"); - boolean flag = true; - UserInfo userinfo = new UserInfo(botAccount); - File configFile = new File(System.getProperty("user.dir") + "/config/" + botAccount + ".txt"); - System.out.println(configFile.getAbsolutePath()); - ServletContext context = this.getServletContext(); - if (!configFile.exists()) { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("文件不存在: " + botAccount); - - } else { - - FileReader reader = new FileReader(configFile); - BufferedReader br = new BufferedReader(reader); - - try { - userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - } catch (Exception e) { - flag = false; - System.out.println(userinfo.botAccount + ".txt 有误"); - e.printStackTrace(); - } - - reader.close(); - br.close(); - - if (!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - response.setStatus(111); - PrintWriter out = response.getWriter(); - out.println("更新失败配置文件有误:" + botAccount + ".txt\\\n"); - - } else { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("重新加载成功"); - out.flush(); - out.close(); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - - - } - - } - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/SaveChatCacheServlet.java b/src/servlet/SaveChatCacheServlet.java deleted file mode 100644 index d74a2da..0000000 --- a/src/servlet/SaveChatCacheServlet.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Map; - -@WebServlet(name = "SaveChatCacheServlet", urlPatterns = {"/saveChatCache"}) -public class SaveChatCacheServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - String chatKey = request.getParameter("chatKey"), message = ""; - ServletContext context = this.getServletContext(); - chatKey = chatKey.split("@@@@")[0]; - Boolean flag = false; - - Map chatCacheMap = (Map)context.getAttribute("chatCache"); - ChatCache chatCache = chatCacheMap.get(chatKey); - - - if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { - flag = ChatCacheController.saveChatCache(chatCache, null); - chatCacheMap.remove(chatKey); - } - - System.out.println("调用接口删除" + chatKey); - - - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - PrintWriter out = response.getWriter(); - - JSONObject retData = new JSONObject(); - retData.put("status", flag); - System.out.println("xx:" + retData.toJSONString()); - out.append(retData.toJSONString()); - out.flush(); - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - doPost(request, response); - } - -} - - diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java deleted file mode 100644 index da89789..0000000 --- a/src/servlet/UpdateServlet.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.SimpleUtil; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -/** - * 用户通过页面更新或提交配置文件,后台解析配置文件信息后保存至本地文件夹中,并更新contextServlet中的userinfo信息。 - */ -@WebServlet(name = "UpdateServlet", urlPatterns = {"/update"}) -public class UpdateServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - //在此处理通过页面提交的配置文件,在servletContext中更新botAccount指定的userinfo,并将配置文件以botAccount.txt的命名方式保存至本地。 - request.setCharacterEncoding("UTF-8"); - String line, extraElements[]; - ArrayList errorList = new ArrayList(); - ServletContext context = this.getServletContext(); - String botAccount = request.getParameter("botAccount"); - - UserInfo userinfo = new UserInfo(botAccount); - userinfo.conditionTable = new HashMap>(); - - List actionList = null; - HashSet keyWordSet = null; - - BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string"))); - boolean flag = true; - String errorStr = ""; - - - while ((line = br.readLine()) != null) { - System.out.println(line); - - if (line.trim().equals("")) - continue; - line = line.replace("\n", ""); - //在用户信息中添加额外信息,如设为active的action - if (line.indexOf("-extraInfo-") != -1) { - extraElements = line.split("\\|"); - userinfo.extraInfo.put(extraElements[1], extraElements[2]); - userinfo.configStr += line + "\n"; - continue; - } - //line = SimpleUtil.convert2Utf8(line.trim()); - userinfo.configStr += line + "\n"; - Action action = new Action(); - try { - action = UserInfoController.buildCondition(action, line); - actionList = userinfo.conditionTable.get(action.getIndexName()); - if (actionList == null) - actionList = new ArrayList(); - actionList.add(action); - userinfo.conditionTable.put(action.getIndexName(), actionList); - /* - for(String name:action.indexName){ - userinfo.conditionTable.put() - } - */ - } catch (Exception e) { - System.out.println("配置文件有误!"); - flag = false; - errorList.add(line); - - - } - - } - br.close(); - if (!flag) { - //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - String returnStr = SimpleUtil.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); - out.println("更新失败,以下行有误: "); - for (String error : errorList) - out.println("---" + error); - out.flush(); - out.close(); - System.out.println("error"); - - } else { - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.println("更新成功+ “ "); - out.flush(); - out.close(); - System.out.println("success"); - - //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); - context.setAttribute(botAccount, userinfo); - String path = System.getProperty("user.dir") + "/config/" + userinfo.botAccount + ".txt"; - File file = new File(path); - File dir = new File(System.getProperty("user.dir") + "/config"); - - if (!dir.exists()) - dir.mkdir(); - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fw = new FileWriter(file); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(userinfo.configStr); - bw.close(); - fw.close(); - - - } - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } -} diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java deleted file mode 100644 index 372c0b2..0000000 --- a/src/servlet/UpdateSingleConfigServlet.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.qiwu.chatbotbackend.servlet; - -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.UserInfoController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; - -@WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"}) -public class UpdateSingleConfigServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.setCharacterEncoding("UTF-8"); - ServletContext context = this.getServletContext(); - String userName = request.getParameter("userName"); - String processType = request.getParameter("type"); - String configId = request.getParameter("configId"); - String data = request.getParameter("configData"); - System.out.println("userName:" + userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); - - if (context.getAttribute(userName) != null) { - switch (processType) { - case "insert_config": - UserInfoController.insertConfig(userName, configId, data, context); - break; - case "update_config": - UserInfoController.deleteConfig(userName, configId, data, context); - UserInfoController.insertConfig(userName, configId, data, context); - break; - case "delete_config": - UserInfoController.deleteConfig(userName, configId, data, context); - break; - case "insert_variable": - UserInfoController.updateVariable(userName, configId, data, context); - break; - case "delete_variable": - UserInfoController.deleteVariable(userName, configId, data, context); - break; - case "update_variable": - UserInfoController.updateVariable(userName, configId, data, context); - break; - case "extra_info": - UserInfoController.updateExtraInfo(userName, data, context); - break; - - case "batch_update": - batchUpdate(userName, data, context); - - } - writeConfig(userName, context); - response.setStatus(200); - - } else if (processType.equals("batch_update")) { - batchUpdate(userName, data, context); - writeConfig(userName, context); - response.setStatus(200); - } else { - response.setStatus(111); - } - - - response.setCharacterEncoding("utf-8"); - response.setContentType("text/plain"); - PrintWriter out = response.getWriter(); - out.write("success"); - out.flush(); - out.close(); - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - } - - - public String writeConfig(String userName, ServletContext context) throws IOException { - String returnMessage = ""; - UserInfo userinfo = (UserInfo) context.getAttribute(userName); - - returnMessage = UserInfoController.writeConfigText(userName, userinfo); - - return returnMessage; - } - - - public void batchUpdate(String userName, String data, ServletContext context) throws IOException { - BufferedReader br = new BufferedReader(new StringReader(data)); - UserInfo userinfo = new UserInfo(userName); - userinfo = UserInfoController.buildUserInfo(br, userinfo, true); - context.setAttribute(userinfo.botAccount, userinfo); - System.out.println("batchupdate"); - } -} diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java deleted file mode 100644 index 0578adc..0000000 --- a/src/task/utils/BasicBotUtil.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - -import com.qiwu.chatbotbackend.entity.Action; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.Solution; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.LogWriter; - -import javax.servlet.ServletContext; -import java.io.IOException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class BasicBotUtil { - Map curInfoPoint = null; - UserInfo userinfo = null; - LogWriter logWriter = null; - ChatCache chatCache = null; - - public String botType = "basic"; - - - public ChatCache getChatCache() { - return chatCache; - } - - public BasicBotUtil(){}; - public BasicBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter){ - this.curInfoPoint = curInfoPoint; - this.userinfo = userinfo; - this.logWriter = logWriter; - this.chatCache = chatCache; - } - - public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { - return infoPointPreprocessing(receiveParameters, context, true); - - - } - - //在接收到请求后对数据做处理,转化为系统可以处理的数据 - - /** - * - * @param receiveParameters - * @param context - * @param setUnknown 如果什么都没识别到就将上一个激活的condition设为unknown - * @return - * @throws IOException - */ - public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context, Boolean setUnknown) throws IOException { - - String return_str = "", k, botType = ""; - String receiveParameterStr = ""; - boolean debugFlag = false; - - HashSet skipSet = new HashSet() { - { - add("chat_key"); - add("randKey"); - add("userKey"); - add("action_name"); - add("bot_name"); - add("emptySet"); - add("query_text"); - } - }; - - - //输出所有actionName的值 - Iterator iit = receiveParameters.keySet().iterator(); - receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; - while (iit.hasNext()) { - k = iit.next(); - // - receiveParameterStr += k + ": "; - curInfoPoint.put(k, receiveParameters.get(k)[0]); - - if (k.equals("debug_mode") || k.equals("debug_rule")) - debugFlag = true; - - String values[] = receiveParameters.get(k); - - receiveParameterStr += values[0] + " " + "
"; - - if (values[0].equals(":")) { - curInfoPoint.put(k, ""); - } - } - logWriter.record(receiveParameterStr, 0); - System.out.println(receiveParameterStr.toString()); - - //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown - iit = curInfoPoint.keySet().iterator(); - boolean unknown_flag = setUnknown; - while (iit.hasNext()) { - k = iit.next(); - String values = curInfoPoint.get(k); - if (skipSet.contains(k)) - continue; - if (!values.equals("")) { - unknown_flag = false; - break; - } - } - - String currentAction = ""; - if (chatCache.getInfoPoint().containsKey("currentAction")) - currentAction = chatCache.getInfoPoint().get("currentAction"); - else if (userinfo.extraInfo.containsKey("activeAction")) { - currentAction = userinfo.extraInfo.get("activeAction"); - chatCache.getInfoPoint().put("currentAction", currentAction); - } else - currentAction = " "; - - - curInfoPoint.put("emptySet", " "); - if (chatCache.getInfoPoint().get("activeList") == null) { - chatCache.getInfoPoint().put("activeList", currentAction); - } - - if (unknown_flag && !currentAction.equals("")) { - String i = "unknown"; - curInfoPoint.put(currentAction, i); - } - - logWriter.record("historyInfoPoint:" + chatCache.getInfoPoint().toString(), 1); - - - - return debugFlag; - } - - public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ - if(chatCache.getInfoPoint().get("error_message") != null && chatCache.getInfoPoint().get("error_message") != ""){ - bestMatch.setAnswer(bestMatch.getAnswer() + chatCache.getInfoPoint().get("error_message")); - } - - - return true; - } - - - /** - * 从当前信息点或者已知信息点中提取关键词 - * @param infoPoint - * @param infoPoint2 - * @param chooseLater - * @param actionName - * @return - */ - public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ - String keyword = ""; - String nameSeries[] = actionName.split("_"); - - /** - * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 - */ - if(chooseLater){ - keyword = infoPoint2.get(actionName); - if(keyword != null && !keyword.equals("")) - return keyword; - } - keyword = infoPoint.get(actionName); - - - return keyword; - }; - - /** - * 更新历史信息点中的某一个键值对 - * @param variableName - * @param updateValue - */ - public void putKeyword(String variableName, String updateValue){ - chatCache.getInfoPoint().put(variableName, updateValue); - } - - public String knowledgeProcess(String variableName, String updateValue){ - return updateValue; - - } - - /** - * 额外的更新操作 - */ - public void extraOperation(Action ansAction, Solution solution) throws IOException { - - } - - //将文本中存在的变量槽位{npc_xxx}替换成变量值 - public String varSlotReplace(String text){ - - String VARIABLE_REPLACE_PATTERN = "(\\{.*?\\-[12]\\})"; - Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); - - //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 - String keyword, variable,reply = text; - Matcher m = replacePattern.matcher(reply); - while (m.find()) { - variable = m.group(1).substring(1, m.group(1).length() - 3); - if (m.group(1).endsWith("-1}")) { - if (curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")) { - keyword = curInfoPoint.get(variable); - - - if(keyword.contains(":")) - keyword = keyword.split(":")[1]; - - reply = reply.replace("{" + variable + "-1}", keyword); - } - } else if (m.group(1).endsWith("-2}")) { - if (chatCache.getInfoPoint().get(variable) != null) - if(chatCache.getInfoPoint().get(variable).equals("do_reset")){ - reply = reply.replace("{" + variable + "-2}", ""); - }else - reply = reply.replace("{" + variable + "-2}", chatCache.getInfoPoint().get(variable)); - } - } - - return reply; - } -} diff --git a/src/task/utils/ContextDestroyListener.java b/src/task/utils/ContextDestroyListener.java deleted file mode 100644 index 5471da6..0000000 --- a/src/task/utils/ContextDestroyListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.processing.ChatCacheController; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; -import java.io.IOException; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.Map; - -@WebListener -public class ContextDestroyListener implements ServletContextListener { - - public void contextDestroyed(ServletContextEvent sce) { - System.out.println("destory context...."); - /** - * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 - */ - - String chatKey; - ServletContext servletContext = sce.getServletContext(); - Object obj = servletContext.getAttribute("chatCache"); - ChatCache cache = null; - SqlHelper helper = null; - - if(obj != null){ - Map chatCacheMap = (Map)obj; - - Iterator cacheIter = chatCacheMap.keySet().iterator(); - try { - helper = new SqlHelper(); - while (cacheIter.hasNext()) { - chatKey = cacheIter.next(); - cache = chatCacheMap.get(chatKey); - - //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 - if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { - System.out.println(String.format("saving %s", chatKey)); - ChatCacheController.saveChatCache(cache, helper); - } - } - cacheIter.remove(); - helper.destroy(); - - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - -} diff --git a/src/task/utils/ContextInitialListener.java b/src/task/utils/ContextInitialListener.java deleted file mode 100644 index f4f93c5..0000000 --- a/src/task/utils/ContextInitialListener.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - -import com.qiwu.chatbotbackend.Config.ConfigInitializer; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; - -@WebListener -public class ContextInitialListener implements ServletContextListener { - String CONFIG_DIR = "config.txt"; - - /** - * 在程序初始化时,从配置文件中加载数据 - * @param sce - */ - public void contextInitialized(ServletContextEvent sce) { - System.out.println("Initial context...."); - - //Config config = new Config(); - ConfigInitializer.init(); - - - - - - - } - -} diff --git a/src/task/utils/DataDeliver.java b/src/task/utils/DataDeliver.java deleted file mode 100644 index 91bfd1e..0000000 --- a/src/task/utils/DataDeliver.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.processing.SimpleUtil; - -import java.io.UnsupportedEncodingException; - -import static com.qiwu.chatbotbackend.Config.Config.CC_URL; - -public class DataDeliver extends Thread { - - JSONObject data = null; - String url = CC_URL; - - public void setData(JSONObject data) { - this.data = data; - } - - - - - public void run() - { - System.out.println("线程开始"); - System.out.println(url); - try { - SimpleUtil.postJSON(CC_URL, data, null); - System.out.println("线程完成"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/task/utils/FileFinder.java b/src/task/utils/FileFinder.java deleted file mode 100644 index db2c1ef..0000000 --- a/src/task/utils/FileFinder.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC1; - -/** - * 实现一个支持通配符的基于广度优先算法的文件查找器 - */ -public class FileFinder { - - /** - * 查找文件。 - * @param baseDirName 待查找的目录 - * @param targetFileName 目标文件名,支持通配符形式 - * @return 满足查询条件的文件名列表 - */ - public static List findFiles(String baseDirName, String targetFileName) { - - String tempName; - List fileList = new ArrayList(); - //判断目录是否存在 - File baseDir = new File(baseDirName); - if (!baseDir.exists() || !baseDir.isDirectory()){ - System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); - return fileList; - } - - File[] files = baseDir.listFiles(); - for (int i = 0; i < files.length; i++) { - //如果是目录则放进队列 - if (files[i].isDirectory()) { - continue; - } else { - //如果是文件则根据文件名与目标文件名进行匹配 - tempName = files[i].getName(); - if (FileFinder.wildcardMatch(targetFileName, tempName)) { - //匹配成功,将文件名添加到结果集 - fileList.add(files[i]); - } - } - } - - return fileList; - } - /** - * 通配符匹配 - * @param pattern 通配符模式 - * @param str 待匹配的字符串 - * @return 匹配成功则返回true,否则返回false - */ - private static boolean wildcardMatch(String pattern, String str) { - int patternLength = pattern.length(); - int strLength = str.length(); - int strIndex = 0; - char ch; - for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) { - ch = pattern.charAt(patternIndex); - if (ch == '*') { - //通配符星号*表示可以匹配任意多个字符 - while (strIndex < strLength) { - if (wildcardMatch(pattern.substring(patternIndex + 1), - str.substring(strIndex))) { - return true; - } - strIndex++; - } - } else if (ch == '?') { - //通配符问号?表示匹配任意一个字符 - strIndex++; - if (strIndex > strLength) { - //表示str中已经没有字符匹配?了。 - return false; - } - } else { - if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) { - return false; - } - strIndex++; - } - } - return (strIndex == strLength); - } - - public static boolean deleteGameArchive(String baseDirName, String botAccount){ - - String tempName; - String regEx = ".*" + COMBINE_PUNC1 + botAccount + "-.*"; - List fileList = new ArrayList(); - Pattern pattern = Pattern.compile(regEx); - Matcher matcher = null; - //判断目录是否存在 - File baseDir = new File(baseDirName); - if (!baseDir.exists() || !baseDir.isDirectory()){ - System.out.println("文件查找失败:" + baseDirName + "不是一个目录!"); - return false; - } - - File[] files = baseDir.listFiles(); - for (int i = 0; i < files.length; i++) { - //如果是目录则放进队列 - if (files[i].isDirectory()) { - continue; - } else { - //如果是文件则根据文件名与目标文件名进行匹配 - tempName = files[i].getName(); - matcher = pattern.matcher(tempName); - if (matcher.find()) { - //匹配成功,将文件名添加到结果集 - files[i].delete(); - } - } - } - - return true; - } - -} diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java deleted file mode 100644 index 7cdcbb1..0000000 --- a/src/task/utils/GameBotUtil.java +++ /dev/null @@ -1,709 +0,0 @@ -package com.qiwu.chatbotbackend.task.utils; - -import com.alibaba.fastjson.JSONObject; -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.*; -import com.qiwu.chatbotbackend.processing.ChatCacheController; -import com.qiwu.chatbotbackend.processing.LogWriter; -import com.qiwu.chatbotbackend.processing.SimpleUtil; -import com.qiwu.chatbotbackend.processing.WorldController; - -import javax.servlet.ServletContext; -import java.io.IOException; -import java.sql.SQLException; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.qiwu.chatbotbackend.Config.Config.*; -import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; - -public class GameBotUtil extends BasicBotUtil{ - - WorldController worldController = null; - public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; - public static String LOAD_BY_LAST = "load_last"; - - - - - public GameBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){ - super(curInfoPoint, chatCache, userinfo, logWriter); - this.worldController = worldController; - this.botType = "game"; - - } - - - - @Override - public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { - Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); - - //将要去的地点的别名替换为真名 -// String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; -// -// for(String conditionName: conditionList) { -// -// if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { -// String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName); -// String destination = info.split(":")[1]; -// String site = historyInfoPoint.get("site"); -// try { -// newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); -// }catch(Exception e){ -// e.printStackTrace(); -// } -// -// logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); -// curInfoPoint.put(conditionName, newInfo); -// } -// } - -// historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); - - String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|"); - if(activeList.length == 0){ - chatCache.getInfoPoint().put("临时变量condition", "yaobuyao"); - }else { - chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]); - } - - - return debugFlag; - - } - - public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ - - - StringBuffer finalText = new StringBuffer(); - String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~")); - //将自动跳转文本、qa文本、查询文本拼接 - String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"}; - String queryResult; - Set keepNoSpeaker = new HashSet(){ - { - add("sendData:archiveList"); - add(GAME_START_HINT); - } - }; - - chatCache.getInfoPoint().put("plot_text", plotText); - - //整合qa问答、地图、npc查询文本和剧情文本 - for(String queryName:queryList){ - queryResult = chatCache.getInfoPoint().get(queryName); - if(queryResult != null){ - if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 - //剧情可以为空,其他不行 - continue; - } - - switch (queryName){ - case "common_answer": - if(!queryResult.equals("no answer")) - finalText.append(queryResult); - break; - case "plot_jump_text": - finalText.append(queryResult); - break; - case "map_query": - case "goods_query": - case "npc_query": - case "error_message": - queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv()); - finalText.append(queryResult); - break; - case "plot_text": - if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪 - finalText.setLength(0); - finalText.append(plotText); - } - //文本为空跳过 - else if(plotText.equals("") && finalText.length() != 0){ - continue; - }else { - - //对剧情文本做处理,或者说对unknown文本做处理 - finalText.append(plotTextFilt(plotText)); - } - - break; - - - } - chatCache.getInfoPoint().put(queryName, ""); - - } - } - bestMatch.setAnswer(finalText.toString()); - - - return true; - } - - public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ - String keyword = ""; - String nameSeries[] = actionName.split("_"); - - - //变量名以npc_开头,就从游戏环境中查询相应的值 - if(actionName.startsWith("npc_")){ - if(nameSeries.length == 4){ - keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); - }else if (nameSeries.length == 3){ - if(nameSeries[1].equals("玩家") && nameSeries[2].equals("物品栏")) { - StringBuffer sb = new StringBuffer(); - List goods = chatCache.getGameEnv().queryGoodsByNpcName("玩家"); - for (String good : goods) { - sb.append("+").append(good); - } - keyword = sb.toString(); - }else{ - keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); - } - } - - }else if (actionName.startsWith("goods_")) { - if(nameSeries.length == 3) { - nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); - keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); - } - //System.out.println("return" + keyword); - - - }else if(actionName.startsWith("isNeighbour")){ - String opPair[] = actionName.split(":"); - if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ - keyword = "not_exist"; - }else { - logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); - keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); - logWriter.record("返回:" + keyword, 1); - } - }else { - - /** - * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 - */ - if(chooseLater){ - keyword = infoPoint2.get(actionName); - if(keyword != null && !keyword.equals("")) - return keyword; - } - keyword = infoPoint.get(actionName); - - } - - if(keyword == null) - keyword = ""; - - - return keyword; - }; - - @Override - public void putKeyword(String variableName, String updateValue){ - - String namePair[] = variableName.split("_"); - - - //如果变量名开头为NPC或者item,就专门交给游戏环境处理 - if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { - try { - if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { - updateValue = "update:" + updateValue; - } - variableName = variableName.replace("所属玩家", "owner"); - String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint()); - updateValue = returnStr; - } catch (Exception e) { - e.printStackTrace(); - updateValue = GAME_MODULE_ERROR; - } - } - - chatCache.getInfoPoint().put(variableName, updateValue); - } - - - public String knowledgeProcess(String variableName, String updateValue){ - String values[] = updateValue.split(":",2), returnValue; - if(values.length > 1 && values[0].equals("update")) - returnValue = values[1]; - else - returnValue = updateValue; - - return returnValue; - } - - - /** - * 主要用于游戏存档和读档 - * @param ansAction - * @param solution - * @throws IOException - */ - @Override - public void extraOperation(Action ansAction, Solution solution) throws IOException { - Boolean flag = true; - String userKey = curInfoPoint.get("userKey"); - String randKey = curInfoPoint.get("randKey"); - String keyword = "", site; - SqlHelper helper = null; - ChatCache chatCache = null; - - - try { - helper = new SqlHelper(); - - //未登录用户没有存取档的操作 - if(userKey.equals(randKey)) - return; - - if(ansAction.getFeatureMap().containsKey("newGame")) { - System.out.println("newGame"); - this.chatCache.setGameStart(true); - - - }else if (ansAction.getFeatureMap().containsKey("gameBackup")) { - - System.out.println("gameBackup"); - chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint()); - flag = ChatCacheController.saveChatCache(chatCache, null); - if(flag) - solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); - else - solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); - - } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { - - System.out.println("loadLastArchive"); - ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); - if(archiveInfo != null){ - System.out.println("存档Id" + archiveInfo.getArchiveId()); - }else{ - System.out.println("没有找到存档"); - } - loading(archiveInfo, solution); - this.chatCache.setGameStart(true); - - } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) { - - System.out.println("loadArchiveBySite"); - if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { - site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; - System.out.println("要读取的存档的地点是:" + site); - ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site); - loading(archiveInfo, solution); - this.chatCache.setGameStart(true); - }else{ - System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); - } - } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){ - - System.out.println("sendArchiveList"); - DataDeliver dataDeliver = new DataDeliver(); - JSONObject data = new JSONObject(); - List archiveList = helper.queryArchiveByUserKey(userKey); - data.put("data", JSONObject.toJSON(archiveList)); - data.put("dataType", "archiveList"); - data.put("userKey", userKey); - dataDeliver.setData(data); - dataDeliver.start(); - - solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个 - } - - } catch (SQLException e) { - - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } finally{ - helper.destroy(); - } - - } - - private void loading(ArchiveInfo archiveInfo, Solution solution){ - String keyword = "", site; - ChatCache loadCache = null; - - - - - if (archiveInfo != null) { - - //如果存在读档,就要将自动跳转和qa的临时数据清空 - chatCache.getInfoPoint().put("plot_jump_text", ""); - chatCache.getInfoPoint().put("common_answer", ""); - - - try { - loadCache = ChatCacheController.loadChatCache(archiveInfo); - } catch (Exception e) { - System.out.println("从本地加载存档失败"); - solution.setAnswer("从本地加载存档失败"); - e.printStackTrace(); - } - - - //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); - this.chatCache.setInfoPoint(loadCache.getInfoPoint()); - this.chatCache.setGameEnv(loadCache.getGameEnv()); - - - System.out.println("----------读档中------------"); - site = loadCache.getInfoPoint().get("site"); - - String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site)); - String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site)); - solution.setAnswer(reply); - solution.setNext("nextStep=" + nextStep); - this.chatCache.setReload(true); - - }else{ - System.out.println("没有找到该存档"); - } - } - - - //将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版 - //@Override - public String varSlotReplace2(String text){ - String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}"; - Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); - - String varElements[] = {}, result = ""; - String keyword, variable, variableSlot, reply = text; - Matcher m = replacePattern.matcher(reply); - while (m.find()) { - variable = m.group(1); - varElements = variable.split("_"); - variableSlot = "${" + variable + "}"; - - switch (varElements[0]){ - //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 - case "globalVariable": - reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); - - case "npc": - result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]); - reply = reply.replace(variableSlot, result); - - case "goods": - result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]); - reply = reply.replace(variableSlot, result); - - case "map": - System.out.println("地图替换还没写"); - - default: - if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ - reply = reply.replace(variableSlot, curInfoPoint.get(variable)); - }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){ - reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); - } - - } - } - - return reply; - } - - - - - - public static Matcher findTalker(String reply){ - Pattern findTalker = Pattern.compile(TALKER); - Matcher m = findTalker.matcher(reply); - - return m; - } - static String findFirstTalker(String reply){ - String npc = ""; - Pattern findTalker = Pattern.compile(TALKER); - Matcher m = findTalker.matcher(reply); - - if(m.find()) { - npc = m.group(1); - } - - return npc; - } - - /** - * 查看回答文本的说话这是否在当前地点 - * 0:没有说话者 - * 1:说话者在当前地点 - * 2:说话者不在当前地点或者不能说话 - * @param reply - * @param curInfoPoint - * @param historyInfoPoint - * @param gameEnv - * @param site - * @param logWriter - * @return - */ - public static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){ - String npc, location; - - Matcher m = findTalker(reply); - int flag = 1; - if(m.find()) { - npc = m.group(1); - - location = gameEnv.queryNpcAttrByNpcName(npc, "location"); - System.out.println("location:" + location + ", npc:" + npc); - if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ - if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ - flag = 1; - logWriter.record("\"" + reply + "\":匹配", 1); - }else { - flag = 2; - logWriter.record(npc + "不能说话", 1); - } - - }else { - logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); - flag = 2; - } - }else{ - logWriter.record("\"" + reply + "\":没有npc名",1 ); - flag = 0; - } - return flag; - - } - - - /** - * 查看回答文本的说话这是否在当前地点 - * 0:没有说话者 - * 1:说话者在当前地点 - * 2:说话者不在当前地点或者不能说话 - * @param npc - * @param site - * @param onlineDetect npc是在线类型才可以通过 - * @return - */ - public Boolean canTalk(String npc, String site, Boolean onlineDetect){ - String location; - - Boolean flag = false; - location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location"); - if( location == null){ - return false; - } - if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ - if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ - - - - if(onlineDetect){ - if(isOnlineMode(npc, chatCache.getInfoPoint())){ - logWriter.record("\"" + npc + "\":匹配", 1); - flag = true; - } - }else { - flag = true; - } - }else { - logWriter.record(npc + "不能说话", 1); - } - }else { - logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 ); - } - - return flag; - - } - - - public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv){ - - return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text; - - } - - - String plotTextFilt(String reply){ - String textType, returnText = "plot text filt error", plotLastTalker; - String site = chatCache.getInfoPoint().get("site"); - - - textType = textTypeDetect(reply, site); - System.out.println("textType:" + textType); - - switch(textType){ - case "direct_return": - returnText = reply; - break; - case "less_talker": - return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv()); - case "to_unknown": - Set candidates = new HashSet(); - Map> npcTextMap = null; - String unknownList = "", foundNPC; - String fieldList[] = {"unknownTextList", "finalUnknownText"}; - String lastReply = chatCache.getInfoPoint().get("lastReply"); - - plotLastTalker = findTextLastTalker(lastReply, site); - - for(String unknownField:fieldList){ - candidates.clear(); - - if(userinfo.varInitialMap.get(unknownField) != null) { - unknownList = userinfo.varInitialMap.get(unknownField); - npcTextMap = unknownTextClassify(unknownList); - - if(!plotLastTalker.equals("")) { - candidates.add(plotLastTalker); - } - - //先找剧情相关的npc - foundNPC = foundCandidateText(candidates, npcTextMap); - if(!foundNPC.equals("")){ - returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); - break; - }else{ - //再找地点相关的npc - candidates.addAll(findRelateTalkers(true)); - foundNPC = foundCandidateText(candidates, npcTextMap); - if(!foundNPC.equals("")){ - returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); - break; - } - } - } - - } - - break; - } - - - return returnText; - - } - - public String textTypeDetect(String text, String site){ - int code = 0; - String textType = "to_unknown", npc; - - - Boolean flag = true; - - npc = findFirstTalker(text); - - if(text.equals("")){ - textType = "to_unknown"; - }else if(npc.equals("")) { - textType = "less_talker"; - }else if(canTalk(npc, site, false)){ - textType = "direct_return"; - }else{ - textType = "to_unknown"; - } - - - - - return textType; - } - - - - private static Boolean isOnlineMode(String npc, Map historyInfoPoint){ - return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); - } - - - private String findTextLastTalker(String text, String site){ - Matcher m = findTalker(text); - String npc, lastTalker = ""; - while(m.find()) { - //回答unknown文本的npc必须处于在线模式 - npc = m.group(1); - //处于离线模式 可以说话 相同地点 - if(canTalk(npc, site, true)) { - //找到最后一个说话且处于离线模式的npc - lastTalker = npc; - }else{ - System.out.println(npc + "是离线模式"); - } - } - - return lastTalker; - } - - /** - * 找到用来说话的人 - * includeSiteNPC 是否包含当前地点的npc - */ - private List findRelateTalkers(Boolean includeSiteNPC){ - String site = chatCache.getInfoPoint().get("site"); - String lastReply = chatCache.getInfoPoint().get("lastReply"); - - List talkers = new ArrayList(); - - - if(lastReply == null) lastReply = ""; - - String plotLastTalker = findTextLastTalker(lastReply, site); - if(!plotLastTalker.equals("")){ - talkers.add(plotLastTalker); - } - - if(includeSiteNPC){ - List npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site")); - for(String npc:npcList){ - if(canTalk(npc, site, true)){ - talkers.add(npc); - } - } - } - - if(talkers.size() == 0){ - talkers.add(chatCache.getInfoPoint().get(ASSISTANT)); - } - - return talkers; - } - - - - - //从unknown文本中提取npc名字 - private Map> unknownTextClassify(String unknownText){ - String talker; - Map> npcTextMap = new HashMap>(); - - for(String ans:unknownText.split("~")){ - talker = findFirstTalker(ans); - npcTextMap.putIfAbsent(talker, new ArrayList()); - npcTextMap.get(talker).add(ans); - } - - return npcTextMap; - - } - - private String foundCandidateText(Set candidates, Map> npcTextMap){ - String foundNPC = ""; - for(String npc:candidates) { - //先看剧情中最后说话的人有没有unknown文本,如果有就。。。 - if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) { - foundNPC = npc; - break; - } - } - - return foundNPC; - } - -} -- libgit2 0.27.1