From 8a2636cf46d96a207885e2e7918bf6d1a1d9bd6d Mon Sep 17 00:00:00 2001 From: Bl4ckSkull666 Date: Sat, 20 Aug 2016 21:35:22 +0200 Subject: [PATCH] Lets Play Quake v.1.0 --- build.xml | 73 + manifest.mf | 3 + nbproject/build-impl.xml | 1419 ++++++++++++++ nbproject/genfiles.properties | 8 + nbproject/project.properties | 86 + nbproject/project.xml | 15 + src/com/Geekpower14/Quake/Arena/APlayer.java | 260 +++ src/com/Geekpower14/Quake/Arena/ATeam.java | 95 + src/com/Geekpower14/Quake/Arena/Arena.java | 425 +++++ .../Geekpower14/Quake/Arena/ArenaManager.java | 172 ++ .../Quake/Arena/ConfigManager.java | 261 +++ src/com/Geekpower14/Quake/Arena/SArena.java | 376 ++++ src/com/Geekpower14/Quake/Arena/TArena.java | 547 ++++++ src/com/Geekpower14/Quake/Arena/Timer.java | 51 + .../Quake/Commands/AddLobbyCommand.java | 38 + .../Quake/Commands/AddSpawnCommand.java | 62 + .../Quake/Commands/BasicCommand.java | 18 + .../Quake/Commands/ChangeTeamCommand.java | 56 + .../Quake/Commands/CreateCommand.java | 50 + .../Quake/Commands/JoinCommand.java | 56 + .../Quake/Commands/LeaveCommand.java | 42 + .../Quake/Commands/MoneyCommand.java | 84 + .../Quake/Commands/MyCommandExecutor.java | 99 + .../Quake/Commands/ReloadCommand.java | 42 + .../Quake/Commands/RemoveCommand.java | 53 + .../Quake/Commands/RemoveLobbyCommand.java | 51 + .../Quake/Commands/RemoveSpawnCommand.java | 67 + .../Quake/Commands/SaveCommand.java | 56 + .../Quake/Commands/SetLobbySpawnCommand.java | 46 + .../Quake/Commands/SetMapCommand.java | 61 + .../Quake/Commands/SetMaxCommand.java | 61 + .../Quake/Commands/SetMinCommand.java | 61 + .../Quake/Commands/ShopCommand.java | 43 + .../Quake/Commands/StartCommand.java | 56 + .../Quake/Commands/StopCommand.java | 56 + .../Quake/Commands/UtilsCommand.java | 54 + src/com/Geekpower14/Quake/Eco/EcoManager.java | 139 ++ .../Quake/Listener/PlayerListener.java | 388 ++++ .../Geekpower14/Quake/Listener/Weather.java | 33 + src/com/Geekpower14/Quake/Lobby/Lobby.java | 24 + .../Geekpower14/Quake/Lobby/LobbyManager.java | 273 +++ .../Geekpower14/Quake/Lobby/Lobby_Sign.java | 15 + src/com/Geekpower14/Quake/Quake.java | 282 +++ .../Quake/Shop/IconMenuManager.java | 87 + src/com/Geekpower14/Quake/Shop/Item.java | 70 + .../Geekpower14/Quake/Shop/ShopManager.java | 466 +++++ .../Quake/Stuff/Armor/ArmorBasic.java | 28 + .../Quake/Stuff/Armor/ArmorCustomFile.java | 40 + .../Quake/Stuff/Armor/ArmorFactory.java | 17 + .../Quake/Stuff/Armor/ArmorRED.java | 26 + .../Geekpower14/Quake/Stuff/Hat/HatBasic.java | 28 + .../Quake/Stuff/Hat/HatCustomFile.java | 77 + .../Quake/Stuff/Hat/HatFactory.java | 21 + .../Geekpower14/Quake/Stuff/Hat/HatJACK.java | 41 + .../Quake/Stuff/Item/DiamondHoe.java | 82 + .../Geekpower14/Quake/Stuff/Item/GoldHoe.java | 36 + .../Geekpower14/Quake/Stuff/Item/IronHoe.java | 36 + .../Quake/Stuff/Item/ItemBasic.java | 295 +++ .../Quake/Stuff/Item/StoneHoe.java | 36 + .../Quake/Stuff/Item/WoodenHoe.java | 52 + .../Geekpower14/Quake/Stuff/StuffManager.java | 407 +++++ src/com/Geekpower14/Quake/Task.java | 87 + src/com/Geekpower14/Quake/Trans/Score.java | 28 + .../Geekpower14/Quake/Trans/Translate.java | 137 ++ src/com/Geekpower14/Quake/Utils/Area.java | 123 ++ src/com/Geekpower14/Quake/Utils/Config.java | 268 +++ .../Quake/Utils/FireworkEffectPlayer.java | 84 + src/com/Geekpower14/Quake/Utils/IconMenu.java | 221 +++ .../InvSerialization/BookSerialization.java | 172 ++ .../InvSerialization/ColorSerialization.java | 78 + .../EnchantmentSerialization.java | 78 + .../FireworkEffectSerialization.java | 79 + .../FireworkSerialization.java | 67 + .../InvSerialization/HorseSerialization.java | 101 + .../InventorySerialization.java | 216 +++ .../LeatherArmorSerialization.java | 71 + .../LivingEntitySerialization.java | 104 ++ .../InvSerialization/OcelotSerialization.java | 76 + .../InvSerialization/PlayerSerialization.java | 82 + .../PlayerStatsSerialization.java | 132 ++ .../PotionEffectSerialization.java | 65 + .../InvSerialization/SerializationConfig.java | 85 + .../Utils/InvSerialization/Serializer.java | 55 + .../SingleItemSerialization.java | 245 +++ .../InvSerialization/SkullSerialization.java | 73 + .../Quake/Utils/InvSerialization/Util.java | 30 + .../InvSerialization/WolfSerialization.java | 78 + .../Quake/Utils/ParticleEffects.java | 661 +++++++ .../Quake/Utils/PlayerSerializer.java | 133 ++ .../Geekpower14/Quake/Utils/Reflection.java | 114 ++ src/com/Geekpower14/Quake/Utils/ScoreB.java | 75 + src/com/Geekpower14/Quake/Utils/Version.java | 57 + src/org/json/CDL.java | 279 +++ src/org/json/Cookie.java | 169 ++ src/org/json/CookieList.java | 90 + src/org/json/HTTP.java | 163 ++ src/org/json/HTTPTokener.java | 77 + src/org/json/JSONArray.java | 906 +++++++++ src/org/json/JSONException.java | 28 + src/org/json/JSONML.java | 467 +++++ src/org/json/JSONObject.java | 1628 +++++++++++++++++ src/org/json/JSONString.java | 18 + src/org/json/JSONStringer.java | 78 + src/org/json/JSONTokener.java | 446 +++++ src/org/json/JSONWriter.java | 327 ++++ src/org/json/XML.java | 508 +++++ src/org/json/XMLTokener.java | 365 ++++ src/plugin.yml | 10 + 108 files changed, 17436 insertions(+) create mode 100644 build.xml create mode 100644 manifest.mf create mode 100644 nbproject/build-impl.xml create mode 100644 nbproject/genfiles.properties create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml create mode 100644 src/com/Geekpower14/Quake/Arena/APlayer.java create mode 100644 src/com/Geekpower14/Quake/Arena/ATeam.java create mode 100644 src/com/Geekpower14/Quake/Arena/Arena.java create mode 100644 src/com/Geekpower14/Quake/Arena/ArenaManager.java create mode 100644 src/com/Geekpower14/Quake/Arena/ConfigManager.java create mode 100644 src/com/Geekpower14/Quake/Arena/SArena.java create mode 100644 src/com/Geekpower14/Quake/Arena/TArena.java create mode 100644 src/com/Geekpower14/Quake/Arena/Timer.java create mode 100644 src/com/Geekpower14/Quake/Commands/AddLobbyCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/AddSpawnCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/BasicCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/ChangeTeamCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/CreateCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/JoinCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/LeaveCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/MoneyCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/MyCommandExecutor.java create mode 100644 src/com/Geekpower14/Quake/Commands/ReloadCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/RemoveCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/RemoveLobbyCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/RemoveSpawnCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/SaveCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/SetLobbySpawnCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/SetMapCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/SetMaxCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/SetMinCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/ShopCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/StartCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/StopCommand.java create mode 100644 src/com/Geekpower14/Quake/Commands/UtilsCommand.java create mode 100644 src/com/Geekpower14/Quake/Eco/EcoManager.java create mode 100644 src/com/Geekpower14/Quake/Listener/PlayerListener.java create mode 100644 src/com/Geekpower14/Quake/Listener/Weather.java create mode 100644 src/com/Geekpower14/Quake/Lobby/Lobby.java create mode 100644 src/com/Geekpower14/Quake/Lobby/LobbyManager.java create mode 100644 src/com/Geekpower14/Quake/Lobby/Lobby_Sign.java create mode 100644 src/com/Geekpower14/Quake/Quake.java create mode 100644 src/com/Geekpower14/Quake/Shop/IconMenuManager.java create mode 100644 src/com/Geekpower14/Quake/Shop/Item.java create mode 100644 src/com/Geekpower14/Quake/Shop/ShopManager.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Armor/ArmorBasic.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Armor/ArmorCustomFile.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Armor/ArmorFactory.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Armor/ArmorRED.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Hat/HatBasic.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Hat/HatCustomFile.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Hat/HatFactory.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Hat/HatJACK.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/DiamondHoe.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/GoldHoe.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/IronHoe.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/ItemBasic.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/StoneHoe.java create mode 100644 src/com/Geekpower14/Quake/Stuff/Item/WoodenHoe.java create mode 100644 src/com/Geekpower14/Quake/Stuff/StuffManager.java create mode 100644 src/com/Geekpower14/Quake/Task.java create mode 100644 src/com/Geekpower14/Quake/Trans/Score.java create mode 100644 src/com/Geekpower14/Quake/Trans/Translate.java create mode 100644 src/com/Geekpower14/Quake/Utils/Area.java create mode 100644 src/com/Geekpower14/Quake/Utils/Config.java create mode 100644 src/com/Geekpower14/Quake/Utils/FireworkEffectPlayer.java create mode 100644 src/com/Geekpower14/Quake/Utils/IconMenu.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/BookSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/ColorSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/EnchantmentSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkEffectSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/HorseSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/InventorySerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/LeatherArmorSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/LivingEntitySerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/OcelotSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerStatsSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/PotionEffectSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/SerializationConfig.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/Serializer.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/SingleItemSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/SkullSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/Util.java create mode 100644 src/com/Geekpower14/Quake/Utils/InvSerialization/WolfSerialization.java create mode 100644 src/com/Geekpower14/Quake/Utils/ParticleEffects.java create mode 100644 src/com/Geekpower14/Quake/Utils/PlayerSerializer.java create mode 100644 src/com/Geekpower14/Quake/Utils/Reflection.java create mode 100644 src/com/Geekpower14/Quake/Utils/ScoreB.java create mode 100644 src/com/Geekpower14/Quake/Utils/Version.java create mode 100644 src/org/json/CDL.java create mode 100644 src/org/json/Cookie.java create mode 100644 src/org/json/CookieList.java create mode 100644 src/org/json/HTTP.java create mode 100644 src/org/json/HTTPTokener.java create mode 100644 src/org/json/JSONArray.java create mode 100644 src/org/json/JSONException.java create mode 100644 src/org/json/JSONML.java create mode 100644 src/org/json/JSONObject.java create mode 100644 src/org/json/JSONString.java create mode 100644 src/org/json/JSONStringer.java create mode 100644 src/org/json/JSONTokener.java create mode 100644 src/org/json/JSONWriter.java create mode 100644 src/org/json/XML.java create mode 100644 src/org/json/XMLTokener.java create mode 100644 src/plugin.yml diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..4e567cb --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project Quake_1.9. + + + diff --git a/manifest.mf b/manifest.mf new file mode 100644 index 0000000..1574df4 --- /dev/null +++ b/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..f2128ba --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1419 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..f19a68d --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=2936ce4c +build.xml.script.CRC32=bd6b80d1 +build.xml.stylesheet.CRC32=8064a381@1.79.1.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=2936ce4c +nbproject/build-impl.xml.script.CRC32=daa86fce +nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48 diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..0c3a9d6 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,86 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=Quake_1.9 +application.vendor=Bl4ckSkull666 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/Quake_1.9.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.spigot-1.10.2.jar=D:\\AMC-Server.de\\JARs\\spigot-1.10.2.jar +file.reference.Vault_v.1.5.6.jar=../../AMC-Server.de/JARs/Vault_v.1.5.6.jar +file.reference.WorldEdit_v6.1.3.jar=D:\\AMC-Server.de\\JARs\\WorldEdit_v6.1.3.jar +file.reference.WorldEdit_v6.1.jar=../../AMC-Server.de/JARs/WorldEdit_v6.1.jar +file.reference.WorldGuard_v6.1.jar=../../AMC-Server.de/JARs/WorldGuard_v6.1.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.WorldEdit_v6.1.jar}:\ + ${file.reference.WorldGuard_v6.1.jar}:\ + ${file.reference.Vault_v.1.5.6.jar}:\ + ${file.reference.WorldEdit_v6.1.3.jar}:\ + ${file.reference.spigot-1.10.2.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.7 +javac.target=1.7 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..85d64f8 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + Quake_1.9 + + + + + + + + + diff --git a/src/com/Geekpower14/Quake/Arena/APlayer.java b/src/com/Geekpower14/Quake/Arena/APlayer.java new file mode 100644 index 0000000..d5edc67 --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/APlayer.java @@ -0,0 +1,260 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic; +import com.Geekpower14.Quake.Stuff.Hat.HatBasic; +import com.Geekpower14.Quake.Stuff.Item.ItemBasic; +import com.Geekpower14.Quake.Utils.PlayerSerializer; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +public class APlayer { + private final Quake _plugin; + private final Arena _game; + private final Player _p; + private Boolean _Reloading = false; + private Boolean _Invincible = false; + private Boolean _VIP = false; + public int _score = 0; + public int _kill = 0; + public int _death = 0; + public ArmorBasic _armor; + public HatBasic _hat; + public ItemBasic _item; + + public APlayer(Quake pl, Arena aren, Player player) { + _plugin = pl; + _game = aren; + _p = player; + if(Quake.hasPermission(player, "Quake.VIP")) + _VIP = true; + APlayer.createConfig(player); + SaveInventory(); + } + + public static void createConfig(Player p) { + String path = Quake.getPlugin().getDataFolder() + "/Players/" + p.getUniqueId() + ".yml"; + File file = new File(path); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)file); + if (!file.exists()) { + config.set("Name", p.getName()); + config.set("Hoe.Selected", "RailGun"); + ArrayList h = new ArrayList<>(); + h.add("RailGun"); + config.set("Hoe.Bought", h); + config.set("Hat.Selected", ""); + ArrayList ha = new ArrayList<>(); + config.set("Hat.Bought", ha); + config.set("Armor.Selected", ""); + ArrayList ar = new ArrayList<>(); + config.set("Armor.Bought", ar); + try { + config.save(new File(path)); + } catch (IOException var7_7) { + // empty catch block + } + } + } + + public void SaveInventory() { + FileConfiguration config = PlayerSerializer.PlayerToConfig(_p); + try { + config.save(new File(_plugin.getDataFolder() + "/Save_Players/" + _p.getUniqueId() + ".yml")); + } catch (IOException var2_2) { + // empty catch block + } + } + + public void RestoreInventory() { + File f = new File(_plugin.getDataFolder() + "/Save_Players/" + _p.getUniqueId() + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)f); + PlayerSerializer.ConfigToPlayer(_p, (FileConfiguration)config); + f.delete(); + } + + public String getConfig() { + return _plugin.getDataFolder() + "/Players/" + _p.getUniqueId() + ".yml"; + } + + public void initConfig() { + } + + public void getKits() { + _item = _plugin._stuff.getSelectedItem(this); + _hat = _plugin._stuff.getSelectedHat(this); + _armor = _plugin._stuff.getSelectedArmor(this); + } + + public void giveKit() { + if (_item != null) { + _p.getInventory().addItem(new ItemStack[]{_item.getItem()}); + } + if (_hat != null) { + _p.getInventory().setHelmet(_hat.getItem()); + } + if (_armor != null) { + _p.getInventory().setChestplate(_armor.getItem()); + } + } + + public void giveHat() { + if (_hat != null) { + _p.getInventory().setHelmet(_hat.getItem()); + } + } + + public void giveArmor() { + if (_armor != null) { + _p.getInventory().setChestplate(_armor.getItem()); + } + } + + public void giveItem() { + if (_item != null) { + _p.getInventory().addItem(new ItemStack[]{_item.getItem()}); + } + } + + public void saveConfig(FileConfiguration config) { + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + _p.getUniqueId() + ".yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save de " + _p.getName() + " impossible !"); + } + } + + public void setReloading(Long Ticks) { + _Reloading = true; + final Long temp = Ticks; + _p.setExp(0.0f); + final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + float xp = _p.getExp(); + if ((xp += getincr(temp)) >= 1.0f) { + xp = 1.0f; + } + _p.setExp(xp); + } + }, 0, 2); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + APlayer.access$1(APlayer.this, false); + _p.setExp(1.0f); + _plugin.getServer().getScheduler().cancelTask(infoxp); + } + }, Ticks.longValue()); + } + + public void setReloading(Boolean t) { + _Reloading = t; + } + + public void setinvincible(Boolean t) { + _Invincible = t; + } + + public boolean isReloading() { + return _Reloading; + } + + public boolean isInvincible() { + return _Invincible; + } + + public boolean isVIP() { + return _VIP; + } + + public void setInvincible(Long Ticks) { + _Invincible = true; + final Long temp = Ticks; + _p.setExp(0.0f); + final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + float xp = _p.getExp(); + if ((xp += getincr(temp)) >= 1.0f) { + xp = 1.0f; + } + _p.setExp(xp); + } + }, 0, 2); + + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + APlayer.access$3(APlayer.this, false); + _p.setExp(1.0f); + _plugin.getServer().getScheduler().cancelTask(infoxp); + } + }, Ticks); + } + + public float getincr(Long time) { + float result = 0.0f; + float temp = time; + result = 100.0f / (temp / 2.0f) / 100.0f; + return result; + } + + public Arena getGame() { + return _game; + } + + public Player getPlayer() { + return _p; + } + + public void tell(String message) { + _p.sendMessage(message); + } + + public void setLevel(int xp) { + _p.setLevel(xp); + } + + public String getName() { + return _p.getName(); + } + + public String getDisplayName() { + return _p.getDisplayName(); + } + + public Location getLocation() { + return _p.getLocation(); + } + + public Location getEyeLocation() { + return _p.getEyeLocation(); + } + + public boolean isDead() { + return _p.isDead(); + } + + static /* synthetic */ void access$1(APlayer aPlayer, Boolean bl) { + aPlayer._Reloading = bl; + } + + static /* synthetic */ void access$3(APlayer aPlayer, Boolean bl) { + aPlayer._Invincible = bl; + } + +} + diff --git a/src/com/Geekpower14/Quake/Arena/ATeam.java b/src/com/Geekpower14/Quake/Arena/ATeam.java new file mode 100644 index 0000000..2653f3d --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/ATeam.java @@ -0,0 +1,95 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import java.util.ArrayList; +import java.util.Set; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.scoreboard.Team; + +public class ATeam { + private Team _team; + public String _name; + public ChatColor _color; + public Color _Scolor; + public Arena _aren; + public int _Score = 0; + + public ATeam(Quake pl, Arena aren, String name, ChatColor color, Color scolor) { + _name = name; + _color = color; + _aren = aren; + _Scolor = scolor; + createTeam(); + } + + public void createTeam() { + _team = _aren._board.registerNewTeam(_name); + _team.setPrefix(String.valueOf(_color)); + _team.setCanSeeFriendlyInvisibles(true); + } + + public void setScore(int s) { + _Score = s; + } + + public int getScore() { + return _Score; + } + + public void addScore(int s) { + _Score += s; + } + + public String getName() { + return _name; + } + + public void addPlayer(Player p) { + _team.addEntry(p.getName()); + } + + public void removePlayer(Player p) { + _team.removeEntry(p.getName()); + } + + public Boolean hasPlayer(Player p) { + return _team.hasEntry(p.getName()); + } + + public void giveChestplate(Player p) { + ItemStack item = new ItemStack(Material.LEATHER_CHESTPLATE); + LeatherArmorMeta meta = (LeatherArmorMeta)item.getItemMeta(); + meta.setDisplayName(_color + "Team " + _name); + ArrayList l = new ArrayList<>(); + l.add(ChatColor.RESET + "A beautiful leather dress!"); + meta.setLore(l); + meta.setColor(_Scolor); + item.setItemMeta((ItemMeta)meta); + p.getInventory().setChestplate(item); + } + + public Set getPlayers() { + return _team.getEntries(); + } + + public int getSize() { + return _team.getEntries().size(); + } + + public void reset() { + _Score = 0; + _team.unregister(); + createTeam(); + } + + public ChatColor getColor() { + return _color; + } +} + diff --git a/src/com/Geekpower14/Quake/Arena/Arena.java b/src/com/Geekpower14/Quake/Arena/Arena.java new file mode 100644 index 0000000..4d57a8c --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/Arena.java @@ -0,0 +1,425 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Eco.EcoManager; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Trans.Score; +import com.Geekpower14.Quake.Utils.FireworkEffectPlayer; +import com.Geekpower14.Quake.Utils.PlayerSerializer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.Plugin; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.ScoreboardManager; + +public abstract class Arena { + public String _name; + public int _ID; + public int _timer; + public Boolean _Active = false; + public Quake _plugin; + public int _ingame = 50; + public int _pregame = 40; + public int _starting = 30; + public long _after = 15; + public Boolean _finished = false; + public Boolean _stopping = false; + public int _compteur = 0; + public int _etat = _pregame; + public int _goal = 25; + public Boolean _full = false; + public Boolean _NaturalDeath = false; + public Boolean _VIP = false; + public Boolean _Sneak = true; + public Boolean _Global_Chat = false; + public Boolean _Auto_Respawn = false; + public HashMap _players = new HashMap(); + public List _spawns_B = new ArrayList<>(); + public List _spawns_R = new ArrayList<>(); + public List _spawns = new ArrayList<>(); + public int _Coins_Win = 0; + public int _Coins_Kill = 0; + public double _VIP_M = 2.0; + public double _VIPP_M = 3.0; + public String _map; + public int _maxplayer; + public int _minplayer; + public ScoreboardManager _scoremanager; + public Scoreboard _board; + public Objective _objective; + public Objective _obj_side; + FireworkEffectPlayer _fw; + public List _potions = new ArrayList<>(); + + public Arena(Quake pl, String n, int ID) { + _plugin = pl; + _name = n; + _ID = ID; + _maxplayer = 11; + _minplayer = 2; + _etat = _pregame; + _map = "unknown"; + _fw = new FireworkEffectPlayer(_plugin); + testConfig(); + loadConfig(); + _scoremanager = Bukkit.getScoreboardManager(); + _board = _scoremanager.getNewScoreboard(); + _Active = true; + } + + public void resetArena() { + _etat = _pregame; + _full = false; + _players.clear(); + _stopping = false; + _finished = false; + _compteur = 0; + } + + public abstract Boolean reloadConfig(); + + public abstract Boolean loadConfig(); + + public abstract Boolean testConfig(); + + public abstract Boolean saveConfig(); + + public String PoToStr(PotionEffect popo) { + return String.valueOf(popo.getType().getName()) + ":" + popo.getAmplifier(); + } + + public PotionEffect StrToPo(String popo) { + String[] list = popo.split(":"); + return new PotionEffect(PotionEffectType.getByName((String)list[0]), Integer.MAX_VALUE, Integer.valueOf(list[1]).intValue()); + } + + protected void setDefaultConfig(FileConfiguration config, String key, Object value) { + if (!config.isSet(key)) { + config.set(key, value); + } + } + + public void broadcast(String message) { + for(APlayer player : _players.values()) + player.tell(ChatColor.GRAY + "[" + ChatColor.RED + "Quake" + ChatColor.GRAY + "]: " + message); + } + + public void chat(String message) { + for(APlayer player : _players.values()) + player.tell(message); + } + + public void nbroadcast(String message) { + for(APlayer player : _players.values()) + player.tell(message); + } + + public void broadcastXP(int xp) { + for(APlayer player : _players.values()) + player.setLevel(xp); + } + + public void playsound(Sound sound, float a, float b) { + for(APlayer player : _players.values()) + player.getPlayer().playSound(player.getPlayer().getLocation(), sound, a, b); + } + + public void getGainKill(Player player) { + double m = 1.0; + if(Quake.hasPermission(player, "Quake.vip")) + m = _VIP_M; + + if(Quake.hasPermission(player, "Quake.vip+")) + m = _VIPP_M; + + EcoManager eco = _plugin._eco; + eco.addPlayerMoney(player, (int)((double)_Coins_Kill*m)); + eco.addScore(player, Score.Type.Kill, 1); + } + + public void getScoreShot(Player p) { + EcoManager eco = _plugin._eco; + eco.addScore(p, Score.Type.Shot, 1); + } + + public void getScoreDeath(Player p) { + EcoManager eco = _plugin._eco; + eco.addScore(p, Score.Type.Death, 1); + } + + public void getGainWin(Player player) { + double m = 1.0; + if (Quake.hasPermission(player, "Quake.vip")) { + m = _VIP_M; + } + if (Quake.hasPermission(player, "Quake.vip+")) { + m = _VIPP_M; + } + double gain = (double)_Coins_Win * m; + EcoManager eco = _plugin._eco; + eco.addPlayerMoney(player, (int)gain); + eco.addScore(player, Score.Type.Win, 1); + } + + public void setActive(Boolean active) { + _Active = active; + } + + public void setmap(String map) { + _map = map; + } + + public void setmax(int max) { + _maxplayer = max; + } + + public void setmin(int min) { + _minplayer = min; + } + + public Location str2loc(String loc) { + if (loc == null) { + return null; + } + Location res = null; + String[] loca = loc.split(", "); + res = new Location(_plugin.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5])); + return res; + } + + protected String loc2str(Location loc) { + return loc.getWorld().getName() + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch(); + } + + public abstract void joinArena(Player var1); + + public abstract void updateScore(); + + public abstract void leaveArena(Player var1); + + public abstract void CrashLeaveArena(Player var1); + + public static void RejoinAfterCrash(Player p) { + Arena.quitcleaner(p); + if (Quake.getPlugin()._lobby._lobbyspawn != null) { + p.teleport(Quake.getPlugin()._lobby._lobbyspawn); + } + PlayerSerializer.RetorePlayer(p); + } + + public void resetCountdown() { + broadcast(_plugin._trad.get("Game.Arena.Message.Aborde-Game")); + _etat = _pregame; + broadcastXP(_starting); + } + + public void cleaner(Player player) { + player.setGameMode(GameMode.SURVIVAL); + player.setHealth(20.0); + player.setSaturation(10.0f); + player.setFoodLevel(20); + player.getInventory().clear(); + player.getInventory().setHelmet(new ItemStack(Material.AIR, 1)); + player.getInventory().setChestplate(new ItemStack(Material.AIR, 1)); + player.getInventory().setLeggings(new ItemStack(Material.AIR, 1)); + player.getInventory().setBoots(new ItemStack(Material.AIR, 1)); + player.getInventory().setHeldItemSlot(0); + player.setExp(1.0f); + player.setLevel(0); + try { + player.updateInventory(); + } + catch (Exception var2_2) { + // empty catch block + } + } + + public static void quitcleaner(Player player) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + try { + player.updateInventory(); + } + catch (Exception effect) { + // empty catch block + } + } + + public abstract void stop(); + + public void startDelayed() { + broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "" + _starting)); + _etat = _starting; + broadcastXP(_etat); + _timer = _plugin.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin)_plugin, (Runnable)new Timer(_plugin, this), 0, 20); + } + + public abstract void start(); + + public void giveStuff(Player player) { + APlayer ap = getAPlayer(player); + ap.getKits(); + ap.giveHat(); + ap.giveItem(); + ap.giveArmor(); + player.getInventory().setItem(8, getLeaveDoor()); + player.getInventory().setHeldItemSlot(0); + } + + public ItemStack getLeaveDoor() { + ItemStack coucou = new ItemStack(Material.WOOD_DOOR, 1); + ItemMeta coucou_meta = coucou.getItemMeta(); + coucou_meta.setDisplayName(_plugin._trad.get("Game.item.leave")); + coucou.setItemMeta(coucou_meta); + return coucou; + } + + public void giveEffect(Player player) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + for (PotionEffect popo : _potions) { + player.addPotionEffect(popo); + } + } + + public void shotplayer(final Player shooter, Player victim, FireworkEffect effect) { + APlayer ashooter = getAPlayer(shooter); + APlayer avictim = getAPlayer(victim); + if (victim != shooter && !avictim.isInvincible()) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + getGainKill(shooter); + } + }, 2); + try { + _fw.playFirework(victim.getWorld(), victim.getLocation(), effect); + } catch (Exception e) { + e.printStackTrace(); + } + kill(victim); + broadcast(_plugin._trad.get("Game.Arena.Message.Shot").replace("[SHOOTER]", shooter.getName()).replace("[KILLED]", victim.getName())); + ++ashooter._score; + if (ashooter._score == _goal) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + win(shooter); + } + }, 2); + } + updateScore(); + } + } + + public void kill(Player p) { + p.setHealth(0.0); + _Auto_Respawn = true; + } + + public abstract void win(Player var1); + + public Color getColor(int i) { + Color c = null; + if (i == 1) { + c = Color.AQUA; + } + if (i == 2) { + c = Color.BLACK; + } + if (i == 3) { + c = Color.BLUE; + } + if (i == 4) { + c = Color.FUCHSIA; + } + if (i == 5) { + c = Color.GRAY; + } + if (i == 6) { + c = Color.GREEN; + } + if (i == 7) { + c = Color.LIME; + } + if (i == 8) { + c = Color.MAROON; + } + if (i == 9) { + c = Color.NAVY; + } + if (i == 10) { + c = Color.OLIVE; + } + if (i == 11) { + c = Color.ORANGE; + } + if (i == 12) { + c = Color.PURPLE; + } + if (i == 13) { + c = Color.RED; + } + if (i == 14) { + c = Color.SILVER; + } + if (i == 15) { + c = Color.TEAL; + } + if (i == 16) { + c = Color.WHITE; + } + if (i == 17) { + c = Color.YELLOW; + } + return c; + } + + public void disable() { + _Active = false; + stop(); + } + + public void tp(Player player) { + player.teleport(getTp(player)); + } + + public abstract Location getTp(Player var1); + + public Boolean isingame(Player player) { + return _players.containsKey(player.getName()); + } + + public int getplayers() { + return _players.size(); + } + + public APlayer getAPlayer(Player play) { + for (APlayer p : _players.values()) { + if (!p.getPlayer().getName().equals(play.getName())) continue; + return p; + } + return null; + } + +} + diff --git a/src/com/Geekpower14/Quake/Arena/ArenaManager.java b/src/com/Geekpower14/Quake/Arena/ArenaManager.java new file mode 100644 index 0000000..49d0331 --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/ArenaManager.java @@ -0,0 +1,172 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +public class ArenaManager { + public Quake _plugin; + public HashMap _ARENAS = new HashMap(); + + public ArenaManager(Quake pl) { + _plugin = pl; + loadArenas(); + } + + public final void loadArenas() { + File folder = new File(_plugin.getDataFolder(), "/arenas/"); + if (!folder.exists()) { + folder.mkdir(); + } + ArrayList Maps = new ArrayList<>(); + for(File f: folder.listFiles()) { + String name = f.getName().replaceAll(".yml", ""); + Maps.add(name); + } + if(Maps.isEmpty()) + return; + + for(String mapname : Maps) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(new File(_plugin.getDataFolder(), "/arenas/" + mapname + ".yml")); + String type = "Solo"; + if(config.getString("Type", "Solo").equalsIgnoreCase("Team")) + type = "Team"; + + createArena(mapname, type); + } + } + + public void createArena(String name, String Type2) { + if (name == null) { + return; + } + Arena arena = null; + if (Type2.equalsIgnoreCase("Solo")) { + arena = new SArena(_plugin, name, _ARENAS.size()); + _ARENAS.put(name, arena); + } else if(Type2.equalsIgnoreCase("Team")) { + arena = new TArena(_plugin, name, _ARENAS.size()); + _ARENAS.put(name, arena); + } + } + + public String getPlayerhoe(String player) { + File fichier_config = new File(_plugin.getDataFolder(), "hoe.yml"); + if(!fichier_config.exists()) + return null; + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config); + return config.getString(player); + } + + public void setPlayerhoe(String player, String hoe) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "hoe.yml")); + config.set(player, hoe); + try { + config.save(new File(_plugin.getDataFolder(), "hoe.yml")); + _plugin.saveConfig(); + } catch (IOException var4_4) { + // empty catch block + } + } + + public void removeArena(String name) { + Arena aren = _ARENAS.get(name); + aren.stop(); + _ARENAS.remove(name); + } + + public void deleteArena(String name) { + Arena aren = _ARENAS.get(name); + aren.stop(); + File file = new File(_plugin.getDataFolder(), "/arenas/" + aren._name + ".yml"); + file.delete(); + _ARENAS.remove(name); + } + + public Boolean exist(String aren) { + return _ARENAS.containsKey(aren); + } + + public Boolean existid(int ID) { + Arena arena = getArenabyID(ID); + return arena != null; + } + + public Arena getArenabyName(String name) { + if (_ARENAS.size() < 1) { + return null; + } + return _ARENAS.get(name); + } + + public Arena getArenabyPlayer(Player player) { + if(_ARENAS.size() < 1) { + return null; + } + for(Arena aren : _ARENAS.values()) { + if(!aren.isingame(player)) + continue; + return aren; + } + return null; + } + + public Boolean isArenaWorld(World world) { + if (_ARENAS.size() < 1) { + return false; + } + for (Arena arena : _ARENAS.values()) { + Location wo; + World w; + if (arena instanceof SArena) { + SArena aren = (SArena)arena; + if(aren._spawns.isEmpty() || world != aren._spawns.get(0).getWorld()) + continue; + return true; + } + if (!(arena instanceof TArena)) + continue; + TArena aren = (TArena)arena; + if(aren._spawns_B.isEmpty() || world != aren._spawns_B.get(0).getWorld()) + continue; + return true; + } + return false; + } + + public Arena getArenabyID(int ID) { + if (_ARENAS.size() < 1) { + return null; + } + for(Arena aren : _ARENAS.values()) { + if (aren._ID != ID) + continue; + return aren; + } + return null; + } + + public void reloadArenas() { + for(Arena aren : _ARENAS.values()) { + aren.reloadConfig(); + } + } + + public void Disable() { + for(Arena aren : _ARENAS.values()) { + aren.disable(); + } + } + + public void updateScoreArenas() { + for(Arena aren : _ARENAS.values()) { + aren.updateScore(); + } + } +} \ No newline at end of file diff --git a/src/com/Geekpower14/Quake/Arena/ConfigManager.java b/src/com/Geekpower14/Quake/Arena/ConfigManager.java new file mode 100644 index 0000000..b8a5a1b --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/ConfigManager.java @@ -0,0 +1,261 @@ +package com.Geekpower14.Quake.Arena; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +public class ConfigManager { + private YamlConfiguration _cfg = new YamlConfiguration(); + private File _configFile; + private Map _booleans; + private Map _ints; + private Map _doubles; + private Map _strings; + + public ConfigManager(File configFile) { + _configFile = configFile; + _booleans = new HashMap<>(); + _ints = new HashMap<>(); + _doubles = new HashMap<>(); + _strings = new HashMap<>(); + } + + public void createDefaults() { + _cfg.options().indent(4); + for(ACFG cfg: ACFG.values()) + _cfg.addDefault(cfg.getNode(), cfg.getValue()); + save(); + } + + public boolean load() { + try { + _cfg.load(_configFile); + reloadMaps(); + return true; + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + return false; + } + } + + public void reloadMaps() { + for(String s : _cfg.getKeys(true)) { + Object object = _cfg.get(s); + if(object instanceof Boolean) { + _booleans.put(s, (Boolean)object); + continue; + } + if(object instanceof Integer) { + _ints.put(s, (Integer)object); + continue; + } + if(object instanceof Double) { + _doubles.put(s, (Double)object); + continue; + } + if(!(object instanceof String)) + continue; + _strings.put(s, (String)object); + } + } + + public boolean save() { + try { + _cfg.save(_configFile); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean delete() { + return _configFile.delete(); + } + + public void setHeader(String header) { + _cfg.options().header(header); + } + + public YamlConfiguration getYamlConfiguration() { + return _cfg; + } + + public Object getUnsafe(String string) { + return _cfg.get(string); + } + + public boolean getBoolean(ACFG cfg) { + return getBoolean(cfg, (Boolean)cfg.getValue()); + } + + private boolean getBoolean(ACFG cfg, boolean def) { + String path = cfg.getNode(); + Boolean result = _booleans.get(path); + return result == null ? def : result; + } + + public int getInt(ACFG cfg) { + return getInt(cfg, (Integer)cfg.getValue()); + } + + public int getInt(ACFG cfg, int def) { + String path = cfg.getNode(); + Integer result = _ints.get(path); + return result == null ? def : result; + } + + public double getDouble(ACFG cfg) { + return getDouble(cfg, (Double)cfg.getValue()); + } + + public double getDouble(ACFG cfg, double def) { + String path = cfg.getNode(); + Double result = _doubles.get(path); + return result == null ? def : result; + } + + public String getString(ACFG cfg) { + return getString(cfg, (String)cfg.getValue()); + } + + public String getString(ACFG cfg, String def) { + String path = cfg.getNode(); + String result = _strings.get(path); + return result == null ? def : result; + } + + public Set getKeys(String path) { + if(_cfg.get(path) == null) { + return null; + } + ConfigurationSection section = _cfg.getConfigurationSection(path); + return section.getKeys(false); + } + + public List getStringList(String path, List def) { + if(_cfg.get(path) == null) { + return def == null ? new LinkedList() : def; + } + return _cfg.getStringList(path); + } + + public void setManually(String path, Object value) { + if(value instanceof Boolean) { + _booleans.put(path, (Boolean)value); + } else if (value instanceof Integer) { + _ints.put(path, (Integer)value); + } else if (value instanceof Double) { + _doubles.put(path, (Double)value); + } else if (value instanceof String) { + _strings.put(path, (String)value); + } else + _cfg.set(path, value); + } + + public void set(ACFG cfg, Object value) { + setManually(cfg.getNode(), value); + } + + public Location str2loc(String loc) { + if (loc == null) { + return null; + } + Location res = null; + String[] loca = loc.split(", "); + res = new Location(Bukkit.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5])); + return res; + } + + public static enum ACFG { + Z("configversion", "v0.9.0.0"), + Spawns("Nombre", new ArrayList()), + CHAT_DEFAULTTEAM("chat.defaultTeam", Boolean.valueOf(false)), + MODULES_WORLDEDIT_AUTOLOAD("modules.worldedit.autoload", Boolean.valueOf(false)), + MODULES_WORLDEDIT_AUTOSAVE("modules.worldedit.autosave", Boolean.valueOf(false)); + + private String _node; + private final Object _value; + private final String _type; + + public static ACFG getByNode(String node) { + ACFG[] arraCFG = ACFG.values(); + int n = arraCFG.length; + int n2 = 0; + while (n2 < n) { + ACFG m = arraCFG[n2]; + if (m.getNode().equals(node)) { + return m; + } + ++n2; + } + return null; + } + + private ACFG(String node, String s) { + _node = node; + _value = s; + _type = "string"; + } + + private ACFG(String node, Boolean b) { + _node = node; + _value = b; + _type = "boolean"; + } + + private ACFG(String node, Integer i) { + _node = node; + _value = i; + _type = "int"; + } + + private ACFG(String node, Double d) { + _node = node; + _value = d; + _type = "double"; + } + + private ACFG(String node, List value) { + _node = node; + _value = value; + _type = "list"; + } + + public String getNode() { + return _node; + } + + public void setNode(String value) { + _node = value; + } + + @Override + public String toString() { + return String.valueOf(_value); + } + + public Object getValue() { + return _value; + } + + public static ACFG[] getValues() { + return ACFG.values(); + } + + public String getType() { + return _type; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Arena/SArena.java b/src/com/Geekpower14/Quake/Arena/SArena.java new file mode 100644 index 0000000..512e920 --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/SArena.java @@ -0,0 +1,376 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.plugin.Plugin; +import org.bukkit.potion.PotionEffect; +import org.bukkit.scoreboard.DisplaySlot; + +public class SArena extends Arena { + public SArena(Quake pl, String n, int ID) { + super(pl, n, ID); + } + + @Override + public Boolean reloadConfig() { + if (_etat != _pregame) { + stop(); + } + testConfig(); + loadConfig(); + return true; + } + + @Override + public Boolean loadConfig() { + File fichier_config = new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config); + if (config.contains("Nombre")) { + int nombre = config.getInt("Nombre"); + for (int i = 0; i < nombre; i++) { + String nom = config.getString("spawn" + i); + _spawns.add(i, str2loc(nom)); + } + } else { + List s = new ArrayList(); + for(String spawn : config.getStringList("Spawns")) { + s.add(str2loc(spawn)); + } + _spawns = s; + } + _map = config.getString("Map"); + _maxplayer = config.getInt("MaxPlayers"); + _minplayer = config.getInt("MinPlayers"); + _Active = config.getBoolean("Active"); + _NaturalDeath = config.getBoolean("Natural-Death"); + _Auto_Respawn = config.getBoolean("Auto-Respawn"); + _VIP = config.getBoolean("VIP"); + _goal = config.getInt("Goal"); + _starting = config.getInt("Time-Before"); + _after = config.getLong("Time-After"); + _Coins_Win = config.getInt("Coins-per-Win"); + _Coins_Kill = config.getInt("Coins-per-Kill"); + _VIP_M = config.getDouble("VIP-Multiplicator"); + _VIPP_M = config.getDouble("VIP+-Multiplicator"); + _Global_Chat = config.getBoolean("Global-Chat"); + _Sneak = config.getBoolean("Sneak"); + ArrayList l = new ArrayList<>(); + for (String popo : config.getStringList("Potions")) + l.add(StrToPo(popo)); + _potions = l; + if(config.contains("Nombre")) + saveConfig(); + return true; + } + + @Override + public Boolean testConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + setDefaultConfig((FileConfiguration)config, "Version", Quake._version); + setDefaultConfig((FileConfiguration)config, "Name", _name); + setDefaultConfig((FileConfiguration)config, "Type", "Solo"); + setDefaultConfig((FileConfiguration)config, "Map", "Unknown"); + setDefaultConfig((FileConfiguration)config, "Active", true); + setDefaultConfig((FileConfiguration)config, "Natural-Death", false); + setDefaultConfig((FileConfiguration)config, "Auto-Respawn", false); + setDefaultConfig((FileConfiguration)config, "VIP", false); + setDefaultConfig((FileConfiguration)config, "Goal", 25); + setDefaultConfig((FileConfiguration)config, "Time-Before", 30); + setDefaultConfig((FileConfiguration)config, "Time-After", 15); + setDefaultConfig((FileConfiguration)config, "Coins-per-Win", 20); + setDefaultConfig((FileConfiguration)config, "Coins-per-Kill", 1); + setDefaultConfig((FileConfiguration)config, "VIP-Multiplicator", 2); + setDefaultConfig((FileConfiguration)config, "VIP+-Multiplicator", 3); + setDefaultConfig((FileConfiguration)config, "Global-Chat", false); + ArrayList l = new ArrayList<>(); + l.add("SPEED:2"); + l.add("JUMP:1"); + setDefaultConfig((FileConfiguration)config, "Potions", l); + setDefaultConfig((FileConfiguration)config, "MaxPlayers", 11); + setDefaultConfig((FileConfiguration)config, "MinPlayers", 2); + setDefaultConfig((FileConfiguration)config, "Sneak", true); + setDefaultConfig((FileConfiguration)config, "Spawns", new ArrayList()); + try { + config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + } catch (IOException e) { + _plugin.getLogger().warning("save default de " + _name + " impossible !"); + disable(); + } + return true; + } + + @Override + public Boolean saveConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + config.set("Name", _name); + config.set("Type", "Solo"); + config.set("Map", _map); + config.set("Active", _Active); + config.set("VIP", _VIP); + config.set("Global-Chat", _Global_Chat); + config.set("Natural-Death", _NaturalDeath); + config.set("Auto-Respawn", _Auto_Respawn); + config.set("Sneak", _Sneak); + ArrayList l = new ArrayList<>(); + for(PotionEffect popo : _potions) + l.add(PoToStr(popo)); + + config.set("Potions", l); + config.set("MaxPlayers", _maxplayer); + config.set("MinPlayers", _minplayer); + config.set("Sneak", _Sneak); + ArrayList s = new ArrayList<>(); + for(Location loc : _spawns) + s.add(loc2str(loc)); + + config.set("Spawns", s); + try { + config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + _plugin.saveConfig(); + } catch (IOException e) { + _plugin.getLogger().warning("save de " + _name + "impossible !"); + disable(); + return false; + } + return true; + } + + @Override + public void joinArena(Player player) { + if (_spawns.isEmpty()) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.NoSpawn")); + return; + } + if (_etat > _pregame && !Quake.hasPermission(player, "Quake.JoinInGame")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.inGame")); + return; + } + if (_VIP && !Quake.hasPermission(player, "Quake.VIP")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.VIP")); + return; + } + if (_full && !Quake.hasPermission(player, "Quake.VIP")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.full")); + return; + } + if (_players.size() > _maxplayer - 1) { + _full = true; + } + APlayer ap = new APlayer(_plugin, this, player); + _players.put(player.getName(), ap); + broadcast(_plugin._trad.get("Game.Arena.Message.Join").replace("[PLAYER]", player.getName()).replace("[NUMBER]", "" + _players.size()).replace("[MAX]", "" + _maxplayer)); + if (_players.size() >= _minplayer && _etat == _pregame) { + startDelayed(); + } + if (_etat > _pregame && Quake.hasPermission(player, "Quake.JoinInGame")) { + tp(player); + cleaner(player); + updateScore(); + ap.setInvincible(40L); + final Player p = player; + Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() { + + @Override + public void run() { + giveStuff(p); + } + }, 20); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + giveEffect(p); + giveEffect(p); + } + }, 35); + } else { + tp(player); + cleaner(player); + player.getInventory().setItem(8, getLeaveDoor()); + player.getInventory().setHeldItemSlot(0); + try { + player.updateInventory(); + } + catch (Exception p) { + // empty catch block + } + } + } + + @Override + public void leaveArena(Player player) { + APlayer ap = getAPlayer(player); + SArena.quitcleaner(player); + player.setScoreboard(_scoremanager.getNewScoreboard()); + if (_players.size() <= 2 && !_stopping && _etat == _ingame) { + stop(); + } + if (_players.size() < _minplayer && !_stopping && _etat <= _starting) { + resetCountdown(); + } + if (_plugin._lobby._lobbyspawn != null) { + player.teleport(_plugin._lobby._lobbyspawn); + } else { + Location wo = (Location)_spawns.get(0); + if (wo != null) { + player.teleport(wo.getWorld().getSpawnLocation()); + } + } + ap.RestoreInventory(); + _players.remove(player.getName()); + } + + @Override + public void CrashLeaveArena(Player player) { + _players.remove(player.getName()); + if (_players.size() <= 1 && !_stopping && _etat == _ingame) { + stop(); + } + if (_players.size() < _minplayer && !_stopping && _etat <= _starting) { + resetCountdown(); + } + } + + @Override + public void updateScore() { + if(_players.size() <= 0) + return; + + for(APlayer player2 : _players.values()) + _objective.getScore(player2.getName()).setScore(player2._score); + + for(APlayer player2 : _players.values()) + player2.getPlayer().setScoreboard(_objective.getScoreboard()); + } + + @Override + public void stop() { + _stopping = true; + _plugin.getServer().getScheduler().cancelTask(_timer); + for(APlayer play : _players.values()) { + Player player = play.getPlayer(); + SArena.quitcleaner(player); + player.setScoreboard(_scoremanager.getNewScoreboard()); + if(_plugin._lobby._lobbyspawn != null) + player.teleport(_plugin._lobby._lobbyspawn); + play.RestoreInventory(); + } + _stopping = false; + resetArena(); + } + + @Override + public void start() { + _etat = _ingame; + if (_objective != null) { + _objective.unregister(); + } + _objective = _board.registerNewObjective(_name, "dummy"); + _objective.setDisplaySlot(DisplaySlot.SIDEBAR); + _objective.setDisplayName("Score"); + for(APlayer play : _players.values()) { + Player player = play.getPlayer(); + cleaner(player); + giveStuff(player); + tp(player); + updateScore(); + giveEffect(player); + } + } + + public void addspawn(Location loc) { + _spawns.add(loc); + } + + public void removespawn(String args) { + _spawns.remove(Integer.parseInt(args)); + } + + @Override + public void win(final Player player) { + getGainWin(player); + _finished = true; + nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#"); + nbroadcast("" + ChatColor.GRAY); + nbroadcast(_plugin._trad.get("Game.Arena.Message.Won").replace("[NAME]", player.getName())); + nbroadcast("" + ChatColor.GRAY); + nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#"); + _plugin.getLogger().log(Level.INFO, _plugin._trad.get("Game.Arena.Message.Won").replace("[NAME]", player.getName())); + final int nb = (int)((double)_after * 1.5); + final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask(_plugin, new Runnable() { + + @Override + public void run() { + if(_compteur >= nb) + return; + + Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK); + FireworkMeta fwm = fw.getFireworkMeta(); + Random r = new Random(); + int rt = r.nextInt(4) + 1; + FireworkEffect.Type type = FireworkEffect.Type.BALL; + if (rt == 1) { + type = FireworkEffect.Type.BALL; + } + if (rt == 2) { + type = FireworkEffect.Type.BALL_LARGE; + } + if (rt == 3) { + type = FireworkEffect.Type.BURST; + } + if (rt == 4) { + type = FireworkEffect.Type.CREEPER; + } + if (rt == 5) { + type = FireworkEffect.Type.STAR; + } + int r1i = r.nextInt(17) + 1; + int r2i = r.nextInt(17) + 1; + Color c1 = getColor(r1i); + Color c2 = getColor(r2i); + FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build(); + fwm.addEffect(effect); + int rp = r.nextInt(2) + 1; + fwm.setPower(rp); + fw.setFireworkMeta(fwm); + _compteur++; + } + }, 5, 5); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + _plugin.getServer().getScheduler().cancelTask(infoxp); + stop(); + } + }, _after * 20); + } + + @Override + public Location getTp(Player player) { + int higher = _spawns.size() - 1; + if (_spawns.size() < 0) { + higher = 0; + } + int random = (int)(Math.random() * (double)higher); + Location loc = (Location)_spawns.get(random); + return loc; + } + +} \ No newline at end of file diff --git a/src/com/Geekpower14/Quake/Arena/TArena.java b/src/com/Geekpower14/Quake/Arena/TArena.java new file mode 100644 index 0000000..d14e956 --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/TArena.java @@ -0,0 +1,547 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.plugin.Plugin; +import org.bukkit.potion.PotionEffect; +import org.bukkit.scoreboard.DisplaySlot; + +public class TArena extends Arena { + public List _Teams = new ArrayList<>(); + + public TArena(Quake pl, String n, int ID) { + super(pl, n, ID); + _Teams.add(new ATeam(pl, this, "Blue", ChatColor.BLUE, Color.BLUE)); + _Teams.add(new ATeam(pl, this, "Red", ChatColor.RED, Color.RED)); + } + + @Override + public Boolean reloadConfig() { + if (_etat != _pregame) { + stop(); + } + testConfig(); + loadConfig(); + return true; + } + + @Override + public Boolean loadConfig() { + File fichier_config = new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config); + ArrayList s = new ArrayList<>(); + for (String spawn : config.getStringList("Spawns_B")) { + s.add(str2loc(spawn)); + } + _spawns_B = s; + ArrayList ss = new ArrayList<>(); + for (String spawn2 : config.getStringList("Spawns_R")) { + ss.add(str2loc(spawn2)); + } + _spawns_R = ss; + _map = config.getString("Map"); + _maxplayer = config.getInt("MaxPlayers"); + _minplayer = config.getInt("MinPlayers"); + _Active = config.getBoolean("Active"); + _NaturalDeath = config.getBoolean("Natural-Death"); + _Auto_Respawn = config.getBoolean("Auto-Respawn"); + _VIP = config.getBoolean("VIP"); + _goal = config.getInt("Goal"); + _starting = config.getInt("Time-Before"); + _after = config.getLong("Time-After"); + _Coins_Win = config.getInt("Coins-per-Win"); + _Coins_Kill = config.getInt("Coins-per-Kill"); + _VIP_M = config.getDouble("VIP-Multiplicator"); + _VIPP_M = config.getDouble("VIP+-Multiplicator"); + _Global_Chat = config.getBoolean("Global-Chat"); + _Sneak = config.getBoolean("Sneak"); + ArrayList l = new ArrayList(); + for (String popo : config.getStringList("Potions")) { + l.add(StrToPo(popo)); + } + _potions = l; + _plugin.getLogger().info("load de " + _name); + return true; + } + + @Override + public Boolean testConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + setDefaultConfig((FileConfiguration)config, "Version", Quake._version); + setDefaultConfig((FileConfiguration)config, "Name", _name); + setDefaultConfig((FileConfiguration)config, "Type", "Team"); + setDefaultConfig((FileConfiguration)config, "Map", "Unknown"); + setDefaultConfig((FileConfiguration)config, "Active", true); + setDefaultConfig((FileConfiguration)config, "Natural-Death", false); + setDefaultConfig((FileConfiguration)config, "Auto-Respawn", false); + setDefaultConfig((FileConfiguration)config, "VIP", false); + setDefaultConfig((FileConfiguration)config, "Goal", 25); + setDefaultConfig((FileConfiguration)config, "Time-Before", 30); + setDefaultConfig((FileConfiguration)config, "Time-After", 15); + setDefaultConfig((FileConfiguration)config, "Coins-per-Win", 20); + setDefaultConfig((FileConfiguration)config, "Coins-per-Kill", 1); + setDefaultConfig((FileConfiguration)config, "VIP-Multiplicator", 2); + setDefaultConfig((FileConfiguration)config, "VIP+-Multiplicator", 3); + setDefaultConfig((FileConfiguration)config, "Global-Chat", false); + ArrayList l = new ArrayList<>(); + l.add("SPEED:2"); + l.add("JUMP:1"); + setDefaultConfig((FileConfiguration)config, "Potions", l); + setDefaultConfig((FileConfiguration)config, "MaxPlayers", 11); + setDefaultConfig((FileConfiguration)config, "MinPlayers", 2); + setDefaultConfig((FileConfiguration)config, "Sneak", true); + setDefaultConfig((FileConfiguration)config, "Spawns_B", new ArrayList()); + setDefaultConfig((FileConfiguration)config, "Spawns_R", new ArrayList()); + try { + config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save default de " + _name + " impossible !"); + disable(); + } + return true; + } + + @Override + public Boolean saveConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + _plugin.getLogger().info("save de " + _name); + config.set("Version", Quake._version); + config.set("Name", _name); + config.set("Type", "Team"); + config.set("Map", _map); + config.set("Active", _Active); + config.set("Natural-Death", _NaturalDeath); + config.set("Auto-Respawn", _Auto_Respawn); + config.set("VIP", _VIP); + config.set("Goal", _goal); + config.set("Time-Before", _starting); + config.set("Time-After", _after); + config.set("Coins-per-Win", _Coins_Win); + config.set("Coins-per-Kill", _Coins_Kill); + config.set("VIP-Multiplicator", _VIP_M); + config.set("VIP+-Multiplicator", _VIPP_M); + config.set("Global-Chat", _Global_Chat); + ArrayList l = new ArrayList<>(); + for(PotionEffect popo : _potions) { + l.add(PoToStr(popo)); + } + config.set("Potions", l); + config.set("MaxPlayers", _maxplayer); + config.set("MinPlayers", _minplayer); + config.set("Sneak", _Sneak); + ArrayList s = new ArrayList<>(); + for(Location loc : _spawns_B) { + s.add(loc2str(loc)); + } + config.set("Spawns_B", s); + ArrayList ss = new ArrayList<>(); + for(Location loc2 : _spawns_R) { + ss.add(loc2str(loc2)); + } + config.set("Spawns_R", ss); + try { + config.save(new File(_plugin.getDataFolder(), "/arenas/" + _name + ".yml")); + _plugin.saveConfig(); + } catch (IOException e) { + _plugin.getLogger().warning("save de " + _name + "impossible !"); + disable(); + return false; + } + return true; + } + + @Override + public void joinArena(Player player) { + if (_spawns_B.isEmpty() || _spawns_R.isEmpty()) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.NoSpawn")); + return; + } + if (_etat > _pregame && !Quake.hasPermission(player, "Quake.JoinInGame")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.inGame")); + return; + } + if (_VIP && !Quake.hasPermission(player, "Quake.VIP")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.VIP")); + return; + } + if (_full && !Quake.hasPermission(player, "Quake.VIP")) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.full")); + return; + } + if (_players.size() > _maxplayer - 1) { + _full = true; + } + APlayer ap = new APlayer(_plugin, this, player); + _players.put(player.getName(), ap); + addPlayerToTeam(player); + if (_players.size() >= _minplayer && _etat == _pregame) { + startDelayed(); + } + if (_etat > _pregame && Quake.hasPermission(player, "Quake.JoinInGame")) { + tp(player); + cleaner(player); + updateScore(); + ap.setInvincible(30L); + final Player p = player; + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + giveStuff(p); + } + }, 20); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + giveEffect(p); + giveEffect(p); + } + }, 35); + } else { + tp(player); + cleaner(player); + player.getInventory().setItem(8, getLeaveDoor()); + player.getInventory().setHeldItemSlot(0); + try { + player.updateInventory(); + } + catch (Exception p) { + // empty catch block + } + } + } + + @Override + public void leaveArena(Player player) { + APlayer ap = getAPlayer(player); + TArena.quitcleaner(player); + player.setScoreboard(_scoremanager.getNewScoreboard()); + if (!(_Teams.get(0).getSize() > 1 && _Teams.get(1).getSize() > 1 || _stopping || _etat != _ingame)) { + stop(); + } + if (_players.size() < _minplayer && !_stopping && _etat <= _starting) { + resetCountdown(); + } + if (_plugin._lobby._lobbyspawn != null) { + player.teleport(_plugin._lobby._lobbyspawn); + } else { + Location wo = (Location)_spawns_B.get(0); + if (wo != null) { + player.teleport(wo.getWorld().getSpawnLocation()); + } + } + ap.RestoreInventory(); + getTeam(player).removePlayer(player); + _players.remove(player.getName()); + } + + @Override + public void CrashLeaveArena(Player player) { + _players.remove(player.getName()); + getTeam(player).removePlayer(player); + if (_players.size() <= 1 && !_stopping && _etat == _ingame) { + stop(); + } + if (_players.size() < _minplayer && !_stopping && _etat <= _starting) { + resetCountdown(); + } + } + + @Override + public void updateScore() { + for (APlayer player2 : _players.values()) + _objective.getScore(player2.getName()).setScore(player2._score); + for (ATeam t : _Teams) + _obj_side.getScore(t.getColor() + t.getName()).setScore(t.getScore()); + for (APlayer player2 : _players.values()) + player2.getPlayer().setScoreboard(_objective.getScoreboard()); + } + + @Override + public void shotplayer(final Player shooter, Player victim, FireworkEffect effect) { + APlayer ashooter = getAPlayer(shooter); + APlayer avictim = getAPlayer(victim); + if (victim != shooter && !avictim.isInvincible() && !isSameTeam(victim, shooter)) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + getGainKill(shooter); + } + }, 2); + try { + _fw.playFirework(victim.getWorld(), victim.getLocation(), effect); + } + catch (Exception e) { + e.printStackTrace(); + } + kill(victim); + broadcast(_plugin._trad.get("Game.Arena.Message.Shot").replace("[SHOOTER]", shooter.getName()).replace("[KILLED]", victim.getName())); + ashooter._score++; + getTeam(ashooter).addScore(1); + if (getTeam(ashooter).getScore() >= _goal) { + Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() { + + @Override + public void run() { + win(getTeam(shooter)); + } + }, 2); + } + updateScore(); + } + } + + @Override + public void resetArena() { + _etat = _pregame; + _full = false; + _players.clear(); + for (ATeam at : _Teams) { + at.reset(); + } + _stopping = false; + _finished = false; + _compteur = 0; + } + + @Override + public void stop() { + _stopping = true; + _plugin.getServer().getScheduler().cancelTask(_timer); + for (APlayer play : _players.values()) { + Player player = play.getPlayer(); + getTeam(player).removePlayer(player); + TArena.quitcleaner(player); + player.setScoreboard(_scoremanager.getNewScoreboard()); + if(_plugin._lobby._lobbyspawn != null) { + player.teleport(_plugin._lobby._lobbyspawn); + } + play.RestoreInventory(); + } + _stopping = false; + resetArena(); + } + + @Override + public void start() { + _etat = _ingame; + if (_objective != null) { + _objective.unregister(); + _objective = null; + } + if (_obj_side != null) { + _obj_side.unregister(); + _obj_side = null; + } + for (APlayer aPlayer : _players.values()) { + } + _obj_side = _board.registerNewObjective(String.valueOf(_name) + "_Team", "dummy"); + _obj_side.setDisplaySlot(DisplaySlot.SIDEBAR); + _obj_side.setDisplayName("Score"); + _objective = _board.registerNewObjective(String.valueOf(_name) + "_Perso", "dummy"); + _objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); + _objective.setDisplayName("Score_P"); + for(APlayer play : _players.values()) { + Player player = play.getPlayer(); + cleaner(player); + giveStuff(player); + tp(player); + giveEffect(player); + } + updateScore(); + } + + @Override + public void giveStuff(Player player) { + APlayer ap = getAPlayer(player); + ap.getKits(); + ap.giveHat(); + ap.giveItem(); + getTeam(player).giveChestplate(player); + player.getInventory().setItem(8, getLeaveDoor()); + player.getInventory().setHeldItemSlot(0); + } + + private void addPlayerToTeam(Player p) { + ATeam result = _Teams.get(0); + for (ATeam t : _Teams) { + if (t.getSize() >= result.getSize()) continue; + result = t; + } + result.addPlayer(p); + broadcast(_plugin._trad.get("Game.Arena.Message.Team-Join").replace("[TEAM]", result.getName()).replace("[PLAYER]", p.getName()).replace("[NUMBER]", "" + _players.size()).replace("[MAX]", "" + _maxplayer)); + } + + public void changeTeam(Player p, String steam) { + ATeam nteam = getTeam(steam); + ATeam oteam = getTeam(p); + if (nteam == null) { + p.sendMessage(_plugin._trad.get("Game.Arena.error.BadTeamName")); + return; + } + if (_etat == _ingame && !Quake.hasPermission(p, "Quake.ChangeTeamInGame")) { + p.sendMessage(_plugin._trad.get("Game.Arena.error.ChangeTeamInGame")); + return; + } + oteam.removePlayer(p); + if (_etat == _ingame) { + kill(p); + } + nteam.addPlayer(p); + p.sendMessage(_plugin._trad.get("Game.Arena.Message.ChangeTeam").replace("[TEAM]", nteam.getColor() + nteam.getName())); + } + + public ATeam getTeam(Player p) { + for(ATeam t : _Teams) { + if (!t.hasPlayer(p)) + continue; + return t; + } + return _Teams.get(0); + } + + public ATeam getTeam(String name) { + for (ATeam t : _Teams) { + if (!t.getName().equalsIgnoreCase(name)) + continue; + return t; + } + return null; + } + + public ATeam getTeam(APlayer p) { + return getTeam(p.getPlayer()); + } + + public Boolean isSameTeam(Player p, Player b) { + return getTeam(p).hasPlayer(b); + } + + public int addspawn(Location loc, String team) { + if (team.equalsIgnoreCase("Blue")) { + _spawns_B.add(loc); + return _spawns_B.size(); + } + if (team.equalsIgnoreCase("Red")) { + _spawns_R.add(loc); + return _spawns_R.size(); + } + return 0; + } + + public int removespawn(String args, String team) { + if (team.equalsIgnoreCase("Blue")) { + _spawns_B.remove(Integer.parseInt(args)); + return _spawns_B.size(); + } + if (team.equalsIgnoreCase("Red")) { + _spawns_R.remove(Integer.parseInt(args)); + return _spawns_R.size(); + } + return 0; + } + + public void win(ATeam team) { + _finished = true; + nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#"); + nbroadcast("" + ChatColor.GRAY); + nbroadcast(_plugin._trad.get("Game.Arena.Message.Team-Won").replace("[TEAM]", team.getName())); + nbroadcast("" + ChatColor.GRAY); + nbroadcast(ChatColor.GOLD + "#" + ChatColor.GRAY + "--------------------" + ChatColor.GOLD + "#"); + _plugin.getLogger().log(Level.INFO, _plugin._trad.get("Game.Arena.Message.Won").replace("[TEAM]", team.getName())); + for(String p : team.getPlayers()) { + Player pl = Bukkit.getPlayer(p); + if(pl != null) + win(pl); + } + + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + stop(); + } + }, _after * 20); + } + + @Override + public void win(final Player player) { + getGainWin(player); + final int nb = (int)((double)_after*1.5); + Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() { + + @Override + public void run() { + if(_compteur <= nb) + Bukkit.getScheduler().scheduleSyncDelayedTask(_plugin, this, 5); + + Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK); + FireworkMeta fwm = fw.getFireworkMeta(); + Random r = new Random(); + int rt = r.nextInt(4) + 1; + FireworkEffect.Type type = FireworkEffect.Type.BALL; + if (rt == 1) { + type = FireworkEffect.Type.BALL; + } + if (rt == 2) { + type = FireworkEffect.Type.BALL_LARGE; + } + if (rt == 3) { + type = FireworkEffect.Type.BURST; + } + if (rt == 4) { + type = FireworkEffect.Type.CREEPER; + } + if (rt == 5) { + type = FireworkEffect.Type.STAR; + } + int r1i = r.nextInt(17) + 1; + int r2i = r.nextInt(17) + 1; + Color c1 = getColor(r1i); + Color c2 = getColor(r2i); + FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build(); + fwm.addEffect(effect); + int rp = r.nextInt(2) + 1; + fwm.setPower(rp); + fw.setFireworkMeta(fwm); + _compteur++; + } + }, 5); + } + + @Override + public Location getTp(Player player) { + List spawns = new ArrayList(); + spawns = getTeam(player).getName().equalsIgnoreCase("Blue") ? _spawns_B : _spawns_R; + int higher = spawns.size() - 1; + if (spawns.size() < 0) { + higher = 0; + } + Random t = new Random(); + int random = t.nextInt(higher); + Location loc = (Location)spawns.get(random); + return loc; + } + +} + diff --git a/src/com/Geekpower14/Quake/Arena/Timer.java b/src/com/Geekpower14/Quake/Arena/Timer.java new file mode 100644 index 0000000..72c393a --- /dev/null +++ b/src/com/Geekpower14/Quake/Arena/Timer.java @@ -0,0 +1,51 @@ +package com.Geekpower14.Quake.Arena; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.Sound; + +public class Timer implements Runnable { + public Quake _plugin; + public Arena _arena; + public int _finish = 15; + + public Timer(Quake pl, Arena aren) { + _plugin = pl; + _arena = aren; + } + + @Override + public void run() { + if(_plugin.getServer().getOnlinePlayers().isEmpty()) + return; + + if(_arena._etat <= _arena._starting && _arena._etat != 0) { + _arena._etat--; + _arena.broadcastXP(_arena._etat); + } + + if(_arena._etat == 10) + _arena.broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "10")); + + if(_arena._etat <= 5 && _arena._etat >= 1) { + _arena.broadcast(_plugin._trad.get("Game.Arena.Message.RemainTime").replace("[TIME]", "" + _arena._etat)); + _arena.playsound(Sound.BLOCK_NOTE_PLING, 0.6f, 50.0f); + //_arena.playsound(Sound.NOTE_PLING, 0.6f, 50.0f); + } + + if (_arena._etat == 0) { + _arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 1.0f); + _arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 5.0f); + _arena.playsound(Sound.BLOCK_NOTE_PLING, 9.0f, 10.0f); + + /*_arena.playsound(Sound.NOTE_PLING, 9.0f, 1.0f); + _arena.playsound(Sound.NOTE_PLING, 9.0f, 5.0f); + _arena.playsound(Sound.NOTE_PLING, 9.0f, 10.0f);*/ + + _arena.broadcast(_plugin._trad.get("Game.Arena.Message.Start")); + _arena.start(); + _arena.nbroadcast(""); + _arena.nbroadcast(_plugin._trad.get("Game.Arena.Message.Start-Info")); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/AddLobbyCommand.java b/src/com/Geekpower14/Quake/Commands/AddLobbyCommand.java new file mode 100644 index 0000000..76fb5f1 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/AddLobbyCommand.java @@ -0,0 +1,38 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.entity.Player; + +public class AddLobbyCommand +implements BasicCommand { + private final Quake _plugin; + + public AddLobbyCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + _plugin._lobby.addLobby(player); + _plugin._lobby.saveconfig(); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake addlobby - Add a sign wall lobby."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.lobby"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/AddSpawnCommand.java b/src/com/Geekpower14/Quake/Commands/AddSpawnCommand.java new file mode 100644 index 0000000..d5a86c9 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/AddSpawnCommand.java @@ -0,0 +1,62 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Arena.SArena; +import com.Geekpower14.Quake.Arena.TArena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class AddSpawnCommand implements BasicCommand { + private final Quake _plugin; + + public AddSpawnCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.valueOf(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (arena instanceof SArena) { + SArena sa = (SArena)arena; + sa.addspawn(player.getLocation()); + player.sendMessage(ChatColor.GREEN + "Spawn number " + (sa._spawns.size() - 1) + " defined !"); + } else if (arena instanceof TArena) { + TArena ta = (TArena)arena; + if (args.length >= 2) { + int nb = ta.addspawn(player.getLocation(), args[1]); + player.sendMessage(ChatColor.GREEN + "Spawn number " + (nb - 1) + " defined !"); + } else { + player.sendMessage(ChatColor.RED + "Please type a team name ! !"); + } + } + arena.saveConfig(); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if(Quake.hasPermission(p, getPermission())) + return "/quake addspawn [Arena] [TEAM|Only for team arena] - Add spawn to an arena."; + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/BasicCommand.java b/src/com/Geekpower14/Quake/Commands/BasicCommand.java new file mode 100644 index 0000000..a5136b1 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/BasicCommand.java @@ -0,0 +1,18 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import org.bukkit.entity.Player; + +public interface BasicCommand { + public boolean onCommand(Player var1, String[] var2); + + public String help(Player var1); + + public String getPermission(); +} + diff --git a/src/com/Geekpower14/Quake/Commands/ChangeTeamCommand.java b/src/com/Geekpower14/Quake/Commands/ChangeTeamCommand.java new file mode 100644 index 0000000..3a2993d --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/ChangeTeamCommand.java @@ -0,0 +1,56 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Arena.SArena; +import com.Geekpower14.Quake.Arena.TArena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class ChangeTeamCommand implements BasicCommand { + private final Quake _plugin; + + public ChangeTeamCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + player.sendMessage(_plugin._trad.get("Game.Arena.Message.NotInAGame")); + return true; + } + if (arena instanceof SArena) { + player.sendMessage(_plugin._trad.get("Game.Arena.error.NotInTeamGame")); + return true; + } + if (arena instanceof TArena) { + TArena ta = (TArena)arena; + if (args.length >= 1) { + ta.changeTeam(player, args[0]); + } else { + player.sendMessage(ChatColor.RED + "Please type a team name !"); + } + } + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake team [Name] - Change your team."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.ChangeTeam"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/CreateCommand.java b/src/com/Geekpower14/Quake/Commands/CreateCommand.java new file mode 100644 index 0000000..4f2a54c --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/CreateCommand.java @@ -0,0 +1,50 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class CreateCommand implements BasicCommand { + private final Quake _plugin; + + public CreateCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + if (args.length != 2) { + player.sendMessage(ChatColor.RED + "Please type a name and a type for the arena !"); + return true; + } + if (_plugin._am.exist(args[0])) { + player.sendMessage(ChatColor.RED + "Arena " + args[0] + " already exist !"); + return true; + } + if (!args[1].equals("Team") && !args[1].equals("Solo")) { + player.sendMessage(ChatColor.RED + "Type " + args[1] + " is not valid (Solo or Team) !"); + return true; + } + _plugin._am.createArena(args[0], args[1]); + player.sendMessage(ChatColor.YELLOW + "Arena " + args[0] + " build with success"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake create [Arena name] [Type] - Create an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/JoinCommand.java b/src/com/Geekpower14/Quake/Commands/JoinCommand.java new file mode 100644 index 0000000..f0e27e1 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/JoinCommand.java @@ -0,0 +1,56 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class JoinCommand implements BasicCommand { + private final Quake _plugin; + + public JoinCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.valueOf(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length != 1) { + player.sendMessage(ChatColor.RED + "Please type a number !"); + return true; + } + if (arena.isingame(player)) { + player.sendMessage(ChatColor.RED + "You are already in game !"); + return true; + } + arena.joinArena(player); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake join [Arena] - Join an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.player"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/LeaveCommand.java b/src/com/Geekpower14/Quake/Commands/LeaveCommand.java new file mode 100644 index 0000000..01a7770 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/LeaveCommand.java @@ -0,0 +1,42 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.entity.Player; + +public class LeaveCommand implements BasicCommand { + private final Quake _plugin; + + public LeaveCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + player.sendMessage(_plugin._trad.get("Game.Arena.Message.NotInAGame")); + return true; + } + arena.leaveArena(player); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return false; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake leave - Leave an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.player"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/MoneyCommand.java b/src/com/Geekpower14/Quake/Commands/MoneyCommand.java new file mode 100644 index 0000000..e8b472c --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/MoneyCommand.java @@ -0,0 +1,84 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.Bukkit + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class MoneyCommand implements BasicCommand { + private final Quake _plugin; + + public MoneyCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + int new_ = 0; + if (args.length < 2) { + player.sendMessage(ChatColor.RED + "Please write good command."); + player.sendMessage(help(player)); + return true; + } + if (args[0].equalsIgnoreCase("get")) { + Player lol = Bukkit.getPlayer((String)args[1]); + new_ = _plugin._eco.getPlayerMoney(lol); + player.sendMessage(ChatColor.GREEN + lol.getName() + " have " + new_); + return true; + } + if (args.length < 3) { + player.sendMessage(ChatColor.RED + "Please write good command."); + player.sendMessage(help(player)); + return true; + } + int amount = Integer.valueOf(args[2]); + if (args[0].equalsIgnoreCase("set")) { + Player lol = Bukkit.getPlayer((String)args[1]); + _plugin._eco.setPlayerMoney(Bukkit.getPlayer((String)args[1]), amount); + new_ = _plugin._eco.getPlayerMoney(lol); + player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + Player lol = Bukkit.getPlayer((String)args[1]); + _plugin._eco.addPlayerMoney(Bukkit.getPlayer((String)args[1]), amount); + new_ = _plugin._eco.getPlayerMoney(lol); + player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_); + return true; + } + if (args[0].equalsIgnoreCase("remove")) { + Player lol = Bukkit.getPlayer((String)args[1]); + _plugin._eco.soustrairePlayerMoney(Bukkit.getPlayer((String)args[1]), amount); + new_ = _plugin._eco.getPlayerMoney(lol); + player.sendMessage(ChatColor.GREEN + lol.getName() + " have now " + new_); + return true; + } + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake money [set/add/remove/get] [Player] [Amount] - Set/Add/Remove/Get money of a player."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/MyCommandExecutor.java b/src/com/Geekpower14/Quake/Commands/MyCommandExecutor.java new file mode 100644 index 0000000..8ffbfd5 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/MyCommandExecutor.java @@ -0,0 +1,99 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class MyCommandExecutor implements CommandExecutor { + public Quake _plugin; + private final HashMap _commands = new HashMap<>(); + + public MyCommandExecutor(Quake pl) { + _plugin = pl; + loadCommands(); + } + + private void loadCommands() { + _commands.put("leave", new LeaveCommand(_plugin)); + _commands.put("addspawn", new AddSpawnCommand(_plugin)); + _commands.put("addlobby", new AddLobbyCommand(_plugin)); + _commands.put("create", new CreateCommand(_plugin)); + _commands.put("setlobbyspawn", new SetLobbySpawnCommand(_plugin)); + _commands.put("join", new JoinCommand(_plugin)); + _commands.put("removelobby", new RemoveLobbyCommand(_plugin)); + _commands.put("removespawn", new RemoveSpawnCommand(_plugin)); + _commands.put("save", new SaveCommand(_plugin)); + _commands.put("setmap", new SetMapCommand(_plugin)); + _commands.put("setmin", new SetMinCommand(_plugin)); + _commands.put("setmax", new SetMaxCommand(_plugin)); + _commands.put("start", new StartCommand(_plugin)); + _commands.put("stop", new StopCommand(_plugin)); + _commands.put("shop", new ShopCommand(_plugin)); + _commands.put("remove", new RemoveCommand(_plugin)); + _commands.put("kill", new UtilsCommand(_plugin, "kill")); + _commands.put("add", new UtilsCommand(_plugin, "add")); + _commands.put("lol", new UtilsCommand(_plugin, "lol")); + _commands.put("reload", new ReloadCommand(_plugin)); + _commands.put("team", new ChangeTeamCommand(_plugin)); + _commands.put("money", new MoneyCommand(_plugin)); + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { + Player player = null; + if (!(sender instanceof Player)) { + sender.sendMessage("You need to be a player !"); + return true; + } + player = (Player)sender; + if(cmd.getName().equalsIgnoreCase("quake")) { + if(args == null || args.length < 1) { + player.sendMessage(ChatColor.YELLOW + "Plugin By Geekpower14"); + player.sendMessage(ChatColor.YELLOW + "Reloaded by Bl4ckSkull666 ( wwww.AMC-Server.de )"); + player.sendMessage(ChatColor.YELLOW + "Version: " + _plugin.getDescription().getVersion()); + return true; + } + + if(args[0].equalsIgnoreCase("help")) { + help(player); + return true; + } + + String sub = args[0]; + ArrayList l = new ArrayList<>(); + l.addAll(Arrays.asList(args)); + l.remove(0); + args = l.toArray(new String[0]); + + if(!_commands.containsKey(sub)) { + player.sendMessage(ChatColor.RED + "Command dosent exist."); + player.sendMessage(ChatColor.GOLD + "Type /quake help for help"); + return true; + } + + try { + _commands.get(sub).onCommand(player, args); + } catch(Exception e) { + e.printStackTrace(); + player.sendMessage(ChatColor.RED + "An error occured while executing the command. Check the console"); + player.sendMessage(ChatColor.BLUE + "Type /quake help for help"); + } + return true; + } + return true; + } + + public void help(Player p) { + p.sendMessage("/Quake "); + for (BasicCommand v : _commands.values()) { + p.sendMessage(ChatColor.GRAY + "- " + v.help(p)); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/ReloadCommand.java b/src/com/Geekpower14/Quake/Commands/ReloadCommand.java new file mode 100644 index 0000000..59c4663 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/ReloadCommand.java @@ -0,0 +1,42 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class ReloadCommand implements BasicCommand { + private final Quake _plugin; + + public ReloadCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + _plugin.loadConfig(); + _plugin._stuff.reloadConfig(); + _plugin._lobby.loadconfig(); + _plugin._am.reloadArenas(); + _plugin._trad.reloadConfig(); + player.sendMessage(ChatColor.GREEN + "Plugin reloaded !"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake reload - Reload config."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.admin"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/RemoveCommand.java b/src/com/Geekpower14/Quake/Commands/RemoveCommand.java new file mode 100644 index 0000000..19c557b --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/RemoveCommand.java @@ -0,0 +1,53 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class RemoveCommand implements BasicCommand { + private final Quake _plugin; + + public RemoveCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.valueOf(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length != 1) { + player.sendMessage(ChatColor.RED + "Please type a number !"); + return true; + } + _plugin._am.deleteArena(arena._name); + player.sendMessage(ChatColor.GREEN + "Arena deleted with success !"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake remove [Arena name] - Remove an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/RemoveLobbyCommand.java b/src/com/Geekpower14/Quake/Commands/RemoveLobbyCommand.java new file mode 100644 index 0000000..dc6a4c8 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/RemoveLobbyCommand.java @@ -0,0 +1,51 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class RemoveLobbyCommand implements BasicCommand { + private final Quake _plugin; + + public RemoveLobbyCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + if (args.length != 1) { + player.sendMessage(ChatColor.RED + "Please type a good number of lobby !"); + return true; + } + int lobby = Integer.valueOf(args[0]); + _plugin._lobby.removeLobby("lobby" + (lobby - 1)); + player.sendMessage(ChatColor.YELLOW + "Lobby number : " + (lobby - 1) + " removed with success"); + _plugin._lobby.saveconfig(); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake removelobby [ID of the lobby] - Remove a lobby wall."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.lobby"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/RemoveSpawnCommand.java b/src/com/Geekpower14/Quake/Commands/RemoveSpawnCommand.java new file mode 100644 index 0000000..1112b5a --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/RemoveSpawnCommand.java @@ -0,0 +1,67 @@ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Arena.SArena; +import com.Geekpower14.Quake.Arena.TArena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class RemoveSpawnCommand implements BasicCommand { + private final Quake _plugin; + + public RemoveSpawnCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.valueOf(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length != 2) { + player.sendMessage(ChatColor.RED + "Please type a number !"); + return true; + } + if (arena instanceof SArena) { + SArena sa = (SArena)arena; + sa.removespawn(args[1]); + player.sendMessage(ChatColor.GREEN + "Spawn number " + (sa._spawns.size() - 1) + " removed !"); + } else if (arena instanceof TArena) { + TArena ta = (TArena)arena; + if (args.length >= 3) { + int nb = ta.removespawn(args[1], args[2]); + player.sendMessage(ChatColor.GREEN + "Spawn number " + (nb - 1) + " removed !"); + } else { + player.sendMessage(ChatColor.RED + "Please type a team name ! !"); + } + } + arena.saveConfig(); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake removespawn [Arena] [Number] - Remove a spawn of the arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/SaveCommand.java b/src/com/Geekpower14/Quake/Commands/SaveCommand.java new file mode 100644 index 0000000..02ad375 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/SaveCommand.java @@ -0,0 +1,56 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SaveCommand implements BasicCommand { + private final Quake _plugin; + + public SaveCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.parseInt(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + arena.saveConfig(); + player.sendMessage(ChatColor.GREEN + "Config saved for the arena : " + args[0]); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake save [Arena] - Save config of the arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/SetLobbySpawnCommand.java b/src/com/Geekpower14/Quake/Commands/SetLobbySpawnCommand.java new file mode 100644 index 0000000..bdb12cf --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/SetLobbySpawnCommand.java @@ -0,0 +1,46 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SetLobbySpawnCommand implements BasicCommand { + private Quake _plugin; + + public SetLobbySpawnCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + _plugin._lobby.setspawn(player); + player.sendMessage(ChatColor.YELLOW + "Lobby's spawn define with success !"); + _plugin._lobby.saveconfig(); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake setlobbyspawn - Set the spawn of the lobby."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.lobby"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/SetMapCommand.java b/src/com/Geekpower14/Quake/Commands/SetMapCommand.java new file mode 100644 index 0000000..a4810b1 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/SetMapCommand.java @@ -0,0 +1,61 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SetMapCommand implements BasicCommand { + private final Quake _plugin; + + public SetMapCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.parseInt(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length < 2) { + player.sendMessage(ChatColor.RED + "Please type a name !"); + return true; + } + arena.setmap(args[1]); + arena.saveConfig(); + player.sendMessage(ChatColor.GREEN + "Set the map with success !"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake setmap [Arena] [Name] - Set display name in the lobby."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/SetMaxCommand.java b/src/com/Geekpower14/Quake/Commands/SetMaxCommand.java new file mode 100644 index 0000000..6bd605f --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/SetMaxCommand.java @@ -0,0 +1,61 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SetMaxCommand implements BasicCommand { + private final Quake _plugin; + + public SetMaxCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.parseInt(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length < 2) { + player.sendMessage(ChatColor.RED + "Please type a number !"); + return true; + } + arena.setmax(Integer.parseInt(args[1])); + arena.saveConfig(); + player.sendMessage(ChatColor.GREEN + "Set the max player with success !"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake setmax [Arena] [Number] - Set max player in the arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/SetMinCommand.java b/src/com/Geekpower14/Quake/Commands/SetMinCommand.java new file mode 100644 index 0000000..b4b88b9 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/SetMinCommand.java @@ -0,0 +1,61 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SetMinCommand implements BasicCommand { + private final Quake _plugin; + + public SetMinCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.valueOf(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + if (args.length < 2) { + player.sendMessage(ChatColor.RED + "Please type a number !"); + return true; + } + arena.setmin(Integer.parseInt(args[1])); + arena.saveConfig(); + player.sendMessage(ChatColor.GREEN + "Set the minimum player with success !"); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake setmin [Arena] [Number] - Set minimum player in the arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.edit"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/ShopCommand.java b/src/com/Geekpower14/Quake/Commands/ShopCommand.java new file mode 100644 index 0000000..85938b4 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/ShopCommand.java @@ -0,0 +1,43 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.entity.Player; + +public class ShopCommand implements BasicCommand { + private final Quake _plugin; + + public ShopCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + _plugin._shop.getMainShop(player); + _plugin._imm.show(player); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return false; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake shop - Open the shop."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.player"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/StartCommand.java b/src/com/Geekpower14/Quake/Commands/StartCommand.java new file mode 100644 index 0000000..547d2cb --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/StartCommand.java @@ -0,0 +1,56 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class StartCommand implements BasicCommand { + private final Quake _plugin; + + public StartCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if(Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.parseInt(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + arena.start(); + player.sendMessage(ChatColor.GREEN + "Force beginning for the arena : " + args[0]); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake start [Arena] - Force start an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.modo"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/StopCommand.java b/src/com/Geekpower14/Quake/Commands/StopCommand.java new file mode 100644 index 0000000..d8f37cc --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/StopCommand.java @@ -0,0 +1,56 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.ChatColor + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class StopCommand implements BasicCommand { + private final Quake _plugin; + + public StopCommand(Quake pl) { + _plugin = pl; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + Arena arena = null; + if (_plugin._am.exist(args[0])) { + arena = _plugin._am.getArenabyName(args[0]); + } else if (args[0].matches("^\\d*$")) { + arena = _plugin._am.getArenabyID(Integer.parseInt(args[0])); + } + if (arena == null) { + player.sendMessage(ChatColor.RED + "Please type a good arena name ! !"); + return true; + } + arena.stop(); + player.sendMessage(ChatColor.RED + "Force stop for the arena : " + args[0]); + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return true; + } + + @Override + public String help(Player p) { + if (Quake.hasPermission(p, getPermission())) { + return "/quake stop [Arena] - Force stop an arena."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.modo"; + } +} + diff --git a/src/com/Geekpower14/Quake/Commands/UtilsCommand.java b/src/com/Geekpower14/Quake/Commands/UtilsCommand.java new file mode 100644 index 0000000..6d6bf14 --- /dev/null +++ b/src/com/Geekpower14/Quake/Commands/UtilsCommand.java @@ -0,0 +1,54 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.entity.Player + */ +package com.Geekpower14.Quake.Commands; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import org.bukkit.entity.Player; + +public class UtilsCommand implements BasicCommand { + private final Quake _plugin; + private String _cmd; + + public UtilsCommand(Quake pl, String cmd) { + _plugin = pl; + _cmd = cmd; + } + + @Override + public boolean onCommand(Player player, String[] args) { + if (Quake.hasPermission(player, getPermission())) { + if (_cmd.equals("kill")) { + player.setHealth(0.0); + } + if (_cmd.equals("add")) { + Arena aren = _plugin._am.getArenabyPlayer(player); + APlayer ap = aren.getAPlayer(player); + ap._score++; + aren.updateScore(); + } + } else { + player.sendMessage(_plugin._trad.get("NoPermission")); + } + return false; + } + + @Override + public String help(Player p) { + if(Quake.hasPermission(p, getPermission())) { + return "/quake " + _cmd + " - Do something."; + } + return ""; + } + + @Override + public String getPermission() { + return "Quake.admin"; + } +} + diff --git a/src/com/Geekpower14/Quake/Eco/EcoManager.java b/src/com/Geekpower14/Quake/Eco/EcoManager.java new file mode 100644 index 0000000..8fbaf40 --- /dev/null +++ b/src/com/Geekpower14/Quake/Eco/EcoManager.java @@ -0,0 +1,139 @@ +package com.Geekpower14.Quake.Eco; + +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Trans.Score; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class EcoManager { + private Quake _plugin; + public static Economy _economy = null; + public Boolean _useVault = false; + + public EcoManager(Quake pl) { + _plugin = pl; + _useVault = _plugin._useVault; + if(_useVault) { + try { + setupEconomy(); + } catch (Exception var2_2) { + // empty catch block + } + } + } + + private boolean setupEconomy() { + RegisteredServiceProvider economyProvider = _plugin.getServer().getServicesManager().getRegistration((Class)Economy.class); + if(economyProvider != null) + _economy = (Economy)economyProvider.getProvider(); + + return _economy != null; + } + + public int getPlayerMoney(Player player) { + int Money = 0; + if (_useVault) { + Money = (int)_economy.getBalance(player); + } else { + YamlConfiguration config = YamlConfiguration.loadConfiguration(new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml")); + Money = config.getInt("Money"); + } + return Money; + } + + public void setPlayerMoney(Player player, int money) { + if(_useVault) { + Economy eco = _economy; + if(getPlayerMoney(player) == money) { + return; + } + if (getPlayerMoney(player) < money) { + eco.depositPlayer(player, (double)(money - getPlayerMoney(player))); + return; + } + if (getPlayerMoney(player) > money) { + eco.withdrawPlayer(player, (double)(getPlayerMoney(player) - money)); + return; + } + } else { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml")); + config.set("Name", player.getName()); + config.set("Money", money); + try { + config.save(new File(_plugin.getDataFolder(), "/Eco/" + player.getName() + ".yml")); + } + catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void soustrairePlayerMoney(Player player, int price) { + int coins = getPlayerMoney(player); + setPlayerMoney(player, coins -= price); + } + + public void addPlayerMoney(Player player, int price) { + int coins = getPlayerMoney(player); + setPlayerMoney(player, coins += price); + } + + public boolean has(Player player, int price) { + int account = getPlayerMoney(player); + if(account >= price) { + return true; + } + return false; + } + + public int getScore(Player p, Score.Type type) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml")); + return config.getInt(type.toString()); + } + + public void setScore(Player p, Score.Type type, int score) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml")); + config.set("Name", p.getName()); + config.set(type.toString(), score); + try { + config.save(new File(_plugin.getDataFolder(), "/Eco/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void addScore(Player p, Score.Type type, int score) { + int k = getScore(p, type); + setScore(p, type, k += score); + } + + public void subtractScore(Player p, Score.Type type, int score) { + int k = getScore(p, type); + setScore(p, type, k -= score); + } + + public void convertToUUID() { + File folder = new File(_plugin.getDataFolder(), "/eco/"); + if (!folder.exists()) { + folder.mkdir(); + } + + ArrayList Maps = new ArrayList<>(); + for(File f: folder.listFiles()) { + String MapName = f.getName(); + String name = f.getName().replaceAll(".yml", ""); + Maps.add(name); + _plugin.getLogger().info("Found arena : " + name); + } + + if(Maps.isEmpty()) + _plugin.getLogger().info(ChatColor.RED + "No Arena found in folder "); + } +} + diff --git a/src/com/Geekpower14/Quake/Listener/PlayerListener.java b/src/com/Geekpower14/Quake/Listener/PlayerListener.java new file mode 100644 index 0000000..8306f6a --- /dev/null +++ b/src/com/Geekpower14/Quake/Listener/PlayerListener.java @@ -0,0 +1,388 @@ +package com.Geekpower14.Quake.Listener; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Utils.FireworkEffectPlayer; +import com.Geekpower14.Quake.Utils.ScoreB; +import java.io.File; + +//1.8.8 +//import net.minecraft.server.v1_8_R3.PacketPlayInClientCommand; +//import net.minecraft.server.v1_8_R3.PacketPlayInClientCommand.EnumClientCommand; +//1.9.2 +//import net.minecraft.server.v1_9_R1.PacketPlayInClientCommand; +//import net.minecraft.server.v1_9_R1.PacketPlayInClientCommand.EnumClientCommand; +//1.9.4 +//import net.minecraft.server.v1_9_R2.PacketPlayInClientCommand; +//import net.minecraft.server.v1_9_R2.PacketPlayInClientCommand.EnumClientCommand; +//1.10 +import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand; +import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand.EnumClientCommand; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +//1.8.8 +//import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +//1.9.2 +//import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +//1.9.4 +//import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer; +//1.10 +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +public class PlayerListener implements Listener { + Quake _plugin; + FireworkEffectPlayer _fw; + + public PlayerListener(Quake pl) { + _plugin = pl; + _fw = new FireworkEffectPlayer(_plugin); + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Action action = event.getAction(); + ItemStack hand = player.getItemInHand(); + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + Block block; + if ((action == Action.LEFT_CLICK_BLOCK || action == Action.RIGHT_CLICK_BLOCK) && _plugin._lobby.isinLobby(event.getClickedBlock().getLocation()) && (block = event.getClickedBlock()).getState() instanceof Sign) { + Sign sign = (Sign)block.getState(); + if (sign.getLine(1).equals("")) { + return; + } + Arena aren = _plugin._am.getArenabyID(Integer.valueOf(sign.getLine(1).replace("T-", "").replace("S-", ""))); + if (aren == null) { + return; + } + aren.joinArena(player); + event.setCancelled(true); + return; + } + if (event.getItem() != null && event.getItem().getType().equals(_plugin._shopId) && _plugin._shopWorlds.contains(event.getPlayer().getWorld().getName()) && Quake.hasPermission(player, "Quake.Shop")) { + _plugin._shop.getMainShop(player); + _plugin._imm.show(player); + event.setCancelled(true); + } + return; + } + APlayer ap = arena.getAPlayer(player); + if (hand != null && hand.getType() == Material.WOOD_DOOR) { + arena.leaveArena(player); + } + } + + public float getincr(Long time) { + float result = 0.0f; + float temp = time; + result = 100.0f / (temp / 2.0f) / 100.0f; + return result; + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerSneak(PlayerToggleSneakEvent event) { + Player p = event.getPlayer(); + Arena arena = _plugin._am.getArenabyPlayer(p); + if (arena == null) { + return; + } + if(arena._Sneak) { + event.setCancelled(true); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerFellOutOfWorld(PlayerMoveEvent event) { + Player p = event.getPlayer(); + Arena arena = _plugin._am.getArenabyPlayer(p); + if(arena == null) + return; + + if(p.getLocation().getY() <= 0.0) { + p.teleport(arena.getTp(p)); + arena.broadcast(_plugin._trad.get("Game.Arena.Message.Void").replace("[KILLED]", p.getName())); + arena.kill(p); + return; + } + } + + public void giveScoreBoard(Player p) { + if (_plugin._scores.containsKey(p.getName())) { + _plugin._scores.get(p.getName()).updateScore(); + } else { + _plugin._scores.put(p.getName(), new ScoreB(_plugin, p)); + } + } + + public Boolean isScoreWorld(String name) { + if (_plugin._ScoreWorlds.contains(name)) { + return true; + } + return false; + } + + private Color getColor(int i) { + Color c = null; + if (i == 1) { + c = Color.AQUA; + } + if (i == 2) { + c = Color.BLACK; + } + if (i == 3) { + c = Color.BLUE; + } + if (i == 4) { + c = Color.FUCHSIA; + } + if (i == 5) { + c = Color.GRAY; + } + if (i == 6) { + c = Color.GREEN; + } + if (i == 7) { + c = Color.LIME; + } + if (i == 8) { + c = Color.MAROON; + } + if (i == 9) { + c = Color.NAVY; + } + if (i == 10) { + c = Color.OLIVE; + } + if (i == 11) { + c = Color.ORANGE; + } + if (i == 12) { + c = Color.PURPLE; + } + if (i == 13) { + c = Color.RED; + } + if (i == 14) { + c = Color.SILVER; + } + if (i == 15) { + c = Color.TEAL; + } + if (i == 16) { + c = Color.WHITE; + } + if (i == 17) { + c = Color.YELLOW; + } + return c; + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onEntityDamaged(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) { + return; + } + Player p = (Player)event.getEntity(); + Arena arena = _plugin._am.getArenabyPlayer(p); + if (arena == null) { + return; + } + if (arena._NaturalDeath && arena._etat == arena._ingame) { + if (event.getCause() == EntityDamageEvent.DamageCause.FALL) { + event.setCancelled(true); + } + } else { + event.setCancelled(true); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerCommand(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + return; + } + if (event.getMessage().startsWith("/")) { + if (player.isOp()) { + return; + } + if (event.getMessage().startsWith("/quake")) { + return; + } + if (event.getMessage().startsWith("/q")) { + return; + } + player.sendMessage(_plugin._trad.get("Game.Arena.error.command")); + event.setCancelled(true); + } else if (!arena._Global_Chat) { + event.setCancelled(true); + arena.chat(player.getDisplayName() + ChatColor.GRAY + ": " + event.getMessage()); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerTeleport(PlayerTeleportEvent event) { + Player p = event.getPlayer(); + if (isScoreWorld(event.getFrom().getWorld().getName()) && !isScoreWorld(event.getTo().getWorld().getName())) { + p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + return; + } + if (!isScoreWorld(event.getFrom().getWorld().getName()) && isScoreWorld(event.getTo().getWorld().getName())) { + if (_plugin._scores.containsKey(p.getName())) { + p.setScoreboard(_plugin._scores.get(p.getName()).getScoreBoard()); + } else { + _plugin._scores.put(p.getName(), new ScoreB(_plugin, p)); + } + return; + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + return; + } + if (!arena._Global_Chat) { + event.setCancelled(true); + arena.chat(player.getDisplayName() + ChatColor.GRAY + ": " + event.getMessage()); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerDeath(PlayerDeathEvent event) { + final Player player = event.getEntity(); + final Arena arena = _plugin._am.getArenabyPlayer(event.getEntity()); + if (arena == null) { + return; + } + APlayer ap = arena.getAPlayer(player); + ap.setinvincible(true); + ap.setReloading(false); + event.setDeathMessage(""); + event.getDrops().clear(); + event.setDroppedExp(0); + _plugin.getServer().getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() { + + @Override + public void run() { + arena.getScoreDeath(player); + } + }); + if(arena._Auto_Respawn) { + _plugin.getServer().getScheduler().scheduleSyncDelayedTask(_plugin, new Runnable() { + @Override + public void run() { + try { + if(Quake.getPlugin().getConfig().getInt("mc-version", 1002) >= 1000 && Quake.getPlugin().getConfig().getInt("mc-version", 1002) <= 1002) + ((CraftPlayer)player).getHandle().playerConnection.a(new PacketPlayInClientCommand(EnumClientCommand.PERFORM_RESPAWN)); + } catch (SecurityException | IllegalArgumentException t) { + t.printStackTrace(); + } + } + }, 20L); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerRespawn(PlayerRespawnEvent event) { + final Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer()); + if (arena == null) { + return; + } + final Player player = event.getPlayer(); + APlayer ap = arena.getAPlayer(player); + arena.giveStuff(player); + event.setRespawnLocation(arena.getTp(event.getPlayer())); + ap.setInvincible(50L); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + @Override + public void run() { + arena.giveEffect(player); + } + }, 10); + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerDrop(PlayerDropItemEvent event) { + Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer()); + if (arena == null) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerFood(FoodLevelChangeEvent event) { + if (event.getEntity() instanceof Player) { + Arena arena = _plugin._am.getArenabyPlayer((Player)event.getEntity()); + if (arena == null) { + return; + } + event.setCancelled(true); + } + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerQuit(PlayerQuitEvent event) { + Arena arena = _plugin._am.getArenabyPlayer(event.getPlayer()); + Player player = event.getPlayer(); + _plugin._scores.remove(player.getName()); + if (arena == null) { + return; + } + _plugin.getLogger().warning("Player : " + player.getName() + " Rage Quit !"); + arena.CrashLeaveArena(event.getPlayer()); + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerLogin(PlayerJoinEvent event) { + Arena arena; + final Player player = event.getPlayer(); + File f = new File(Quake.getPlugin().getDataFolder() + "/Save_Players/" + player.getName() + ".yml"); + if (f.exists()) { + player.teleport(_plugin._lobby._lobbyspawn); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + player.teleport(Quake.getPlugin()._lobby._lobbyspawn); + } + }, 30); + _plugin.getLogger().warning("Player : " + player.getName() + " rejoin after Rage Quit !"); + Arena.RejoinAfterCrash(player); + } + if ((arena = _plugin._am.getArenabyPlayer(event.getPlayer())) != null) { + arena.leaveArena(event.getPlayer()); + } + } + +} + diff --git a/src/com/Geekpower14/Quake/Listener/Weather.java b/src/com/Geekpower14/Quake/Listener/Weather.java new file mode 100644 index 0000000..344aef6 --- /dev/null +++ b/src/com/Geekpower14/Quake/Listener/Weather.java @@ -0,0 +1,33 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.World + * org.bukkit.event.EventHandler + * org.bukkit.event.Listener + * org.bukkit.event.weather.WeatherChangeEvent + */ +package com.Geekpower14.Quake.Listener; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.weather.WeatherChangeEvent; + +public class Weather implements Listener { + public final Quake _plugin; + + public Weather(Quake pl) { + _plugin = pl; + } + + @EventHandler + public void onWeatherChange(WeatherChangeEvent event) { + World w = event.getWorld(); + if(_plugin._am.isArenaWorld(w) && event.toWeatherState()) { + event.setCancelled(true); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Lobby/Lobby.java b/src/com/Geekpower14/Quake/Lobby/Lobby.java new file mode 100644 index 0000000..f18a953 --- /dev/null +++ b/src/com/Geekpower14/Quake/Lobby/Lobby.java @@ -0,0 +1,24 @@ +/* + * Decompiled with CFR 0_114. + */ +package com.Geekpower14.Quake.Lobby; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Utils.Area; +import java.util.ArrayList; +import java.util.List; + +public class Lobby { + public final Quake _plugin; + public final List _LOBBYS_SIGN = new ArrayList<>(); + + public Lobby(Quake pl, Area area) { + _plugin = pl; + } + + public Boolean init(List arena) { + return true; + } +} + diff --git a/src/com/Geekpower14/Quake/Lobby/LobbyManager.java b/src/com/Geekpower14/Quake/Lobby/LobbyManager.java new file mode 100644 index 0000000..0bf0044 --- /dev/null +++ b/src/com/Geekpower14/Quake/Lobby/LobbyManager.java @@ -0,0 +1,273 @@ +package com.Geekpower14.Quake.Lobby; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Arena.SArena; +import com.Geekpower14.Quake.Arena.TArena; +import com.Geekpower14.Quake.Quake; +import com.sk89q.worldedit.bukkit.selections.Selection; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +public class LobbyManager { + public Quake _plugin; + public HashMap _locmin = new HashMap(); + public HashMap _locmax = new HashMap(); + public Location _lobbyspawn = null; + public List _LOBBYS = new ArrayList<>(); + public List _LOBBYS_SIGN = new ArrayList<>(); + + public LobbyManager(Quake pl) { + _plugin = pl; + loadconfig(); + } + + public final void loadconfig() { + String nom; + File fichier_config = new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)fichier_config); + _lobbyspawn = str2loc(config.getString("LobbySpawn")); + int nombre = config.getInt("Nombre"); + int i = 0; + while (i < nombre) { + nom = config.getString("min.lobby" + i); + _locmin.put("lobby" + i, str2loc(nom)); + ++i; + } + i = 0; + while (i < nombre) { + nom = config.getString("max.lobby" + i); + _locmax.put("lobby" + i, str2loc(nom)); + ++i; + } + _plugin.getLogger().info("load des Lobby "); + } + + public void saveconfig() { + Location loc; + File fichier_config = new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(fichier_config); + if(_lobbyspawn != null) { + config.set("LobbySpawn", (String.valueOf(_lobbyspawn.getWorld().getName()) + ", " + _lobbyspawn.getX() + ", " + _lobbyspawn.getY() + ", " + _lobbyspawn.getZ() + ", " + _lobbyspawn.getYaw() + ", " + _lobbyspawn.getPitch())); + } + + config.set("Nombre", _locmin.size()); + for(String l2 : _locmin.keySet()) { + loc = _locmin.get(l2); + config.set("min." + l2, (String.valueOf(loc.getWorld().getName()) + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch())); + } + + for(String l2 : _locmax.keySet()) { + loc = _locmax.get(l2); + config.set("max." + l2, (String.valueOf(loc.getWorld().getName()) + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch())); + } + + try { + config.save(new File(_plugin.getDataFolder(), String.valueOf(File.separator) + "lobby.yml")); + _plugin.saveConfig(); + } catch (IOException l) { + // empty catch block + } + _plugin.getLogger().info("save des Lobby "); + } + + public Location str2loc(String loc) { + if (loc == null) { + return null; + } + Location res = null; + String[] loca = loc.split(", "); + res = new Location(_plugin.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5])); + return res; + } + + public void setspawn(Player player) { + _lobbyspawn = player.getLocation(); + } + + public Boolean removeLobby(String lobby) { + _locmin.remove(lobby); + _locmax.remove(lobby); + HashMap tempmin = new HashMap<>(); + HashMap tempmax = new HashMap<>(); + int i = 0; + for (String s : _locmin.keySet()) { + tempmin.put("lobby" + i, _locmin.get(s)); + tempmax.put("lobby" + i, _locmax.get(s)); + ++i; + } + _locmin = tempmin; + _locmax = tempmax; + return true; + } + + public Boolean addLobby(Player player) { + String lobby = "lobby" + _locmin.size(); + Selection selection = _plugin._worldEdit.getSelection(player); + if (selection != null) { + //World world = selection.getWorld(); + Location un = selection.getMinimumPoint(); + Location deux = selection.getMaximumPoint(); + /*String direction = ""; + if (un.getX() == deux.getX()) { + direction = "Z"; + } else if (un.getZ() == deux.getZ()) { + direction = "X"; + } else { + _plugin.log.warning("Pas m\u00eame X ou Z pour : " + lobby); + return false; + }*/ + Location tempmin = un; + Location tempmax = deux; + _locmin.put(lobby, tempmin); + _locmax.put(lobby, tempmax); + player.sendMessage(ChatColor.YELLOW + "Lobby " + _locmin.size() + " cr\u00e9e avec succ\u00e9s"); + initsign(); + return true; + } + player.sendMessage(ChatColor.RED + "Veuillez faire une s\u00e9lection d'abord !"); + return false; + } + + public Boolean initsign() { + int index = 0; + int i = 0; + while(i < _locmin.size()) { + int x; + int y; + Arena arena; + String lobby = "lobby" + i; + Location min = _locmin.get(lobby); + Location max = _locmax.get(lobby); + int xmax = 0; + int xmin = 0; + int z = 0; + World w = min.getWorld(); + if (w == null) { + return false; + } + if (min.getBlockX() == max.getBlockX()) { + xmax = max.getBlockZ(); + xmin = min.getBlockZ(); + z = min.getBlockX(); + x = xmin; + while (x <= xmax) { + y = min.getBlockY(); + while (y <= max.getBlockY()) { + arena = _plugin._am.getArenabyID(index); + if (arena != null) { + updateSign(w, z, y, x, arena); + } else { + clearSign(w, z, y, x); + } + ++index; + ++y; + } + ++x; + } + } else if (min.getBlockZ() == max.getBlockZ()) { + xmax = max.getBlockX(); + xmin = min.getBlockX(); + z = min.getBlockZ(); + x = xmin; + while (x <= xmax) { + y = max.getBlockY(); + while (y >= min.getBlockY()) { + arena = _plugin._am.getArenabyID(index); + if (arena != null) { + updateSign(w, x, y, z, arena); + } else { + clearSign(w, x, y, z); + } + ++index; + --y; + } + ++x; + } + } + ++i; + } + return true; + } + + public Boolean isinLobby(Location loc) { + int oui = _locmin.size(); + int i = 0; + while (i < _locmin.size()) { + String lobby = "lobby" + i; + Location min = _locmin.get(lobby); + Location max = _locmax.get(lobby); + if (min.getWorld() != loc.getWorld()) { + --oui; + } else if (loc.getX() < min.getX()) { + --oui; + } else if (loc.getX() > max.getX()) { + --oui; + } else if (loc.getZ() < min.getZ()) { + --oui; + } else if (loc.getZ() > max.getZ()) { + --oui; + } else if (loc.getY() < min.getY()) { + --oui; + } else if (loc.getY() > max.getY()) { + --oui; + } + ++i; + } + if (oui <= 0) { + return false; + } + return true; + } + + public void updateSign(World w, int x, int y, int z, Arena arena) { + Location bloc = new Location(w, (double)x, (double)y, (double)z); + if(bloc.getBlock() == null || bloc.getBlock().getType().equals(Material.AIR)) + return; + + Block block = bloc.getBlock(); + if (block.getState() instanceof Sign) { + Sign sign = (Sign)block.getState(); + String ligne0 = arena._etat <= arena._pregame ? (arena.getplayers() == arena._maxplayer ? ChatColor.DARK_PURPLE + "[FULL]" : (arena._VIP ? ChatColor.AQUA + "[VIP]" : (arena._etat <= arena._starting ? ChatColor.GOLD + "[Starting]" : ChatColor.GREEN + "[Join]"))) : ChatColor.RED + "[InGame]"; + String tmp = ""; + if (arena instanceof SArena) { + tmp = "S-"; + } + if (arena instanceof TArena) { + tmp = "T-"; + } + String ligne1 = tmp + arena._ID; + String ligne2 = (arena.getplayers() >= (arena._maxplayer * 0.75))? "" + ChatColor.RED + arena.getplayers() + "/" + arena._maxplayer : "" + arena.getplayers() + "/" + arena._maxplayer; + String ligne3 = arena._map; + sign.setLine(0, ligne0); + sign.setLine(1, ligne1); + sign.setLine(2, ligne2); + sign.setLine(3, ligne3); + sign.update(true); + } + } + + public void clearSign(World w, int x, int y, int z) { + Location bloc = new Location(w, (double)x, (double)y, (double)z); + Block block = bloc.getBlock(); + if (block.getState() instanceof Sign) { + Sign sign = (Sign)block.getState(); + sign.setLine(0, ChatColor.GRAY + "[" + ChatColor.RED + "Quake" + ChatColor.GRAY + "]"); + sign.setLine(1, ""); + sign.setLine(2, ChatColor.GRAY + "Offline"); + sign.setLine(3, ""); + sign.update(true); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Lobby/Lobby_Sign.java b/src/com/Geekpower14/Quake/Lobby/Lobby_Sign.java new file mode 100644 index 0000000..77522ce --- /dev/null +++ b/src/com/Geekpower14/Quake/Lobby/Lobby_Sign.java @@ -0,0 +1,15 @@ +package com.Geekpower14.Quake.Lobby; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; + +public class Lobby_Sign { + private final Quake _plugin; + private final Arena _arena; + + public Lobby_Sign(Quake pl, Arena arena) { + _plugin = pl; + _arena = arena; + } +} + diff --git a/src/com/Geekpower14/Quake/Quake.java b/src/com/Geekpower14/Quake/Quake.java new file mode 100644 index 0000000..aaac886 --- /dev/null +++ b/src/com/Geekpower14/Quake/Quake.java @@ -0,0 +1,282 @@ +package com.Geekpower14.Quake; + +import com.Geekpower14.Quake.Arena.ArenaManager; +import com.Geekpower14.Quake.Commands.MyCommandExecutor; +import com.Geekpower14.Quake.Eco.EcoManager; +import com.Geekpower14.Quake.Listener.PlayerListener; +import com.Geekpower14.Quake.Listener.Weather; +import com.Geekpower14.Quake.Lobby.LobbyManager; +import com.Geekpower14.Quake.Shop.IconMenuManager; +import com.Geekpower14.Quake.Shop.ShopManager; +import com.Geekpower14.Quake.Stuff.StuffManager; +import com.Geekpower14.Quake.Trans.Translate; +import com.Geekpower14.Quake.Utils.ParticleEffects; +import com.Geekpower14.Quake.Utils.Reflection; +import com.Geekpower14.Quake.Utils.ScoreB; +import com.Geekpower14.Quake.Utils.Version; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Random; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.command.CommandExecutor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scoreboard.Scoreboard; + +public class Quake +extends JavaPlugin { + public static boolean _debug = false; + public static String _version = "3.0.0"; + public static Version _ver = new Version(_version); + public ArenaManager _am = null; + public LobbyManager _lobby = null; + public int _threadlob = 0; + public int _thread = 0; + public int _compteur = 0; + public Boolean _geeklove = true; + public static Quake _instance = null; + public WorldEditPlugin _worldEdit; + public ShopManager _shop; + public Translate _trad; + public StuffManager _stuff; + public IconMenuManager _imm; + public EcoManager _eco; + public FileConfiguration _config; + public Boolean _useVault = false; + public Material _shopId = Material.EMERALD; + public List _shopWorlds = new ArrayList<>(); + public List _ScoreWorlds = new ArrayList<>(); + public HashMap _scores = new HashMap(); + public Scoreboard _board; + + @Override + public void onEnable() { + _instance = this; + + _imm = new IconMenuManager((Plugin)this); + _board = Bukkit.getScoreboardManager().getNewScoreboard(); + _config = YamlConfiguration.loadConfiguration((File)new File(getDataFolder(), "config.yml")); + _shopWorlds.add("world"); + _ScoreWorlds.add("world"); + loadConfig(); + saveConfig(); + getDataFolder().mkdir(); + new File(getDataFolder().getPath() + "/arenas").mkdir(); + _worldEdit = (WorldEditPlugin)Bukkit.getServer().getPluginManager().getPlugin("WorldEdit"); + if(_worldEdit == null) { + getLogger().warning("WorldEdit not found !!"); + } + try { + _eco = new EcoManager(this); + } catch (Exception var1_2) { + // empty catch block + } + _trad = new Translate(this); + _shop = new ShopManager(this); + _stuff = new StuffManager(this); + getServer().getPluginManager().registerEvents(new PlayerListener(this), this); + getServer().getPluginManager().registerEvents(new Weather(this), this); + getCommand("Quake").setExecutor(new MyCommandExecutor(this)); + _am = new ArenaManager(this); + _lobby = new LobbyManager(this); + _threadlob = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ + @Override + public void run() { + _lobby.initsign(); + } + }, 0, 2); + _thread = Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin)this, (Runnable)new Task(this), 0, 20); + } + + @Override + public void onDisable() { + _am.Disable(); + _stuff.disable(); + getServer().getScheduler().cancelTask(_threadlob); + getServer().getScheduler().cancelTask(_thread); + HandlerList.unregisterAll((Plugin)this); + } + + public void loadConfig() { + _debug = _config.getBoolean("debug", false); + _useVault = _config.getBoolean("useVault", true); + _shopId = Material.getMaterial(_config.getString("shop.id", "EMERALD")); + if(_config.contains("shop.world")) { + _shopWorlds = _config.getStringList("shop.world"); + } + if(_config.contains("ScoreBoard.world")) { + _ScoreWorlds = _config.getStringList("ScoreBoard.world"); + } + } + + @Override + public void saveConfig() { + _config.set("debug", _debug); + _config.set("useVault", _useVault); + _config.set("shop.id", _shopId.name()); + _config.set("shop.world", _shopWorlds); + _config.set("ScoreBoard.world", _ScoreWorlds); + try { + _config.save(new File(getDataFolder(), "config.yml")); + } catch (IOException e) { + getLogger().log(Level.WARNING, "Failed to save configuration!"); + } + } + + public static Boolean hasPermission(Player p, String perm) { + if(perm.equalsIgnoreCase("")) + return true; + if(p.isOp()) + return true; + if(p.hasPermission("Quake.admin")) + return true; + return p.hasPermission(perm); + } + + public static void sendTabName(Player p, String s, Boolean visible, int ping) { + try { + Object packet = (Object)Reflection.getNMSClass("PacketPlayOutPlayerInfo").newInstance(); + ParticleEffects.ReflectionUtilities.setValue(packet, "a", s); + ParticleEffects.ReflectionUtilities.setValue(packet, "b", visible); + ParticleEffects.ReflectionUtilities.setValue(packet, "c", ping); + ParticleEffects.sendPacket(packet, p); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void win(final Player player) { + final int infoxp = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { + + @Override + public void run() { + if(_compteur >= 150) + return; + + Firework fw = (Firework)player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK); + FireworkMeta fwm = fw.getFireworkMeta(); + Random r = new Random(); + int rt = r.nextInt(4) + 1; + FireworkEffect.Type type = FireworkEffect.Type.BALL; + if(rt == 1) + type = FireworkEffect.Type.BALL; + if(rt == 2) + type = FireworkEffect.Type.BALL_LARGE; + if(rt == 3) + type = FireworkEffect.Type.BURST; + if(rt == 4) + type = FireworkEffect.Type.CREEPER; + if(rt == 5) + type = FireworkEffect.Type.STAR; + + int r1i = r.nextInt(17) + 1; + int r2i = r.nextInt(17) + 1; + Color c1 = getColor(r1i); + Color c2 = getColor(r2i); + FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build(); + fwm.addEffect(effect); + int rp = r.nextInt(2) + 1; + fwm.setPower(rp); + fw.setFireworkMeta(fwm); + _compteur++; + } + }, 5, 1); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)this, new Runnable() { + + @Override + public void run() { + getServer().getScheduler().cancelTask(infoxp); + } + }, 300); + } + + private Color getColor(int i) { + Color c = null; + if (i == 1) { + c = Color.AQUA; + } + if (i == 2) { + c = Color.BLACK; + } + if (i == 3) { + c = Color.BLUE; + } + if (i == 4) { + c = Color.FUCHSIA; + } + if (i == 5) { + c = Color.GRAY; + } + if (i == 6) { + c = Color.GREEN; + } + if (i == 7) { + c = Color.LIME; + } + if (i == 8) { + c = Color.MAROON; + } + if (i == 9) { + c = Color.NAVY; + } + if (i == 10) { + c = Color.OLIVE; + } + if (i == 11) { + c = Color.ORANGE; + } + if (i == 12) { + c = Color.PURPLE; + } + if (i == 13) { + c = Color.RED; + } + if (i == 14) { + c = Color.SILVER; + } + if (i == 15) { + c = Color.TEAL; + } + if (i == 16) { + c = Color.WHITE; + } + if (i == 17) { + c = Color.YELLOW; + } + return c; + } + + public static Quake getPlugin() { + return _instance; + } + + public static void debug(Exception ex) { + debug("An error was found:", ex); + } + + public static void debug(String msg) { + debug(msg, null); + } + + public static void debug(String msg, Exception ex) { + if(_instance._config.getBoolean("debug", false)) + _instance.getLogger().log(Level.INFO, "An error was found:", ex); + } +} + diff --git a/src/com/Geekpower14/Quake/Shop/IconMenuManager.java b/src/com/Geekpower14/Quake/Shop/IconMenuManager.java new file mode 100644 index 0000000..3809913 --- /dev/null +++ b/src/com/Geekpower14/Quake/Shop/IconMenuManager.java @@ -0,0 +1,87 @@ +package com.Geekpower14.Quake.Shop; + +import com.Geekpower14.Quake.Utils.IconMenu; +import java.util.HashMap; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +public class IconMenuManager implements Listener { + private final HashMap _menus = new HashMap(); + private final Plugin _plugin; + + public IconMenuManager(Plugin pl) { + _plugin = pl; + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + public void closeall() { + for(Player p : _menus.keySet()) + destroy(p); + } + + public void create(Player p, String name, int size, IconMenu.OptionClickEventHandler handler) { + if(_menus.containsKey(p)) + destroy(p); + IconMenu im = new IconMenu(name, size, handler, _plugin); + _menus.put(p, im); + } + + public void show(Player p) { + if(!_menus.containsKey(p)) + return; + _menus.get(p).open(p); + } + + public void reopen(Player p) { + if(!_menus.containsKey(p)) + return; + _menus.get(p).reopen(p); + } + + public void setOption(Player p, int position, ItemStack icon, String reg) { + if(!_menus.containsKey(p)) + return; + _menus.get(p).setOption(position, icon, reg); + } + + public void setOption(Player p, int position, ItemStack icon, String name, String reg, String[] info) { + if(!_menus.containsKey(p)) + return; + _menus.get(p).setOption(position, icon, name, reg, info); + } + + public void destroy(Player p) { + if(!_menus.containsKey(p)) + return; + + _menus.get(p).destroy(); + _menus.remove(p); + p.getOpenInventory().close(); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if(!(event.getWhoClicked() instanceof Player)) + return; + + Player p = (Player)event.getWhoClicked(); + if(_menus.containsKey(p)) + _menus.get(p).onInventoryClick(event); + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if(!(event.getPlayer() instanceof Player)) + return; + + Player p = (Player)event.getPlayer(); + if(_menus.containsKey(p)) + _menus.get(p).onInventoryClose(event); + } +} + diff --git a/src/com/Geekpower14/Quake/Shop/Item.java b/src/com/Geekpower14/Quake/Shop/Item.java new file mode 100644 index 0000000..b5265bc --- /dev/null +++ b/src/com/Geekpower14/Quake/Shop/Item.java @@ -0,0 +1,70 @@ +package com.Geekpower14.Quake.Shop; + +import org.bukkit.inventory.ItemStack; + +public class Item { + public String _name; + public ItemStack _icon; + public String[] _description; + public String _reg; + public int _position; + public int _price; + + public Item(String n, ItemStack ic, String id, String[] desc, int prix, int pos) { + _name = n; + _icon = ic; + _reg = id; + _description = desc; + _position = pos; + _price = prix; + } + + public void setName(String n) { + _name = n; + } + + public void setIcon(ItemStack ic) { + _icon = ic; + } + + public void setID(String id) { + _reg = id; + } + + public void setDescription(String[] desc) { + _description = desc; + } + + public void setPosition(int pos) { + _position = pos; + } + + public void setPrice(int prix) { + _price = prix; + } + + public String getName() { + return _name; + } + + public ItemStack getIcon() { + return _icon; + } + + public String getID() { + return _reg; + } + + public String[] getDescription() { + return _description; + } + + public int getPos() { + return _position; + } + + public int getPrice() { + return _price; + } +} + diff --git a/src/com/Geekpower14/Quake/Shop/ShopManager.java b/src/com/Geekpower14/Quake/Shop/ShopManager.java new file mode 100644 index 0000000..c03c92a --- /dev/null +++ b/src/com/Geekpower14/Quake/Shop/ShopManager.java @@ -0,0 +1,466 @@ +package com.Geekpower14.Quake.Shop; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Eco.EcoManager; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic; +import com.Geekpower14.Quake.Stuff.Hat.HatBasic; +import com.Geekpower14.Quake.Stuff.Item.ItemBasic; +import com.Geekpower14.Quake.Utils.IconMenu; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.Plugin; + +public class ShopManager { + public Quake _plugin; + public HashMap _objects = new HashMap(); + + public ShopManager(Quake b) { + _plugin = b; + } + + public void getMainShop(Player p) { + _plugin._imm.create(p, "Quake Manager", 54, new IconMenu.OptionClickEventHandler() { + + @Override + public void onOptionClick(IconMenu.OptionClickEvent event) { + if (event.getName() == null) { + return; + } + Quake.getPlugin()._shop.Main_Manager(event.getPlayer(), event.getName()); + } + }); + _plugin._imm.setOption(p, 0, new ItemStack(Material.DIAMOND_HOE, 1), _plugin._trad.get("Shop.ManagerHoe"), "Hoe_manager", new String[]{_plugin._trad.get("Shop.SelectHoe")}); + _plugin._imm.setOption(p, 3, new ItemStack(Material.LEATHER_CHESTPLATE, 1), _plugin._trad.get("Shop.ManagerArmor"), "Armor_manager", new String[]{_plugin._trad.get("Shop.SelectArmor")}); + _plugin._imm.setOption(p, 5, new ItemStack(Material.JACK_O_LANTERN, 1), _plugin._trad.get("Shop.ManagerHat"), "Hat_manager", new String[]{_plugin._trad.get("Shop.SelectHat")}); + _plugin._imm.setOption(p, 8, new ItemStack(Material.EMERALD, 1), _plugin._trad.get("Shop.Shop"), "Shop", new String[]{_plugin._trad.get("Shop.BuyNewStuff")}); + _plugin._imm.setOption(p, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.Exit"), "Exit", new String[]{_plugin._trad.get("Shop.ExitDesc")}); + } + + public void getHoeManager(Player player, int page) { + APlayer.createConfig(player); + _plugin._imm.create(player, "Hoe Manager", 54, new IconMenu.OptionClickEventHandler(){ + + @Override + public void onOptionClick(IconMenu.OptionClickEvent event) { + if (event.getName() == null) { + return; + } + event.setWillDestroy(true); + Quake.getPlugin()._shop.Hoe_Manager(event.getPlayer(), event.getName()); + } + }); + List Hoes = _plugin._stuff.getItems(player); + int i = 0; + i = page; + while (i <= (page >= 1 ? 44 * page : 44)) { + if (Hoes.size() < i + 1) break; + ItemBasic item = _plugin._stuff.getItem(Hoes.get(i)); + String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()]; + stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr); + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr); + ++i; + } + _plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")}); + } + + public void getHatManager(Player player, int page) { + _plugin._imm.create(player, "Hat Manager", 54, new IconMenu.OptionClickEventHandler(){ + + @Override + public void onOptionClick(IconMenu.OptionClickEvent event) { + if (event.getName() == null) { + return; + } + event.setWillDestroy(true); + Quake.getPlugin()._shop.Hat_Manager(event.getPlayer(), event.getName()); + } + }); + List Hat = _plugin._stuff.getHats(player); + int i = 0; + i = page; + while (i <= (page >= 1 ? 44 * page : 44)) { + if (Hat.size() < i + 1) break; + HatBasic item = _plugin._stuff.getHat(Hat.get(i)); + String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()]; + stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr); + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr); + ++i; + } + _plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")}); + } + + public void getArmorManager(Player player, int page) { + _plugin._imm.create(player, "Armor Manager", 54, new IconMenu.OptionClickEventHandler(){ + + @Override + public void onOptionClick(IconMenu.OptionClickEvent event) { + if (event.getName() == null) { + return; + } + event.setWillDestroy(true); + Quake.getPlugin()._shop.Armor_Manager(event.getPlayer(), event.getName()); + } + }); + List Armor = _plugin._stuff.getArmors(player); + int i = 0; + i = page; + while (i <= (page >= 1 ? 44 * page : 44)) { + if (Armor.size() < i + 1) break; + ArmorBasic item = _plugin._stuff.getArmor(Armor.get(i)); + String[] stockArr = new String[item.getItem().getItemMeta().getLore().size()]; + stockArr = item.getItem().getItemMeta().getLore().toArray(stockArr); + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), item._name, stockArr); + ++i; + } + _plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")}); + } + + public void getShopMenu(Player player, int page) { + int slot; + String name = "Shop"; + if (page > 0) { + name = "Shop - Page " + page; + } + _plugin._imm.create(player, name, 54, new IconMenu.OptionClickEventHandler(){ + + @Override + public void onOptionClick(IconMenu.OptionClickEvent event) { + if (event.getName() == null) { + return; + } + Quake.getPlugin()._shop.Shop_Manager(event.getPlayer(), event.getName()); + if (!event.getName().equalsIgnoreCase("Home")) { + openShop(event.getPlayer()); + } + } + }); + ArrayList Hoes = _plugin._stuff.getItems(); + ArrayList Armor = _plugin._stuff.getArmors(); + ArrayList Hat = _plugin._stuff.getHats(); + int i = slot = page >= 1 ? 44 * page : 0; + int tmp = 0; + tmp = 0; + while (i <= slot + 44 && tmp < Hoes.size()) { + if (Hoes.size() < tmp + 1) break; + ItemBasic item = Hoes.get(tmp); + String[] arrstring = new String[2]; + arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price)); + arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : ""; + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "HOE_" + item._name, arrstring); + tmp++; + i++; + } + tmp = 0; + while (i <= slot + 44 && tmp < Hat.size()) { + if (Hat.size() < tmp + 1) break; + HatBasic item = Hat.get(tmp); + String[] arrstring = new String[2]; + arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price)); + arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : ""; + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "HAT_" + item._name, arrstring); + tmp++; + i++; + } + tmp = 0; + while (i <= slot + 44 && tmp < Armor.size()) { + if (Armor.size() < tmp + 1) break; + ArmorBasic item = Armor.get(tmp); + String[] arrstring = new String[2]; + arrstring[0] = _plugin._trad.get("Shop.price").replace("[PRICE]", Integer.toString(item._price)); + arrstring[1] = !item._needToBuy.equals("") ? _plugin._trad.get("Shop.needToBuy").replace("[NEED]", item._needToBuy) : ""; + _plugin._imm.setOption(player, i, item.getItem(), item.getItem().getItemMeta().getDisplayName(), "ARMOR_" + item._name, arrstring); + tmp++; + i++; + } + if (page > 0) { + _plugin._imm.setOption(player, 45, new ItemStack(Material.SIGN, 1), _plugin._trad.get("Shop.navigation.previousPage"), "Page-" + (page - 1), new String[]{_plugin._trad.get("Shop.navigation.previousPageDesc")}); + } + _plugin._imm.setOption(player, 49, new ItemStack(Material.BED, 1), _plugin._trad.get("Shop.navigation.home"), "Home", new String[]{_plugin._trad.get("Shop.navigation.homeDesc")}); + Item so = getItemShop(player); + _plugin._imm.setOption(player, 50, so.getIcon(), so.getName(), "Nothing", so.getDescription()); + if (i == slot + 44) { + _plugin._imm.setOption(player, 53, new ItemStack(Material.SIGN, 1), _plugin._trad.get("Shop.navigation.nextPage"), "Page-" + (page + 1), new String[]{_plugin._trad.get("Shop.navigation.nextPageDesc")}); + } + } + + public void getShopItem(Player player) { + PlayerInventory i = player.getInventory(); + ItemStack coucou = new ItemStack(Material.EMERALD, 1); + ItemMeta coucou_meta = coucou.getItemMeta(); + coucou_meta.setDisplayName(_plugin._trad.get("Shop.item.name")); + coucou.setItemMeta(coucou_meta); + i.addItem(new ItemStack[]{coucou}); + } + + public ItemStack getShop() { + ItemStack coucou = new ItemStack(_plugin._shopId, 1); + ItemMeta coucou_meta = coucou.getItemMeta(); + coucou_meta.setDisplayName(_plugin._trad.get("Shop.item.name")); + coucou.setItemMeta(coucou_meta); + return coucou; + } + + public String getMeta() { + return _plugin._trad.get("Shop.item.name"); + } + + public Item getItemShop(Player player) { + EcoManager eco = _plugin._eco; + int coins = eco.getPlayerMoney(player); + return new Item("Shop", new ItemStack(Material.EMERALD, 1), "shop", new String[] {_plugin._trad.get("Shop.youHave"), "" + ChatColor.GOLD + coins + " " + _plugin._trad.get("Shop.Coins.name")}, 0, 0); + } + + public void openShop(final Player p) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + Quake.getPlugin()._shop.getShopMenu(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + } + + public void Main_Manager(final Player p, String id) { + if (id.equalsIgnoreCase("Hoe_manager")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getHoeManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (id.equalsIgnoreCase("Hat_manager")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getHatManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (id.equalsIgnoreCase("Armor_manager")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getArmorManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (id.equalsIgnoreCase("Shop")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getShopMenu(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + } + + public void Hoe_Manager(final Player p, String id) { + if (id.equalsIgnoreCase("Home")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getMainShop(p); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (_plugin._stuff.setSelectedItem(p, id)) { + p.sendMessage(_plugin._trad.get("Shop.Selection.Hoe")); + } else { + p.sendMessage(ChatColor.RED + " Error: Hoe not successful selected !"); + } + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getHoeManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + } + + public void Hat_Manager(final Player p, String id) { + if (id.equalsIgnoreCase("Home")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getMainShop(p); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (_plugin._stuff.setSelectedHat(p, id)) { + p.sendMessage(_plugin._trad.get("Shop.Selection.Hat")); + } else { + p.sendMessage(ChatColor.RED + " Error: Hat not successful selected !"); + } + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getHatManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + } + + public void Armor_Manager(final Player p, String id) { + if (id.equalsIgnoreCase("Home")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + Quake.getPlugin()._shop.getMainShop(p); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (_plugin._stuff.setSelectedArmor(p, id)) { + p.sendMessage(_plugin._trad.get("Shop.Selection.Armor")); + } else { + p.sendMessage(ChatColor.RED + " Error: Armor not successful selected !"); + } + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable() { + + @Override + public void run() { + Quake.getPlugin()._shop.getArmorManager(p, 0); + Quake.getPlugin()._imm.show(p); + } + }, 2); + } + + public void Shop_Manager(final Player p, String id) { + if (id.startsWith("Page")) { + final String[] pa = id.split("-"); + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + Quake.getPlugin()._shop.getShopMenu(p, Integer.valueOf(pa[1])); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (id.equalsIgnoreCase("Home")) { + Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)_plugin, new Runnable(){ + + @Override + public void run() { + Quake.getPlugin()._shop.getMainShop(p); + Quake.getPlugin()._imm.show(p); + } + }, 2); + return; + } + if (id.startsWith("HOE")) { + ItemBasic need; + String[] pa = id.split("_"); + String ide = pa[1]; + ItemBasic item = _plugin._stuff.getItem(ide); + if (!item._needToBuy.equals("") && (need = _plugin._stuff.getItem(item._needToBuy)) != null && !_plugin._stuff.hasItem(p, item._needToBuy)) { + p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy)); + return; + } + if (!Quake.hasPermission(p, item._needPerm)) { + p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy")); + return; + } + if (!_plugin._eco.has(p, item._price)) { + p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney")); + return; + } + if (_plugin._stuff.hasItem(p, item._name)) { + p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveItem")); + return; + } + _plugin._eco.soustrairePlayerMoney(p, item._price); + _plugin._stuff.addItem(p, item._name); + p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name)); + return; + } + if (id.startsWith("HAT")) { + HatBasic need; + String[] pa = id.split("_"); + String ide = pa[1]; + HatBasic item = _plugin._stuff.getHat(ide); + if (!item._needToBuy.equals("") && (need = _plugin._stuff.getHat(item._needToBuy)) != null && !_plugin._stuff.hasHat(p, item._needToBuy)) { + p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy)); + return; + } + if (!Quake.hasPermission(p, item._needPerm)) { + p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy")); + return; + } + if (!_plugin._eco.has(p, item._price)) { + p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney")); + return; + } + if (_plugin._stuff.hasHat(p, item._name)) { + p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveThisHat")); + return; + } + _plugin._eco.soustrairePlayerMoney(p, item._price); + _plugin._stuff.addHat(p, item._name); + p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name)); + return; + } + if (id.startsWith("ARMOR")) { + ArmorBasic need; + String[] pa = id.split("_"); + String ide = pa[1]; + ArmorBasic item = _plugin._stuff.getArmor(ide); + if (!item._needToBuy.equals("") && (need = _plugin._stuff.getArmor(item._needToBuy)) != null && !_plugin._stuff.hasArmor(p, item._needToBuy)) { + p.sendMessage(_plugin._trad.get("Shop.YouNeed").replace("[NEED]", item._needToBuy)); + return; + } + if (!Quake.hasPermission(p, item._needPerm)) { + p.sendMessage(_plugin._trad.get("Shop.NoPermissionToBuy")); + return; + } + if (!_plugin._eco.has(p, item._price)) { + p.sendMessage(_plugin._trad.get("Shop.NotEnoughMoney")); + return; + } + if (_plugin._stuff.hasArmor(p, item._name)) { + p.sendMessage(_plugin._trad.get("Shop.AlreadyHaveThisArmor")); + return; + } + _plugin._eco.soustrairePlayerMoney(p, item._price); + _plugin._stuff.addArmor(p, item._name); + p.sendMessage(_plugin._trad.get("Shop.YouHaveBoughtItem").replace("[NAME]", item._name)); + return; + } + } + +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Armor/ArmorBasic.java b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorBasic.java new file mode 100644 index 0000000..b68dbaa --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorBasic.java @@ -0,0 +1,28 @@ +package com.Geekpower14.Quake.Stuff.Armor; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.inventory.ItemStack; + +public abstract class ArmorBasic { + public Quake _plugin = Quake.getPlugin(); + public int _price = 0; + public String _name = "Unknown"; + public String _needPerm = ""; + public String _givePerm = "Quake.admin"; + public String _needToBuy = ""; + + public abstract ItemStack getItem(); + + public String getNeededPerm() { + return _needPerm; + } + + public String getGivePerm() { + return _givePerm; + } + + public abstract void disable(); + + public abstract void saveConfig(); +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Armor/ArmorCustomFile.java b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorCustomFile.java new file mode 100644 index 0000000..e990445 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorCustomFile.java @@ -0,0 +1,40 @@ +package com.Geekpower14.Quake.Stuff.Armor; + +import java.io.File; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class ArmorCustomFile extends ArmorBasic implements Listener { + FileConfiguration _config; + + public ArmorCustomFile(String path) { + _config = YamlConfiguration.loadConfiguration(new File(path)); + _price = _config.getInt("Price"); + _name = _config.getString("Name"); + _givePerm = "Quake.admin"; + _needToBuy = ""; + ItemStack item = _config.getItemStack("Material"); + if (item == null) { + _plugin.getLogger().severe(_config.getString("Name") + " not a valid Material."); + } else + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + return _config.getItemStack("Material"); + } + + @Override + public void disable() { + HandlerList.unregisterAll((Listener)this); + } + + @Override + public void saveConfig() { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Armor/ArmorFactory.java b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorFactory.java new file mode 100644 index 0000000..e515f2b --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorFactory.java @@ -0,0 +1,17 @@ +/* + * Decompiled with CFR 0_114. + */ +package com.Geekpower14.Quake.Stuff.Armor; + +public class ArmorFactory { + public static ArmorBasic getInstance(String hatName, String path) { + if (hatName.equals("ArmorRED")) { + return new ArmorRED(); + } + if (hatName.equals("ArmorCustomFile")) { + return new ArmorCustomFile(path); + } + return null; + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Armor/ArmorRED.java b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorRED.java new file mode 100644 index 0000000..6bf40fa --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Armor/ArmorRED.java @@ -0,0 +1,26 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.inventory.ItemStack + */ +package com.Geekpower14.Quake.Stuff.Armor; + +import org.bukkit.inventory.ItemStack; + +public class ArmorRED +extends ArmorBasic { + @Override + public ItemStack getItem() { + return null; + } + + @Override + public void disable() { + } + + @Override + public void saveConfig() { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Hat/HatBasic.java b/src/com/Geekpower14/Quake/Stuff/Hat/HatBasic.java new file mode 100644 index 0000000..184e65a --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Hat/HatBasic.java @@ -0,0 +1,28 @@ +package com.Geekpower14.Quake.Stuff.Hat; + +import com.Geekpower14.Quake.Quake; +import org.bukkit.inventory.ItemStack; + +public abstract class HatBasic { + public Quake _plugin = Quake.getPlugin(); + public int _price = 0; + public String _name = "Unknown"; + public String _needPerm = ""; + public String _givePerm = "Quake.admin"; + public String _needToBuy = ""; + + public abstract ItemStack getItem(); + + public String getNeededPerm() { + return _needPerm; + } + + public String getGivePerm() { + return _givePerm; + } + + public abstract void disable(); + + public abstract void saveConfig(); +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Hat/HatCustomFile.java b/src/com/Geekpower14/Quake/Stuff/Hat/HatCustomFile.java new file mode 100644 index 0000000..39a15ca --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Hat/HatCustomFile.java @@ -0,0 +1,77 @@ +package com.Geekpower14.Quake.Stuff.Hat; + +import com.Geekpower14.Quake.Trans.Translate; +import java.io.File; +import java.util.ArrayList; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +public class HatCustomFile extends HatBasic implements Listener { + FileConfiguration _config; + + public HatCustomFile(String path) { + _config = YamlConfiguration.loadConfiguration(new File(path)); + _price = _config.getInt("Price"); + _name = _config.getString("Name"); + _givePerm = "Quake.admin"; + _needToBuy = ""; + Material material = Material.getMaterial(_config.getString("Material")); + if(material == null || material == Material.AIR) { + _plugin.getLogger().severe(_config.getString("Material") + " not a valid Material. Example: " + Material.APPLE.name()); + } + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + public static ItemStack Skull(String skullOwner) { + ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)SkullType.PLAYER.ordinal()); + SkullMeta skullMeta = (SkullMeta)skull.getItemMeta(); + skullMeta.setOwner(skullOwner); + skull.setItemMeta((ItemMeta)skullMeta); + return skull; + } + + @Override + public ItemStack getItem() { + ItemStack item = null; + if(_config.getString("Material").startsWith("Player:")) { + String tmp = _config.getString("Material"); + String[] tb = tmp.split(":"); + item = HatCustomFile.Skull(tb[1]); + } else { + Material material = Material.getMaterial((String)_config.getString("Material")); + if (material == null || material == Material.AIR) { + _plugin.getLogger().severe(_config.getString("Material") + " not a valid Material. Example: " + Material.APPLE.name()); + } + item = new ItemStack(material, 1); + } + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.GREEN + _name); + ArrayList arg0 = new ArrayList<>(); + String desc = _config.getString("Description"); + if(desc == null) { + _plugin.getLogger().severe("Description not set"); + } + arg0.add(ChatColor.RESET + Translate.replaceColors(desc)); + meta.setLore(arg0); + item.setItemMeta(meta); + return item; + } + + @Override + public void disable() { + HandlerList.unregisterAll((Listener)this); + } + + @Override + public void saveConfig() { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Hat/HatFactory.java b/src/com/Geekpower14/Quake/Stuff/Hat/HatFactory.java new file mode 100644 index 0000000..6e0fd71 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Hat/HatFactory.java @@ -0,0 +1,21 @@ +/* + * Decompiled with CFR 0_114. + */ +package com.Geekpower14.Quake.Stuff.Hat; + +import com.Geekpower14.Quake.Stuff.Hat.HatBasic; +import com.Geekpower14.Quake.Stuff.Hat.HatCustomFile; +import com.Geekpower14.Quake.Stuff.Hat.HatJACK; + +public class HatFactory { + public static HatBasic getInstance(String hatName, String path) { + if (hatName.equals("HatJACK")) { + return new HatJACK(); + } + if (hatName.equals("HatCustomFile")) { + return new HatCustomFile(path); + } + return null; + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Hat/HatJACK.java b/src/com/Geekpower14/Quake/Stuff/Hat/HatJACK.java new file mode 100644 index 0000000..1201593 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Hat/HatJACK.java @@ -0,0 +1,41 @@ +package com.Geekpower14.Quake.Stuff.Hat; + +import java.util.ArrayList; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class HatJACK extends HatBasic implements Listener { + public HatJACK() { + _price = 50; + _name = "JackOHat"; + _givePerm = "Quake.admin"; + _needToBuy = ""; + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = new ItemStack(Material.JACK_O_LANTERN, 1); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.GREEN + _name); + ArrayList arg0 = new ArrayList<>(); + arg0.add(ChatColor.BOLD + "It's cool !"); + meta.setLore(arg0); + item.setItemMeta(meta); + return item; + } + + @Override + public void disable() { + HandlerList.unregisterAll((Listener)this); + } + + @Override + public void saveConfig() { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/DiamondHoe.java b/src/com/Geekpower14/Quake/Stuff/Item/DiamondHoe.java new file mode 100644 index 0000000..69ea32c --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/DiamondHoe.java @@ -0,0 +1,82 @@ +package com.Geekpower14.Quake.Stuff.Item; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Arena.Arena; +import java.util.ArrayList; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +public class DiamondHoe extends ItemBasic implements Listener { + public DiamondHoe() { + _name = "Amazing RailGun"; + _needToBuy = "GoldenGun"; + _Time = 20L; + _price = 1200; + loadConfig(); + saveConfig(); + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = defaultItem(Material.DIAMOND_HOE, _Time); + return item; + } + + @Override + public void shot(Player player) { + BasicShot(player, FireworkEffect.builder().withColor(Color.AQUA).with(FireworkEffect.Type.BURST).build()); + } + + @Override + public void eject(Player player) { + } + + public void explode(Player player, FireworkEffect effect) { + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + return; + } + APlayer ap = arena.getAPlayer(player); + if (ap.isReloading()) { + return; + } + ap.setReloading(true); + try { + _fw.playFirework(player.getWorld(), player.getLocation(), effect); + } catch (Exception e) { + e.printStackTrace(); + } + long startTime = System.currentTimeMillis(); + int maxRange = 15; + ArrayList targets = new ArrayList<>(); + + for(Player online: Bukkit.getOnlinePlayers()) { + if (online != player && online.getLocation().distance(player.getEyeLocation()) < (double)maxRange) { + targets.add(online); + } + } + + Location loc = player.getEyeLocation(); + for(Player p : targets) { + if (p.getUniqueId() == player.getUniqueId()) continue; + Location two = p.getEyeLocation(); + Vector from = new Vector(loc.getX(), loc.getY(), loc.getZ()); + Vector to = new Vector(two.getX(), two.getY(), two.getZ()); + Vector vector = to.subtract(from).normalize(); + vector.add(new Vector(0, 1, 0)); + vector.multiply(1.7); + p.setVelocity(vector); + } + + ap.setReloading(_Time); + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/GoldHoe.java b/src/com/Geekpower14/Quake/Stuff/Item/GoldHoe.java new file mode 100644 index 0000000..01a2d39 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/GoldHoe.java @@ -0,0 +1,36 @@ +package com.Geekpower14.Quake.Stuff.Item; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class GoldHoe extends ItemBasic implements Listener { + public GoldHoe() { + _name = "GoldenGun"; + _needToBuy = "Boosted RailGun"; + _Time = 28L; + _price = 800; + loadConfig(); + saveConfig(); + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = defaultItem(Material.GOLD_HOE, _Time); + return item; + } + + @Override + public void shot(Player player) { + BasicShot(player, FireworkEffect.builder().withColor(Color.YELLOW).with(FireworkEffect.Type.BALL_LARGE).build()); + } + + @Override + public void eject(Player player) { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/IronHoe.java b/src/com/Geekpower14/Quake/Stuff/Item/IronHoe.java new file mode 100644 index 0000000..2c37512 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/IronHoe.java @@ -0,0 +1,36 @@ +package com.Geekpower14.Quake.Stuff.Item; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class IronHoe extends ItemBasic implements Listener { + public IronHoe() { + _name = "Boosted RailGun"; + _needToBuy = "Advanced RailGun"; + _Time = 32L; + _price = 600; + loadConfig(); + saveConfig(); + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = defaultItem(Material.IRON_HOE, _Time); + return item; + } + + @Override + public void shot(Player player) { + BasicShot(player, FireworkEffect.builder().withColor(Color.GRAY).with(FireworkEffect.Type.BALL_LARGE).build()); + } + + @Override + public void eject(Player player) { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/ItemBasic.java b/src/com/Geekpower14/Quake/Stuff/Item/ItemBasic.java new file mode 100644 index 0000000..bdddb8e --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/ItemBasic.java @@ -0,0 +1,295 @@ +package com.Geekpower14.Quake.Stuff.Item; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Utils.FireworkEffectPlayer; +import com.Geekpower14.Quake.Utils.ParticleEffects; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Vector; + +public abstract class ItemBasic implements Listener { + public Quake _plugin = Quake.getPlugin(); + public int _price = 0; + public String _name = "Unknown"; + public String _alias = ""; + public String _needPerm = ""; + public String _givePerm = "Quake.admin"; + public String _needToBuy = ""; + public Long _Time; + FireworkEffectPlayer _fw; + + public abstract ItemStack getItem(); + + public ItemStack defaultItem(Material material, Long time) { + ItemStack item = new ItemStack(material, 1); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.GREEN + _alias); + ArrayList arg0 = new ArrayList<>(); + arg0.add(_plugin._trad.get("Shop.Hoe.Desc1")); + float t = (float)time; + arg0.add(_plugin._trad.get("Shop.Hoe.Desc2").replace("[TIME]", "" + t / 20.0f)); + meta.setLore(arg0); + item.setItemMeta(meta); + return item; + } + + public ItemBasic() { + loadConfig(); + _fw = new FireworkEffectPlayer(_plugin); + } + + public ItemBasic(Arena aren, String name) { + loadConfig(); + _name = name; + _fw = new FireworkEffectPlayer(_plugin); + } + + public ItemBasic(Arena aren, String name, int price) { + loadConfig(); + _price = price; + _name = name; + _fw = new FireworkEffectPlayer(_plugin); + } + + public String getNeededPerm() { + return _needPerm; + } + + public String getGivePerm() { + return _givePerm; + } + + protected void BasicShot(Player player, FireworkEffect effect) { + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + return; + } + APlayer ap = arena.getAPlayer(player); + if (ap.isReloading()) { + return; + } + ap.setReloading(true); + int compte = 0; + List victims = getTargetV3(arena, player, 100, 1.2, false); + for(Player victim : victims) { + arena.shotplayer(player, victim, effect); + } + compte = victims.size(); + + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 2.0f); + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.5f); + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.4f); + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.3f); + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.1f, 1.2f); + + /*player.getWorld().playSound(player.getLocation(), org.bukkit.Sound.EXPLODE, 0.1f, 2.0f); + player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.5f); + player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.4f); + player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.3f); + player.getWorld().playSound(player.getLocation(), Sound.EXPLODE, 0.1f, 1.2f);*/ + + if (compte == 2) { + arena.broadcast(_plugin._trad.get("Game.Arena.Kill.Double")); + } else if (compte == 3) { + arena.broadcast(_plugin._trad.get("Game.Arena.Kill.Triple")); + } else if (compte >= 4) { + arena.broadcast(_plugin._trad.get("Game.Arena.Kill.More")); + } + arena.getScoreShot(player); + ap.setReloading(_Time); + } + + public List getTargetV3(Arena arena, Player player, int maxRange, double aiming, boolean wallHack) { + ArrayList target = new ArrayList<>(); + Location playerEyes = player.getEyeLocation(); + Vector direction = playerEyes.getDirection().normalize(); + ArrayList targets = new ArrayList<>(); + for(Player online: player.getWorld().getPlayers()) { + Arena oArena = Quake.getPlugin()._am.getArenabyPlayer(online); + if(oArena == null || !oArena.equals(arena)) + continue; + + if(online != player && online.getLocation().distanceSquared(playerEyes) < (double)(maxRange * maxRange)) { + targets.add(online); + } + } + Location loc = playerEyes.clone(); + Vector progress = direction.clone().multiply(0.7); + maxRange = 100 * maxRange / 70; + int loop = 0; + while(loop < maxRange) { + loop++; + loc.add(progress); + Block block = loc.getBlock(); + if (!wallHack && block.getType().isSolid()) + break; + + double lx = loc.getX(); + double ly = loc.getY(); + double lz = loc.getZ(); + for(APlayer apa: arena._players.values()) { + try { + ParticleEffects.FIREWORKS_SPARK.sendToPlayer(apa.getPlayer(), loc, 0.1f, 0.1f, 0.1f, 0.05f, 2); + } catch (Exception e) { + e.printStackTrace(); + } + } + + for(Player possibleTarget : targets) { + if(possibleTarget.getUniqueId() == player.getUniqueId()) + continue; + Location testLoc = possibleTarget.getLocation().add(0.0, 0.85, 0.0); + double px = testLoc.getX(); + double py = testLoc.getY(); + double pz = testLoc.getZ(); + boolean dX = Math.abs(lx - px) < 0.7 * aiming; + boolean dY = Math.abs(ly - py) < 1.7 * aiming; + boolean dZ = Math.abs(lz - pz) < 0.7 * aiming; + if(!dX || !dY || !dZ || target.contains(possibleTarget)) + continue; + target.add(possibleTarget); + } + } + return target; + } + + public Boolean istheSame(ItemStack it) { + ItemStack item = getItem(); + ItemMeta meta = item.getItemMeta(); + ItemMeta met = it.getItemMeta(); + if (meta == null && met == null) { + return true; + } + if (meta == null || met == null) { + return false; + } + if (!meta.getDisplayName().equalsIgnoreCase(met.getDisplayName())) { + return false; + } + return meta.getLore().equals(met.getLore()); + } + + @EventHandler(priority=EventPriority.HIGHEST) + public void onPlayerInteract(PlayerInteractEvent event) { + Action action = event.getAction(); + Player player = event.getPlayer(); + ItemStack hand = player.getItemInHand(); + Quake.debug("Debug Item Player Listener Interact Part 1"); + Arena arena = _plugin._am.getArenabyPlayer(player); + if (arena == null) { + return; + } + Quake.debug("Debug Item Player Listener Interact Part 2"); + APlayer ap = arena.getAPlayer(player); + if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) { + Quake.debug("Debug Item Player Listener Interact Part 3"); + if (!istheSame(hand)) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 4"); + if (arena._etat != arena._ingame || arena._finished) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 5"); + if (ap.isReloading()) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 6"); + eject(player); + event.setCancelled(true); + return; + } + if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { + Quake.debug("Debug Item Player Listener Interact Part 7"); + if (!istheSame(hand)) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 8"); + if (arena._etat != arena._ingame || arena._finished) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 9"); + if (ap.isReloading()) { + event.setCancelled(true); + return; + } + Quake.debug("Debug Item Player Listener Interact Part 10"); + shot(player); + event.setCancelled(true); + } + } + + public abstract void eject(Player var1); + + public abstract void shot(Player var1); + + public void disable() { + HandlerList.unregisterAll((Listener)this); + } + + public final void loadConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Stuff/Hoes/" + _name + ".yml")); + if (config.contains("Name")) { + _name = config.getString("Name"); + } + _alias = _name; + if (config.contains("Alias")) { + _alias = config.getString("Alias"); + } + if (config.contains("Reload-Time")) { + _Time = config.getLong("Reload-Time"); + } + if (config.contains("Price")) { + _price = config.getInt("Price"); + } + if (config.contains("Needed-Permissions")) { + _needPerm = config.getString("Needed-Permissions"); + } + if (config.contains("Permissions-To-Give")) { + _givePerm = config.getString("Permissions-To-Give"); + } + } + + public final void saveConfig() { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File("")); + config.set("Name",_name); + config.set("Alias", _alias); + config.set("Reload-Time", _Time); + config.set("Price", _price); + config.set("Needed-Permissions", _needPerm); + config.set("Permissions-To-Give", _givePerm); + try { + config.save(new File(_plugin.getDataFolder(), "/Stuff/Hoes/" + _name + ".yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save de " + _name + " impossible !"); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/StoneHoe.java b/src/com/Geekpower14/Quake/Stuff/Item/StoneHoe.java new file mode 100644 index 0000000..82ff4c0 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/StoneHoe.java @@ -0,0 +1,36 @@ +package com.Geekpower14.Quake.Stuff.Item; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +public class StoneHoe extends ItemBasic implements Listener { + public StoneHoe() { + _name = "Advanced RailGun"; + _Time = 36L; + _price = 400; + loadConfig(); + saveConfig(); + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = defaultItem(Material.STONE_HOE, _Time); + return item; + } + + @Override + public void shot(Player player) { + BasicShot(player, FireworkEffect.builder().withColor(Color.GREEN).with(FireworkEffect.Type.BALL_LARGE).build()); + } + + @Override + public void eject(Player player) { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/Item/WoodenHoe.java b/src/com/Geekpower14/Quake/Stuff/Item/WoodenHoe.java new file mode 100644 index 0000000..271fdec --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/Item/WoodenHoe.java @@ -0,0 +1,52 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.Color + * org.bukkit.FireworkEffect + * org.bukkit.FireworkEffect$Builder + * org.bukkit.FireworkEffect$Type + * org.bukkit.Material + * org.bukkit.Server + * org.bukkit.entity.Player + * org.bukkit.event.Listener + * org.bukkit.inventory.ItemStack + * org.bukkit.plugin.Plugin + * org.bukkit.plugin.PluginManager + */ +package com.Geekpower14.Quake.Stuff.Item; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class WoodenHoe extends ItemBasic implements Listener { + public WoodenHoe() { + _name = "RailGun"; + _Time = 40L; + _givePerm = ""; + _price = 0; + loadConfig(); + saveConfig(); + _plugin.getServer().getPluginManager().registerEvents((Listener)this, _plugin); + } + + @Override + public ItemStack getItem() { + ItemStack item = defaultItem(Material.WOOD_HOE, _Time); + return item; + } + + @Override + public void shot(Player player) { + BasicShot(player, FireworkEffect.builder().withColor(Color.RED).with(FireworkEffect.Type.BALL_LARGE).build()); + } + + @Override + public void eject(Player player) { + } +} + diff --git a/src/com/Geekpower14/Quake/Stuff/StuffManager.java b/src/com/Geekpower14/Quake/Stuff/StuffManager.java new file mode 100644 index 0000000..3f790e8 --- /dev/null +++ b/src/com/Geekpower14/Quake/Stuff/StuffManager.java @@ -0,0 +1,407 @@ +package com.Geekpower14.Quake.Stuff; + +import com.Geekpower14.Quake.Arena.APlayer; +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Stuff.Armor.ArmorBasic; +import com.Geekpower14.Quake.Stuff.Armor.ArmorFactory; +import com.Geekpower14.Quake.Stuff.Hat.HatBasic; +import com.Geekpower14.Quake.Stuff.Hat.HatFactory; +import com.Geekpower14.Quake.Stuff.Item.DiamondHoe; +import com.Geekpower14.Quake.Stuff.Item.GoldHoe; +import com.Geekpower14.Quake.Stuff.Item.IronHoe; +import com.Geekpower14.Quake.Stuff.Item.ItemBasic; +import com.Geekpower14.Quake.Stuff.Item.StoneHoe; +import com.Geekpower14.Quake.Stuff.Item.WoodenHoe; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; + +public class StuffManager { + private final Quake _plugin; + private ArrayList _armors = new ArrayList(); + private ArrayList _hats = new ArrayList(); + private ArrayList _item = new ArrayList(); + + public StuffManager(Quake pl) { + _plugin = pl; + loadItem(); + loadHat(); + loadArmor(); + } + + public void reloadConfig() { + loadItem(); + loadHat(); + loadArmor(); + } + + public final void loadItem() { + _item = new ArrayList(); + _item.add(new WoodenHoe()); + _item.add(new StoneHoe()); + _item.add(new IronHoe()); + _item.add(new GoldHoe()); + _item.add(new DiamondHoe()); + } + + public final void loadHat() { + File[] files; + _hats = new ArrayList(); + File f = new File(_plugin.getDataFolder(), "/Stuff/Hats"); + if (!f.exists()) { + YamlConfiguration nhat = YamlConfiguration.loadConfiguration((File)new File("")); + nhat.set("Implementation", "HatCustomFile"); + nhat.set("Price", 50); + nhat.set("Name", "JackOHat"); + nhat.set("Material", Material.JACK_O_LANTERN.toString()); + nhat.set("Description", (String.valueOf(ChatColor.BOLD.toString()) + "It's cool !")); + try { + nhat.save(new File(_plugin.getDataFolder(), "/Stuff/Hats/JackOHat.yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save JackOHat impossible !"); + } + YamlConfiguration nhatt = YamlConfiguration.loadConfiguration((File)new File("")); + nhatt.set("Implementation", "HatCustomFile"); + nhatt.set("Price", 500000); + nhatt.set("Name", "Geekpower14"); + nhatt.set("Material", "Player:geekpower14"); + nhatt.set("Description", (String.valueOf(ChatColor.BOLD.toString()) + "He's cool !")); + try { + nhatt.save(new File(_plugin.getDataFolder(), "/Stuff/Hats/Geekpower14.yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save JackOHat impossible !"); + } + f.mkdirs(); + } + File[] arrfile = files = new File(_plugin.getDataFolder(), "/Stuff/Hats").listFiles(); + int n = arrfile.length; + int e = 0; + while (e < n) { + YamlConfiguration config; + File file = arrfile[e]; + _plugin.getLogger().warning(file.getPath()); + if (file.isFile() && file.getPath().endsWith(".yml") && (config = YamlConfiguration.loadConfiguration((File)file)).contains("Implementation")) { + _plugin.getLogger().info(String.valueOf(file.getPath()) + " found implementation"); + HatBasic hat = HatFactory.getInstance(config.getString("Implementation"), file.getPath()); + if (hat == null) { + _plugin.getLogger().severe(String.valueOf(file.getPath()) + " invalid implementation"); + } else { + _hats.add(hat); + } + } + ++e; + } + } + + public final void loadArmor() { + File[] files; + _armors = new ArrayList(); + File f = new File(_plugin.getDataFolder(), "/Stuff/Armors"); + if (!f.exists()) { + YamlConfiguration nhat = YamlConfiguration.loadConfiguration((File)new File("")); + nhat.set("Implementation", "ArmorCustomFile"); + nhat.set("Price", 100); + nhat.set("Name", "ArmorRED"); + ItemStack item = new ItemStack(Material.LEATHER_CHESTPLATE); + LeatherArmorMeta meta = (LeatherArmorMeta)item.getItemMeta(); + meta.setDisplayName(ChatColor.RED + "ArmorRED"); + ArrayList l = new ArrayList(); + l.add(ChatColor.RESET + "A beautiful leather dress!"); + meta.setLore(l); + meta.setColor(Color.RED); + item.setItemMeta((ItemMeta)meta); + nhat.set("Material", item); + try { + nhat.save(new File(_plugin.getDataFolder(), "/Stuff/Armors/ArmorRED.yml")); + } + catch (IOException e) { + _plugin.getLogger().warning("save ArmorRED impossible !"); + } + f.mkdirs(); + } + File[] e = files = new File(_plugin.getDataFolder(), "/Stuff/Armors").listFiles(); + int l = e.length; + int meta = 0; + while (meta < l) { + YamlConfiguration config; + File file = e[meta]; + _plugin.getLogger().warning(file.getPath()); + if (file.isFile() && file.getPath().endsWith(".yml") && (config = YamlConfiguration.loadConfiguration((File)file)).contains("Implementation")) { + _plugin.getLogger().info(file.getPath() + " found implementation"); + ArmorBasic armor = ArmorFactory.getInstance(config.getString("Implementation"), file.getPath()); + if (armor == null) { + _plugin.getLogger().severe(file.getPath() + " invalid implementation"); + } else { + _armors.add(armor); + } + } + ++meta; + } + } + + public ArrayList getItems() { + return _item; + } + + public ItemBasic getSelectedItem(APlayer player) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + player.getPlayer().getName() + ".yml")); + String id = config.getString("Hoe.Selected"); + if (id == null) { + id = "RailGun"; + } + return getItem(id); + } + + public ItemBasic getSelectedItem(Player player) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + player.getName() + ".yml")); + String id = config.getString("Hoe.Selected"); + if (id == null) { + id = "RailGun"; + } + return getItem(id); + } + + public Boolean setSelectedItem(Player p, String name) { + if (getItem(name) == null) { + return false; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + config.set("Hoe.Selected", name); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + return true; + } + + public Boolean hasItem(Player p, String name) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hoe.Bought"); + if (list.contains(name)) { + return true; + } + + ArrayList result = new ArrayList<>(); + for (ItemBasic it : _item) { + if (!Quake.hasPermission(p, it._givePerm)) continue; + result.add(it._name); + } + if (result.contains(name)) { + return true; + } + return false; + } + + public List getItems(Player p) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hoe.Bought"); + ArrayList result = new ArrayList<>(); + for (String l : list) { + ItemBasic ite = getItem(l); + if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l)) + continue; + result.add(l); + } + for (ItemBasic it : _item) { + if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name)) continue; + result.add(it._name); + } + return result; + } + + public List getHats(Player p) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hat.Bought"); + ArrayList result = new ArrayList<>(); + for (String l : list) { + HatBasic ite = getHat(l); + if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l)) + continue; + result.add(l); + } + for(HatBasic it : _hats) { + if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name)) + continue; + result.add(it._name); + } + return result; + } + + public List getArmors(Player p) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Armor.Bought"); + ArrayList result = new ArrayList<>(); + for (String l : list) { + ArmorBasic ite = getArmor(l); + if (ite == null || !Quake.hasPermission(p, ite._needPerm) || result.contains(l)) + continue; + result.add(l); + } + for (ArmorBasic it : _armors) { + if (!Quake.hasPermission(p, it._givePerm) || result.contains(it._name)) + continue; + result.add(it._name); + } + return result; + } + + public void addItem(Player p, String name) { + if (getItem(name) == null) { + return; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hoe.Bought"); + list.add(name); + config.set("Hoe.Bought", list); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void addHat(Player p, String name) { + if (getHat(name) == null) { + return; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hat.Bought"); + list.add(name); + config.set("Hat.Bought", list); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void addArmor(Player p, String name) { + if (getArmor(name) == null) { + return; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Armor.Bought"); + list.add(name); + config.set("Armor.Bought", list); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public Boolean setSelectedHat(Player p, String name) { + if (getHat(name) == null) { + return false; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + config.set("Hat.Selected", name); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + return true; + } + + public Boolean setSelectedArmor(Player p, String name) { + if (getArmor(name) == null) { + return false; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + config.set("Armor.Selected", name); + try { + config.save(new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + } catch (IOException e) { + e.printStackTrace(); + } + return true; + } + + public Boolean hasHat(Player p, String name) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Hat.Bought"); + if (list.contains(name)) { + return true; + } + return false; + } + + public HatBasic getSelectedHat(APlayer player) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(player.getConfig())); + String id = config.getString("Hat.Selected"); + return getHat(id); + } + + public ArmorBasic getSelectedArmor(APlayer player) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(player.getConfig())); + String id = config.getString("Armor.Selected"); + return getArmor(id); + } + + public Boolean hasArmor(Player p, String name) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Players/" + p.getName() + ".yml")); + List list = config.getStringList("Armor.Bought"); + if (list.contains(name)) { + return true; + } + return false; + } + + public ItemBasic getItem(String name) { + for (ItemBasic it : _item) { + if (!it._name.equalsIgnoreCase(name)) continue; + return it; + } + return null; + } + + public HatBasic getHat(String name) { + for (HatBasic it : _hats) { + if (!it._name.equalsIgnoreCase(name)) continue; + return it; + } + return null; + } + + public ArmorBasic getArmor(String name) { + for (ArmorBasic it : _armors) { + if (!it._name.equalsIgnoreCase(name)) continue; + return it; + } + return null; + } + + public ArrayList getHats() { + return _hats; + } + + public ArrayList getArmors() { + return _armors; + } + + public void disable() { + for (ItemBasic it22 : _item) { + it22.disable(); + } + for (HatBasic it : _hats) { + it.disable(); + } + for (ArmorBasic it2 : _armors) { + it2.disable(); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Task.java b/src/com/Geekpower14/Quake/Task.java new file mode 100644 index 0000000..a8d31f6 --- /dev/null +++ b/src/com/Geekpower14/Quake/Task.java @@ -0,0 +1,87 @@ +package com.Geekpower14.Quake; + +import com.Geekpower14.Quake.Arena.Arena; +import com.Geekpower14.Quake.Arena.SArena; +import com.Geekpower14.Quake.Arena.TArena; +import com.Geekpower14.Quake.Utils.ScoreB; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class Task implements Runnable { + private final Quake _plugin; + + public Task(Quake pl) { + _plugin = pl; + } + + /* + * Enabled force condition propagation + * Lifted jumps to return sites + */ + public void resetTime(Arena arena) { + Location wo = null; + if(arena instanceof TArena) { + if(((TArena)arena)._spawns_B.isEmpty()) + return; + wo = ((TArena)arena)._spawns_B.get(0); + } else if(arena instanceof SArena) { + if(((SArena)arena)._spawns.isEmpty()) + return; + wo = ((SArena)arena)._spawns.get(0); + } + if(wo == null || wo.getWorld() == null || wo.getWorld().getTime() < 10000) + return; + wo.getWorld().setTime(4000); + _plugin.getLogger().info("Time set for :" + arena._name); + } + + @Override + public void run() { + for(Player p: Bukkit.getOnlinePlayers()) { + //while (n2 < n) { + Arena arena = _plugin._am.getArenabyPlayer(p); + if (arena != null) { + resetTime(arena); + return; + } + if (_plugin._shopWorlds.contains(p.getWorld().getName()) && !p.getInventory().contains(_plugin._shop.getShop()) && Quake.hasPermission(p, "Quake.Shop")) { + ItemStack[] arritemStack = p.getInventory().getContents(); + int n3 = arritemStack.length; + int n4 = 0; + while (n4 < n3) { + ItemStack it = arritemStack[n4]; + if (it != null && it.getItemMeta() != null && it.getItemMeta().getDisplayName() != null && it.getItemMeta().getDisplayName().equalsIgnoreCase(_plugin._shop.getShop().getItemMeta().getDisplayName())) { + try { + p.getInventory().remove(it); + } catch (Exception var10_10) { + // empty catch block + } + } + ++n4; + } + p.getInventory().addItem(new ItemStack[]{_plugin._shop.getShop()}); + } + if (isScoreWorld(p.getWorld().getName())) { + giveScoreBoard(p); + } + } + } + + public void giveScoreBoard(Player p) { + if (_plugin._scores.containsKey(p.getName())) { + _plugin._scores.get(p.getName()).updateScore(); + } else { + _plugin._scores.put(p.getName(), new ScoreB(_plugin, p)); + } + } + + public Boolean isScoreWorld(String name) { + if (_plugin._ScoreWorlds.contains(name)) { + return true; + } + return false; + } +} + diff --git a/src/com/Geekpower14/Quake/Trans/Score.java b/src/com/Geekpower14/Quake/Trans/Score.java new file mode 100644 index 0000000..ddc7c2a --- /dev/null +++ b/src/com/Geekpower14/Quake/Trans/Score.java @@ -0,0 +1,28 @@ +/* + * Decompiled with CFR 0_114. + */ +package com.Geekpower14.Quake.Trans; + +public class Score { + + public static enum Type { + Win("Wins"), + Kill("Kills"), + Death("Deaths"), + Shot("Shots"), + TeamWin("TeamWins"); + + String _type; + + private Type(String s) { + _type = s; + } + + @Override + public String toString() { + return _type; + } + } + +} + diff --git a/src/com/Geekpower14/Quake/Trans/Translate.java b/src/com/Geekpower14/Quake/Trans/Translate.java new file mode 100644 index 0000000..331bb00 --- /dev/null +++ b/src/com/Geekpower14/Quake/Trans/Translate.java @@ -0,0 +1,137 @@ +package com.Geekpower14.Quake.Trans; + +import com.Geekpower14.Quake.Quake; +import java.io.File; +import java.io.IOException; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +public class Translate { + Quake _plugin; + FileConfiguration _config; + + private void setDefaultConfig(String key, String value) { + if (!_config.isSet(key)) { + _config.set(key, value); + } + } + + public void reloadConfig() { + _config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Language.yml")); + } + + public Translate(Quake pl) { + _plugin = pl; + _config = YamlConfiguration.loadConfiguration((File)new File(_plugin.getDataFolder(), "/Language.yml")); + try { + setDefaultConfig("Shop.item.name", "&aShop &6(Click to Open)"); + setDefaultConfig("Shop.item.description", ""); + setDefaultConfig("Game.hoe.diamond", "Amazing RailGun"); + setDefaultConfig("Game.hoe.gold", "GoldenGun"); + setDefaultConfig("Game.hoe.iron", "Boosted RailGun"); + setDefaultConfig("Game.hoe.stone", "Advanced RailGun"); + setDefaultConfig("Game.hoe.wood", "RailGun"); + setDefaultConfig("Game.item.leave", "&aExit &6(Click to Leave)"); + setDefaultConfig("Shop.Coins.name", "Coins"); + setDefaultConfig("ScoreBoard.Kills.name", "Kills"); + setDefaultConfig("ScoreBoard.Deaths.name", "Deaths"); + setDefaultConfig("ScoreBoard.Shots.name", "Shots"); + setDefaultConfig("ScoreBoard.Wins.name", "Wins"); + setDefaultConfig("ScoreBoard.name", "Scores"); + setDefaultConfig("Shop.price", "&r&o&6Price: [PRICE]"); + setDefaultConfig("Shop.needToBuy", "&r&o&6Need: [NEED]"); + setDefaultConfig("Shop.navigation.previousPage", "&aBack"); + setDefaultConfig("Shop.navigation.previousPageDesc", "Back to previous page !"); + setDefaultConfig("Shop.navigation.home", "&aHome"); + setDefaultConfig("Shop.navigation.homeDesc", "Back to Home !"); + setDefaultConfig("Shop.navigation.nextPage", "&aNext"); + setDefaultConfig("Shop.navigation.nextPageDesc", "Go to next page !"); + setDefaultConfig("Shop.youHave", "&aYou have :"); + setDefaultConfig("NoPermission", "&cYou have not the permissions."); + setDefaultConfig("Shop.NoPermissionToBuy", "&cYou have not the permission to buy it !"); + setDefaultConfig("Shop.NotEnoughMoney", "&cYou have not enough money to buy it !"); + setDefaultConfig("Shop.AlreadyHaveItem", "&cYou have already this Item !"); + setDefaultConfig("Shop.YouHaveBoughtItem", "&aYou have bought [NAME] !"); + setDefaultConfig("Shop.AlreadyHaveThisHat", "&cYou have already this Hat !"); + setDefaultConfig("Shop.AlreadyHaveThisArmor", "&cYou have already this Armor !"); + setDefaultConfig("Shop.SelectHoe", "Select your Hoe !"); + setDefaultConfig("Shop.SelectArmor", "Select your Armor !"); + setDefaultConfig("Shop.SelectHat", "Select your Hat !"); + setDefaultConfig("Shop.BuyNewStuff", "Buy new stuff !"); + setDefaultConfig("Shop.ExitDesc", "Exit !"); + setDefaultConfig("Shop.ManagerHoe", "&aHoe Manager"); + setDefaultConfig("Shop.ManagerArmor", "&aArmor Manager"); + setDefaultConfig("Shop.ManagerHat", "&aHat Manager"); + setDefaultConfig("Shop.Shop", "&aShop"); + setDefaultConfig("Shop.Exit", "&aExit"); + setDefaultConfig("Shop.Selection.Hoe", "&aHoe successful selected !"); + setDefaultConfig("Shop.Selection.Hat", "&aHat successful selected"); + setDefaultConfig("Shop.Selection.Armor", "&aArmor successful selected !"); + setDefaultConfig("Shop.YouNeed", "&cYou need [NEED] !"); + setDefaultConfig("Shop.Hoe.Desc1", "&lRight-Click to Instant-Kill !"); + setDefaultConfig("Shop.Hoe.Desc2", "&lRecharge in [TIME] s"); + setDefaultConfig("", ""); + setDefaultConfig("", ""); + setDefaultConfig("", ""); + setDefaultConfig("", ""); + setDefaultConfig("", ""); + setDefaultConfig("", ""); + setDefaultConfig("Shop.message.error.Unknown-Item", "&cError Unknown Item !"); + setDefaultConfig("Shop.message.error.NoEnought-Coin", "&cYou have not enought coins !"); + setDefaultConfig("Shop.message.error.HaveAlreadyHoe", "&cYou have already this hoe !"); + setDefaultConfig("Shop.message.error.HaveBetterHoe", "&cYou have a better hoe !"); + setDefaultConfig("Shop.message.error.MustHaveLowerHoe", "You must have the lower hoe !"); + setDefaultConfig("Shop.message.success.NewHoe", "&aCongratulation, You have a new hoe !"); + setDefaultConfig("Game.Arena.Message.Join", "[PLAYER]&e joined the arena ([NUMBER]/[MAX])"); + setDefaultConfig("Game.Arena.Message.Team-Join", "[PLAYER]&e joined as [TEAM] ([NUMBER]/[MAX])"); + setDefaultConfig("Game.Arena.Message.RemainTime", "&eGame Starting in [TIME] sec"); + setDefaultConfig("Game.Arena.Message.ChangeTeam", "&aYou are now [TEAM] &a!"); + setDefaultConfig("Game.Arena.Message.Aborde-Game", "&eA player leave the arena ! Starting Aborded!"); + setDefaultConfig("Game.Arena.Message.Start", "&eLet's go ! May the Odds be ever in your favour .."); + setDefaultConfig("Game.Arena.Message.Start-Info", "&eRigh-Click with your gun to Instant-Kill other players !"); + setDefaultConfig("Game.Arena.Message.Shot", "&c[SHOOTER] &8shot [KILLED]"); + setDefaultConfig("Game.Arena.Message.Void", "&c[KILLED] fell out of the world !"); + setDefaultConfig("Game.Arena.Message.Won", "&7[NAME] won the Game !"); + setDefaultConfig("Game.Arena.Message.Team-Won", "&7[TEAM] &7won the Game !"); + setDefaultConfig("Game.Arena.Message.ChangeTeamInGame", "&cYou can't change Team in Game !"); + setDefaultConfig("Game.Arena.Message.NotInAGame", "&cYou are not in game !"); + setDefaultConfig("Game.Arena.error.NotInTeamGame", "&cYou are not in a Team Game !"); + setDefaultConfig("Game.Arena.error.BadTeamName", "&cBad Team Name !"); + setDefaultConfig("Game.Arena.error.inGame", "&cGame in progress !"); + setDefaultConfig("Game.Arena.error.NoSpawn", "&cWhere are no spawn !"); + setDefaultConfig("Game.Arena.error.full", "&cGame is Full !"); + setDefaultConfig("Game.Arena.error.VIP", "&cGame is VIP !"); + setDefaultConfig("Game.Arena.error.command", "&cCommands not allowed in the arena !"); + setDefaultConfig("Game.Arena.Kill.Double", "&cDouble Kill !!"); + setDefaultConfig("Game.Arena.Kill.Triple", "&cTriple Kill !!!"); + setDefaultConfig("Game.Arena.Kill.More", "&cEpic Kill !!!!"); + _config.save(new File(_plugin.getDataFolder(), "/Language.yml")); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + public String get(String path) { + String result = _config.getString(path); + if (result == null) { + return ChatColor.RED + path + " Undefined in config"; + } + return Translate.replaceColors(result); + } + + public static String replaceColors(String message) { + String s = message; + ChatColor[] arrchatColor = ChatColor.values(); + int n = arrchatColor.length; + int n2 = 0; + while (n2 < n) { + ChatColor color = arrchatColor[n2]; + s = s.replaceAll("(?i)&" + color.getChar(), color + ""); + n2++; + } + return s; + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/Area.java b/src/com/Geekpower14/Quake/Utils/Area.java new file mode 100644 index 0000000..db9601b --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/Area.java @@ -0,0 +1,123 @@ +package com.Geekpower14.Quake.Utils; + +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +public class Area { + private Location _min = new Location(null, 0.0, 0.0, 0.0); + private Location _max = new Location(null, 0.0, 0.0, 0.0); + + public Area(Location un, Location deux) { + if (un == null || deux == null) { + return; + } + if (un.getX() >= deux.getX()) { + _max.setX(un.getX()); + _min.setX(deux.getX()); + } else { + _max.setX(deux.getX()); + _min.setX(un.getX()); + } + if (un.getY() >= deux.getY()) { + _max.setY(un.getY()); + _min.setY(deux.getY()); + } else { + _max.setY(deux.getY()); + _min.setY(un.getY()); + } + if (un.getZ() >= deux.getZ()) { + _max.setZ(un.getZ()); + _min.setZ(deux.getZ()); + } else { + _max.setZ(deux.getZ()); + _min.setZ(un.getZ()); + } + } + + public Area(List src) { + if (src == null) { + return; + } + if (src.size() < 1 || src.size() > 2) { + return; + } + Location un = str2loc(src.get(0)); + Location deux = str2loc(src.get(1)); + if (un.getX() >= deux.getX()) { + _max.setX(un.getX()); + _min.setX(deux.getX()); + } else { + _max.setX(deux.getX()); + _min.setX(un.getX()); + } + if (un.getY() >= deux.getY()) { + _max.setY(un.getY()); + _min.setY(deux.getY()); + } else { + _max.setY(deux.getY()); + _min.setY(un.getY()); + } + if (un.getZ() >= deux.getZ()) { + _max.setZ(un.getZ()); + _min.setZ(deux.getZ()); + } else { + _max.setZ(deux.getZ()); + _min.setZ(un.getZ()); + } + } + + public Location getMin() { + return _min; + } + + public Location getMax() { + return _max; + } + + public Boolean isInArea(Location loc) { + if (loc == null) { + return false; + } + if (loc.getX() > _max.getX() || _min.getX() > loc.getX()) { + return false; + } + if (loc.getY() > _max.getY() || _min.getY() > loc.getY()) { + return false; + } + return !(loc.getZ() > _max.getZ() || _min.getZ() > loc.getZ()); + } + + public Boolean isInLimit(Location loc, int range) { + if (loc == null) { + return false; + } + if (loc.getX() > _max.getX() - (double)range || _min.getX() + (double)range > loc.getX()) { + return true; + } + return loc.getZ() > _max.getZ() - (double)range || _min.getZ() + (double)range > loc.getZ(); + } + + public List ToString() { + ArrayList result = new ArrayList<>(); + result.add(loc2str(_min)); + result.add(loc2str(_max)); + return result; + } + + private Location str2loc(String loc) { + if (loc == null) { + return null; + } + Location res = null; + String[] loca = loc.split(", "); + res = new Location(Bukkit.getServer().getWorld(loca[0]), Double.parseDouble(loca[1]), Double.parseDouble(loca[2]), Double.parseDouble(loca[3]), Float.parseFloat(loca[4]), Float.parseFloat(loca[5])); + return res; + } + + private String loc2str(Location loc) { + return loc.getWorld().getName() + ", " + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ", " + loc.getYaw() + ", " + loc.getPitch(); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/Config.java b/src/com/Geekpower14/Quake/Utils/Config.java new file mode 100644 index 0000000..841fa91 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/Config.java @@ -0,0 +1,268 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.configuration.ConfigurationSection + * org.bukkit.configuration.file.YamlConfiguration + * org.bukkit.configuration.file.YamlConfigurationOptions + */ +package com.Geekpower14.Quake.Utils; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; + +public class Config { + private YamlConfiguration _cfg = new YamlConfiguration(); + private File _configFile; + private Map _booleans; + private Map _ints; + private Map _doubles; + private Map _strings; + + public Config(File configFile) { + _configFile = configFile; + _booleans = new HashMap<>(); + _ints = new HashMap<>(); + _doubles = new HashMap<>(); + _strings = new HashMap<>(); + } + + public void createDefaults() { + _cfg.options().indent(4); + ACFG[] arraCFG = ACFG.values(); + int n = arraCFG.length; + int n2 = 0; + while (n2 < n) { + ACFG cfg = arraCFG[n2]; + _cfg.addDefault(cfg.getNode(), cfg.getValue()); + ++n2; + } + save(); + } + + public boolean load() { + try { + _cfg.load(_configFile); + reloadMaps(); + return true; + } + catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public void reloadMaps() { + for (String s : _cfg.getKeys(true)) { + Object object = _cfg.get(s); + if (object instanceof Boolean) { + _booleans.put(s, (Boolean)object); + continue; + } + if (object instanceof Integer) { + _ints.put(s, (Integer)object); + continue; + } + if (object instanceof Double) { + _doubles.put(s, (Double)object); + continue; + } + if (!(object instanceof String)) continue; + _strings.put(s, (String)object); + } + } + + public boolean save() { + try { + _cfg.save(_configFile); + return true; + } + catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean delete() { + return _configFile.delete(); + } + + public void setHeader(String header) { + _cfg.options().header(header); + } + + public YamlConfiguration getYamlConfiguration() { + return _cfg; + } + + public Object getUnsafe(String string) { + return _cfg.get(string); + } + + public boolean getBoolean(ACFG cfg) { + return getBoolean(cfg, (Boolean)cfg.getValue()); + } + + private boolean getBoolean(ACFG cfg, boolean def) { + String path = cfg.getNode(); + Boolean result = _booleans.get(path); + return result == null ? def : result; + } + + public int getInt(ACFG cfg) { + return getInt(cfg, (Integer)cfg.getValue()); + } + + public int getInt(ACFG cfg, int def) { + String path = cfg.getNode(); + Integer result = _ints.get(path); + return result == null ? def : result; + } + + public double getDouble(ACFG cfg) { + return getDouble(cfg, (Double)cfg.getValue()); + } + + public double getDouble(ACFG cfg, double def) { + String path = cfg.getNode(); + Double result = _doubles.get(path); + return result == null ? def : result; + } + + public String getString(ACFG cfg) { + return getString(cfg, (String)cfg.getValue()); + } + + public String getString(ACFG cfg, String def) { + String path = cfg.getNode(); + String result = _strings.get(path); + return result == null ? def : result; + } + + public Set getKeys(String path) { + if (_cfg.get(path) == null) { + return null; + } + ConfigurationSection section = _cfg.getConfigurationSection(path); + return section.getKeys(false); + } + + public List getStringList(String path, List def) { + if (_cfg.get(path) == null) { + return def == null ? new LinkedList() : def; + } + return _cfg.getStringList(path); + } + + public void setManually(String path, Object value) { + if (value instanceof Boolean) { + _booleans.put(path, (Boolean)value); + } else if (value instanceof Integer) { + _ints.put(path, (Integer)value); + } else if (value instanceof Double) { + _doubles.put(path, (Double)value); + } else if (value instanceof String) { + _strings.put(path, (String)value); + } + if (value == null) { + _booleans.remove(value); + _ints.remove(value); + _doubles.remove(value); + _strings.remove(value); + } + _cfg.set(path, value); + } + + public void set(ACFG cfg, Object value) { + setManually(cfg.getNode(), value); + } + + public static enum ACFG { + Z("configversion", "v0.9.0.0"), + CHAT_COLORNICK("chat.colorNick", true), + CHAT_DEFAULTTEAM("chat.defaultTeam", false), + MODULES_WORLDEDIT_AUTOLOAD("modules.worldedit.autoload", false), + MODULES_WORLDEDIT_AUTOSAVE("modules.worldedit.autosave", false); + + private String _node; + private Object _value; + private String _type; + + public static ACFG getByNode(String node) { + ACFG[] arraCFG = ACFG.values(); + int n = arraCFG.length; + int n2 = 0; + while (n2 < n) { + ACFG m = arraCFG[n2]; + if (m.getNode().equals(node)) { + return m; + } + ++n2; + } + return null; + } + + private ACFG(String node, String value) { + _node = node; + _value = value; + _type = "string"; + } + + private ACFG(String node, Boolean value) { + _node = node; + _value = value; + _type = "boolean"; + } + + private ACFG(String node, Integer value) { + _node = node; + _value = value; + _type = "int"; + } + + private ACFG(String node, Double value) { + _node = node; + _value = value; + _type = "double"; + } + + private ACFG(String node, List value) { + _node = node; + _value = value; + _type = "list"; + } + + public String getNode() { + return _node; + } + + public void setNode(String value) { + _node = value; + } + + @Override + public String toString() { + return String.valueOf(_value); + } + + public Object getValue() { + return _value; + } + + public static ACFG[] getValues() { + return ACFG.values(); + } + + public String getType() { + return _type; + } + } + +} + diff --git a/src/com/Geekpower14/Quake/Utils/FireworkEffectPlayer.java b/src/com/Geekpower14/Quake/Utils/FireworkEffectPlayer.java new file mode 100644 index 0000000..76e43bf --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/FireworkEffectPlayer.java @@ -0,0 +1,84 @@ +package com.Geekpower14.Quake.Utils; + +import com.Geekpower14.Quake.Quake; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Firework; +import org.bukkit.inventory.meta.FireworkMeta; + +public class FireworkEffectPlayer { + public Quake _plugin; + private Method _world_getHandle = null; + private Method _nms_world_broadcastEntityEffect = null; + private Method _firework_getHandle = null; + + public FireworkEffectPlayer(Quake pl) { + _plugin = pl; + } + + public void playFirework(World world, Location loc, FireworkEffect fe) throws Exception { + Firework fw = (Firework)world.spawn(loc, (Class)Firework.class); + Object nms_world = null; + Object nms_firework = null; + if (_world_getHandle == null) { + _world_getHandle = FireworkEffectPlayer.getMethod(world.getClass(), "getHandle"); + _firework_getHandle = FireworkEffectPlayer.getMethod(fw.getClass(), "getHandle"); + } + + nms_world = _world_getHandle.invoke(world, (Object[])null); + nms_firework = _firework_getHandle.invoke(fw, (Object[])null); + if (_nms_world_broadcastEntityEffect == null) { + _nms_world_broadcastEntityEffect = FireworkEffectPlayer.getMethod(nms_world.getClass(), "broadcastEntityEffect"); + } + FireworkMeta data = fw.getFireworkMeta(); + data.clearEffects(); + data.setPower(1); + data.addEffect(fe); + fw.setFireworkMeta(data); + _nms_world_broadcastEntityEffect.invoke(nms_world, nms_firework, (byte)17); + fw.remove(); + } + + public void playFirework(World world, Location loc) throws Exception { + Firework fw = (Firework)world.spawn(loc, (Class)Firework.class); + if (_world_getHandle == null) { + _world_getHandle = FireworkEffectPlayer.getMethod(world.getClass(), "getHandle"); + _firework_getHandle = FireworkEffectPlayer.getMethod(fw.getClass(), "getHandle"); + } + + Object nms_world = _world_getHandle.invoke(world, (Object[])null); + Object nms_firework = _firework_getHandle.invoke(fw, (Object[])null); + if (_nms_world_broadcastEntityEffect == null) { + _nms_world_broadcastEntityEffect = FireworkEffectPlayer.getMethod(nms_world.getClass(), "broadcastEntityEffect"); + } + + FireworkMeta data = fw.getFireworkMeta(); + data.clearEffects(); + data.setPower(1); + fw.setFireworkMeta(data); + try { + _nms_world_broadcastEntityEffect.invoke(nms_world, nms_firework, (byte)17); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + fw.remove(); + } + + private static Method getMethod(Class cl, String method) { + Method[] arrmethod = cl.getMethods(); + int n = arrmethod.length; + int n2 = 0; + while (n2 < n) { + Method m = arrmethod[n2]; + if (m.getName().equals(method)) { + return m; + } + ++n2; + } + return null; + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/IconMenu.java b/src/com/Geekpower14/Quake/Utils/IconMenu.java new file mode 100644 index 0000000..409d07c --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/IconMenu.java @@ -0,0 +1,221 @@ +package com.Geekpower14.Quake.Utils; + +import java.util.Arrays; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.Plugin; + +public class IconMenu implements Listener { + private String _name = null; + private int _size; + private OptionClickEventHandler _handler; + private Plugin _plugin; + private String[] _optionNames; + private String[] _optionRegs; + private ItemStack[] _optionIcons; + private boolean _autodestroy = true; + + public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) { + _name = name; + _size = size; + _handler = handler; + _plugin = plugin; + _optionNames = new String[size]; + _optionRegs = new String[size]; + _optionIcons = new ItemStack[size]; + _autodestroy = true; + } + + public IconMenu setOption(int position, ItemStack icon, String name, String reg, String[] info) { + _optionRegs[position] = reg; + _optionNames[position] = name; + _optionIcons[position] = setItemNameAndLore(icon, name, info); + return this; + } + + public IconMenu setOption(int position, ItemStack icon, String reg) { + _optionRegs[position] = reg; + _optionNames[position] = _name; + _optionIcons[position] = icon; + return this; + } + + public void open(Player player) { + Inventory inventory = Bukkit.createInventory((InventoryHolder)player, (int)_size, (String)_name); + int i = 0; + while (i < _optionIcons.length) { + if (_optionIcons[i] != null) { + inventory.setItem(i, _optionIcons[i]); + } + ++i; + } + player.openInventory(inventory); + } + + public void reopen(Player p) { + int i = 0; + while (i < _optionIcons.length) { + if (_optionIcons[i] != null) { + p.getOpenInventory().setItem(i, _optionIcons[i]); + } + ++i; + } + } + + public void setAutoDestroy(boolean autodestroy) { + _autodestroy = autodestroy; + } + + public void destroy() { + try { + _handler = null; + _plugin = null; + _optionNames = null; + _optionIcons = null; + _optionRegs = null; + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void onInventoryClose(InventoryCloseEvent event) { + if (!event.getInventory().getName().equals(_name)) { + return; + } + if(_autodestroy) { + destroy(); + } + } + + public void onInventoryClick(InventoryClickEvent event) { + if (!event.getInventory().getName().equals(_name)) { + return; + } + event.setCancelled(true); + int slot = event.getRawSlot(); + if (slot >= 0 && slot < _size && _optionNames[slot] != null) { + if (_optionRegs[slot].equals("") || _optionRegs[slot].trim().equals("-cancel-")) { + event.setCancelled(true); + return; + } + Plugin plugin = _plugin; + OptionClickEvent e = new OptionClickEvent((Player)event.getWhoClicked(), slot, _optionRegs[slot], this, event.isRightClick(), event.isLeftClick(), event.isShiftClick()); + _handler.onOptionClick(e); + if (e.willClose()) { + final Player p = (Player)event.getWhoClicked(); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + p.closeInventory(); + } + }, 1); + } + if (e.willDestroy()) { + destroy(); + } + event.setCancelled(true); + } + } + + private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) { + ItemMeta im = item.getItemMeta(); + if (im == null) { + return item; + } + if(!name.equals("")) { + im.setDisplayName(name); + } + if (lore != null) { + im.setLore(Arrays.asList(lore)); + } + item.setItemMeta(im); + return item; + } + + public int size() { + return _size; + } + + public class OptionClickEvent { + private final Player _player; + private final int _position; + private final String _name; + private boolean _close; + private boolean _destroy; + private final IconMenu _im; + private final boolean _rightClick; + private final boolean _leftClick; + private boolean _Shift; + + public OptionClickEvent(Player player, int position, String name, IconMenu im, boolean rightClick, boolean leftClick, boolean Shift) { + _player = player; + _position = position; + _name = name; + _close = true; + _destroy = false; + _im = im; + _rightClick = rightClick; + _leftClick = leftClick; + _Shift = Shift; + } + + public Player getPlayer() { + return _player; + } + + public int getPosition() { + return _position; + } + + public String getName() { + return _name; + } + + public IconMenu getIconMenu() { + return _im; + } + + public boolean willClose() { + return _close; + } + + public boolean willDestroy() { + return _destroy; + } + + public void setWillClose(boolean close) { + _close = close; + } + + public void setWillDestroy(boolean destroy) { + _destroy = destroy; + } + + public boolean isRightClick() { + return _rightClick; + } + + public boolean isLeftClick() { + return _leftClick; + } + + public boolean isShiftClick() { + return _Shift; + } + } + + public static interface OptionClickEventHandler { + public void onOptionClick(OptionClickEvent var1); + } + +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/BookSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/BookSerialization.java new file mode 100644 index 0000000..44904ce --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/BookSerialization.java @@ -0,0 +1,172 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class BookSerialization { + protected BookSerialization() { + } + + public static BookMeta getBookMeta(String json) { + try { + return BookSerialization.getBookMeta(new JSONObject(json)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static BookMeta getBookMeta(JSONObject json) { + try { + ItemStack dummyItems = new ItemStack(Material.WRITTEN_BOOK, 1); + BookMeta meta = (BookMeta)dummyItems.getItemMeta(); + String title = null; + String author = null; + JSONArray pages = null; + if (json.has("title")) { + title = json.getString("title"); + } + if (json.has("author")) { + author = json.getString("author"); + } + if (json.has("pages")) { + pages = json.getJSONArray("pages"); + } + if (title != null) { + meta.setTitle(title); + } + if (author != null) { + meta.setAuthor(author); + } + if (pages != null) { + String[] allPages = new String[pages.length()]; + for (int i = 0; i < pages.length(); ++i) { + String page = pages.getString(i); + if (page.isEmpty() || page == null) { + page = ""; + } + allPages[i] = page; + } + meta.setPages(allPages); + } + return meta; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static JSONObject serializeBookMeta(BookMeta meta) { + try { + JSONObject root = new JSONObject(); + if (meta.hasTitle()) { + root.put("title", meta.getTitle()); + } + if (meta.hasAuthor()) { + root.put("author", meta.getAuthor()); + } + if (meta.hasPages()) { + String[] pages = meta.getPages().toArray(new String[0]); + root.put("pages", pages); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeBookMetaAsString(BookMeta meta) { + return BookSerialization.serializeBookMetaAsString(meta, false); + } + + public static String serializeBookMetaAsString(BookMeta meta, boolean pretty) { + return BookSerialization.serializeBookMetaAsString(meta, pretty, 5); + } + + public static String serializeBookMetaAsString(BookMeta meta, boolean pretty, int indentFactor) { + try { + if (pretty) { + return BookSerialization.serializeBookMeta(meta).toString(indentFactor); + } + return BookSerialization.serializeBookMeta(meta).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static EnchantmentStorageMeta getEnchantedBookMeta(String json) { + try { + return BookSerialization.getEnchantedBookMeta(new JSONObject(json)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static EnchantmentStorageMeta getEnchantedBookMeta(JSONObject json) { + try { + ItemStack dummyItems = new ItemStack(Material.ENCHANTED_BOOK, 1); + EnchantmentStorageMeta meta = (EnchantmentStorageMeta)dummyItems.getItemMeta(); + if (json.has("enchantments")) { + Map enchants = EnchantmentSerialization.getEnchantments(json.getString("enchantments")); + for (Enchantment e : enchants.keySet()) { + meta.addStoredEnchant(e, enchants.get((Object)e).intValue(), true); + } + } + return meta; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static JSONObject serializeEnchantedBookMeta(EnchantmentStorageMeta meta) { + try { + JSONObject root = new JSONObject(); + String enchants = EnchantmentSerialization.serializeEnchantments(meta.getStoredEnchants()); + root.put("enchantments", enchants); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta) { + return BookSerialization.serializeEnchantedBookMetaAsString(meta, false); + } + + public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta, boolean pretty) { + return BookSerialization.serializeEnchantedBookMetaAsString(meta, pretty, 5); + } + + public static String serializeEnchantedBookMetaAsString(EnchantmentStorageMeta meta, boolean pretty, int indentFactor) { + try { + if (pretty) { + return BookSerialization.serializeEnchantedBookMeta(meta).toString(indentFactor); + } + return BookSerialization.serializeEnchantedBookMeta(meta).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/ColorSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/ColorSerialization.java new file mode 100644 index 0000000..df86d53 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/ColorSerialization.java @@ -0,0 +1,78 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Color; +import org.json.JSONException; +import org.json.JSONObject; + +public class ColorSerialization { + protected ColorSerialization() { + } + + public static JSONObject serializeColor(Color color) { + try { + JSONObject root = new JSONObject(); + root.put("red", color.getRed()); + root.put("green", color.getGreen()); + root.put("blue", color.getBlue()); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Color getColor(String color) { + try { + return ColorSerialization.getColor(new JSONObject(color)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Color getColor(JSONObject color) { + try { + int r = 0; + int g = 0; + int b = 0; + if (color.has("red")) { + r = color.getInt("red"); + } + if (color.has("green")) { + g = color.getInt("green"); + } + if (color.has("blue")) { + b = color.getInt("blue"); + } + return Color.fromRGB((int)r, (int)g, (int)b); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeColorAsString(Color color) { + return ColorSerialization.serializeColorAsString(color, false); + } + + public static String serializeColorAsString(Color color, boolean pretty) { + return ColorSerialization.serializeColorAsString(color, pretty, 5); + } + + public static String serializeColorAsString(Color color, boolean pretty, int indentFactor) { + try { + if (pretty) { + return ColorSerialization.serializeColor(color).toString(indentFactor); + } + return ColorSerialization.serializeColor(color).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/EnchantmentSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/EnchantmentSerialization.java new file mode 100644 index 0000000..d259cd3 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/EnchantmentSerialization.java @@ -0,0 +1,78 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.util.HashMap; +import java.util.Map; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +public class EnchantmentSerialization { + protected EnchantmentSerialization() { + } + + public static String serializeEnchantments(Map enchantments) { + String serialized = ""; + for (Enchantment e : enchantments.keySet()) { + serialized = serialized + e.getId() + ":" + enchantments.get((Object)e) + ";"; + } + return serialized; + } + + public static Map getEnchantments(String serializedEnchants) { + HashMap enchantments = new HashMap(); + if (serializedEnchants.isEmpty()) { + return enchantments; + } + String[] enchants = serializedEnchants.split(";"); + for (int i = 0; i < enchants.length; ++i) { + String[] ench = enchants[i].split(":"); + if (ench.length < 2) { + throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): split must at least have a length of 2"); + } + if (!Util.isNum(ench[0])) { + throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): id is not an integer"); + } + if (!Util.isNum(ench[1])) { + throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): level is not an integer"); + } + int id = Integer.parseInt(ench[0]); + int level = Integer.parseInt(ench[1]); + Enchantment e = Enchantment.getById((int)id); + if (e == null) { + throw new IllegalArgumentException(serializedEnchants + " - Enchantment " + i + " (" + enchants[i] + "): no Enchantment with id of " + id); + } + enchantments.put(e, level); + } + return enchantments; + } + + public static Map getEnchantsFromOldFormat(String oldFormat) { + HashMap enchants = new HashMap(); + if (oldFormat.length() == 0) { + return enchants; + } + String nums = "" + Long.parseLong(oldFormat, 32) + ""; + System.out.println(nums); + for (int i = 0; i < nums.length(); i += 3) { + int enchantId = Integer.parseInt(nums.substring(i, i + 2)); + int enchantLevel = Integer.parseInt("" + nums.charAt(i + 2) + ""); + Enchantment ench = Enchantment.getById((int)enchantId); + enchants.put(ench, enchantLevel); + } + return enchants; + } + + public static String convert(String oldFormat) { + Map enchants = EnchantmentSerialization.getEnchantsFromOldFormat(oldFormat); + return EnchantmentSerialization.serializeEnchantments(enchants); + } + + public static Map convertAndGetEnchantments(String oldFormat) { + String newFormat = EnchantmentSerialization.convert(oldFormat); + return EnchantmentSerialization.getEnchantments(newFormat); + } + + public static void addEnchantments(String code, ItemStack items) { + items.addUnsafeEnchantments(EnchantmentSerialization.getEnchantments(code)); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkEffectSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkEffectSerialization.java new file mode 100644 index 0000000..a89a63a --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkEffectSerialization.java @@ -0,0 +1,79 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class FireworkEffectSerialization { + protected FireworkEffectSerialization() { + } + + public static FireworkEffect getFireworkEffect(String json) { + return FireworkEffectSerialization.getFireworkEffect(json); + } + + public static FireworkEffect getFireworkEffect(JSONObject json) { + try { + FireworkEffect.Builder builder = FireworkEffect.builder(); + JSONArray colors = json.getJSONArray("colors"); + for (int j = 0; j < colors.length(); ++j) { + builder.withColor(ColorSerialization.getColor(colors.getJSONObject(j))); + } + JSONArray fadeColors = json.getJSONArray("fade-colors"); + for (int j2 = 0; j2 < fadeColors.length(); ++j2) { + builder.withFade(ColorSerialization.getColor(colors.getJSONObject(j2))); + } + if (json.getBoolean("flicker")) { + builder.withFlicker(); + } + if (json.getBoolean("trail")) { + builder.withTrail(); + } + builder.with(FireworkEffect.Type.valueOf((String)json.getString("type"))); + return builder.build(); + } + catch (IllegalArgumentException | JSONException e) { + e.printStackTrace(); + } + return null; + } + + public static JSONObject serializeFireworkEffect(FireworkEffect effect) { + try { + JSONObject root = new JSONObject(); + JSONArray colors = new JSONArray(); + for (Object c : effect.getColors()) { + colors.put(ColorSerialization.serializeColor((Color)c)); + } + root.put("colors", colors); + JSONArray fadeColors = new JSONArray(); + for (Color c2 : effect.getFadeColors()) { + fadeColors.put(ColorSerialization.serializeColor(c2)); + } + root.put("fade-colors", fadeColors); + root.put("flicker", effect.hasFlicker()); + root.put("trail", effect.hasTrail()); + root.put("type", effect.getType().name()); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeFireworkEffectAsString(FireworkEffect effect) { + return FireworkEffectSerialization.serializeFireworkEffectAsString(effect, false); + } + + public static String serializeFireworkEffectAsString(FireworkEffect effect, boolean pretty) { + return FireworkEffectSerialization.serializeFireworkEffectAsString(effect, false, 5); + } + + public static String serializeFireworkEffectAsString(FireworkEffect effect, boolean pretty, int indentFactor) { + return Serializer.toString(FireworkEffectSerialization.serializeFireworkEffect(effect), pretty, indentFactor); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkSerialization.java new file mode 100644 index 0000000..fb23be4 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/FireworkSerialization.java @@ -0,0 +1,67 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.FireworkMeta; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class FireworkSerialization { + protected FireworkSerialization() { + } + + public static FireworkMeta getFireworkMeta(String json) { + return FireworkSerialization.getFireworkMeta(json); + } + + public static FireworkMeta getFireworkMeta(JSONObject json) { + try { + FireworkMeta dummy = (FireworkMeta)new ItemStack(Material.FIREWORK).getItemMeta(); + dummy.setPower(json.optInt("power", 1)); + JSONArray effects = json.getJSONArray("effects"); + for (int i = 0; i < effects.length(); ++i) { + JSONObject effectDto = effects.getJSONObject(i); + FireworkEffect effect = FireworkEffectSerialization.getFireworkEffect(effectDto); + if (effect == null) continue; + dummy.addEffect(effect); + } + return dummy; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static JSONObject serializeFireworkMeta(FireworkMeta meta) { + try { + JSONObject root = new JSONObject(); + root.put("power", meta.getPower()); + JSONArray effects = new JSONArray(); + for (FireworkEffect e : meta.getEffects()) { + effects.put(FireworkEffectSerialization.serializeFireworkEffect(e)); + } + root.put("effects", effects); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeFireworkMetaAsString(FireworkMeta meta) { + return FireworkSerialization.serializeFireworkMetaAsString(meta, false); + } + + public static String serializeFireworkMetaAsString(FireworkMeta meta, boolean pretty) { + return FireworkSerialization.serializeFireworkMetaAsString(meta, false, 5); + } + + public static String serializeFireworkMetaAsString(FireworkMeta meta, boolean pretty, int indentFactor) { + return Serializer.toString(FireworkSerialization.serializeFireworkMeta(meta), pretty, indentFactor); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/HorseSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/HorseSerialization.java new file mode 100644 index 0000000..63b89f5 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/HorseSerialization.java @@ -0,0 +1,101 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Location; +import org.bukkit.entity.Horse; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.Inventory; +import org.json.JSONException; +import org.json.JSONObject; + +public class HorseSerialization { + protected HorseSerialization() { + } + + public static JSONObject serializeHorse(Horse horse) { + try { + JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)horse); + if (HorseSerialization.shouldSerialize("color")) { + root.put("color", horse.getColor().name()); + } + if (HorseSerialization.shouldSerialize("inventory")) { + root.put("inventory", InventorySerialization.serializeInventory((Inventory)horse.getInventory())); + } + if (HorseSerialization.shouldSerialize("jump-strength")) { + root.put("jump-strength", horse.getJumpStrength()); + } + if (HorseSerialization.shouldSerialize("style")) { + root.put("style", (Object)horse.getStyle()); + } + if (HorseSerialization.shouldSerialize("variant")) { + root.put("variant", (Object)horse.getVariant()); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeHorseAsString(Horse horse) { + return HorseSerialization.serializeHorseAsString(horse, false); + } + + public static String serializeHorseAsString(Horse horse, boolean pretty) { + return HorseSerialization.serializeHorseAsString(horse, pretty, 5); + } + + public static String serializeHorseAsString(Horse horse, boolean pretty, int indentFactor) { + try { + if (pretty) { + return HorseSerialization.serializeHorse(horse).toString(indentFactor); + } + return HorseSerialization.serializeHorse(horse).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Horse spawnHorse(Location location, String stats) { + try { + return HorseSerialization.spawnHorse(location, new JSONObject(stats)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Horse spawnHorse(Location location, JSONObject stats) { + try { + Horse horse = (Horse)LivingEntitySerialization.spawnEntity(location, stats); + if (stats.has("color")) { + horse.setColor(Horse.Color.valueOf((String)stats.getString("color"))); + } + if (stats.has("jump-strength")) { + horse.setCustomName(stats.getString("name")); + } + if (stats.has("style")) { + horse.setStyle(Horse.Style.valueOf((String)stats.getString("style"))); + } + if (stats.has("inventory")) { + PotionEffectSerialization.addPotionEffects(stats.getString("potion-effects"), (LivingEntity)horse); + } + if (stats.has("variant")) { + horse.setVariant(Horse.Variant.valueOf((String)stats.getString("variant"))); + } + return horse; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("horse." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/InventorySerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/InventorySerialization.java new file mode 100644 index 0000000..f60c18b --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/InventorySerialization.java @@ -0,0 +1,216 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class InventorySerialization { + protected InventorySerialization() { + } + + public static JSONArray serializeInventory(Inventory inv) { + JSONArray inventory = new JSONArray(); + for (int i = 0; i < inv.getSize(); ++i) { + JSONObject values = SingleItemSerialization.serializeItemInInventory(inv.getItem(i), i); + if (values == null) + continue; + inventory.put(values); + } + return inventory; + } + + public static JSONObject serializePlayerInventory(PlayerInventory inv) { + try { + JSONObject root = new JSONObject(); + JSONArray inventory = InventorySerialization.serializeInventory((Inventory)inv); + JSONArray armor = InventorySerialization.serializeInventory(inv.getArmorContents()); + root.put("inventory", inventory); + root.put("armor", armor); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializePlayerInventoryAsString(PlayerInventory inv) { + return InventorySerialization.serializePlayerInventoryAsString(inv, false); + } + + public static String serializePlayerInventoryAsString(PlayerInventory inv, boolean pretty) { + return InventorySerialization.serializePlayerInventoryAsString(inv, pretty, 5); + } + + public static String serializePlayerInventoryAsString(PlayerInventory inv, boolean pretty, int indentFactor) { + try { + if (pretty) { + return InventorySerialization.serializePlayerInventory(inv).toString(indentFactor); + } + return InventorySerialization.serializePlayerInventory(inv).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeInventoryAsString(Inventory inventory) { + return InventorySerialization.serializeInventoryAsString(inventory, false); + } + + public static String serializeInventoryAsString(Inventory inventory, boolean pretty) { + return InventorySerialization.serializeInventoryAsString(inventory, pretty, 5); + } + + public static String serializeInventoryAsString(Inventory inventory, boolean pretty, int indentFactor) { + try { + if (pretty) { + return InventorySerialization.serializeInventory(inventory).toString(indentFactor); + } + return InventorySerialization.serializeInventory(inventory).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeInventoryAsString(ItemStack[] contents) { + return InventorySerialization.serializeInventoryAsString(contents, false); + } + + public static String serializeInventoryAsString(ItemStack[] contents, boolean pretty) { + return InventorySerialization.serializeInventoryAsString(contents, pretty, 5); + } + + public static String serializeInventoryAsString(ItemStack[] contents, boolean pretty, int indentFactor) { + try { + if (pretty) { + return InventorySerialization.serializeInventory(contents).toString(indentFactor); + } + return InventorySerialization.serializeInventory(contents).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static JSONArray serializeInventory(ItemStack[] contents) { + JSONArray inventory = new JSONArray(); + for (int i = 0; i < contents.length; ++i) { + JSONObject values = SingleItemSerialization.serializeItemInInventory(contents[i], i); + if (values == null) continue; + inventory.put(values); + } + return inventory; + } + + public static ItemStack[] getInventory(String json, int size) { + try { + return InventorySerialization.getInventory(new JSONArray(json), size); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static ItemStack[] getInventory(JSONArray inv, int size) { + try { + ItemStack[] contents = new ItemStack[size]; + for (int i = 0; i < inv.length(); ++i) { + ItemStack stuff; + JSONObject item = inv.getJSONObject(i); + int index = item.getInt("index"); + if (index > size) { + throw new IllegalArgumentException("index found is greator than expected size (" + index + ">" + size + ")"); + } + if (index > contents.length || index < 0) { + throw new IllegalArgumentException("Item " + i + " - Slot " + index + " does not exist in this inventory"); + } + contents[index] = stuff = SingleItemSerialization.getItem(item); + } + return contents; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static ItemStack[] getInventory(File jsonFile, int size) { + String source = ""; + try { + Scanner x = new Scanner(jsonFile); + while (x.hasNextLine()) { + source = source + x.nextLine() + "\n"; + } + x.close(); + return InventorySerialization.getInventory(source, size); + } + catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static void setInventory(InventoryHolder holder, String inv) { + InventorySerialization.setInventory(holder.getInventory(), inv); + } + + public static void setInventory(InventoryHolder holder, JSONArray inv) { + InventorySerialization.setInventory(holder.getInventory(), inv); + } + + public static void setInventory(Inventory inventory, String inv) { + try { + InventorySerialization.setInventory(inventory, new JSONArray(inv)); + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void setInventory(Inventory inventory, JSONArray inv) { + ItemStack[] items = InventorySerialization.getInventory(inv, inventory.getSize()); + inventory.clear(); + for (int i = 0; i < items.length; ++i) { + ItemStack item = items[i]; + if (item == null) continue; + inventory.setItem(i, item); + } + } + + public static void setPlayerInventory(Player player, String inv) { + try { + InventorySerialization.setPlayerInventory(player, new JSONObject(inv)); + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void setPlayerInventory(Player player, JSONObject inv) { + try { + PlayerInventory inventory = player.getInventory(); + ItemStack[] armor = InventorySerialization.getInventory(inv.getJSONArray("armor"), 4); + inventory.clear(); + inventory.setArmorContents(armor); + InventorySerialization.setInventory((InventoryHolder)player, inv.getJSONArray("inventory")); + } + catch (JSONException e) { + e.printStackTrace(); + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/LeatherArmorSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/LeatherArmorSerialization.java new file mode 100644 index 0000000..7e82532 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/LeatherArmorSerialization.java @@ -0,0 +1,71 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.json.JSONException; +import org.json.JSONObject; + +public class LeatherArmorSerialization { + protected LeatherArmorSerialization() { + } + + public static JSONObject serializeArmor(LeatherArmorMeta meta) { + try { + JSONObject root = new JSONObject(); + root.put("color", ColorSerialization.serializeColor(meta.getColor())); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeArmorAsString(LeatherArmorMeta meta) { + return LeatherArmorSerialization.serializeArmorAsString(meta, false); + } + + public static String serializeArmorAsString(LeatherArmorMeta meta, boolean pretty) { + return LeatherArmorSerialization.serializeArmorAsString(meta, pretty, 5); + } + + public static String serializeArmorAsString(LeatherArmorMeta meta, boolean pretty, int indentFactor) { + try { + if (pretty) { + return LeatherArmorSerialization.serializeArmor(meta).toString(indentFactor); + } + return LeatherArmorSerialization.serializeArmor(meta).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static LeatherArmorMeta getLeatherArmorMeta(String json) { + try { + return LeatherArmorSerialization.getLeatherArmorMeta(new JSONObject(json)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static LeatherArmorMeta getLeatherArmorMeta(JSONObject json) { + try { + ItemStack dummyItems = new ItemStack(Material.LEATHER_HELMET, 1); + LeatherArmorMeta meta = (LeatherArmorMeta)dummyItems.getItemMeta(); + if (json.has("color")) { + meta.setColor(ColorSerialization.getColor(json.getJSONObject("color"))); + } + return meta; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/LivingEntitySerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/LivingEntitySerialization.java new file mode 100644 index 0000000..d80420b --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/LivingEntitySerialization.java @@ -0,0 +1,104 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Location; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.json.JSONException; +import org.json.JSONObject; + +public class LivingEntitySerialization { + protected LivingEntitySerialization() { + } + + public static JSONObject serializeEntity(LivingEntity entity) { + if (entity instanceof Player) { + return PlayerSerialization.serializePlayer((Player)entity); + } + try { + JSONObject root = new JSONObject(); + if (LivingEntitySerialization.shouldSerialize("age") && entity instanceof Ageable) { + root.put("age", ((Ageable)entity).getAge()); + } + if (LivingEntitySerialization.shouldSerialize("health")) { + root.put("health", entity.getHealth()); + } + if (LivingEntitySerialization.shouldSerialize("name")) { + root.put("name", entity.getCustomName()); + } + if (LivingEntitySerialization.shouldSerialize("potion-effects")) { + root.put("potion-effects", PotionEffectSerialization.serializeEffects(entity.getActivePotionEffects())); + } + root.put("type", entity.getType().getTypeId()); + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeEntityAsString(LivingEntity entity) { + return LivingEntitySerialization.serializeEntityAsString(entity, false); + } + + public static String serializeEntityAsString(LivingEntity entity, boolean pretty) { + return LivingEntitySerialization.serializeEntityAsString(entity, pretty, 5); + } + + public static String serializeEntityAsString(LivingEntity entity, boolean pretty, int indentFactor) { + try { + if (pretty) { + return LivingEntitySerialization.serializeEntity(entity).toString(indentFactor); + } + return LivingEntitySerialization.serializeEntity(entity).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static LivingEntity spawnEntity(Location location, String stats) { + try { + return LivingEntitySerialization.spawnEntity(location, new JSONObject(stats)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static LivingEntity spawnEntity(Location location, JSONObject stats) { + try { + if (!stats.has("type")) { + throw new IllegalArgumentException("The type of the entity cannot be determined"); + } + LivingEntity entity = (LivingEntity)location.getWorld().spawnEntity(location, EntityType.fromId((int)stats.getInt("type"))); + if (stats.has("age") && entity instanceof Ageable) { + ((Ageable)entity).setAge(stats.getInt("age")); + } + if (stats.has("health")) { + entity.setHealth(stats.getDouble("health")); + } + if (stats.has("name")) { + entity.setCustomName(stats.getString("name")); + } + if (stats.has("potion-effects")) { + // empty if block + } + PotionEffectSerialization.addPotionEffects(stats.getString("potion-effects"), entity); + return entity; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("living-entity." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/OcelotSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/OcelotSerialization.java new file mode 100644 index 0000000..ce55912 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/OcelotSerialization.java @@ -0,0 +1,76 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Ocelot; +import org.json.JSONException; +import org.json.JSONObject; + +public class OcelotSerialization { + protected OcelotSerialization() { + } + + public static JSONObject serializeOcelot(Ocelot ocelot) { + try { + JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)ocelot); + if (OcelotSerialization.shouldSerialize("type")) { + root.put("type", ocelot.getCatType().name()); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeOcelotAsString(Ocelot ocelot) { + return OcelotSerialization.serializeOcelotAsString(ocelot, false); + } + + public static String serializeOcelotAsString(Ocelot ocelot, boolean pretty) { + return OcelotSerialization.serializeOcelotAsString(ocelot, pretty, 5); + } + + public static String serializeOcelotAsString(Ocelot ocelot, boolean pretty, int indentFactor) { + try { + if (pretty) { + return OcelotSerialization.serializeOcelot(ocelot).toString(indentFactor); + } + return OcelotSerialization.serializeOcelot(ocelot).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Ocelot spawnOcelot(Location location, String stats) { + try { + return OcelotSerialization.spawnOcelot(location, new JSONObject(stats)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Ocelot spawnOcelot(Location location, JSONObject stats) { + try { + Ocelot ocelot = (Ocelot)LivingEntitySerialization.spawnEntity(location, stats); + if (stats.has("type")) { + ocelot.setCatType(Ocelot.Type.valueOf((String)stats.getString("type"))); + } + return ocelot; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("ocelot." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerSerialization.java new file mode 100644 index 0000000..0a56e21 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerSerialization.java @@ -0,0 +1,82 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.entity.Player; +import org.json.JSONException; +import org.json.JSONObject; + +public class PlayerSerialization { + protected PlayerSerialization() { + } + + public static JSONObject serializePlayer(Player player) { + try { + JSONObject root = new JSONObject(); + if (SerializationConfig.getShouldSerialize("player-ender-chest")) { + root.put("ender-chest", InventorySerialization.serializeInventory(player.getEnderChest())); + } + if (SerializationConfig.getShouldSerialize("player.inventory")) { + root.put("inventory", InventorySerialization.serializePlayerInventory(player.getInventory())); + } + if (SerializationConfig.getShouldSerialize("player.stats")) { + root.put("stats", PlayerStatsSerialization.serializePlayerStats(player)); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializePlayerAsString(Player player) { + return PlayerSerialization.serializePlayerAsString(player, false); + } + + public static String serializePlayerAsString(Player player, boolean pretty) { + return PlayerSerialization.serializePlayerAsString(player, pretty, 5); + } + + public static String serializePlayerAsString(Player player, boolean pretty, int indentFactor) { + try { + if (pretty) { + return PlayerSerialization.serializePlayer(player).toString(indentFactor); + } + return PlayerSerialization.serializePlayer(player).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static void setPlayer(String meta, Player player) { + try { + PlayerSerialization.setPlayer(new JSONObject(meta), player); + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void setPlayer(JSONObject meta, Player player) { + try { + if (meta.has("ender-chest")) { + InventorySerialization.setInventory(player.getEnderChest(), meta.getJSONArray("ender-chest")); + } + if (meta.has("inventory")) { + InventorySerialization.setPlayerInventory(player, meta.getJSONObject("inventory")); + } + if (meta.has("stats")) { + PlayerStatsSerialization.applyPlayerStats(player, meta.getJSONObject("stats")); + } + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("player." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerStatsSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerStatsSerialization.java new file mode 100644 index 0000000..a7cf82d --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/PlayerStatsSerialization.java @@ -0,0 +1,132 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.json.JSONException; +import org.json.JSONObject; + +public class PlayerStatsSerialization { + protected PlayerStatsSerialization() { + } + + public static JSONObject serializePlayerStats(Player player) { + try { + JSONObject root = new JSONObject(); + if (PlayerStatsSerialization.shouldSerialize("can-fly")) { + root.put("can-fly", player.getAllowFlight()); + } + if (PlayerStatsSerialization.shouldSerialize("display-name")) { + root.put("display-name", player.getDisplayName()); + } + if (PlayerStatsSerialization.shouldSerialize("exhaustion")) { + root.put("exhaustion", player.getExhaustion()); + } + if (PlayerStatsSerialization.shouldSerialize("exp")) { + root.put("exp", player.getExp()); + } + if (PlayerStatsSerialization.shouldSerialize("flying")) { + root.put("flying", player.isFlying()); + } + if (PlayerStatsSerialization.shouldSerialize("food")) { + root.put("food", player.getFoodLevel()); + } + if (PlayerStatsSerialization.shouldSerialize("gamemode")) { + root.put("gamemode", player.getGameMode().ordinal()); + } + if (PlayerStatsSerialization.shouldSerialize("health")) { + root.put("health", player.getHealthScale()); + } + if (PlayerStatsSerialization.shouldSerialize("level")) { + root.put("level", player.getLevel()); + } + if (PlayerStatsSerialization.shouldSerialize("potion-effects")) { + root.put("potion-effects", PotionEffectSerialization.serializeEffects(player.getActivePotionEffects())); + } + if (PlayerStatsSerialization.shouldSerialize("saturation")) { + root.put("saturation", player.getSaturation()); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializePlayerStatsAsString(Player player) { + return PlayerStatsSerialization.serializePlayerStatsAsString(player, false); + } + + public static String serializePlayerStatsAsString(Player player, boolean pretty) { + return PlayerStatsSerialization.serializePlayerStatsAsString(player, pretty, 5); + } + + public static String serializePlayerStatsAsString(Player player, boolean pretty, int indentFactor) { + try { + if (pretty) { + return PlayerStatsSerialization.serializePlayerStats(player).toString(indentFactor); + } + return PlayerStatsSerialization.serializePlayerStats(player).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static void applyPlayerStats(Player player, String stats) { + try { + PlayerStatsSerialization.applyPlayerStats(player, new JSONObject(stats)); + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void applyPlayerStats(Player player, JSONObject stats) { + try { + if (stats.has("can-fly")) { + player.setAllowFlight(stats.getBoolean("can-fly")); + } + if (stats.has("display-name")) { + player.setDisplayName(stats.getString("display-name")); + } + if (stats.has("exhaustion")) { + player.setExhaustion((float)stats.getDouble("exhaustion")); + } + if (stats.has("exp")) { + player.setExp((float)stats.getDouble("exp")); + } + if (stats.has("flying")) { + player.setFlying(stats.getBoolean("flying")); + } + if (stats.has("food")) { + player.setFoodLevel(stats.getInt("food")); + } + if (stats.has("health")) { + player.setHealth(stats.getDouble("health")); + } + if (stats.has("gamemode")) { + player.setGameMode(GameMode.getByValue((int)stats.getInt("gamemode"))); + } + if (stats.has("level")) { + player.setLevel(stats.getInt("level")); + } + if (stats.has("potion-effects")) { + PotionEffectSerialization.setPotionEffects(stats.getString("potion-effects"), (LivingEntity)player); + } + if (stats.has("saturation")) { + player.setSaturation((float)stats.getDouble("saturation")); + } + } + catch (JSONException e) { + e.printStackTrace(); + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("player-stats." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/PotionEffectSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/PotionEffectSerialization.java new file mode 100644 index 0000000..6e44a0c --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/PotionEffectSerialization.java @@ -0,0 +1,65 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.util.ArrayList; +import java.util.Collection; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class PotionEffectSerialization { + protected PotionEffectSerialization() { + } + + public static String serializeEffects(Collection effects) { + String serialized = ""; + for (PotionEffect e : effects) { + serialized = serialized + e.getType().getId() + ":" + e.getDuration() + ":" + e.getAmplifier() + ";"; + } + return serialized; + } + + public static Collection getPotionEffects(String serializedEffects) { + ArrayList effects = new ArrayList(); + if (serializedEffects.isEmpty()) { + return effects; + } + String[] effs = serializedEffects.split(";"); + for (int i = 0; i < effs.length; ++i) { + String[] effect = effs[i].split(":"); + if (effect.length < 3) { + throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): split must at least have a length of 3"); + } + if (!Util.isNum(effect[0])) { + throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): id is not an integer"); + } + if (!Util.isNum(effect[1])) { + throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): duration is not an integer"); + } + if (!Util.isNum(effect[2])) { + throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): amplifier is not an integer"); + } + int id = Integer.parseInt(effect[0]); + int duration = Integer.parseInt(effect[1]); + int amplifier = Integer.parseInt(effect[2]); + PotionEffectType effectType = PotionEffectType.getById((int)id); + if (effectType == null) { + throw new IllegalArgumentException(serializedEffects + " - PotionEffect " + i + " (" + effs[i] + "): no PotionEffectType with id of " + id); + } + PotionEffect e = new PotionEffect(effectType, duration, amplifier); + effects.add(e); + } + return effects; + } + + public static void addPotionEffects(String code, LivingEntity entity) { + entity.addPotionEffects(PotionEffectSerialization.getPotionEffects(code)); + } + + public static void setPotionEffects(String code, LivingEntity entity) { + for (PotionEffect effect : entity.getActivePotionEffects()) { + entity.removePotionEffect(effect.getType()); + } + PotionEffectSerialization.addPotionEffects(code, entity); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/SerializationConfig.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/SerializationConfig.java new file mode 100644 index 0000000..6cc9a9e --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/SerializationConfig.java @@ -0,0 +1,85 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.io.File; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; + +public class SerializationConfig { + private static YamlConfiguration config; + + protected SerializationConfig() { + } + + public static File getDataFolder() { + File pluginFolder = Bukkit.getServer().getPluginManager().getPlugins()[0].getDataFolder(); + return new File(pluginFolder.getParentFile() + "/TacoSerialization/"); + } + + public static File getConfigFile() { + return new File(SerializationConfig.getDataFolder() + "/config.yml"); + } + + public static void reload() { + config = YamlConfiguration.loadConfiguration((File)SerializationConfig.getConfigFile()); + SerializationConfig.setDefaults(); + SerializationConfig.save(); + Logger.getLogger("Minecraft").log(Level.INFO, "[TacoSerialization] Config reloaded"); + } + + public static void save() { + try { + config.save(SerializationConfig.getConfigFile()); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + private static void setDefaults() { + SerializationConfig.addDefault("horse.color", true); + SerializationConfig.addDefault("horse.inventory", true); + SerializationConfig.addDefault("horse.jump-stength", true); + SerializationConfig.addDefault("horse.style", true); + SerializationConfig.addDefault("horse.variant", true); + SerializationConfig.addDefault("living-entity.age", true); + SerializationConfig.addDefault("living-entity.health", true); + SerializationConfig.addDefault("living-entity.name", true); + SerializationConfig.addDefault("living-entity.potion-effects", true); + SerializationConfig.addDefault("ocelot.type", true); + SerializationConfig.addDefault("player.ender-chest", true); + SerializationConfig.addDefault("player.inventory", true); + SerializationConfig.addDefault("player.stats", true); + SerializationConfig.addDefault("player-stats.can-fly", true); + SerializationConfig.addDefault("player-stats.display-name", true); + SerializationConfig.addDefault("player-stats.exhaustion", true); + SerializationConfig.addDefault("player-stats.exp", true); + SerializationConfig.addDefault("player-stats.food", true); + SerializationConfig.addDefault("player-stats.flying", true); + SerializationConfig.addDefault("player-stats.health", true); + SerializationConfig.addDefault("player-stats.level", true); + SerializationConfig.addDefault("player-stats.potion-effects", true); + SerializationConfig.addDefault("player-stats.saturation", true); + SerializationConfig.addDefault("wolf.collar-color", true); + } + + public static void addDefault(String path, Object value) { + if (!SerializationConfig.getConfig().contains(path)) { + SerializationConfig.getConfig().set(path, value); + } + } + + private static YamlConfiguration getConfig() { + if (config == null) { + SerializationConfig.reload(); + } + return config; + } + + public static boolean getShouldSerialize(String path) { + return SerializationConfig.getConfig().getBoolean(path); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/Serializer.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/Serializer.java new file mode 100644 index 0000000..88c0730 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/Serializer.java @@ -0,0 +1,55 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.Scanner; +import org.json.JSONException; +import org.json.JSONObject; + +public class Serializer { + public static String toString(JSONObject object) { + return Serializer.toString(object, true); + } + + public static String toString(JSONObject object, boolean pretty) { + return Serializer.toString(object, pretty, 5); + } + + public static String toString(JSONObject object, boolean pretty, int tabSize) { + try { + if (pretty) { + return object.toString(tabSize); + } + return object.toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static JSONObject getObjectFromFile(File file) throws FileNotFoundException, JSONException { + return Serializer.getObjectFromStream(new FileInputStream(file)); + } + + public static JSONObject getObjectFromStream(InputStream stream) throws JSONException { + return new JSONObject(Serializer.getStringFromStream(stream)); + } + + public static String getStringFromFile(File file) throws FileNotFoundException { + return Serializer.getStringFromStream(new FileInputStream(file)); + } + + public static String getStringFromStream(InputStream stream) { + Scanner x = new Scanner(stream); + String str = ""; + while (x.hasNextLine()) { + str = str + x.nextLine() + "\n"; + } + x.close(); + return str.trim(); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/SingleItemSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/SingleItemSerialization.java new file mode 100644 index 0000000..3e9ee1a --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/SingleItemSerialization.java @@ -0,0 +1,245 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import java.util.ArrayList; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.Repairable; +import org.bukkit.inventory.meta.SkullMeta; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class SingleItemSerialization { + protected SingleItemSerialization() { + } + + public static JSONObject serializeItemInInventory(ItemStack items, int index) { + return SingleItemSerialization.serializeItems(items, true, index); + } + + public static JSONObject serializeItem(ItemStack items) { + return SingleItemSerialization.serializeItems(items, false, 0); + } + + private static JSONObject serializeItems(ItemStack items, boolean useIndex, int index) { + try { + JSONObject values = new JSONObject(); + if (items == null) { + return null; + } + int amount = items.getAmount(); + short data = items.getDurability(); + boolean hasMeta = items.hasItemMeta(); + String name = null; + String enchants = null; + String[] lore = null; + int repairPenalty = 0; + Material mat = items.getType(); + JSONObject bookMeta = null; + JSONObject armorMeta = null; + JSONObject skullMeta = null; + JSONObject fwMeta = null; + if (mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) { + bookMeta = BookSerialization.serializeBookMeta((BookMeta)items.getItemMeta()); + } else if (mat == Material.ENCHANTED_BOOK) { + bookMeta = BookSerialization.serializeEnchantedBookMeta((EnchantmentStorageMeta)items.getItemMeta()); + } else if (Util.isLeatherArmor(mat)) { + armorMeta = LeatherArmorSerialization.serializeArmor((LeatherArmorMeta)items.getItemMeta()); + } else if (mat == Material.SKULL_ITEM) { + skullMeta = SkullSerialization.serializeSkull((SkullMeta)items.getItemMeta()); + } else if (mat == Material.FIREWORK) { + fwMeta = FireworkSerialization.serializeFireworkMeta((FireworkMeta)items.getItemMeta()); + } + if (hasMeta) { + Repairable rep; + ItemMeta meta = items.getItemMeta(); + if (meta.hasDisplayName()) { + name = meta.getDisplayName(); + } + if (meta.hasLore()) { + lore = meta.getLore().toArray(new String[0]); + } + if (meta.hasEnchants()) { + enchants = EnchantmentSerialization.serializeEnchantments(meta.getEnchants()); + } + if (meta instanceof Repairable && (rep = (Repairable)meta).hasRepairCost()) { + repairPenalty = rep.getRepairCost(); + } + } + values.put("id", mat.name()); + values.put("amount", amount); + values.put("data", data); + if (useIndex) { + values.put("index", index); + } + if (name != null) { + values.put("name", name); + } + if (enchants != null) { + values.put("enchantments", enchants); + } + if (lore != null) { + values.put("lore", lore); + } + if (repairPenalty != 0) { + values.put("repairPenalty", repairPenalty); + } + if (bookMeta != null && bookMeta.length() > 0) { + values.put("book-meta", bookMeta); + } + if (armorMeta != null && armorMeta.length() > 0) { + values.put("armor-meta", armorMeta); + } + if (skullMeta != null && skullMeta.length() > 0) { + values.put("skull-meta", skullMeta); + } + if (fwMeta != null && fwMeta.length() > 0) { + values.put("firework-meta", fwMeta); + } + return values; + } catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static ItemStack getItem(String item) { + return SingleItemSerialization.getItem(item, 0); + } + + public static ItemStack getItem(String item, int index) { + try { + return SingleItemSerialization.getItem(new JSONObject(item), index); + } catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static ItemStack getItem(JSONObject item) { + return SingleItemSerialization.getItem(item, 0); + } + + public static ItemStack getItem(JSONObject item, int index) { + try{ + String id = item.getString("id"); + int amount = item.getInt("amount"); + int data = item.getInt("data"); + String name = null; + Map enchants = null; + ArrayList lore = null; + int repairPenalty = 0; + if (item.has("name")) { + name = item.getString("name"); + } + if (item.has("enchantments")) { + enchants = EnchantmentSerialization.getEnchantments(item.getString("enchantments")); + } + if (item.has("lore")) { + JSONArray l = item.getJSONArray("lore"); + lore = new ArrayList<>(); + for (int j = 0; j < l.length(); ++j) { + lore.add(l.getString(j)); + } + } + if (item.has("repairPenalty")) { + repairPenalty = item.getInt("repairPenalty"); + } + if (!Util.isNum(id) && Material.getMaterial((String)id) == null) { + throw new IllegalArgumentException("Item " + index + " - No Material found with Material of " + id); + } + if (Util.isNum(id) && Material.getMaterial((int)Integer.parseInt(id)) == null) { + throw new IllegalArgumentException("Item " + index + " - No Material found with id of " + id); + } + Material mat = Util.isNum(id) ? Material.getMaterial((int)Integer.parseInt(id)) : Material.getMaterial((String)id); + ItemStack stuff = new ItemStack(mat, amount, (short)data); + ItemMeta meta; + if ((mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) && item.has("book-meta")) { + meta = BookSerialization.getBookMeta(item.getJSONObject("book-meta")); + stuff.setItemMeta((ItemMeta)meta); + } else if (mat == Material.ENCHANTED_BOOK && item.has("book-meta")) { + meta = BookSerialization.getEnchantedBookMeta(item.getJSONObject("book-meta")); + stuff.setItemMeta((ItemMeta)meta); + } else if (Util.isLeatherArmor(mat) && item.has("armor-meta")) { + meta = LeatherArmorSerialization.getLeatherArmorMeta(item.getJSONObject("armor-meta")); + stuff.setItemMeta((ItemMeta)meta); + } else if (mat == Material.SKULL_ITEM && item.has("skull-meta")) { + meta = SkullSerialization.getSkullMeta(item.getJSONObject("skull-meta")); + stuff.setItemMeta((ItemMeta)meta); + } else if (mat == Material.FIREWORK && item.has("firework-meta")) { + meta = FireworkSerialization.getFireworkMeta(item.getJSONObject("firework-meta")); + stuff.setItemMeta((ItemMeta)meta); + } + meta = stuff.getItemMeta(); + if (name != null) { + meta.setDisplayName(name); + } + if (lore != null) { + meta.setLore(lore); + } + stuff.setItemMeta((ItemMeta)meta); + if (repairPenalty != 0) { + Repairable rep = (Repairable)meta; + rep.setRepairCost(repairPenalty); + stuff.setItemMeta((ItemMeta)rep); + } + if(enchants != null) { + stuff.addUnsafeEnchantments(enchants); + } + return stuff; + } catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeItemInInventoryAsString(ItemStack items, int index) { + return SingleItemSerialization.serializeItemInInventoryAsString(items, index, false); + } + + public static String serializeItemInInventoryAsString(ItemStack items, int index, boolean pretty) { + return SingleItemSerialization.serializeItemInInventoryAsString(items, index, pretty, 5); + } + + public static String serializeItemInInventoryAsString(ItemStack items, int index, boolean pretty, int indentFactor) { + try { + if (pretty) { + return SingleItemSerialization.serializeItemInInventory(items, index).toString(indentFactor); + } + return SingleItemSerialization.serializeItemInInventory(items, index).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeItemAsString(ItemStack items) { + return SingleItemSerialization.serializeItemAsString(items, false); + } + + public static String serializeItemAsString(ItemStack items, boolean pretty) { + return SingleItemSerialization.serializeItemAsString(items, pretty, 5); + } + + public static String serializeItemAsString(ItemStack items, boolean pretty, int indentFactor) { + try { + if (pretty) { + return SingleItemSerialization.serializeItem(items).toString(indentFactor); + } + return SingleItemSerialization.serializeItem(items).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/SkullSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/SkullSerialization.java new file mode 100644 index 0000000..a62b7b7 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/SkullSerialization.java @@ -0,0 +1,73 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.json.JSONException; +import org.json.JSONObject; + +public class SkullSerialization { + protected SkullSerialization() { + } + + public static JSONObject serializeSkull(SkullMeta meta) { + try { + JSONObject root = new JSONObject(); + if (meta.hasOwner()) { + root.put("owner", meta.getOwner()); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeSkullAsString(SkullMeta meta) { + return SkullSerialization.serializeSkullAsString(meta, false); + } + + public static String serializeSkullAsString(SkullMeta meta, boolean pretty) { + return SkullSerialization.serializeSkullAsString(meta, pretty, 5); + } + + public static String serializeSkullAsString(SkullMeta meta, boolean pretty, int indentFactor) { + try { + if (pretty) { + return SkullSerialization.serializeSkull(meta).toString(indentFactor); + } + return SkullSerialization.serializeSkull(meta).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static SkullMeta getSkullMeta(String meta) { + try { + return SkullSerialization.getSkullMeta(new JSONObject(meta)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static SkullMeta getSkullMeta(JSONObject meta) { + try { + ItemStack dummyItems = new ItemStack(Material.SKULL_ITEM); + SkullMeta dummyMeta = (SkullMeta)dummyItems.getItemMeta(); + if (meta.has("owner")) { + dummyMeta.setOwner(meta.getString("owner")); + } + return dummyMeta; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/Util.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/Util.java new file mode 100644 index 0000000..f825db4 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/Util.java @@ -0,0 +1,30 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Material; + +public class Util { + protected Util() { + } + + public static boolean isNum(String s) { + try { + Integer.parseInt(s); + return true; + } + catch (NumberFormatException e) { + return false; + } + } + + public static boolean isLeatherArmor(Material material) { + return material == Material.LEATHER_HELMET || material == Material.LEATHER_CHESTPLATE || material == Material.LEATHER_LEGGINGS || material == Material.LEATHER_BOOTS; + } + + public static boolean keyFound(String[] array, String key) { + for (String s : array) { + if (!s.equalsIgnoreCase(key)) continue; + } + return false; + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/InvSerialization/WolfSerialization.java b/src/com/Geekpower14/Quake/Utils/InvSerialization/WolfSerialization.java new file mode 100644 index 0000000..a3feff9 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/InvSerialization/WolfSerialization.java @@ -0,0 +1,78 @@ +package com.Geekpower14.Quake.Utils.InvSerialization; + +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Wolf; +import org.json.JSONException; +import org.json.JSONObject; + +public class WolfSerialization { + protected WolfSerialization() { + } + + public static JSONObject serializeWolf(Wolf wolf) { + try { + JSONObject root = LivingEntitySerialization.serializeEntity((LivingEntity)wolf); + if (WolfSerialization.shouldSerialize("collar-color")) { + root.put("collar-color", ColorSerialization.serializeColor(wolf.getCollarColor().getColor())); + } + return root; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static String serializeWolfAsString(Wolf wolf) { + return WolfSerialization.serializeWolfAsString(wolf, false); + } + + public static String serializeWolfAsString(Wolf wolf, boolean pretty) { + return WolfSerialization.serializeWolfAsString(wolf, pretty, 5); + } + + public static String serializeWolfAsString(Wolf wolf, boolean pretty, int indentFactor) { + try { + if (pretty) { + return WolfSerialization.serializeWolf(wolf).toString(indentFactor); + } + return WolfSerialization.serializeWolf(wolf).toString(); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Wolf spawnWolf(Location location, String stats) { + try { + return WolfSerialization.spawnWolf(location, new JSONObject(stats)); + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static Wolf spawnWolf(Location location, JSONObject stats) { + try { + Wolf wolf = (Wolf)LivingEntitySerialization.spawnEntity(location, stats); + if (stats.has("collar-color")) { + wolf.setCollarColor(DyeColor.getByColor((Color)ColorSerialization.getColor(stats.getString("collar-color")))); + } + return wolf; + } + catch (JSONException e) { + e.printStackTrace(); + return null; + } + } + + public static boolean shouldSerialize(String key) { + return SerializationConfig.getShouldSerialize("wolf." + key); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/ParticleEffects.java b/src/com/Geekpower14/Quake/Utils/ParticleEffects.java new file mode 100644 index 0000000..1251ca2 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/ParticleEffects.java @@ -0,0 +1,661 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.Geekpower14.Quake.Utils; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +//1.8.8 +//import net.minecraft.server.v1_9_R1.EnumParticle; +//1.9.2 +//import net.minecraft.server.v1_9_R1.EnumParticle; +//1.9.4 +//import net.minecraft.server.v1_9_R2.EnumParticle; +//1.10 +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public enum ParticleEffects { + HUGE_EXPLOSION("hugeexplosion", "EXPLOSION_HUGE"), + LARGE_EXPLODE("largeexplode", "EXPLOSION_LARGE"), + BUBBLE("bubble", "WATER_BUBBLE"), + SUSPEND("suspended", "SUSPENDED"), + DEPTH_SUSPEND("depthsuspend", "SUSPENDED_DEPTH"), + MAGIC_CRIT("magicCrit", "CRIT_MAGIC"), + MOB_SPELL("mobSpell", "SPELL_MOB", true), + MOB_SPELL_AMBIENT("mobSpellAmbient", "SPELL_MOB_AMBIENT"), + INSTANT_SPELL("instantSpell", "SPELL_INSTANT"), + WITCH_MAGIC("witchMagic", "SPELL_WITCH"), + EXPLODE("explode", "EXPLOSION_NORMAL"), + SPLASH("splash", "WATER_SPLASH"), + LARGE_SMOKE("largesmoke", "SMOKE_LARGE"), + RED_DUST("reddust", "REDSTONE", true), + SNOWBALL_POOF("snowballpoof", "SNOWBALL"), + ANGRY_VILLAGER("angryVillager", "VILLAGER_ANGRY"), + HAPPY_VILLAGER("happyVillager", "VILLAGER_HAPPY"), + EXPLOSION_NORMAL(EXPLODE.getName()), + EXPLOSION_LARGE(LARGE_EXPLODE.getName()), + EXPLOSION_HUGE(HUGE_EXPLOSION.getName()), + FIREWORKS_SPARK("fireworksSpark"), + WATER_BUBBLE(BUBBLE.getName()), + WATER_SPLASH(SPLASH.getName()), + WATER_WAKE("wake"), + SUSPENDED(SUSPEND.getName()), + SUSPENDED_DEPTH(DEPTH_SUSPEND.getName()), + CRIT("crit"), + CRIT_MAGIC(MAGIC_CRIT.getName()), + SMOKE_NORMAL("smoke"), + SMOKE_LARGE(LARGE_SMOKE.getName()), + SPELL("spell"), + SPELL_INSTANT(INSTANT_SPELL.getName()), + SPELL_MOB(MOB_SPELL.getName(), true), + SPELL_MOB_AMBIENT(MOB_SPELL_AMBIENT.getName()), + SPELL_WITCH(WITCH_MAGIC.getName()), + DRIP_WATER("dripWater"), + DRIP_LAVA("dripLava"), + VILLAGER_ANGRY(ANGRY_VILLAGER.getName()), + VILLAGER_HAPPY(HAPPY_VILLAGER.getName()), + TOWN_AURA("townaura"), NOTE("note", true), + PORTAL("portal"), + ENCHANTMENT_TABLE("enchantmenttable"), + FLAME("flame"), + LAVA("lava"), + FOOTSTEP("footstep"), + CLOUD("cloud"), + REDSTONE("reddust", true), + SNOWBALL("snowballpoof"), + SNOW_SHOVEL("snowshovel"), + SLIME("slime"), + HEART("heart"), + BARRIER("barrier"), + ITEM_CRACK("iconcrack_"), + BLOCK_CRACK("blockcrack_"), + BLOCK_DUST("blockdust_"), + WATER_DROP("droplet"), + ITEM_TAKE("take"), + MOB_APPEARANCE("mobappearance"); + + private final String _particleName; + private final String _enumValue; + private final boolean _hasColor; + private static Class _nmsPacketPlayOutParticle; + private static Class _nmsEnumParticle; + private static int _particleRange; + private static Class _nmsPlayerConnection; + private static Class _nmsEntityPlayer; + private static Class _ioNettyChannel; + private static Method _nmsNetworkGetVersion; + private static Field _nmsFieldPlayerConnection; + private static Field _nmsFieldNetworkManager; + private static Field _nmsFieldNetworkManagerI; + private static Field _nmsFieldNetworkManagerM; + + private ParticleEffects(String particleName, String enumValue, boolean hasColor) { + _particleName = particleName; + _enumValue = enumValue; + _hasColor = hasColor; + } + + private ParticleEffects(String particleName, String enumValue) { + _particleName = particleName; + _enumValue = enumValue; + _hasColor = false; + } + + private ParticleEffects(String particleName) { + _particleName = particleName; + _enumValue = null; + _hasColor = false; + } + + private ParticleEffects(String particleName, boolean hasColor) { + _particleName = particleName; + _enumValue = null; + _hasColor = hasColor; + } + + public String getName() { + return _particleName; + } + + public boolean hasColor() { + return _hasColor; + } + + public static void setRange(int range) { + if(range < 0) { + throw new IllegalArgumentException("Range must be positive!"); + } + _particleRange = range; + } + + public static int getRange() { + return _particleRange; + } + + private void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, int... extra) throws Exception { + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, false, extra); + } + + private void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force, int... extra) throws Exception { + if((!force) && (!isPlayerInRange(player, location))) { + return; + } + //if(ReflectionUtilities.getVersion().contains("v1_8")) { + try { + if(_nmsEnumParticle == null) + _nmsEnumParticle = ReflectionUtilities.getNMSClass("EnumParticle"); + if(this == BLOCK_CRACK) { + int id = 0; + int data = 0; + if (extra.length > 0) { + id = extra[0]; + } + if (extra.length > 1) { + data = extra[1]; + } + extra = new int[] { id, id | data << 12 }; + } + Object packet = _nmsPacketPlayOutParticle.getConstructor(new Class[] { _nmsEnumParticle, Boolean.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Integer.TYPE, int[].class }).newInstance(new Object[] { getEnum(_nmsEnumParticle.getName() + "." + (_enumValue != null ? _enumValue : name().toUpperCase())), true, (float)location.getX(), (float)location.getY(), (float)location.getZ(), offsetX, offsetY, offsetZ, speed, count, extra }); + Object handle = ReflectionUtilities.getHandle(player); + Object connection = ReflectionUtilities.getField(handle.getClass(), "playerConnection").get(handle); + ReflectionUtilities.getMethod(connection.getClass(), "sendPacket", new Class[0]).invoke(connection, new Object[] { packet }); + } catch (Exception e) { + throw e; + } + /*} else { + try { + if(_particleName == null) + _particleName = name().toLowerCase(); + + String name = _particleName; + if((this == BLOCK_CRACK) || (this == ITEM_CRACK) || (this == BLOCK_DUST)) { + int id = 0; + int data = 0; + if(extra.length > 0) + id = extra[0]; + + if(extra.length > 1) + data = extra[1]; + + name = name + id + "_" + data; + } + Object packet = _nmsPacketPlayOutParticle.getConstructor(new Class[] { String.class, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Integer.TYPE }).newInstance(new Object[] { name, (float)location.getX(), (float)location.getY(), (float)location.getZ(), offsetX, offsetY, offsetZ, speed, count}); + Object handle = ReflectionUtilities.getHandle(player); + Object connection = ReflectionUtilities.getField(handle.getClass(), "playerConnection").get(handle); + ReflectionUtilities.getMethod(connection.getClass(), "sendPacket", new Class[0]).invoke(connection, new Object[] { packet }); + } catch (Exception e) { + throw e; + } + }*/ + } + + public void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) throws Exception { + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[0]); + } + + public void sendToPlayer(Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception { + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, false); + } + + public void sendToPlayers(Collection players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception { + for(Player p : players) + sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count); + } + + public void sendToPlayers(Collection players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) throws Exception { + for(Player p : players) + sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, force); + } + + public void sendToPlayers(Player[] players, Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception { + for (Player p : players) + sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count); + } + + public void sendColor(Player p, Location location, org.bukkit.Color color) throws Exception { + if(!_hasColor) + return; + sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0); + } + + public void sendColor(Player p, Location location, org.bukkit.Color color, boolean force) throws Exception { + if(!_hasColor) + return; + sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0, force); + } + + @Deprecated + public void sendColor(Player p, Location location, java.awt.Color color) throws Exception { + if(!_hasColor) + return; + sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0); + } + + public void sendColor(Player p, Location location, java.awt.Color color, boolean force) throws Exception { + if(!_hasColor) + return; + sendToPlayer(p, location, getColor(color.getRed()), getColor(color.getGreen()), getColor(color.getBlue()), 1.0F, 0, force); + } + + @Deprecated + public void sendColor(Collection players, Location location, java.awt.Color color) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color); + } + + public void sendColor(Collection players, Location location, java.awt.Color color, boolean force) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color, force); + } + + public void sendColor(Collection players, Location location, org.bukkit.Color color) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color); + } + + @Deprecated + public void sendColor(Collection players, Location location, org.bukkit.Color color, boolean force) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color, force); + } + + @Deprecated + public void sendColor(Player[] players, Location location, org.bukkit.Color color) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color); + } + + @Deprecated + public void sendColor(Player[] players, Location location, java.awt.Color color) throws Exception { + if(!_hasColor) + return; + for(Player p : players) + sendColor(p, location, color); + } + + protected float getColor(float value) { + if(value <= 0.0F) + value = -1.0F; + return value / 255.0F; + } + + public static void sendPacket(Object packet, Player player) { + try { + Object nms_player = _nmsNetworkGetVersion.invoke(player, new Object[0]); + Object nms_connection = _nmsFieldPlayerConnection.get(nms_player); + _nmsNetworkGetVersion.invoke(nms_connection, packet); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + + @Deprecated + public void sendBlockCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_CRACK) { + throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!"); + } + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id, data }); + } + + public void sendBlockCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != BLOCK_CRACK) { + throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!"); + } + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id, data }); + } + + @Deprecated + public void sendBlockCrack(Collection players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_CRACK) { + throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!"); + } + for (Player p : players) { + sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count); + } + } + + public void sendBlockCrack(Collection players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != BLOCK_CRACK) { + throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!"); + } + for (Player p : players) { + sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count, force); + } + } + + @Deprecated + public void sendBlockCrack(Player[] players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_CRACK) { + throw new IllegalArgumentException("This method is only available for BLOCK_CRACK!"); + } + for (Player p : players) { + sendBlockCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count); + } + } + + @Deprecated + public void sendItemCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != ITEM_CRACK) { + throw new IllegalArgumentException("This method is only available for ITEM_CRACK!"); + } + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id, data }); + } + + public void sendItemCrack(Player player, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != ITEM_CRACK) { + throw new IllegalArgumentException("This method is only available for ITEM_CRACK!"); + } + sendToPlayer(player, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id, data }); + } + + @Deprecated + public void sendItemCrack(Collection players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != ITEM_CRACK) { + throw new IllegalArgumentException("This method is only available for ITEM_CRACK!"); + } + for (Player p : players) { + sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count); + } + } + + public void sendItemCrack(Collection players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != ITEM_CRACK) { + throw new IllegalArgumentException("This method is only available for ITEM_CRACK!"); + } + for (Player p : players) { + sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count, force); + } + } + + @Deprecated + public void sendItemCrack(Player[] players, Location location, int id, byte data, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != ITEM_CRACK) { + throw new IllegalArgumentException("This method is only available for ITEM_CRACK!"); + } + for (Player p : players) { + sendItemCrack(p, location, id, data, offsetX, offsetY, offsetZ, speed, count); + } + } + + @Deprecated + public void sendBlockDust(Player p, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_DUST) { + throw new IllegalArgumentException("This method is only available for BLOCK_DUST!"); + } + sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, new int[] { id }); + } + + public void sendBlockDust(Player p, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != BLOCK_DUST) { + throw new IllegalArgumentException("This method is only available for BLOCK_DUST!"); + } + sendToPlayer(p, location, offsetX, offsetY, offsetZ, speed, count, force, new int[] { id }); + } + + @Deprecated + public void sendBlockDust(Collection players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_DUST) { + throw new IllegalArgumentException("This method is only available for BLOCK_DUST!"); + } + for (Player p : players) { + sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count); + } + } + + public void sendBlockDust(Collection players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count, boolean force) + throws Exception + { + if (this != BLOCK_DUST) { + throw new IllegalArgumentException("This method is only available for BLOCK_DUST!"); + } + for (Player p : players) { + sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count, force); + } + } + + @Deprecated + public void sendBlockDust(Player[] players, Location location, int id, float offsetX, float offsetY, float offsetZ, float speed, int count) + throws Exception + { + if (this != BLOCK_DUST) { + throw new IllegalArgumentException("This method is only available for BLOCK_DUST!"); + } + for (Player p : players) { + sendBlockDust(p, location, id, offsetX, offsetY, offsetZ, speed, count); + } + } + + protected static int getVersion(Player p) + { + try + { + Object handle = ReflectionUtilities.getHandle(p); + Object connection = _nmsFieldPlayerConnection.get(handle); + Object network = _nmsFieldNetworkManager.get(connection); + Object channel; + if (ReflectionUtilities.getVersion().contains("1_7")) { + channel = _nmsFieldNetworkManagerM.get(network); + } else { + channel = _nmsFieldNetworkManagerI.get(network); + } + Object version = ReflectionUtilities.getVersion().contains("1_7") ? _nmsNetworkGetVersion.invoke(network, new Object[] { channel }) : Integer.valueOf(47); + return ((Integer)version).intValue(); + } + catch (Exception e) + { + e.printStackTrace(); + } + return 0; + } + + static + { + _nmsPacketPlayOutParticle = ReflectionUtilities.getNMSClass("PacketPlayOutWorldParticles"); + + _particleRange = 25; + + String ver = ReflectionUtilities.getVersion(); + try + { + _nmsPlayerConnection = ReflectionUtilities.getNMSClass("PlayerConnection"); + _nmsEntityPlayer = ReflectionUtilities.getNMSClass("EntityPlayer"); + _ioNettyChannel = ver.contains("1_7") ? Class.forName("net.minecraft.util.io.netty.channel.Channel") : Class.forName("io.netty.channel.Channel"); + + _nmsFieldPlayerConnection = ReflectionUtilities.getField(_nmsEntityPlayer, "playerConnection"); + _nmsFieldNetworkManager = ReflectionUtilities.getField(_nmsPlayerConnection, "networkManager"); + _nmsFieldNetworkManagerI = ReflectionUtilities.getField(_nmsFieldNetworkManager.getType(), "i"); + _nmsFieldNetworkManagerM = ReflectionUtilities.getField(_nmsFieldNetworkManager.getType(), "m"); + + _nmsNetworkGetVersion = ReflectionUtilities.getMethod(_nmsFieldNetworkManager.getType(), "getVersion", new Class[] { _ioNettyChannel }); + } + catch (Exception e) + { + System.err.println("[ParticleLIB] Error while loading: " + e.getMessage()); + e.printStackTrace(System.err); + Bukkit.getPluginManager().disablePlugin(Bukkit.getPluginManager().getPlugin("ParticleLIB")); + } + } + + private static Enum getEnum(String enumFullName) { + String[] x = enumFullName.split("\\.(?=[^\\.]+$)"); + if (x.length == 2) + { + String enumClassName = x[0]; + String enumName = x[1]; + try { + Class cl = (Class)Class.forName(enumClassName); + return Enum.valueOf(cl, enumName); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + return null; + } + + public static boolean isPlayerInRange(Player p, Location center) + { + double distance = 0.0D; + if (!p.getLocation().getWorld().equals(center.getWorld())) { + return false; + } + if ((distance = center.distanceSquared(p.getLocation())) > Double.MAX_VALUE) { + return false; + } + return distance < _particleRange * _particleRange; + } + + public static class ReflectionUtilities + { + public static void setValue(Object instance, String fieldName, Object value) + throws Exception + { + Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } + + public static Object getValue(Object instance, String fieldName) + throws Exception + { + Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(instance); + } + + public static String getVersion() + { + String name = Bukkit.getServer().getClass().getPackage().getName(); + String version = name.substring(name.lastIndexOf('.') + 1) + "."; + return version; + } + + public static Class getNMSClass(String className) + { + String fullName = "net.minecraft.server." + getVersion() + className; + Class clazz = null; + try + { + clazz = Class.forName(fullName); + } + catch (Exception e) + { + e.printStackTrace(); + } + return clazz; + } + + public static Class getOBCClass(String className) + { + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; + Class clazz = null; + try + { + clazz = Class.forName(fullName); + } + catch (Exception e) + { + e.printStackTrace(); + } + return clazz; + } + + public static Object getHandle(Object obj) + { + try + { + return getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj, new Object[0]); + } + catch (Exception e) + { + e.printStackTrace(); + } + return null; + } + + public static Field getField(Class clazz, String name) + { + try + { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field; + } + catch (Exception e) + { + e.printStackTrace(); + } + return null; + } + + public static Method getMethod(Class clazz, String name, Class... args) + { + for (Method m : clazz.getMethods()) { + if ((m.getName().equals(name)) && ((args.length == 0) || (ClassListEqual(args, m.getParameterTypes())))) + { + m.setAccessible(true); + return m; + } + } + return null; + } + + public static boolean ClassListEqual(Class[] l1, Class[] l2) + { + boolean equal = true; + if (l1.length != l2.length) { + return false; + } + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) + { + equal = false; + break; + } + } + return equal; + } + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/PlayerSerializer.java b/src/com/Geekpower14/Quake/Utils/PlayerSerializer.java new file mode 100644 index 0000000..97c69fe --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/PlayerSerializer.java @@ -0,0 +1,133 @@ +package com.Geekpower14.Quake.Utils; + +import com.Geekpower14.Quake.Quake; +import java.io.File; +import org.bukkit.GameMode; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class PlayerSerializer { + public static FileConfiguration PlayerToConfig(Player p) { + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)new File("")); + config.set("Name", p.getName()); + config.set("Health", p.getHealth()); + config.set("Food", p.getFoodLevel()); + config.set("Saturation", p.getSaturation()); + config.set("Exhaustion", p.getExhaustion()); + config.set("XP-Level", p.getLevel()); + config.set("Exp", p.getExp()); + config.set("GameMode", p.getGameMode().name()); + PlayerSerializer.ItemStackToConfig((FileConfiguration)config, "Armor", p.getInventory().getArmorContents()); + PlayerSerializer.ItemStackToConfig((FileConfiguration)config, "Inventaire", p.getInventory().getContents()); + return config; + } + + public static Boolean RetorePlayer(Player p) { + File f = new File(Quake.getPlugin().getDataFolder() + "/Save_Players/" + p.getName() + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration((File)f); + PlayerSerializer.ConfigToPlayer(p, (FileConfiguration)config); + f.delete(); + return true; + } + + public static Boolean ConfigToPlayer(Player p, FileConfiguration config) { + if (!config.contains("Name") || !config.getString("Name").equals(p.getName())) { + return false; + } + p.setHealth(config.getDouble("Health")); + p.setFoodLevel(config.getInt("Food")); + p.setSaturation((float)config.getDouble("Saturation")); + p.setExhaustion((float)config.getDouble("Exhaustion")); + p.setLevel(config.getInt("XP-Level")); + p.setExp((float)config.getDouble("Exp")); + try { + p.setGameMode(GameMode.valueOf(config.getString("GameMode"))); + } catch (Exception var2_2) { + // empty catch block + } + p.getInventory().clear(); + p.getInventory().setArmorContents(PlayerSerializer.ConfigToItemStack(config, "Armor")); + p.getInventory().setContents(PlayerSerializer.ConfigToItemStack(config, "Inventaire")); + try { + p.updateInventory(); + } catch (Exception var2_3) { + // empty catch block + } + return true; + } + + public static ItemStack[] ConfigToItemStack(FileConfiguration config, String path) { + int nb = config.getInt(String.valueOf(path) + ".Item-Nb"); + ItemStack[] item = new ItemStack[nb]; + int i = 0; + while (i < nb) { + item[i] = config.getItemStack(String.valueOf(path) + ".Item" + i); + ++i; + } + return item; + } + + public static FileConfiguration ItemStackToConfig(FileConfiguration config, String path, ItemStack[] items) { + if (config == null) { + return null; + } + config.set(String.valueOf(path) + ".Item-Nb", items.length); + int i = 0; + ItemStack[] arritemStack = items; + int n = arritemStack.length; + int n2 = 0; + while (n2 < n) { + ItemStack it = arritemStack[n2]; + config.set(String.valueOf(path) + ".Item" + i, it); + ++i; + ++n2; + } + return config; + } + + /*public static String InventoryToString(Inventory inv) { + if(inv instanceof PlayerInventory) + return InventorySerialization.serializePlayerInventoryAsString((PlayerInventory)inv); + else + return InventorySerialization.serializeInventoryAsString(inv); + }*/ + + /*public static Inventory StringToInventory(String invString) { + return InventorySerialization. + String[] serializedBlocks = invString.split(";"); + String invInfo = serializedBlocks[0]; + Inventory deserializedInventory = Bukkit.getServer().createInventory(null, Integer.valueOf(invInfo)); + return + int i = 1; + while (i < serializedBlocks.length) { + String[] serializedBlock = serializedBlocks[i].split("#"); + int stackPosition = Integer.valueOf(serializedBlock[0]); + if(stackPosition < deserializedInventory.getSize()) { + ItemStack is = null; + String[] arrstring = serializedBlock[1].split(":"); + int n = arrstring.length; + int n2 = 0; + while(n2 < n) { + String itemInfo = arrstring[n2]; + String[] itemAttribute = itemInfo.split("@"); + if (itemAttribute[0].equals("t")) { + is = new ItemStack(Material.getMaterial(itemAttribute[1])); + } else if (itemAttribute[0].equals("d") && is != null) { + is.setDurability(Short.valueOf(itemAttribute[1])); + } else if (itemAttribute[0].equals("a") && is != null) { + is.setAmount(Integer.valueOf(itemAttribute[1])); + } else if (itemAttribute[0].equals("e") && is != null) { + is.addEnchantment(Enchantment.getByName(itemAttribute[1]), Integer.valueOf(itemAttribute[2])); + } + n2++; + } + deserializedInventory.setItem(stackPosition, is); + } + i++; + } + return deserializedInventory; + }*/ +} + diff --git a/src/com/Geekpower14/Quake/Utils/Reflection.java b/src/com/Geekpower14/Quake/Utils/Reflection.java new file mode 100644 index 0000000..b3575de --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/Reflection.java @@ -0,0 +1,114 @@ +/* + * Decompiled with CFR 0_114. + * + * Could not load the following classes: + * org.bukkit.Bukkit + */ +package com.Geekpower14.Quake.Utils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.bukkit.Bukkit; + +public class Reflection { + public static String getVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + String version = String.valueOf(name.substring(name.lastIndexOf(46) + 1)) + "."; + return version; + } + + public static Class getNMSClass(String className) { + String fullName = "net.minecraft.server." + Reflection.getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } + catch (Exception e) { + e.printStackTrace(); + } + return clazz; + } + + public static Enum getNMSEnum(String className) { + String enumFullName = "net.minecraft.server." + Reflection.getVersion() + className; + String[] x = enumFullName.split("\\.(?=[^\\.]+$)"); + if (x.length == 2) { + String enumClassName = x[0]; + String enumName = x[1]; + try { + Class cl = Class.forName(enumClassName); + return Enum.valueOf(cl, enumName); + } + catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + return null; + } + + public static Class getOBCClass(String className) { + String fullName = "org.bukkit.craftbukkit." + Reflection.getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } + catch (Exception e) { + e.printStackTrace(); + } + return clazz; + } + + public static Object getHandle(Object obj) { + try { + return Reflection.getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj, new Object[0]); + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Field getField(Class clazz, String name) { + try { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Method getMethod(Class clazz, String name, Class ... args) { + Method[] arrmethod = clazz.getMethods(); + int n = arrmethod.length; + int n2 = 0; + while (n2 < n) { + Method m = arrmethod[n2]; + if (m.getName().equals(name) && (args.length == 0 || Reflection.ClassListEqual(args, m.getParameterTypes()))) { + m.setAccessible(true); + return m; + } + ++n2; + } + return null; + } + + public static boolean ClassListEqual(Class[] l1, Class[] l2) { + boolean equal = true; + if (l1.length != l2.length) { + return false; + } + int i = 0; + while (i < l1.length) { + if (l1[i] != l2[i]) { + equal = false; + break; + } + ++i; + } + return equal; + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/ScoreB.java b/src/com/Geekpower14/Quake/Utils/ScoreB.java new file mode 100644 index 0000000..facfecf --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/ScoreB.java @@ -0,0 +1,75 @@ +package com.Geekpower14.Quake.Utils; + +import com.Geekpower14.Quake.Quake; +import com.Geekpower14.Quake.Trans.Score; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Scoreboard; + +public final class ScoreB { + public Quake _plugin; + public int _Money = 0; + public int _Kills = 0; + public int _Deaths = 0; + public int _Shots = 0; + public int _Wins = 0; + public Player _player; + public Objective _objective; + public Scoreboard _board; + + public ScoreB(Quake pl, Player p) { + _plugin = pl; + _player = p; + _Kills = _plugin._eco.getScore(p, Score.Type.Kill); + _Deaths = _plugin._eco.getScore(p, Score.Type.Death); + _Shots = _plugin._eco.getScore(p, Score.Type.Shot); + _Wins = _plugin._eco.getScore(p, Score.Type.Win); + _Money = _plugin._eco.getPlayerMoney(p); + _board = Bukkit.getScoreboardManager().getNewScoreboard(); + _objective = _board.registerNewObjective("Score", "dummy"); + _objective.setDisplaySlot(DisplaySlot.SIDEBAR); + _objective.setDisplayName(_plugin._trad.get("ScoreBoard.name")); + _objective.getScore(_plugin._trad.get("Shop.Coins.name")).setScore(_Money); + _objective.getScore(_plugin._trad.get("ScoreBoard.Kills.name")).setScore(_Kills); + _objective.getScore(_plugin._trad.get("ScoreBoard.Deaths.name")).setScore(_Deaths); + _objective.getScore(_plugin._trad.get("ScoreBoard.Shots.name")).setScore(_Shots); + _objective.getScore(_plugin._trad.get("ScoreBoard.Wins.name")).setScore(_Wins); + if (isScoreWorld(_player.getWorld().getName())) { + _player.setScoreboard(_board); + } else if (!isScoreWorld(_player.getWorld().getName())) { + _player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + } + + public void updateScore() { + if (_Shots == _plugin._eco.getScore(_player, Score.Type.Shot) && _Deaths == _plugin._eco.getScore(_player, Score.Type.Death) && _Money == _plugin._eco.getPlayerMoney(_player)) { + return; + } + _Kills = _plugin._eco.getScore(_player, Score.Type.Kill); + _Deaths = _plugin._eco.getScore(_player, Score.Type.Death); + _Shots = _plugin._eco.getScore(_player, Score.Type.Shot); + _Wins = _plugin._eco.getScore(_player, Score.Type.Win); + _Money = _plugin._eco.getPlayerMoney(_player); + _objective.getScore(_plugin._trad.get("Shop.Coins.name")).setScore(_Money); + _objective.getScore(_plugin._trad.get("ScoreBoard.Kills.name")).setScore(_Kills); + _objective.getScore(_plugin._trad.get("ScoreBoard.Deaths.name")).setScore(_Deaths); + _objective.getScore(_plugin._trad.get("ScoreBoard.Shots.name")).setScore(_Shots); + _objective.getScore(_plugin._trad.get("ScoreBoard.Wins.name")).setScore(_Wins); + if (isScoreWorld(_player.getWorld().getName())) { + _player.setScoreboard(_board); + } else { + _player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + } + + public Scoreboard getScoreBoard() { + return _board; + } + + public Boolean isScoreWorld(String name) { + return _plugin._ScoreWorlds.contains(name); + } +} + diff --git a/src/com/Geekpower14/Quake/Utils/Version.java b/src/com/Geekpower14/Quake/Utils/Version.java new file mode 100644 index 0000000..049eb59 --- /dev/null +++ b/src/com/Geekpower14/Quake/Utils/Version.java @@ -0,0 +1,57 @@ +package com.Geekpower14.Quake.Utils; + +public class Version implements Comparable { + private String _version; + + public final String get() { + return _version; + } + + public Version(String version) { + if (version == null) { + throw new IllegalArgumentException("Version can not be null"); + } + if (!version.matches("[0-9]+(\\.[0-9]+)*")) { + throw new IllegalArgumentException("Invalid version format"); + } + _version = version; + } + + @Override + public int compareTo(Version that) { + if (that == null) { + return 1; + } + String[] thisParts = get().split("\\."); + String[] thatParts = that.get().split("\\."); + int length = Math.max(thisParts.length, thatParts.length); + int i = 0; + while (i < length) { + int thatPart; + int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; + int n = thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; + if (thisPart < thatPart) { + return -1; + } + if (thisPart > thatPart) { + return 1; + } + ++i; + } + return 0; + } + + @Override + public boolean equals(Object that) { + if (this == that) { + return true; + } + if (that == null) { + return false; + } + if (getClass() != that.getClass()) { + return false; + } + return compareTo((Version)that) == 0; + } +} \ No newline at end of file diff --git a/src/org/json/CDL.java b/src/org/json/CDL.java new file mode 100644 index 0000000..0fc3cf8 --- /dev/null +++ b/src/org/json/CDL.java @@ -0,0 +1,279 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * This provides static methods to convert comma delimited text into a + * JSONArray, and to covert a JSONArray into comma delimited text. Comma + * delimited text is a very popular format for data interchange. It is + * understood by most database, spreadsheet, and organizer programs. + *

+ * Each row of text represents a row in a table or a data record. Each row + * ends with a NEWLINE character. Each row contains one or more values. + * Values are separated by commas. A value can contain any character except + * for comma, unless is is wrapped in single quotes or double quotes. + *

+ * The first row usually contains the names of the columns. + *

+ * A comma delimited list can be converted into a JSONArray of JSONObjects. + * The names for the elements in the JSONObjects can be taken from the names + * in the first row. + * @author JSON.org + * @version 2012-11-13 + */ +public class CDL { + + /** + * Get the next value. The value can be wrapped in quotes. The value can + * be empty. + * @param x A JSONTokener of the source text. + * @return The value string, or null if empty. + * @throws JSONException if the quoted string is badly formed. + */ + private static String getValue(JSONTokener x) throws JSONException { + char c; + char q; + StringBuffer sb; + do { + c = x.next(); + } while (c == ' ' || c == '\t'); + switch (c) { + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (;;) { + c = x.next(); + if (c == q) { + break; + } + if (c == 0 || c == '\n' || c == '\r') { + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); + } + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); + } + } + + /** + * Produce a JSONArray of strings from a row of comma delimited values. + * @param x A JSONTokener of the source text. + * @return A JSONArray of strings. + * @throws JSONException + */ + public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { + JSONArray ja = new JSONArray(); + for (;;) { + String value = getValue(x); + char c = x.next(); + if (value == null || + (ja.length() == 0 && value.length() == 0 && c != ',')) { + return null; + } + ja.put(value); + for (;;) { + if (c == ',') { + break; + } + if (c != ' ') { + if (c == '\n' || c == '\r' || c == 0) { + return ja; + } + throw x.syntaxError("Bad character '" + c + "' (" + + (int)c + ")."); + } + c = x.next(); + } + } + } + + /** + * Produce a JSONObject from a row of comma delimited text, using a + * parallel JSONArray of strings to provides the names of the elements. + * @param names A JSONArray of names. This is commonly obtained from the + * first row of a comma delimited text file using the rowToJSONArray + * method. + * @param x A JSONTokener of the source text. + * @return A JSONObject combining the names and values. + * @throws JSONException + */ + public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) + throws JSONException { + JSONArray ja = rowToJSONArray(x); + return ja != null ? ja.toJSONObject(names) : null; + } + + /** + * Produce a comma delimited text row from a JSONArray. Values containing + * the comma character will be quoted. Troublesome characters may be + * removed. + * @param ja A JSONArray of strings. + * @return A string ending in NEWLINE. + */ + public static String rowToString(JSONArray ja) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < ja.length(); i += 1) { + if (i > 0) { + sb.append(','); + } + Object object = ja.opt(i); + if (object != null) { + String string = object.toString(); + if (string.length() > 0 && (string.indexOf(',') >= 0 || + string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || + string.indexOf(0) >= 0 || string.charAt(0) == '"')) { + sb.append('"'); + int length = string.length(); + for (int j = 0; j < length; j += 1) { + char c = string.charAt(j); + if (c >= ' ' && c != '"') { + sb.append(c); + } + } + sb.append('"'); + } else { + sb.append(string); + } + } + } + sb.append('\n'); + return sb.toString(); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(String string) throws JSONException { + return toJSONArray(new JSONTokener(string)); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * @param x The JSONTokener containing the comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONTokener x) throws JSONException { + return toJSONArray(rowToJSONArray(x), x); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * @param names A JSONArray of strings. + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONArray names, String string) + throws JSONException { + return toJSONArray(names, new JSONTokener(string)); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * @param names A JSONArray of strings. + * @param x A JSONTokener of the source text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONArray names, JSONTokener x) + throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + JSONArray ja = new JSONArray(); + for (;;) { + JSONObject jo = rowToJSONObject(names, x); + if (jo == null) { + break; + } + ja.put(jo); + } + if (ja.length() == 0) { + return null; + } + return ja; + } + + + /** + * Produce a comma delimited text from a JSONArray of JSONObjects. The + * first row will be a list of names obtained by inspecting the first + * JSONObject. + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws JSONException + */ + public static String toString(JSONArray ja) throws JSONException { + JSONObject jo = ja.optJSONObject(0); + if (jo != null) { + JSONArray names = jo.names(); + if (names != null) { + return rowToString(names) + toString(names, ja); + } + } + return null; + } + + /** + * Produce a comma delimited text from a JSONArray of JSONObjects using + * a provided list of names. The list of names is not included in the + * output. + * @param names A JSONArray of strings. + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws JSONException + */ + public static String toString(JSONArray names, JSONArray ja) + throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < ja.length(); i += 1) { + JSONObject jo = ja.optJSONObject(i); + if (jo != null) { + sb.append(rowToString(jo.toJSONArray(names))); + } + } + return sb.toString(); + } +} diff --git a/src/org/json/Cookie.java b/src/org/json/Cookie.java new file mode 100644 index 0000000..9cf5ce2 --- /dev/null +++ b/src/org/json/Cookie.java @@ -0,0 +1,169 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * Convert a web browser cookie specification to a JSONObject and back. + * JSON and Cookies are both notations for name/value pairs. + * @author JSON.org + * @version 2010-12-24 + */ +public class Cookie { + + /** + * Produce a copy of a string in which the characters '+', '%', '=', ';' + * and control characters are replaced with "%hh". This is a gentle form + * of URL encoding, attempting to cause as little distortion to the + * string as possible. The characters '=' and ';' are meta characters in + * cookies. By convention, they are escaped using the URL-encoding. This is + * only a convention, not a standard. Often, cookies are expected to have + * encoded values. We encode '=' and ';' because we must. We encode '%' and + * '+' because they are meta characters in URL encoding. + * @param string The source string. + * @return The escaped result. + */ + public static String escape(String string) { + char c; + String s = string.trim(); + StringBuffer sb = new StringBuffer(); + int length = s.length(); + for (int i = 0; i < length; i += 1) { + c = s.charAt(i); + if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { + sb.append('%'); + sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char)(c & 0x0f), 16)); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + + /** + * Convert a cookie specification string into a JSONObject. The string + * will contain a name value pair separated by '='. The name and the value + * will be unescaped, possibly converting '+' and '%' sequences. The + * cookie properties may follow, separated by ';', also represented as + * name=value (except the secure property, which does not have a value). + * The name will be stored under the key "name", and the value will be + * stored under the key "value". This method does not do checking or + * validation of the parameters. It only converts the cookie string into + * a JSONObject. + * @param string The cookie specification string. + * @return A JSONObject containing "name", "value", and possibly other + * members. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + String name; + JSONObject jo = new JSONObject(); + Object value; + JSONTokener x = new JSONTokener(string); + jo.put("name", x.nextTo('=')); + x.next('='); + jo.put("value", x.nextTo(';')); + x.next(); + while (x.more()) { + name = unescape(x.nextTo("=;")); + if (x.next() != '=') { + if (name.equals("secure")) { + value = Boolean.TRUE; + } else { + throw x.syntaxError("Missing '=' in cookie parameter."); + } + } else { + value = unescape(x.nextTo(';')); + x.next(); + } + jo.put(name, value); + } + return jo; + } + + + /** + * Convert a JSONObject into a cookie specification string. The JSONObject + * must contain "name" and "value" members. + * If the JSONObject contains "expires", "domain", "path", or "secure" + * members, they will be appended to the cookie specification string. + * All other members are ignored. + * @param jo A JSONObject + * @return A cookie specification string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + StringBuffer sb = new StringBuffer(); + + sb.append(escape(jo.getString("name"))); + sb.append("="); + sb.append(escape(jo.getString("value"))); + if (jo.has("expires")) { + sb.append(";expires="); + sb.append(jo.getString("expires")); + } + if (jo.has("domain")) { + sb.append(";domain="); + sb.append(escape(jo.getString("domain"))); + } + if (jo.has("path")) { + sb.append(";path="); + sb.append(escape(jo.getString("path"))); + } + if (jo.optBoolean("secure")) { + sb.append(";secure"); + } + return sb.toString(); + } + + /** + * Convert %hh sequences to single characters, and + * convert plus to space. + * @param string A string that may contain + * + (plus) and + * %hh sequences. + * @return The unescaped string. + */ + public static String unescape(String string) { + int length = string.length(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; ++i) { + char c = string.charAt(i); + if (c == '+') { + c = ' '; + } else if (c == '%' && i + 2 < length) { + int d = JSONTokener.dehexchar(string.charAt(i + 1)); + int e = JSONTokener.dehexchar(string.charAt(i + 2)); + if (d >= 0 && e >= 0) { + c = (char)(d * 16 + e); + i += 2; + } + } + sb.append(c); + } + return sb.toString(); + } +} diff --git a/src/org/json/CookieList.java b/src/org/json/CookieList.java new file mode 100644 index 0000000..7f4fe07 --- /dev/null +++ b/src/org/json/CookieList.java @@ -0,0 +1,90 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.util.Iterator; + +/** + * Convert a web browser cookie list string to a JSONObject and back. + * @author JSON.org + * @version 2010-12-24 + */ +public class CookieList { + + /** + * Convert a cookie list into a JSONObject. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The names and the values + * will be unescaped, possibly converting '+' and '%' sequences. + * + * To add a cookie to a cooklist, + * cookielistJSONObject.put(cookieJSONObject.getString("name"), + * cookieJSONObject.getString("value")); + * @param string A cookie list string + * @return A JSONObject + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + JSONTokener x = new JSONTokener(string); + while (x.more()) { + String name = Cookie.unescape(x.nextTo('=')); + x.next('='); + jo.put(name, Cookie.unescape(x.nextTo(';'))); + x.next(); + } + return jo; + } + + + /** + * Convert a JSONObject into a cookie list. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The characters '%', '+', '=', and ';' + * in the names and values are replaced by "%hh". + * @param jo A JSONObject + * @return A cookie list string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + boolean b = false; + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + while (keys.hasNext()) { + string = keys.next().toString(); + if (!jo.isNull(string)) { + if (b) { + sb.append(';'); + } + sb.append(Cookie.escape(string)); + sb.append("="); + sb.append(Cookie.escape(jo.getString(string))); + b = true; + } + } + return sb.toString(); + } +} diff --git a/src/org/json/HTTP.java b/src/org/json/HTTP.java new file mode 100644 index 0000000..43d04a8 --- /dev/null +++ b/src/org/json/HTTP.java @@ -0,0 +1,163 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.util.Iterator; + +/** + * Convert an HTTP header to a JSONObject and back. + * @author JSON.org + * @version 2010-12-24 + */ +public class HTTP { + + /** Carriage return/line feed. */ + public static final String CRLF = "\r\n"; + + /** + * Convert an HTTP header string into a JSONObject. It can be a request + * header or a response header. A request header will contain + *

{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header will contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that
+     *    Date: Sun, 26 May 2002 18:06:04 GMT
+     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
+     *    Cache-Control: no-cache
+ * become + *
{...
+     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
+     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
+     *    "Cache-Control": "no-cache",
+     * ...}
+ * It does no further checking or conversion. It does not parse dates. + * It does not do '%' transforms on URLs. + * @param string An HTTP header string. + * @return A JSONObject containing the elements and attributes + * of the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; + + token = x.nextToken(); + if (token.toUpperCase().startsWith("HTTP")) { + +// Response + + jo.put("HTTP-Version", token); + jo.put("Status-Code", x.nextToken()); + jo.put("Reason-Phrase", x.nextTo('\0')); + x.next(); + + } else { + +// Request + + jo.put("Method", token); + jo.put("Request-URI", x.nextToken()); + jo.put("HTTP-Version", x.nextToken()); + } + +// Fields + + while (x.more()) { + String name = x.nextTo(':'); + x.next(':'); + jo.put(name, x.nextTo('\0')); + x.next(); + } + return jo; + } + + + /** + * Convert a JSONObject into an HTTP header. A request header must contain + *
{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header must contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * Any other members of the JSONObject will be output as HTTP fields. + * The result will end with two CRLF pairs. + * @param jo A JSONObject + * @return An HTTP header string. + * @throws JSONException if the object does not contain enough + * information. + */ + public static String toString(JSONObject jo) throws JSONException { + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { + sb.append(jo.getString("HTTP-Version")); + sb.append(' '); + sb.append(jo.getString("Status-Code")); + sb.append(' '); + sb.append(jo.getString("Reason-Phrase")); + } else if (jo.has("Method") && jo.has("Request-URI")) { + sb.append(jo.getString("Method")); + sb.append(' '); + sb.append('"'); + sb.append(jo.getString("Request-URI")); + sb.append('"'); + sb.append(' '); + sb.append(jo.getString("HTTP-Version")); + } else { + throw new JSONException("Not enough material for an HTTP header."); + } + sb.append(CRLF); + while (keys.hasNext()) { + string = keys.next().toString(); + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && + !"Reason-Phrase".equals(string) && !"Method".equals(string) && + !"Request-URI".equals(string) && !jo.isNull(string)) { + sb.append(string); + sb.append(": "); + sb.append(jo.getString(string)); + sb.append(CRLF); + } + } + sb.append(CRLF); + return sb.toString(); + } +} diff --git a/src/org/json/HTTPTokener.java b/src/org/json/HTTPTokener.java new file mode 100644 index 0000000..ed41744 --- /dev/null +++ b/src/org/json/HTTPTokener.java @@ -0,0 +1,77 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * The HTTPTokener extends the JSONTokener to provide additional methods + * for the parsing of HTTP headers. + * @author JSON.org + * @version 2012-11-13 + */ +public class HTTPTokener extends JSONTokener { + + /** + * Construct an HTTPTokener from a string. + * @param string A source string. + */ + public HTTPTokener(String string) { + super(string); + } + + + /** + * Get the next token or string. This is used in parsing HTTP headers. + * @throws JSONException + * @return A String. + */ + public String nextToken() throws JSONException { + char c; + char q; + StringBuffer sb = new StringBuffer(); + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == '"' || c == '\'') { + q = c; + for (;;) { + c = next(); + if (c < ' ') { + throw syntaxError("Unterminated string."); + } + if (c == q) { + return sb.toString(); + } + sb.append(c); + } + } + for (;;) { + if (c == 0 || Character.isWhitespace(c)) { + return sb.toString(); + } + sb.append(c); + c = next(); + } + } +} diff --git a/src/org/json/JSONArray.java b/src/org/json/JSONArray.java new file mode 100644 index 0000000..b5a2dd4 --- /dev/null +++ b/src/org/json/JSONArray.java @@ -0,0 +1,906 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +/** + * A JSONArray is an ordered sequence of values. Its external text form is a + * string wrapped in square brackets with commas separating the values. The + * internal form is an object having get and opt + * methods for accessing the values by index, and put methods for + * adding or replacing values. The values can be any of these types: + * Boolean, JSONArray, JSONObject, + * Number, String, or the + * JSONObject.NULL object. + *

+ * The constructor can convert a JSON text into a Java object. The + * toString method converts to JSON text. + *

+ * A get method returns a value if one can be found, and throws an + * exception if one cannot be found. An opt method returns a + * default value instead of throwing an exception, and so is useful for + * obtaining optional values. + *

+ * The generic get() and opt() methods return an + * object which you can cast or query for type. There are also typed + * get and opt methods that do type checking and type + * coercion for you. + *

+ * The texts produced by the toString methods strictly conform to + * JSON syntax rules. The constructors are more forgiving in the texts they will + * accept: + *

    + *
  • An extra , (comma) may appear just + * before the closing bracket.
  • + *
  • The null value will be inserted when there is , + *  (comma) elision.
  • + *
  • Strings may be quoted with ' (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, and + * if they do not contain any of these characters: + * { } [ ] / \ : , = ; # and if they do not look like numbers and + * if they are not the reserved words true, false, or + * null.
  • + *
  • Values can be separated by ; (semicolon) as + * well as by , (comma).
  • + *
+ * + * @author JSON.org + * @version 2012-11-13 + */ +public class JSONArray { + + + /** + * The arrayList where the JSONArray's properties are kept. + */ + private final ArrayList myArrayList; + + + /** + * Construct an empty JSONArray. + */ + public JSONArray() { + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a JSONTokener. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + + /** + * Construct a JSONArray from a source JSON text. + * @param source A string that begins with + * [ (left bracket) + * and ends with ] (right bracket). + * @throws JSONException If there is a syntax error. + */ + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONArray from a Collection. + * @param collection A Collection. + */ + public JSONArray(Collection collection) { + this.myArrayList = new ArrayList(); + if (collection != null) { + Iterator iter = collection.iterator(); + while (iter.hasNext()) { + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } + + + /** + * Construct a JSONArray from an array + * @throws JSONException If not an array. + */ + public JSONArray(Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException( +"JSONArray initial value should be a string or collection or array."); + } + } + + + /** + * Get the object value associated with an index. + * @param index + * The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get(int index) throws JSONException { + Object object = this.opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + + /** + * Get the boolean value associated with an index. + * The string values "true" and "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the + * value is not convertible to boolean. + */ + public boolean getBoolean(int index) throws JSONException { + Object object = this.get(index); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String)object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String)object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } + + + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public double getDouble(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number + ? ((Number)object).doubleValue() + : Double.parseDouble((String)object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value is not a number. + */ + public int getInt(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number + ? ((Number)object).intValue() + : Integer.parseInt((String)object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the JSONArray associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the + * value is not a JSONArray + */ + public JSONArray getJSONArray(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONArray) { + return (JSONArray)object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONArray."); + } + + + /** + * Get the JSONObject associated with an index. + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the + * value is not a JSONObject + */ + public JSONObject getJSONObject(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONObject) { + return (JSONObject)object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONObject."); + } + + + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public long getLong(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number + ? ((Number)object).longValue() + : Long.parseLong((String)object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the string associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no string value for the index. + */ + public String getString(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof String) { + return (String)object; + } + throw new JSONException("JSONArray[" + index + "] not a string."); + } + + + /** + * Determine if the value is null. + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is no value. + */ + public boolean isNull(int index) { + return JSONObject.NULL.equals(this.opt(index)); + } + + + /** + * Make a string from the contents of this JSONArray. The + * separator string is inserted between each element. + * Warning: This method assumes that the data structure is acyclical. + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException { + int len = this.length(); + StringBuffer sb = new StringBuffer(); + + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length() { + return this.myArrayList.size(); + } + + + /** + * Get the optional object value associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no + * object at that index. + */ + public Object opt(int index) { + return (index < 0 || index >= this.length()) + ? null + : this.myArrayList.get(index); + } + + + /** + * Get the optional boolean value associated with an index. + * It returns false if there is no value at that index, + * or if the value is not Boolean.TRUE or the String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public boolean optBoolean(int index) { + return this.optBoolean(index, false); + } + + + /** + * Get the optional boolean value associated with an index. + * It returns the defaultValue if there is no value at that index or if + * it is not a Boolean or the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public boolean optBoolean(int index, boolean defaultValue) { + try { + return this.getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional double value associated with an index. + * NaN is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble(int index) { + return this.optDouble(index, Double.NaN); + } + + + /** + * Get the optional double value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble(int index, double defaultValue) { + try { + return this.getDouble(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional int value associated with an index. + * Zero is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public int optInt(int index) { + return this.optInt(index, 0); + } + + + /** + * Get the optional int value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public int optInt(int index, int defaultValue) { + try { + return this.getInt(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional JSONArray associated with an index. + * @param index subscript + * @return A JSONArray value, or null if the index has no value, + * or if the value is not a JSONArray. + */ + public JSONArray optJSONArray(int index) { + Object o = this.opt(index); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + + /** + * Get the optional JSONObject associated with an index. + * Null is returned if the key is not found, or null if the index has + * no value, or if the value is not a JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index) { + Object o = this.opt(index); + return o instanceof JSONObject ? (JSONObject)o : null; + } + + + /** + * Get the optional long value associated with an index. + * Zero is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public long optLong(int index) { + return this.optLong(index, 0); + } + + + /** + * Get the optional long value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public long optLong(int index, long defaultValue) { + try { + return this.getLong(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional string value associated with an index. It returns an + * empty string if there is no value at that index. If the value + * is not a string and is not null, then it is coverted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString(int index) { + return this.optString(index, ""); + } + + + /** + * Get the optional string associated with an index. + * The defaultValue is returned if the key is not found. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. + */ + public String optString(int index, String defaultValue) { + Object object = this.opt(index); + return JSONObject.NULL.equals(object) + ? defaultValue + : object.toString(); + } + + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put(boolean value) { + this.put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * @param value A Collection value. + * @return this. + */ + public JSONArray put(Collection value) { + this.put(new JSONArray(value)); + return this; + } + + + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @throws JSONException if the value is not finite. + * @return this. + */ + public JSONArray put(double value) throws JSONException { + Double d = new Double(value); + JSONObject.testValidity(d); + this.put(d); + return this; + } + + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put(int value) { + this.put(new Integer(value)); + return this; + } + + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put(long value) { + this.put(new Long(value)); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject which is produced from a Map. + * @param value A Map value. + * @return this. + */ + public JSONArray put(Map value) { + this.put(new JSONObject(value)); + return this; + } + + + /** + * Append an object value. This increases the array's length by one. + * @param value An object value. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + */ + public JSONArray put(Object value) { + this.myArrayList.add(value); + return this; + } + + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, boolean value) throws JSONException { + this.put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, Collection value) throws JSONException { + this.put(index, new JSONArray(value)); + return this; + } + + + /** + * Put or replace a double value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, double value) throws JSONException { + this.put(index, new Double(value)); + return this; + } + + + /** + * Put or replace an int value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, int value) throws JSONException { + this.put(index, new Integer(value)); + return this; + } + + + /** + * Put or replace a long value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, long value) throws JSONException { + this.put(index, new Long(value)); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject that is produced from a Map. + * @param index The subscript. + * @param value The Map value. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Map value) throws JSONException { + this.put(index, new JSONObject(value)); + return this; + } + + + /** + * Put or replace an object value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < this.length()) { + this.myArrayList.set(index, value); + } else { + while (index != this.length()) { + this.put(JSONObject.NULL); + } + this.put(value); + } + return this; + } + + + /** + * Remove an index and close the hole. + * @param index The index of the element to be removed. + * @return The value that was associated with the index, + * or null if there was no value. + */ + public Object remove(int index) { + Object o = this.opt(index); + this.myArrayList.remove(index); + return o; + } + + + /** + * Produce a JSONObject by combining a JSONArray of names with the values + * of this JSONArray. + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. + * @return A JSONObject, or null if there are no names or if this JSONArray + * has no values. + * @throws JSONException If any of the names are null. + */ + public JSONObject toJSONObject(JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || this.length() == 0) { + return null; + } + JSONObject jo = new JSONObject(); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + + /** + * Make a JSON text of this JSONArray. For compactness, no + * unnecessary whitespace is added. If it is not possible to produce a + * syntactically correct JSON text then null will be returned instead. This + * could occur if the array contains an invalid number. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable + * representation of the array. + */ + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + + /** + * Make a prettyprinted JSON text of this JSONArray. + * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with [ (left bracket) and ending + * with ] (right bracket). + * @throws JSONException + */ + public String toString(int indentFactor) throws JSONException { + StringWriter sw = new StringWriter(); + synchronized (sw.getBuffer()) { + return this.write(sw, indentFactor, 0).toString(); + } + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor + * The number of spaces to add to each level of indentation. + * @param indent + * The indention of the top level. + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) + throws JSONException { + try { + boolean commanate = false; + int length = this.length(); + writer.write('['); + + if (length == 1) { + JSONObject.writeValue(writer, this.myArrayList.get(0), + indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; + + for (int i = 0; i < length; i += 1) { + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, newindent); + JSONObject.writeValue(writer, this.myArrayList.get(i), + indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, indent); + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } +} diff --git a/src/org/json/JSONException.java b/src/org/json/JSONException.java new file mode 100644 index 0000000..289b602 --- /dev/null +++ b/src/org/json/JSONException.java @@ -0,0 +1,28 @@ +package org.json; + +/** + * The JSONException is thrown by the JSON.org classes when things are amiss. + * @author JSON.org + * @version 2010-12-24 + */ +public class JSONException extends Exception { + private static final long serialVersionUID = 0; + private Throwable cause; + + /** + * Constructs a JSONException with an explanatory message. + * @param message Detail about the reason for the exception. + */ + public JSONException(String message) { + super(message); + } + + public JSONException(Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } + + public Throwable getCause() { + return this.cause; + } +} diff --git a/src/org/json/JSONML.java b/src/org/json/JSONML.java new file mode 100644 index 0000000..4be6863 --- /dev/null +++ b/src/org/json/JSONML.java @@ -0,0 +1,467 @@ +package org.json; + +/* +Copyright (c) 2008 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.util.Iterator; + + +/** + * This provides static methods to convert an XML text into a JSONArray or + * JSONObject, and to covert a JSONArray or JSONObject into an XML text using + * the JsonML transform. + * + * @author JSON.org + * @version 2012-03-28 + */ +public class JSONML { + + /** + * Parse XML values and store them in a JSONArray. + * @param x The XMLTokener containing the source string. + * @param arrayForm true if array form, false if object form. + * @param ja The JSONArray that is containing the current tag or null + * if we are at the outermost level. + * @return A JSONArray if the value is the outermost tag, otherwise null. + * @throws JSONException + */ + private static Object parse( + XMLTokener x, + boolean arrayForm, + JSONArray ja + ) throws JSONException { + String attribute; + char c; + String closeTag = null; + int i; + JSONArray newja = null; + JSONObject newjo = null; + Object token; + String tagName = null; + +// Test for and skip past these forms: +// +// +// +// + + while (true) { + if (!x.more()) { + throw x.syntaxError("Bad XML"); + } + token = x.nextContent(); + if (token == XML.LT) { + token = x.nextToken(); + if (token instanceof Character) { + if (token == XML.SLASH) { + +// Close tag "); + } else { + x.back(); + } + } else if (c == '[') { + token = x.nextToken(); + if (token.equals("CDATA") && x.next() == '[') { + if (ja != null) { + ja.put(x.nextCDATA()); + } + } else { + throw x.syntaxError("Expected 'CDATA['"); + } + } else { + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + } + } else if (token == XML.QUEST) { + +// "); + } else { + throw x.syntaxError("Misshaped tag"); + } + +// Open tag < + + } else { + if (!(token instanceof String)) { + throw x.syntaxError("Bad tagName '" + token + "'."); + } + tagName = (String)token; + newja = new JSONArray(); + newjo = new JSONObject(); + if (arrayForm) { + newja.put(tagName); + if (ja != null) { + ja.put(newja); + } + } else { + newjo.put("tagName", tagName); + if (ja != null) { + ja.put(newjo); + } + } + token = null; + for (;;) { + if (token == null) { + token = x.nextToken(); + } + if (token == null) { + throw x.syntaxError("Misshaped tag"); + } + if (!(token instanceof String)) { + break; + } + +// attribute = value + + attribute = (String)token; + if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { + throw x.syntaxError("Reserved attribute."); + } + token = x.nextToken(); + if (token == XML.EQ) { + token = x.nextToken(); + if (!(token instanceof String)) { + throw x.syntaxError("Missing value"); + } + newjo.accumulate(attribute, XML.stringToValue((String)token)); + token = null; + } else { + newjo.accumulate(attribute, ""); + } + } + if (arrayForm && newjo.length() > 0) { + newja.put(newjo); + } + +// Empty tag <.../> + + if (token == XML.SLASH) { + if (x.nextToken() != XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + +// Content, between <...> and + + } else { + if (token != XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + closeTag = (String)parse(x, arrayForm, newja); + if (closeTag != null) { + if (!closeTag.equals(tagName)) { + throw x.syntaxError("Mismatched '" + tagName + + "' and '" + closeTag + "'"); + } + tagName = null; + if (!arrayForm && newja.length() > 0) { + newjo.put("childNodes", newja); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + } + } + } + } else { + if (ja != null) { + ja.put(token instanceof String + ? XML.stringToValue((String)token) + : token); + } + } + } + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child tags. + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * @param string The source string. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(String string) throws JSONException { + return toJSONArray(new XMLTokener(string)); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child content and tags. + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * @param x An XMLTokener. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(XMLTokener x) throws JSONException { + return (JSONArray)parse(x, true, null); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * @param x An XMLTokener of the XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(XMLTokener x) throws JSONException { + return (JSONObject)parse(x, false, null); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * @param string The XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + return toJSONObject(new XMLTokener(string)); + } + + + /** + * Reverse the JSONML transformation, making an XML text from a JSONArray. + * @param ja A JSONArray. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONArray ja) throws JSONException { + int i; + JSONObject jo; + String key; + Iterator keys; + int length; + Object object; + StringBuffer sb = new StringBuffer(); + String tagName; + String value; + +// Emit = length) { + sb.append('/'); + sb.append('>'); + } else { + sb.append('>'); + do { + object = ja.get(i); + i += 1; + if (object != null) { + if (object instanceof String) { + sb.append(XML.escape(object.toString())); + } else if (object instanceof JSONObject) { + sb.append(toString((JSONObject)object)); + } else if (object instanceof JSONArray) { + sb.append(toString((JSONArray)object)); + } + } + } while (i < length); + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONObject. + * The JSONObject must contain a "tagName" property. If it has children, + * then it must have a "childNodes" property containing an array of objects. + * The other properties are attributes with string values. + * @param jo A JSONObject. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + StringBuffer sb = new StringBuffer(); + int i; + JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; + +//Emit '); + } else { + sb.append('>'); + length = ja.length(); + for (i = 0; i < length; i += 1) { + object = ja.get(i); + if (object != null) { + if (object instanceof String) { + sb.append(XML.escape(object.toString())); + } else if (object instanceof JSONObject) { + sb.append(toString((JSONObject)object)); + } else if (object instanceof JSONArray) { + sb.append(toString((JSONArray)object)); + } else { + sb.append(object.toString()); + } + } + } + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } +} diff --git a/src/org/json/JSONObject.java b/src/org/json/JSONObject.java new file mode 100644 index 0000000..399f093 --- /dev/null +++ b/src/org/json/JSONObject.java @@ -0,0 +1,1628 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; + +/** + * A JSONObject is an unordered collection of name/value pairs. Its external + * form is a string wrapped in curly braces with colons between the names and + * values, and commas between the values and names. The internal form is an + * object having get and opt methods for accessing the + * values by name, and put methods for adding or replacing values + * by name. The values can be any of these types: Boolean, + * JSONArray, JSONObject, Number, + * String, or the JSONObject.NULL object. A JSONObject + * constructor can be used to convert an external form JSON text into an + * internal form whose values can be retrieved with the get and + * opt methods, or to convert values into a JSON text using the + * put and toString methods. A get method + * returns a value if one can be found, and throws an exception if one cannot be + * found. An opt method returns a default value instead of throwing + * an exception, and so is useful for obtaining optional values. + *

+ * The generic get() and opt() methods return an + * object, which you can cast or query for type. There are also typed + * get and opt methods that do type checking and type + * coercion for you. The opt methods differ from the get methods in that they do + * not throw. Instead, they return a specified value, such as null. + *

+ * The put methods add or replace values in an object. For example, + * + *

+ * myString = new JSONObject().put("JSON", "Hello, World!").toString();
+ * 
+ * + * produces the string {"JSON": "Hello, World"}. + *

+ * The texts produced by the toString methods strictly conform to + * the JSON syntax rules. The constructors are more forgiving in the texts they + * will accept: + *

    + *
  • An extra , (comma) may appear just + * before the closing brace.
  • + *
  • Strings may be quoted with ' (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, and + * if they do not contain any of these characters: + * { } [ ] / \ : , = ; # and if they do not look like numbers and + * if they are not the reserved words true, false, or + * null.
  • + *
  • Keys can be followed by = or => as well as by + * :.
  • + *
  • Values can be followed by ; (semicolon) as + * well as by , (comma).
  • + *
+ * + * @author JSON.org + * @version 2012-12-01 + */ +public class JSONObject { + /** + * The maximum number of keys in the key pool. + */ + private static final int keyPoolSize = 100; + + /** + * Key pooling is like string interning, but without permanently tying up + * memory. To help conserve memory, storage of duplicated key strings in + * JSONObjects will be avoided by using a key pool to manage unique key + * string objects. This is used by JSONObject.put(string, object). + */ + private static HashMap keyPool = new HashMap(keyPoolSize); + + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. + */ + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * @return NULL. + */ + protected final Object clone() { + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object + * or null. + */ + public boolean equals(Object object) { + return object == null || object == this; + } + + /** + * Get the "null" string value. + * @return The string "null". + */ + public String toString() { + return "null"; + } + } + + + /** + * The map where the JSONObject's properties are kept. + */ + private final Map map; + + + /** + * It is sometimes more convenient and less ambiguous to have a + * NULL object than to use Java's null value. + * JSONObject.NULL.equals(null) returns true. + * JSONObject.NULL.toString() returns "null". + */ + public static final Object NULL = new Null(); + + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + this.map = new HashMap(); + } + + + /** + * Construct a JSONObject from a subset of another JSONObject. + * An array of strings is used to identify the keys that should be copied. + * Missing keys are ignored. + * @param jo A JSONObject. + * @param names An array of strings. + * @throws JSONException + * @exception JSONException If a value is a non-finite number or if a name is duplicated. + */ + public JSONObject(JSONObject jo, String[] names) { + this(); + for (int i = 0; i < names.length; i += 1) { + try { + this.putOnce(names[i], jo.opt(names[i])); + } catch (Exception ignore) { + } + } + } + + + /** + * Construct a JSONObject from a JSONTokener. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string + * or a duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + +// The key is followed by ':'. We will also tolerate '=' or '=>'. + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + this.putOnce(key, x.nextValue()); + +// Pairs are separated by ','. We will also tolerate ';'. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + * @throws JSONException + */ + public JSONObject(Map map) { + this.map = new HashMap(); + if (map != null) { + Iterator i = map.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry)i.next(); + Object value = e.getValue(); + if (value != null) { + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with "get" or "is" followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + * + * The key is formed by removing the "get" or "is" prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + * + * For example, if an object has a method named "getName", and + * if the result of calling object.getName() is "Larry Fine", + * then the JSONObject will contain "name": "Larry Fine". + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + */ + public JSONObject(Object bean) { + this(); + this.populateMap(bean); + } + + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings + * from the names array, and the values will be the field values associated + * with those keys in the object. If a key is not found or not visible, + * then it will not be copied into the new JSONObject. + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String names[]) { + this(); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + this.putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + + /** + * Construct a JSONObject from a source JSON text string. + * This is the most commonly used JSONObject constructor. + * @param source A string beginning + * with { (left brace) and ending + * with } (right brace). + * @exception JSONException If there is a syntax error in the source + * string or a duplicated key. + */ + public JSONObject(String source) throws JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONObject from a ResourceBundle. + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws JSONException { + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, + Thread.currentThread().getContextClassLoader()); + +// Iterate through the keys in the bundle. + + Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key instanceof String) { + +// Go through the path, ensuring that there is a nested JSONObject for each +// segment except the last. Add the value using the last segment's name into +// the deepest nested JSONObject. + + String[] path = ((String)key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String)key)); + } + } + } + + + /** + * Accumulate values under a key. It is similar to the put method except + * that if there is already an object stored under the key then a + * JSONArray is stored under the key to hold all of the accumulated values. + * If there is already a JSONArray, then the new value is appended to it. + * In contrast, the put method replaces the previous value. + * + * If only one value is accumulated that is not a JSONArray, then the + * result will be the same as using put. But if multiple values are + * accumulated, then the result will be like append. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is an invalid number + * or if the key is null. + */ + public JSONObject accumulate( + String key, + Object value + ) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, value instanceof JSONArray + ? new JSONArray().put(value) + : value); + } else if (object instanceof JSONArray) { + ((JSONArray)object).put(value); + } else { + this.put(key, new JSONArray().put(object).put(value)); + } + return this; + } + + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value + * associated with the key is not a JSONArray. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + this.put(key, ((JSONArray)object).put(value)); + } else { + throw new JSONException("JSONObject[" + key + + "] is not a JSONArray."); + } + return this; + } + + + /** + * Produce a string from a double. The string "null" will be returned if + * the number is not finite. + * @param d A double. + * @return A String. + */ + public static String doubleToString(double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } + +// Shave off trailing zeros and decimal point, if possible. + + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + + "] not found."); + } + return object; + } + + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException + * if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object object = this.get(key); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String)object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String)object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a Boolean."); + } + + + /** + * Get the double value associated with a key. + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or + * if the value is not a Number object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number + ? ((Number)object).doubleValue() + : Double.parseDouble((String)object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a number."); + } + } + + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to an integer. + */ + public int getInt(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number + ? ((Number)object).intValue() + : Integer.parseInt((String)object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not an int."); + } + } + + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONArray) { + return (JSONArray)object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a JSONArray."); + } + + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONObject) { + return (JSONObject)object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a JSONObject."); + } + + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to a long. + */ + public long getLong(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number + ? ((Number)object).longValue() + : Long.parseLong((String)object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a long."); + } + } + + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(JSONObject jo) { + int length = jo.length(); + if (length == 0) { + return null; + } + Iterator iterator = jo.keys(); + String[] names = new String[length]; + int i = 0; + while (iterator.hasNext()) { + names[i] = (String)iterator.next(); + i += 1; + } + return names; + } + + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if there is no string value for the key. + */ + public String getString(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof String) { + return (String)object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] not a string."); + } + + + /** + * Determine if the JSONObject contains a specific key. + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + + /** + * Increment a property of a JSONObject. If there is no such property, + * create one with a value of 1. If there is such a property, and if + * it is an Integer, Long, Double, or Float, then add one to it. + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name + * that is not an Integer, Long, Double, or Float. + */ + public JSONObject increment(String key) throws JSONException { + Object value = this.opt(key); + if (value == null) { + this.put(key, 1); + } else if (value instanceof Integer) { + this.put(key, ((Integer)value).intValue() + 1); + } else if (value instanceof Long) { + this.put(key, ((Long)value).longValue() + 1); + } else if (value instanceof Double) { + this.put(key, ((Double)value).doubleValue() + 1); + } else if (value instanceof Float) { + this.put(key, ((Float)value).floatValue() + 1); + } else { + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + + /** + * Determine if the value associated with the key is null or if there is + * no value. + * @param key A key string. + * @return true if there is no value associated with the key or if + * the value is the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(this.opt(key)); + } + + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.keySet().iterator(); + } + + + /** + * Get a set of keys of the JSONObject. + * + * @return A keySet. + */ + public Set keySet() { + return this.map.keySet(); + } + + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names() { + JSONArray ja = new JSONArray(); + Iterator keys = this.keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) + throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); + +// Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + + /** + * Get an optional value associated with a key. + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + + /** + * Get an optional boolean associated with a key. + * It returns false if there is no such key, or if the value is not + * Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return this.optBoolean(key, false); + } + + + /** + * Get an optional boolean associated with a key. + * It returns the defaultValue if there is no such key, or if it is not + * a Boolean or the String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + try { + return this.getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get an optional double associated with a key, + * or NaN if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return this.optDouble(key, Double.NaN); + } + + + /** + * Get an optional double associated with a key, or the + * defaultValue if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + try { + return this.getDouble(key); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get an optional int value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return this.optInt(key, 0); + } + + + /** + * Get an optional int value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + try { + return this.getInt(key); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get an optional JSONArray associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + Object o = this.opt(key); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + + /** + * Get an optional JSONObject associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key) { + Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject)object : null; + } + + + /** + * Get an optional long value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return this.optLong(key, 0); + } + + + /** + * Get an optional long value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + try { + return this.getLong(key); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get an optional string associated with a key. + * It returns an empty string if there is no such key. If the value is not + * a string and is not null, then it is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return this.optString(key, ""); + } + + + /** + * Get an optional string associated with a key. + * It returns the defaultValue if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + + private void populateMap(Object bean) { + Class klass = bean.getClass(); + +// If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = includeSuperClass + ? klass.getMethods() + : klass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i += 1) { + try { + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + if ("getClass".equals(name) || + "getDeclaringClass".equals(name)) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && + Character.isUpperCase(key.charAt(0)) && + method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + + key.substring(1); + } + + Object result = method.invoke(bean, (Object[])null); + if (result != null) { + this.map.put(key, wrap(result)); + } + } + } + } catch (Exception ignore) { + } + } + } + + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONArray which is produced from a Collection. + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Collection value) throws JSONException { + this.put(key, new JSONArray(value)); + return this; + } + + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put(String key, double value) throws JSONException { + this.put(key, new Double(value)); + return this; + } + + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + this.put(key, new Integer(value)); + return this; + } + + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + this.put(key, new Long(value)); + return this; + } + + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Map value) throws JSONException { + this.put(key, new JSONObject(value)); + return this; + } + + + /** + * Put a key/value pair in the JSONObject. If the value is null, + * then the key will be removed from the JSONObject if it is present. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number + * or if the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + String pooled; + if (key == null) { + throw new JSONException("Null key."); + } + if (value != null) { + testValidity(value); + pooled = (String)keyPool.get(key); + if (pooled == null) { + if (keyPool.size() >= keyPoolSize) { + keyPool = new HashMap(keyPoolSize); + } + keyPool.put(key, key); + } else { + key = pooled; + } + this.map.put(key, value); + } else { + this.remove(key); + } + return this; + } + + + /** + * Put a key/value pair in the JSONObject, but only if the key and the + * value are both non-null, and only if there is not already a member + * with that name. + * @param key + * @param value + * @return his. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (this.opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + this.put(key, value); + } + return this; + } + + + /** + * Put a key/value pair in the JSONObject, but only if the + * key and the value are both non-null. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + this.put(key, value); + } + return this; + } + + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') + || (c >= '\u2000' && c < '\u2100')) { + w.write("\\u"); + hhhh = Integer.toHexString(c); + w.write("0000", 0, 4 - hhhh.length()); + w.write(hhhh); + } else { + w.write(c); + } + } + } + w.write('"'); + return w; + } + + /** + * Remove a name and its value, if present. + * @param key The name to be removed. + * @return The value that was associated with the name, + * or null if there was no value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + Double d; + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. + * If a number cannot be produced, then the value will just + * be a string. Note that the plus and implied string + * conventions are non-standard. A JSON parser may accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + try { + if (string.indexOf('.') > -1 || + string.indexOf('e') > -1 || string.indexOf('E') > -1) { + d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()) { + return d; + } + } else { + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } catch (Exception ignore) { + } + } + return string; + } + + + /** + * Throw an exception if the object is a NaN or infinite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double)o).isInfinite() || ((Double)o).isNaN()) { + throw new JSONException( + "JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float)o).isInfinite() || ((Float)o).isNaN()) { + throw new JSONException( + "JSON does not allow non-finite numbers."); + } + } + } + } + + + /** + * Produce a JSONArray containing the values of the members of this + * JSONObject. + * @param names A JSONArray containing a list of key strings. This + * determines the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace + * is added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + */ + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws JSONException { + StringWriter w = new StringWriter(); + synchronized (w.getBuffer()) { + return this.write(w, indentFactor, 0).toString(); + } + } + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce + * the JSON text. The method is required to produce a strictly + * conforming text. If the object does not contain a toJSONString + * method (which is the most common case), then a text will be + * produced by other means. If the value is an array or Collection, + * then a JSONArray will be made from it and its toJSONString method + * will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the + * value's toString method will be called, and the result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString)value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (object instanceof String) { + return (String)object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean || value instanceof JSONObject || + value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + return new JSONObject((Map)value).toString(); + } + if (value instanceof Collection) { + return new JSONArray((Collection)value).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If + * it is a map, wrap it in a JSONObject. If it is a standard property + * (Double, String, et al) then it is already wrapped. Otherwise, if it + * comes from one of the java packages, turn it into a string. And if + * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, + * then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || + NULL.equals(object) || object instanceof JSONString || + object instanceof Byte || object instanceof Character || + object instanceof Short || object instanceof Integer || + object instanceof Long || object instanceof Boolean || + object instanceof Float || object instanceof Double || + object instanceof String) { + return object; + } + + if (object instanceof Collection) { + return new JSONArray((Collection)object); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + return new JSONObject((Map)object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null + ? objectPackage.getName() + : ""; + if ( + objectPackageName.startsWith("java.") || + objectPackageName.startsWith("javax.") || + object.getClass().getClassLoader() == null + ) { + return object.toString(); + } + return new JSONObject(object); + } catch(Exception exception) { + return null; + } + } + + + /** + * Write the contents of the JSONObject as JSON text to a writer. + * For compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + + static final Writer writeValue(Writer writer, Object value, + int indentFactor, int indent) throws JSONException, IOException { + if (value == null || value.equals(null)) { + writer.write("null"); + } else if (value instanceof JSONObject) { + ((JSONObject) value).write(writer, indentFactor, indent); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer, indentFactor, indent); + } else if (value instanceof Map) { + new JSONObject((Map) value).write(writer, indentFactor, indent); + } else if (value instanceof Collection) { + new JSONArray((Collection) value).write(writer, indentFactor, + indent); + } else if (value.getClass().isArray()) { + new JSONArray(value).write(writer, indentFactor, indent); + } else if (value instanceof Number) { + writer.write(numberToString((Number) value)); + } else if (value instanceof Boolean) { + writer.write(value.toString()); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else { + quote(value.toString(), writer); + } + return writer; + } + + static final void indent(Writer writer, int indent) throws IOException { + for (int i = 0; i < indent; i += 1) { + writer.write(' '); + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) + throws JSONException { + try { + boolean commanate = false; + final int length = this.length(); + Iterator keys = this.keys(); + writer.write('{'); + + if (length == 1) { + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; + while (keys.hasNext()) { + Object key = keys.next(); + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, newindent); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, + newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, indent); + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } +} diff --git a/src/org/json/JSONString.java b/src/org/json/JSONString.java new file mode 100644 index 0000000..1f2d77d --- /dev/null +++ b/src/org/json/JSONString.java @@ -0,0 +1,18 @@ +package org.json; +/** + * The JSONString interface allows a toJSONString() + * method so that a class can change the behavior of + * JSONObject.toString(), JSONArray.toString(), + * and JSONWriter.value(Object). The + * toJSONString method will be used instead of the default behavior + * of using the Object's toString() method and quoting the result. + */ +public interface JSONString { + /** + * The toJSONString method allows a class to produce its own JSON + * serialization. + * + * @return A strictly syntactically correct JSON text. + */ + public String toJSONString(); +} diff --git a/src/org/json/JSONStringer.java b/src/org/json/JSONStringer.java new file mode 100644 index 0000000..25c2e5d --- /dev/null +++ b/src/org/json/JSONStringer.java @@ -0,0 +1,78 @@ +package org.json; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.io.StringWriter; + +/** + * JSONStringer provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONStringer can produce one JSON text. + *

+ * A JSONStringer instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting cascade style. For example,

+ * myString = new JSONStringer()
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject()
+ *     .toString();
which produces the string
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONStringer adds them for + * you. Objects and arrays can be nested up to 20 levels deep. + *

+ * This can sometimes be easier than using a JSONObject to build a string. + * @author JSON.org + * @version 2008-09-18 + */ +public class JSONStringer extends JSONWriter { + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer() { + super(new StringWriter()); + } + + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return null if there was a + * problem in the construction of the JSON text (such as the calls to + * array were not properly balanced with calls to + * endArray). + * @return The JSON text. + */ + public String toString() { + return this.mode == 'd' ? this.writer.toString() : null; + } +} diff --git a/src/org/json/JSONTokener.java b/src/org/json/JSONTokener.java new file mode 100644 index 0000000..13c84f1 --- /dev/null +++ b/src/org/json/JSONTokener.java @@ -0,0 +1,446 @@ +package org.json; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * A JSONTokener takes a source string and extracts characters and tokens from + * it. It is used by the JSONObject and JSONArray constructors to parse + * JSON source strings. + * @author JSON.org + * @version 2012-02-16 + */ +public class JSONTokener { + + private long character; + private boolean eof; + private long index; + private long line; + private char previous; + private Reader reader; + private boolean usePrevious; + + + /** + * Construct a JSONTokener from a Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader) { + this.reader = reader.markSupported() + ? reader + : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + + /** + * Construct a JSONTokener from an InputStream. + */ + public JSONTokener(InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s) { + this(new StringReader(s)); + } + + + /** + * Back up one character. This provides a sort of lookahead capability, + * so that you can test for a digit or letter before attempting to parse + * the next number or identifier. + */ + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + + /** + * Get the hex value of a character (base16). + * @param c A character between '0' and '9' or between 'A' and 'F' or + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. + */ + public static int dehexchar(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + + public boolean end() { + return this.eof && !this.usePrevious; + } + + + /** + * Determine if the source string still contains characters that next() + * can consume. + * @return true if not yet at the end of the source. + */ + public boolean more() throws JSONException { + this.next(); + if (this.end()) { + return false; + } + this.back(); + return true; + } + + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + */ + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char) c; + return this.previous; + } + + + /** + * Consume the next character, and check that it matches a specified + * character. + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next(char c) throws JSONException { + char n = this.next(); + if (n != c) { + throw this.syntaxError("Expected '" + c + "' and instead saw '" + + n + "'"); + } + return n; + } + + + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException + * Substring bounds error if there are not + * n characters remaining in the source string. + */ + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } + + char[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + + /** + * Get the next char in the string, skipping whitespace. + * @throws JSONException + * @return A character, or 0 if there are no more characters. + */ + public char nextClean() throws JSONException { + for (;;) { + char c = this.next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + + /** + * Return the characters up to the next close quote character. + * Backslash processing is done. The formal JSON format does not + * allow strings in single quotes, but an implementation is allowed to + * accept them. + * @param quote The quoting character, either + * " (double quote) or + * ' (single quote). + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (;;) { + c = this.next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char)Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + + /** + * Get the text up but not including the specified character or the + * end of line, whichever comes first. + * @param delimiter A delimiter character. + * @return A string. + */ + public String nextTo(char delimiter) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (;;) { + char c = this.next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + + /** + * Get the text up but not including one of the specified delimiter + * characters or the end of line, whichever comes first. + * @param delimiters A set of delimiter characters. + * @return A string, trimmed. + */ + public String nextTo(String delimiters) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (;;) { + c = this.next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || + c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + + /** + * Get the next value. The value can be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. + * @throws JSONException If syntax error. + * + * @return An object. + */ + public Object nextValue() throws JSONException { + char c = this.nextClean(); + String string; + + switch (c) { + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or + * null, or it can be a number. An implementation (such as this one) + * is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + StringBuffer sb = new StringBuffer(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = this.next(); + } + this.back(); + + string = sb.toString().trim(); + if ("".equals(string)) { + throw this.syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + + /** + * Skip characters until the next character is the requested character. + * If the requested character is not found, no characters are skipped. + * @param to A character to skip to. + * @return The requested character, or zero if the requested character + * is not found. + */ + public char skipTo(char to) throws JSONException { + char c; + try { + long startIndex = this.index; + long startCharacter = this.character; + long startLine = this.line; + this.reader.mark(1000000); + do { + c = this.next(); + if (c == 0) { + this.reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + } while (c != to); + } catch (IOException exc) { + throw new JSONException(exc); + } + + this.back(); + return c; + } + + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message) { + return new JSONException(message + this.toString()); + } + + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString() { + return " at " + this.index + " [character " + this.character + " line " + + this.line + "]"; + } +} diff --git a/src/org/json/JSONWriter.java b/src/org/json/JSONWriter.java new file mode 100644 index 0000000..855b2bd --- /dev/null +++ b/src/org/json/JSONWriter.java @@ -0,0 +1,327 @@ +package org.json; + +import java.io.IOException; +import java.io.Writer; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * JSONWriter provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONWriter can produce one JSON text. + *

+ * A JSONWriter instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting a cascade style. For example,

+ * new JSONWriter(myWriter)
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject();
which writes
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONWriter adds them for + * you. Objects and arrays can be nested up to 20 levels deep. + *

+ * This can sometimes be easier than using a JSONObject to build a string. + * @author JSON.org + * @version 2011-11-24 + */ +public class JSONWriter { + private static final int maxdepth = 200; + + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + + /** + * The current mode. Values: + * 'a' (array), + * 'd' (done), + * 'i' (initial), + * 'k' (key), + * 'o' (object). + */ + protected char mode; + + /** + * The object/array stack. + */ + private final JSONObject stack[]; + + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; + + /** + * The writer that will receive the output. + */ + protected Writer writer; + + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + */ + public JSONWriter(Writer w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } + + /** + * Append a value. + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.write(','); + } + this.writer.write(string); + } catch (IOException e) { + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } + + /** + * Begin appending a new array. All values until the balancing + * endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + + /** + * End something. + * @param mode Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char mode, char c) throws JSONException { + if (this.mode != mode) { + throw new JSONException(mode == 'a' + ? "Misplaced endArray." + : "Misplaced endObject."); + } + this.pop(mode); + try { + this.writer.write(c); + } catch (IOException e) { + throw new JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.end('k', '}'); + } + + /** + * Append a key. The key will be associated with the next value. In an + * object, every value must be preceded by a key. + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + this.stack[this.top - 1].putOnce(string, Boolean.TRUE); + if (this.comma) { + this.writer.write(','); + } + this.writer.write(JSONObject.quote(string)); + this.writer.write(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + + + /** + * Begin appending a new object. All keys and values until the balancing + * endObject will be appended to this object. The + * endObject method must be called to mark the object's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); + + } + + + /** + * Pop an array or object scope. + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 + ? 'd' + : this.stack[this.top - 1] == null + ? 'a' + : 'k'; + } + + /** + * Push an array or object scope. + * @param c The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } + + + /** + * Append either the value true or the value + * false. + * @param b A boolean. + * @return this + * @throws JSONException + */ + public JSONWriter value(boolean b) throws JSONException { + return this.append(b ? "true" : "false"); + } + + /** + * Append a double value. + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value(double d) throws JSONException { + return this.value(new Double(d)); + } + + /** + * Append a long value. + * @param l A long. + * @return this + * @throws JSONException + */ + public JSONWriter value(long l) throws JSONException { + return this.append(Long.toString(l)); + } + + + /** + * Append an object value. + * @param object The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements JSONString. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value(Object object) throws JSONException { + return this.append(JSONObject.valueToString(object)); + } +} diff --git a/src/org/json/XML.java b/src/org/json/XML.java new file mode 100644 index 0000000..d49784d --- /dev/null +++ b/src/org/json/XML.java @@ -0,0 +1,508 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.util.Iterator; + + +/** + * This provides static methods to convert an XML text into a JSONObject, + * and to covert a JSONObject into an XML text. + * @author JSON.org + * @version 2012-10-26 + */ +public class XML { + + /** The Character '&'. */ + public static final Character AMP = new Character('&'); + + /** The Character '''. */ + public static final Character APOS = new Character('\''); + + /** The Character '!'. */ + public static final Character BANG = new Character('!'); + + /** The Character '='. */ + public static final Character EQ = new Character('='); + + /** The Character '>'. */ + public static final Character GT = new Character('>'); + + /** The Character '<'. */ + public static final Character LT = new Character('<'); + + /** The Character '?'. */ + public static final Character QUEST = new Character('?'); + + /** The Character '"'. */ + public static final Character QUOT = new Character('"'); + + /** The Character '/'. */ + public static final Character SLASH = new Character('/'); + + /** + * Replace special characters with XML escapes: + *

+     * & (ampersand) is replaced by &amp;
+     * < (less than) is replaced by &lt;
+     * > (greater than) is replaced by &gt;
+     * " (double quote) is replaced by &quot;
+     * 
+ * @param string The string to be escaped. + * @return The escaped string. + */ + public static String escape(String string) { + StringBuffer sb = new StringBuffer(); + for (int i = 0, length = string.length(); i < length; i++) { + char c = string.charAt(i); + switch (c) { + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Throw an exception if the string contains whitespace. + * Whitespace is not allowed in tagNames and attributes. + * @param string + * @throws JSONException + */ + public static void noSpace(String string) throws JSONException { + int i, length = string.length(); + if (length == 0) { + throw new JSONException("Empty string."); + } + for (i = 0; i < length; i += 1) { + if (Character.isWhitespace(string.charAt(i))) { + throw new JSONException("'" + string + + "' contains a space character."); + } + } + } + + /** + * Scan the content following the named tag, attaching it to the context. + * @param x The XMLTokener containing the source string. + * @param context The JSONObject that will include the new material. + * @param name The tag name. + * @return true if the close tag is processed. + * @throws JSONException + */ + private static boolean parse(XMLTokener x, JSONObject context, + String name) throws JSONException { + char c; + int i; + JSONObject jsonobject = null; + String string; + String tagName; + Object token; + +// Test for and skip past these forms: +// +// +// +// +// Report errors for these forms: +// <> +// <= +// << + + token = x.nextToken(); + +// "); + return false; + } + x.back(); + } else if (c == '[') { + token = x.nextToken(); + if ("CDATA".equals(token)) { + if (x.next() == '[') { + string = x.nextCDATA(); + if (string.length() > 0) { + context.accumulate("content", string); + } + return false; + } + } + throw x.syntaxError("Expected 'CDATA['"); + } + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + return false; + } else if (token == QUEST) { + +// "); + return false; + } else if (token == SLASH) { + +// Close tag + + } else if (token == SLASH) { + if (x.nextToken() != GT) { + throw x.syntaxError("Misshaped tag"); + } + if (jsonobject.length() > 0) { + context.accumulate(tagName, jsonobject); + } else { + context.accumulate(tagName, ""); + } + return false; + +// Content, between <...> and + + } else if (token == GT) { + for (;;) { + token = x.nextContent(); + if (token == null) { + if (tagName != null) { + throw x.syntaxError("Unclosed tag " + tagName); + } + return false; + } else if (token instanceof String) { + string = (String)token; + if (string.length() > 0) { + jsonobject.accumulate("content", + XML.stringToValue(string)); + } + +// Nested element + + } else if (token == LT) { + if (parse(x, jsonobject, tagName)) { + if (jsonobject.length() == 0) { + context.accumulate(tagName, ""); + } else if (jsonobject.length() == 1 && + jsonobject.opt("content") != null) { + context.accumulate(tagName, + jsonobject.opt("content")); + } else { + context.accumulate(tagName, jsonobject); + } + return false; + } + } + } + } else { + throw x.syntaxError("Misshaped tag"); + } + } + } + } + + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. This is much less ambitious than + * JSONObject.stringToValue, especially because it does not attempt to + * convert plus forms, octal forms, hex forms, or E forms lacking decimal + * points. + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + if ("".equals(string)) { + return string; + } + if ("true".equalsIgnoreCase(string)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(string)) { + return Boolean.FALSE; + } + if ("null".equalsIgnoreCase(string)) { + return JSONObject.NULL; + } + if ("0".equals(string)) { + return new Integer(0); + } + +// If it might be a number, try converting it. If that doesn't work, +// return the string. + + try { + char initial = string.charAt(0); + boolean negative = false; + if (initial == '-') { + initial = string.charAt(1); + negative = true; + } + if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { + return string; + } + if ((initial >= '0' && initial <= '9')) { + if (string.indexOf('.') >= 0) { + return Double.valueOf(string); + } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } + } catch (Exception ignore) { + } + return string; + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject. Some information may be lost in this transformation + * because JSON is a data format and XML is a document format. XML uses + * elements, attributes, and content text, while JSON uses unordered + * collections of name/value pairs and arrays of values. JSON does not + * does not like to distinguish between elements and attributes. + * Sequences of similar elements are represented as JSONArrays. Content + * text may be placed in a "content" member. Comments, prologs, DTDs, and + * <[ [ ]]> are ignored. + * @param string The source string. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + XMLTokener x = new XMLTokener(string); + while (x.more() && x.skipPast("<")) { + parse(x, jo, null); + } + return jo; + } + + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * @param object A JSONObject. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object) throws JSONException { + return toString(object, null); + } + + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object, String tagName) + throws JSONException { + StringBuffer sb = new StringBuffer(); + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; + if (object instanceof JSONObject) { + +// Emit + + if (tagName != null) { + sb.append('<'); + sb.append(tagName); + sb.append('>'); + } + +// Loop thru the keys. + + jo = (JSONObject)object; + keys = jo.keys(); + while (keys.hasNext()) { + key = keys.next().toString(); + value = jo.opt(key); + if (value == null) { + value = ""; + } + if (value instanceof String) { + string = (String)value; + } else { + string = null; + } + +// Emit content in body + + if ("content".equals(key)) { + if (value instanceof JSONArray) { + ja = (JSONArray)value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + if (i > 0) { + sb.append('\n'); + } + sb.append(escape(ja.get(i).toString())); + } + } else { + sb.append(escape(value.toString())); + } + +// Emit an array of similar keys + + } else if (value instanceof JSONArray) { + ja = (JSONArray)value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + value = ja.get(i); + if (value instanceof JSONArray) { + sb.append('<'); + sb.append(key); + sb.append('>'); + sb.append(toString(value)); + sb.append("'); + } else { + sb.append(toString(value, key)); + } + } + } else if ("".equals(value)) { + sb.append('<'); + sb.append(key); + sb.append("/>"); + +// Emit a new tag + + } else { + sb.append(toString(value, key)); + } + } + if (tagName != null) { + +// Emit the close tag + + sb.append("'); + } + return sb.toString(); + +// XML does not have good support for arrays. If an array appears in a place +// where XML is lacking, synthesize an element. + + } else { + if (object.getClass().isArray()) { + object = new JSONArray(object); + } + if (object instanceof JSONArray) { + ja = (JSONArray)object; + length = ja.length(); + for (i = 0; i < length; i += 1) { + sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); + } + return sb.toString(); + } else { + string = (object == null) ? "null" : escape(object.toString()); + return (tagName == null) ? "\"" + string + "\"" : + (string.length() == 0) ? "<" + tagName + "/>" : + "<" + tagName + ">" + string + ""; + } + } + } +} diff --git a/src/org/json/XMLTokener.java b/src/org/json/XMLTokener.java new file mode 100644 index 0000000..be15ebe --- /dev/null +++ b/src/org/json/XMLTokener.java @@ -0,0 +1,365 @@ +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * The XMLTokener extends the JSONTokener to provide additional methods + * for the parsing of XML texts. + * @author JSON.org + * @version 2012-11-13 + */ +public class XMLTokener extends JSONTokener { + + + /** The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; + + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } + + /** + * Construct an XMLTokener from a string. + * @param s A source string. + */ + public XMLTokener(String s) { + super(s); + } + + /** + * Get the text in the CDATA block. + * @return The string up to the ]]>. + * @throws JSONException If the ]]> is not found. + */ + public String nextCDATA() throws JSONException { + char c; + int i; + StringBuffer sb = new StringBuffer(); + for (;;) { + c = next(); + if (end()) { + throw syntaxError("Unclosed CDATA"); + } + sb.append(c); + i = sb.length() - 3; + if (i >= 0 && sb.charAt(i) == ']' && + sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + sb.setLength(i); + return sb.toString(); + } + } + } + + + /** + * Get the next XML outer token, trimming whitespace. There are two kinds + * of tokens: the '<' character which begins a markup tag, and the content + * text between markup tags. + * + * @return A string, or a '<' Character, or null if there is no more + * source text. + * @throws JSONException + */ + public Object nextContent() throws JSONException { + char c; + StringBuffer sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == 0) { + return null; + } + if (c == '<') { + return XML.LT; + } + sb = new StringBuffer(); + for (;;) { + if (c == '<' || c == 0) { + back(); + return sb.toString().trim(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + c = next(); + } + } + + + /** + * Return the next entity. These entities are translated to Characters: + * & ' > < ". + * @param ampersand An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException If missing ';' in XML entity. + */ + public Object nextEntity(char ampersand) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (;;) { + char c = next(); + if (Character.isLetterOrDigit(c) || c == '#') { + sb.append(Character.toLowerCase(c)); + } else if (c == ';') { + break; + } else { + throw syntaxError("Missing ';' in XML entity: &" + sb); + } + } + String string = sb.toString(); + Object object = entity.get(string); + return object != null ? object : ampersand + string + ";"; + } + + + /** + * Returns the next XML meta token. This is used for skipping over + * and structures. + * @return Syntax characters (< > / = ! ?) are returned as + * Character, and strings and names are returned as Boolean. We don't care + * what the values actually are. + * @throws JSONException If a string is not properly closed or if the XML + * is badly structured. + */ + public Object nextMeta() throws JSONException { + char c; + char q; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (;;) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } + } + default: + for (;;) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } + } + } + } + + + /** + * Get the next XML Token. These tokens are found inside of angle + * brackets. It may be one of these characters: / > = ! ? or it + * may be a string wrapped in single quotes or double quotes, or it may be a + * name. + * @return a String or a Character. + * @throws JSONException If the XML is not well formed. + */ + public Object nextToken() throws JSONException { + char c; + char q; + StringBuffer sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + +// Quoted string + + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (;;) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + } + default: + +// Name + + sb = new StringBuffer(); + for (;;) { + sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } + } + } + } + + + /** + * Skip characters until past the requested string. + * If it is not found, we are left at the end of the source with a result of false. + * @param to A string to skip past. + * @throws JSONException + */ + public boolean skipPast(String to) throws JSONException { + boolean b; + char c; + int i; + int j; + int offset = 0; + int length = to.length(); + char[] circle = new char[length]; + + /* + * First fill the circle buffer with as many characters as are in the + * to string. If we reach an early end, bail. + */ + + for (i = 0; i < length; i += 1) { + c = next(); + if (c == 0) { + return false; + } + circle[i] = c; + } + + /* We will loop, possibly for all of the remaining characters. */ + + for (;;) { + j = offset; + b = true; + + /* Compare the circle buffer with the to string. */ + + for (i = 0; i < length; i += 1) { + if (circle[j] != to.charAt(i)) { + b = false; + break; + } + j += 1; + if (j >= length) { + j -= length; + } + } + + /* If we exit the loop with b intact, then victory is ours. */ + + if (b) { + return true; + } + + /* Get the next character. If there isn't one, then defeat is ours. */ + + c = next(); + if (c == 0) { + return false; + } + /* + * Shove the character in the circle buffer and advance the + * circle offset. The offset is mod n. + */ + circle[offset] = c; + offset += 1; + if (offset >= length) { + offset -= length; + } + } + } +} diff --git a/src/plugin.yml b/src/plugin.yml new file mode 100644 index 0000000..9860f35 --- /dev/null +++ b/src/plugin.yml @@ -0,0 +1,10 @@ +name: Quake +author: Geekpower14 +main: com.Geekpower14.Quake.Quake +version: 3.0.0 +depend: [WorldEdit,Vault] +commands: + quake: + description: Quake command + usage: /quake + aliases: [q] \ No newline at end of file