From 2b6b1f2fa74e4b751057c293d87e87f5f3a92993 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 19 Apr 2025 12:29:39 +0200 Subject: [PATCH 1/5] refactor: implement anweisen/utilities --- mongo-connector/pom.xml | 13 +- .../mongoconnector/MongoConnector.java | 2 +- .../common/config/document/BsonDocument.java | 304 ++++++++ .../commons/common/misc/BsonUtils.java | 135 ++++ .../commons/common/misc/MongoUtils.java | 66 ++ .../database/mongodb/MongoDBDatabase.java | 148 ++++ .../mongodb/count/MongoDBCountEntries.java | 42 ++ .../mongodb/deletion/MongoDBDeletion.java | 108 +++ .../mongodb/insertion/MongoDBInsertion.java | 61 ++ .../MongoDBInsertionOrUpdate.java | 85 +++ .../mongodb/list/MongoDBListTables.java | 29 + .../database/mongodb/query/MongoDBQuery.java | 128 ++++ .../database/mongodb/query/MongoDBResult.java | 18 + .../mongodb/update/MongoDBUpdate.java | 139 ++++ .../database/mongodb/where/MongoDBWhere.java | 17 + .../database/mongodb/where/ObjectWhere.java | 49 ++ .../mongodb/where/StringIgnoreCaseWhere.java | 47 ++ plugin/pom.xml | 36 +- .../challenges/plugin/Challenges.java | 4 +- .../challenges/custom/CustomChallenge.java | 2 +- .../custom/settings/CustomSettingsLoader.java | 4 +- .../settings/action/ChallengeAction.java | 2 +- .../settings/action/IChallengeAction.java | 2 +- .../action/impl/BoostEntityInAirAction.java | 2 +- .../action/impl/ChangeWorldBorderAction.java | 2 +- .../action/impl/HealEntityAction.java | 2 +- .../action/impl/PlaceStructureAction.java | 4 +- .../action/impl/PotionEffectAction.java | 4 +- .../action/impl/SpawnEntityAction.java | 2 +- .../action/impl/SwapRandomMobAction.java | 2 +- .../settings/sub/SubSettingsBuilder.java | 2 +- .../custom/settings/sub/ValueSetting.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 2 +- .../settings/sub/impl/BooleanSetting.java | 2 +- .../settings/sub/impl/ModifierSetting.java | 6 +- .../trigger/impl/EntityDamageTrigger.java | 4 +- .../challenge/DamageTeleportChallenge.java | 2 +- .../challenge/ZeroHeartsChallenge.java | 4 +- .../damage/BlockPlaceDamageChallenge.java | 2 +- .../damage/DeathOnFallChallenge.java | 2 +- .../damage/DelayDamageChallenge.java | 2 +- .../challenge/damage/FreezeChallenge.java | 2 +- .../challenge/damage/JumpDamageChallenge.java | 2 +- .../damage/WaterAllergyChallenge.java | 2 +- .../effect/BlockEffectChallenge.java | 6 +- .../effect/ChunkRandomEffectChallenge.java | 6 +- .../effect/EntityRandomEffectChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 8 +- .../effect/RandomPotionEffectChallenge.java | 4 +- .../entities/AllMobsToDeathPoint.java | 2 +- .../entities/BlockMobsChallenge.java | 2 +- .../entities/HydraPlusChallenge.java | 2 +- .../entities/InvisibleMobsChallenge.java | 2 +- .../entities/MobSightDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 2 +- .../entities/MobsRespawnInEndChallenge.java | 6 +- .../entities/NewEntityOnJumpChallenge.java | 2 +- .../entities/StoneSightChallenge.java | 4 +- .../extraworld/JumpAndRunChallenge.java | 4 +- .../challenge/force/ForceBiomeChallenge.java | 4 +- .../challenge/force/ForceBlockChallenge.java | 4 +- .../challenge/force/ForceHeightChallenge.java | 4 +- .../challenge/force/ForceItemChallenge.java | 6 +- .../challenge/force/ForceMobChallenge.java | 2 +- .../inventory/MissingItemsChallenge.java | 14 +- .../MovementItemRemovingChallenge.java | 2 +- .../inventory/NoDupedItemsChallenge.java | 4 +- .../inventory/PermanentItemChallenge.java | 4 +- .../inventory/PickupItemLaunchChallenge.java | 2 +- .../inventory/UncraftItemsChallenge.java | 4 +- .../miscellaneous/EnderGamesChallenge.java | 4 +- .../miscellaneous/FoodLaunchChallenge.java | 2 +- .../miscellaneous/InvertHealthChallenge.java | 4 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../NoSharedAdvancementsChallenge.java | 6 +- .../movement/AlwaysRunningChallenge.java | 4 +- .../movement/DontStopRunningChallenge.java | 2 +- .../movement/FiveHundredBlocksChallenge.java | 8 +- .../movement/HungerPerBlockChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDirtChallenge.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 4 +- .../challenge/quiz/QuizChallenge.java | 12 +- .../randomizer/BlockRandomizerChallenge.java | 4 +- .../CraftingRandomizerChallenge.java | 2 +- .../EntityLootRandomizerChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 4 +- .../randomizer/MobRandomizerChallenge.java | 6 +- .../randomizer/RandomChallengeChallenge.java | 2 +- .../randomizer/RandomEventChallenge.java | 6 +- .../randomizer/RandomItemChallenge.java | 2 +- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../RandomItemSwappingChallenge.java | 2 +- .../RandomTeleportOnHitChallenge.java | 2 +- .../randomizer/RandomizedHPChallenge.java | 2 +- .../challenge/time/MaxBiomeTimeChallenge.java | 2 +- .../time/MaxHeightTimeChallenge.java | 2 +- .../world/AllBlocksDisappearChallenge.java | 6 +- .../challenge/world/AnvilRainChallenge.java | 2 +- .../challenge/world/BedrockWallChallenge.java | 2 +- .../world/BlockFlyInAirChallenge.java | 2 +- .../BlocksDisappearAfterTimeChallenge.java | 2 +- .../world/ChunkDeconstructionChallenge.java | 2 +- .../world/ChunkDeletionChallenge.java | 2 +- .../challenge/world/IceFloorChallenge.java | 4 +- .../challenge/world/LevelBorderChallenge.java | 8 +- .../challenge/world/LoopChallenge.java | 8 +- .../world/RepeatInChunkChallenge.java | 10 +- .../challenge/world/SnakeChallenge.java | 2 +- .../challenge/world/SurfaceHoleChallenge.java | 2 +- .../challenge/world/TsunamiChallenge.java | 6 +- .../goal/AllAdvancementGoal.java | 2 +- .../goal/CollectAllItemsGoal.java | 10 +- .../goal/CollectHorseAmorGoal.java | 4 +- .../goal/CollectIceBlocksGoal.java | 2 +- .../goal/CollectMostDeathsGoal.java | 4 +- .../goal/CollectMostExpGoal.java | 2 +- .../goal/CollectMostItemsGoal.java | 4 +- .../goal/CollectSwordsGoal.java | 4 +- .../implementation/goal/CollectWoodGoal.java | 4 +- .../goal/CollectWorkstationsGoal.java | 4 +- .../implementation/goal/EatCakeGoal.java | 2 +- .../implementation/goal/EatMostGoal.java | 2 +- .../implementation/goal/FindElytraGoal.java | 2 +- .../implementation/goal/FinishRaidGoal.java | 4 +- .../goal/FirstOneToDieGoal.java | 2 +- .../goal/GetFullHealthGoal.java | 4 +- .../goal/KillAllBossesGoal.java | 2 +- .../goal/KillAllBossesNewGoal.java | 4 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 4 +- .../goal/KillElderGuardianGoal.java | 4 +- .../goal/KillEnderDragonGoal.java | 2 +- .../goal/KillIronGolemGoal.java | 4 +- .../goal/KillSnowGolemGoal.java | 4 +- .../implementation/goal/KillWardenGoal.java | 6 +- .../implementation/goal/KillWitherGoal.java | 2 +- .../goal/LastManStandingGoal.java | 2 +- .../implementation/goal/MaxHeightGoal.java | 2 +- .../implementation/goal/MinHeightGoal.java | 4 +- .../implementation/goal/MostEmeraldsGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 4 +- .../implementation/goal/RaceGoal.java | 6 +- .../forcebattle/ExtremeForceBattleGoal.java | 6 +- .../ForceAdvancementBattleGoal.java | 6 +- .../forcebattle/ForceBiomeBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 4 +- .../forcebattle/ForceDamageBattleGoal.java | 2 +- .../forcebattle/ForceHeightBattleGoal.java | 4 +- .../goal/forcebattle/ForceItemBattleGoal.java | 4 +- .../goal/forcebattle/ForceMobBattleGoal.java | 4 +- .../forcebattle/ForcePositionBattleGoal.java | 2 +- .../goal/forcebattle/targets/BlockTarget.java | 2 +- .../goal/forcebattle/targets/ItemTarget.java | 2 +- .../forcebattle/targets/PositionTarget.java | 6 +- .../setting/BackpackSetting.java | 6 +- .../setting/BastionSpawnSetting.java | 4 +- .../setting/CutCleanSetting.java | 6 +- .../setting/DamageDisplaySetting.java | 2 +- .../setting/DeathPositionSetting.java | 2 +- .../setting/DifficultySetting.java | 2 +- .../setting/EnderChestCommandSetting.java | 2 +- .../setting/FortressSpawnSetting.java | 2 +- .../setting/HealthDisplaySetting.java | 6 +- .../setting/ImmediateRespawnSetting.java | 2 +- .../setting/MaxHealthSetting.java | 10 +- .../setting/NoOffhandSetting.java | 2 +- .../implementation/setting/OldPvPSetting.java | 4 +- .../setting/PositionSetting.java | 4 +- .../setting/RespawnSetting.java | 2 +- .../setting/SlotLimitSetting.java | 2 +- .../implementation/setting/SoupSetting.java | 2 +- .../setting/SplitHealthSetting.java | 2 +- .../implementation/setting/TimberSetting.java | 4 +- .../setting/TopCommandSetting.java | 2 +- .../setting/TotemSaveDeathSetting.java | 2 +- .../challenges/type/EmptyChallenge.java | 4 +- .../plugin/challenges/type/IChallenge.java | 2 +- .../plugin/challenges/type/IGoal.java | 2 +- .../type/abstraction/AbstractChallenge.java | 6 +- .../abstraction/AbstractForceChallenge.java | 4 +- .../type/abstraction/CollectionGoal.java | 4 +- .../CompletableForceChallenge.java | 2 +- .../abstraction/EndingForceChallenge.java | 2 +- .../abstraction/ForceBattleDisplayGoal.java | 2 +- .../type/abstraction/ForceBattleGoal.java | 6 +- .../type/abstraction/ItemCollectionGoal.java | 2 +- .../type/abstraction/KillMobsGoal.java | 2 +- .../challenges/type/abstraction/MenuGoal.java | 2 +- .../type/abstraction/MenuSetting.java | 10 +- .../challenges/type/abstraction/Modifier.java | 4 +- .../abstraction/ModifierCollectionGoal.java | 2 +- .../abstraction/NetherPortalSpawnSetting.java | 2 +- .../type/abstraction/PointsGoal.java | 4 +- .../type/abstraction/RandomizerSetting.java | 6 +- .../challenges/type/abstraction/Setting.java | 6 +- .../type/abstraction/SettingGoal.java | 2 +- .../type/abstraction/SettingModifier.java | 4 +- .../SettingModifierCollectionGoal.java | 4 +- .../type/abstraction/SettingModifierGoal.java | 2 +- .../type/abstraction/TimedChallenge.java | 4 +- .../abstraction/WorldDependentChallenge.java | 2 +- .../type/helper/ChallengeConfigHelper.java | 2 +- .../type/helper/ChallengeHelper.java | 4 +- .../challenges/type/helper/GoalHelper.java | 2 +- .../type/helper/SubSettingsHelper.java | 6 +- .../plugin/content/ItemDescription.java | 2 +- .../challenges/plugin/content/Message.java | 4 +- .../plugin/content/impl/MessageImpl.java | 4 +- .../plugin/content/loader/LanguageLoader.java | 14 +- .../plugin/content/loader/LoaderRegistry.java | 2 +- .../plugin/content/loader/PrefixLoader.java | 6 +- .../plugin/content/loader/UpdateLoader.java | 6 +- .../management/blocks/BlockDropManager.java | 2 +- .../management/bstats/MetricsLoader.java | 10 +- .../challenges/ChallengeLoader.java | 2 +- .../challenges/ChallengeManager.java | 12 +- .../challenges/CustomChallengesLoader.java | 6 +- .../challenges/ModuleChallengeLoader.java | 6 +- .../annotations/RequireVersion.java | 2 +- .../entities/GamestateSaveable.java | 2 +- .../management/cloud/CloudSupportManager.java | 6 +- .../management/database/DatabaseManager.java | 28 +- .../management/files/ConfigManager.java | 14 +- .../inventory/PlayerInventoryManager.java | 10 +- .../plugin/management/menu/MenuManager.java | 10 +- .../generator/ChallengeMenuGenerator.java | 10 +- .../menu/generator/ChooseItemGenerator.java | 6 +- .../ChooseMultipleItemGenerator.java | 6 +- .../menu/generator/MenuGenerator.java | 4 +- .../generator/MultiPageMenuGenerator.java | 2 +- .../menu/generator/ValueMenuGenerator.java | 6 +- .../categorised/CategorisedMenuGenerator.java | 4 +- .../implementation/SettingsMenuGenerator.java | 2 +- .../implementation/TimerMenuGenerator.java | 6 +- .../custom/InfoMenuGenerator.java | 8 +- .../custom/MainCustomMenuGenerator.java | 4 +- .../custom/MaterialMenuGenerator.java | 2 +- .../menu/info/ChallengeMenuClickInfo.java | 2 +- .../menu/position/GeneratorMenuPosition.java | 2 +- .../scheduler/AbstractTaskExecutor.java | 2 +- .../management/scheduler/ScheduleManager.java | 4 +- .../scheduler/timer/ChallengeTimer.java | 6 +- .../scheduler/timer/TimerFormat.java | 2 +- .../management/server/GameWorldStorage.java | 2 +- .../server/GeneratorWorldPortalManager.java | 6 +- .../management/server/ServerManager.java | 10 +- .../management/server/TitleManager.java | 2 +- .../management/server/WorldManager.java | 8 +- .../server/scoreboard/ChallengeBossBar.java | 4 +- .../scoreboard/ChallengeScoreboard.java | 4 +- .../plugin/management/stats/PlayerStats.java | 4 +- .../plugin/management/stats/Statistic.java | 2 +- .../plugin/management/stats/StatsManager.java | 4 +- .../plugin/management/team/TeamProvider.java | 2 +- .../spigot/command/DatabaseCommand.java | 4 +- .../spigot/command/GamestateCommand.java | 2 +- .../plugin/spigot/command/HealCommand.java | 2 +- .../plugin/spigot/command/InvseeCommand.java | 4 +- .../spigot/command/LeaderboardCommand.java | 8 +- .../plugin/spigot/command/ResetCommand.java | 6 +- .../plugin/spigot/command/ResultCommand.java | 2 +- .../plugin/spigot/command/SearchCommand.java | 4 +- .../plugin/spigot/command/StatsCommand.java | 6 +- .../plugin/spigot/command/TimeCommand.java | 2 +- .../plugin/spigot/command/TimerCommand.java | 4 +- .../plugin/spigot/command/VillageCommand.java | 2 +- .../spigot/generator/VoidMapGenerator.java | 4 +- .../spigot/listener/BlockDropListener.java | 4 +- .../plugin/spigot/listener/CheatListener.java | 2 +- .../spigot/listener/CustomEventListener.java | 2 +- .../listener/PlayerConnectionListener.java | 4 +- .../utils/bukkit/command/PlayerCommand.java | 2 +- .../utils/bukkit/command/SenderCommand.java | 2 +- .../bukkit/jumpgeneration/IJumpGenerator.java | 2 +- .../jumpgeneration/RandomJumpGenerator.java | 2 +- .../utils/bukkit/misc/BukkitStringUtils.java | 6 +- .../bukkit/misc/version/MinecraftVersion.java | 114 --- .../utils/bukkit/misc/version/Version.java | 105 --- .../misc/version/VersionComparator.java | 13 - .../bukkit/misc/version/VersionInfo.java | 70 -- .../plugin/utils/bukkit/nms/NMSProvider.java | 8 +- .../plugin/utils/bukkit/nms/NMSUtils.java | 8 +- .../utils/bukkit/nms/ReflectionUtil.java | 2 +- .../v1_13/BorderPacketFactory_1_13.java | 2 +- .../v1_13/CraftPlayer_1_13.java | 4 +- .../v1_13/PacketBorder_1_13.java | 16 +- .../v1_13/PlayerConnection_1_13.java | 2 +- .../v1_13/WorldServer_1_13.java | 2 +- .../v1_17/BorderPacketFactory_1_17.java | 2 +- .../v1_17/CraftPlayer_1_17.java | 4 +- .../v1_18/PacketBorder_1_18.java | 10 +- .../v1_18/PlayerConnection_1_18.java | 2 +- .../plugin/utils/item/ItemBuilder.java | 4 +- .../plugin/utils/item/ItemUtils.java | 117 --- .../plugin/utils/logging/ConsolePrint.java | 2 +- .../plugin/utils/misc/DatabaseHelper.java | 4 +- .../plugin/utils/misc/InventoryUtils.java | 8 +- .../plugin/utils/misc/MapUtils.java | 4 +- .../utils/misc/MinecraftNameWrapper.java | 2 +- .../plugin/utils/misc/ParticleUtils.java | 4 +- .../plugin/utils/misc/StatsHelper.java | 2 +- .../challenges/plugin/utils/misc/Utils.java | 6 +- .../commons/bukkit/core/BukkitModule.java | 375 ++++++++++ .../bukkit/core/RequirementsChecker.java | 94 +++ .../bukkit/core/SimpleConfigManager.java | 44 ++ .../utils/animation/AnimatedInventory.java | 168 +++++ .../utils/animation/AnimationFrame.java | 84 +++ .../bukkit/utils/animation/SoundSample.java | 113 +++ .../utils/bstats/JsonObjectBuilder.java | 210 ++++++ .../commons/bukkit/utils/bstats/Metrics.java | 333 +++++++++ .../utils/bstats/chart/AdvancedBarChart.java | 47 ++ .../utils/bstats/chart/AdvancedPie.java | 47 ++ .../utils/bstats/chart/CustomChart.java | 40 ++ .../utils/bstats/chart/DrilldownPie.java | 51 ++ .../utils/bstats/chart/MultiLineChart.java | 47 ++ .../utils/bstats/chart/SimpleBarChart.java | 37 + .../bukkit/utils/bstats/chart/SimplePie.java | 32 + .../utils/bstats/chart/SingleLineChart.java | 32 + .../bukkit/utils/item/BannerPattern.java | 64 ++ .../bukkit/utils/item/ItemBuilder.java | 424 +++++++++++ .../commons/bukkit/utils/item/ItemUtils.java | 117 +++ .../commons/bukkit/utils/logging/Logger.java | 39 + .../bukkit/utils/menu/MenuClickInfo.java | 75 ++ .../bukkit/utils/menu/MenuPosition.java | 44 ++ .../bukkit/utils/menu/MenuPositionHolder.java | 16 + .../utils/menu/MenuPositionListener.java | 47 ++ .../menu/positions/EmptyMenuPosition.java | 16 + .../menu/positions/SlottedMenuPosition.java | 50 ++ .../utils/misc/BukkitReflectionUtils.java | 170 +++++ .../bukkit/utils/misc/CompatibilityUtils.java | 50 ++ .../bukkit/utils/misc/GameProfileUtils.java | 91 +++ .../bukkit/utils/misc/MinecraftVersion.java | 115 +++ .../bukkit/utils/wrapper/ActionListener.java | 57 ++ .../utils}/wrapper/AttributeWrapper.java | 4 +- .../bukkit/utils/wrapper/MaterialWrapper.java | 27 + .../utils/wrapper/SimpleEventExecutor.java | 31 + .../common/annotations/AlsoKnownAs.java | 17 + .../common/annotations/DeprecatedSince.java | 17 + .../common/annotations/ReplaceWith.java | 17 + .../commons/common/annotations/Since.java | 14 + .../common/collection/ArrayWalker.java | 56 ++ .../common/collection/ClassWalker.java | 65 ++ .../commons/common/collection/Colors.java | 38 + .../common/collection/FontBuilder.java | 93 +++ .../commons/common/collection/IOUtils.java | 43 ++ .../commons/common/collection/IRandom.java | 152 ++++ .../common/collection/NamedThreadFactory.java | 37 + .../common/collection/NumberFormatter.java | 357 ++++++++++ .../collection/PublicSecurityManager.java | 12 + .../common/collection/RandomWrapper.java | 149 ++++ .../common/collection/RomanNumerals.java | 47 ++ .../common/collection/RunnableTimerTask.java | 19 + .../collection/SeededRandomWrapper.java | 35 + .../common/collection/SingletonRandom.java | 13 + .../collection/StringBuilderPrintWriter.java | 28 + .../collection/StringBuilderWriter.java | 68 ++ .../commons/common/collection/Triple.java | 20 + .../commons/common/collection/Tuple.java | 19 + .../common/collection/WrappedException.java | 61 ++ .../commons/common/collection/pair/Pair.java | 32 + .../common/collection/pair/Quadro.java | 139 ++++ .../common/collection/pair/Triple.java | 123 ++++ .../commons/common/collection/pair/Tuple.java | 106 +++ .../cache/CleanAndWriteDatabaseCache.java | 118 ++++ .../concurrent/cache/CleanWriteableCache.java | 83 +++ .../concurrent/cache/CoolDownCache.java | 83 +++ .../concurrent/cache/DatabaseCache.java | 19 + .../common/concurrent/cache/ICache.java | 40 ++ .../concurrent/cache/WriteableCache.java | 17 + .../concurrent/task/CompletableTask.java | 169 +++++ .../common/concurrent/task/CompletedTask.java | 108 +++ .../commons/common/concurrent/task/Task.java | 228 ++++++ .../common/concurrent/task/TaskListener.java | 16 + .../commons/common/config/Config.java | 97 +++ .../commons/common/config/Document.java | 345 +++++++++ .../commons/common/config/FileDocument.java | 172 +++++ .../commons/common/config/Json.java | 48 ++ .../commons/common/config/PropertyHelper.java | 49 ++ .../commons/common/config/Propertyable.java | 199 ++++++ .../config/document/AbstractConfig.java | 278 ++++++++ .../config/document/AbstractDocument.java | 162 +++++ .../common/config/document/EmptyDocument.java | 518 ++++++++++++++ .../common/config/document/GsonDocument.java | 508 +++++++++++++ .../common/config/document/MapDocument.java | 292 ++++++++ .../config/document/PropertiesDocument.java | 285 ++++++++ .../common/config/document/YamlDocument.java | 355 ++++++++++ ...kkitReflectionSerializableTypeAdapter.java | 60 ++ .../document/gson/ClassTypeAdapter.java | 32 + .../document/gson/ColorTypeAdapter.java | 27 + .../document/gson/DocumentTypeAdapter.java | 46 ++ .../config/document/gson/GsonTypeAdapter.java | 62 ++ .../config/document/gson/PairTypeAdapter.java | 37 + .../readonly/ReadOnlyDocumentWrapper.java | 26 + .../document/wrapper/FileDocumentWrapper.java | 62 ++ .../document/wrapper/WrappedDocument.java | 510 ++++++++++++++ .../exceptions/ConfigReadOnlyException.java | 11 + .../commons/common/debug/TimingsHelper.java | 50 ++ .../common/discord/DiscordWebhook.java | 498 +++++++++++++ .../function/ExceptionallyBiConsumer.java | 21 + .../function/ExceptionallyBiFunction.java | 21 + .../function/ExceptionallyConsumer.java | 21 + .../function/ExceptionallyDoubleFunction.java | 21 + .../function/ExceptionallyFunction.java | 29 + .../function/ExceptionallyIntFunction.java | 21 + .../function/ExceptionallyLongFunction.java | 21 + .../function/ExceptionallyRunnable.java | 27 + .../function/ExceptionallySupplier.java | 27 + .../ExceptionallyToDoubleFunction.java | 21 + .../function/ExceptionallyToIntFunction.java | 21 + .../function/ExceptionallyToLongFunction.java | 21 + .../commons/common/logging/ILogger.java | 282 ++++++++ .../common/logging/ILoggerFactory.java | 15 + .../commons/common/logging/LogLevel.java | 82 +++ .../common/logging/LogOutputStream.java | 28 + .../common/logging/LoggingApiUser.java | 47 ++ .../common/logging/WrappedILogger.java | 159 +++++ .../logging/handler/HandledAsyncLogger.java | 23 + .../common/logging/handler/HandledLogger.java | 69 ++ .../logging/handler/HandledSyncLogger.java | 17 + .../common/logging/handler/LogEntry.java | 49 ++ .../common/logging/handler/LogHandler.java | 13 + .../logging/internal/BukkitLoggerWrapper.java | 25 + .../logging/internal/FallbackLogger.java | 62 ++ .../logging/internal/JavaLoggerWrapper.java | 666 ++++++++++++++++++ .../common/logging/internal/SimpleLogger.java | 365 ++++++++++ .../logging/internal/Slf4jILoggerWrapper.java | 173 +++++ .../logging/internal/Slf4jLoggerWrapper.java | 369 ++++++++++ .../factory/ConstantLoggerFactory.java | 29 + .../factory/DefaultLoggerFactory.java | 36 + .../internal/factory/Slf4jLoggerFactory.java | 25 + .../common/logging/lib/JavaILogger.java | 19 + .../common/logging/lib/Slf4jILogger.java | 41 ++ .../BukkitReflectionSerializationUtils.java | 101 +++ .../commons/common/misc/FileUtils.java | 565 +++++++++++++++ .../commons/common/misc/GsonUtils.java | 127 ++++ .../commons/common/misc/ImageUtils.java | 109 +++ .../commons/common/misc/MathHelper.java | 12 + .../commons/common/misc/PropertiesUtils.java | 18 + .../commons/common/misc/ReflectionUtils.java | 258 +++++++ .../common/misc/SimpleCollectionUtils.java | 143 ++++ .../commons/common/misc/StringUtils.java | 181 +++++ .../commons/common/version/Version.java | 105 +++ .../common/version/VersionComparator.java | 13 + .../commons/common/version/VersionInfo.java | 80 +++ .../codingarea/commons/database/Database.java | 110 +++ .../commons/database/DatabaseConfig.java | 105 +++ .../commons/database/EmptyDatabase.java | 288 ++++++++ .../codingarea/commons/database/Order.java | 13 + .../commons/database/SQLColumn.java | 134 ++++ .../database/SimpleDatabaseTypeResolver.java | 39 + .../commons/database/SpecificDatabase.java | 66 ++ .../abstraction/AbstractDatabase.java | 100 +++ .../abstraction/DefaultExecutedQuery.java | 124 ++++ .../abstraction/DefaultSpecificDatabase.java | 90 +++ .../database/access/CachedDatabaseAccess.java | 85 +++ .../database/access/DatabaseAccess.java | 33 + .../database/access/DatabaseAccessConfig.java | 32 + .../database/access/DirectDatabaseAccess.java | 69 ++ .../database/action/DatabaseAction.java | 82 +++ .../database/action/DatabaseCountEntries.java | 21 + .../database/action/DatabaseDeletion.java | 42 ++ .../database/action/DatabaseInsertion.java | 26 + .../action/DatabaseInsertionOrUpdate.java | 45 ++ .../database/action/DatabaseListTables.java | 18 + .../database/action/DatabaseQuery.java | 53 ++ .../database/action/DatabaseUpdate.java | 47 ++ .../database/action/ExecutedQuery.java | 86 +++ .../action/hierarchy/OrderedAction.java | 13 + .../database/action/hierarchy/SetAction.java | 11 + .../action/hierarchy/WhereAction.java | 29 + .../DatabaseAlreadyConnectedException.java | 12 + .../DatabaseConnectionClosedException.java | 12 + .../exceptions/DatabaseException.java | 31 + .../DatabaseUnsupportedFeatureException.java | 14 + .../exceptions/UnsignedDatabaseException.java | 24 + .../sql/abstraction/AbstractSQLDatabase.java | 134 ++++ .../database/sql/abstraction/SQLHelper.java | 37 + .../abstraction/count/SQLCountEntries.java | 54 ++ .../sql/abstraction/deletion/SQLDeletion.java | 110 +++ .../abstraction/insertion/SQLInsertion.java | 95 +++ .../insertorupdate/SQLInsertionOrUpdate.java | 85 +++ .../sql/abstraction/query/SQLQuery.java | 176 +++++ .../sql/abstraction/query/SQLResult.java | 33 + .../sql/abstraction/update/SQLUpdate.java | 140 ++++ .../sql/abstraction/where/ObjectWhere.java | 44 ++ .../sql/abstraction/where/SQLWhere.java | 13 + .../where/StringIgnoreCaseWhere.java | 41 ++ .../database/sql/mysql/MySQLDatabase.java | 36 + .../sql/mysql/list/MySQLListTables.java | 38 + .../database/sql/sqlite/SQLiteDatabase.java | 53 ++ .../sql/sqlite/list/SQLiteListTables.java | 38 + pom.xml | 1 - 495 files changed, 20080 insertions(+), 1010 deletions(-) create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java rename plugin/src/main/java/net/codingarea/{challenges/plugin/utils/bukkit/misc => commons/bukkit/utils}/wrapper/AttributeWrapper.java (80%) create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Config.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Document.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Json.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/Version.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/Database.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/Order.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 7dfe556eb..0fcaef25e 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc spigot-api @@ -45,12 +52,6 @@ ${project.version} - - com.github.anweisen.Utility - database-mongodb - ${utilities.version} - - diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index 745bf6468..ee9999e4d 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.mongoconnector; -import net.anweisen.utilities.database.internal.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.plugin.java.JavaPlugin; diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java new file mode 100644 index 000000000..f801ab556 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -0,0 +1,304 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.FileUtils; +import org.bson.BsonArray; +import org.bson.BsonValue; +import org.bson.json.JsonWriterSettings; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class BsonDocument extends AbstractDocument { + + protected org.bson.Document bsonDocument; + + public BsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public BsonDocument(@Nonnull Reader reader) { + BufferedReader buffered = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + StringBuilder content = new StringBuilder(); + buffered.lines().forEach(content::append); + bsonDocument = org.bson.Document.parse(content.toString()); + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument) { + this.bsonDocument = bsonDocument; + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.bsonDocument = bsonDocument; + } + + public BsonDocument() { + this(new org.bson.Document()); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + org.bson.Document document = bsonDocument.get(path, org.bson.Document.class); + if (document == null) { + bsonDocument.put(path, document = new org.bson.Document()); + } + + return new BsonDocument(document, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + BsonArray array = bsonDocument.get(path, BsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + for (BsonValue value : array) { + if (!value.isDocument()) continue; + String json = value.asDocument().toJson(); + org.bson.Document document = org.bson.Document.parse(json); + documents.add(new BsonDocument(document, root, this)); + } + return documents; + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = getObject(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + Object value = bsonDocument.get(path); + if (value instanceof Boolean) return (Boolean) value; + if (value instanceof String) return Boolean.parseBoolean((String) value); + } catch (Exception ex) { + } + return def; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return bsonDocument.get(path); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return bsonDocument.getList(path, String.class); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object value = bsonDocument.get(path); + if (value instanceof UUID) return (UUID) value; + if (value instanceof String) return UUID.fromString((String) value); + } catch (Exception ex) { + } + return null; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return bsonDocument.getDate(path); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof OffsetDateTime) + return (OffsetDateTime) value; + if (value instanceof Date) + return ((Date)value).toInstant().atOffset(ZoneOffset.UTC); + if (value instanceof String) + return OffsetDateTime.parse((CharSequence) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.time.OffsetDateTime"); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof Color) + return (Color) value; + if (value instanceof String) + return Color.decode((String) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.awt.Color"); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Override + public boolean contains(@Nonnull String path) { + return bsonDocument.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof org.bson.Document; + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isList(path) && !isDocument(path); + } + + @Override + public int size() { + return bsonDocument.size(); + } + + @Override + public void clear0() { + bsonDocument.clear(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + bsonDocument.put(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + bsonDocument.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + String json = bsonDocument.toString(); + writer.write(json); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(bsonDocument); + } + + @Nonnull + @Override + public Collection keys() { + return bsonDocument.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + bsonDocument.forEach(action); + } + + @Nonnull + @Override + public String toJson() { + return bsonDocument.toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return bsonDocument.toJson(JsonWriterSettings.builder().indent(true).build()); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java new file mode 100644 index 000000000..05611a0b0 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -0,0 +1,135 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.MongoClient; +import net.codingarea.commons.common.logging.ILogger; +import org.bson.*; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public final class BsonUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + + private BsonUtils() { + } + + @Nonnull + public static BsonDocument convertBsonToBsonDocument(@Nonnull Bson bson) { + return bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()); + } + + @Nullable + public static Object unpackBsonElement(@Nullable Object value) { + if (value == null || value instanceof BsonNull) { + return null; + } else if (value instanceof BsonString) { + return ((BsonString) value).getValue(); + } else if (value instanceof BsonDouble) { + return ((BsonDouble) value).getValue(); + } else if (value instanceof BsonInt32) { + return ((BsonInt32) value).getValue(); + } else if (value instanceof BsonInt64) { + return ((BsonInt64) value).getValue(); + } else if (value instanceof BsonBinary) { + return ((BsonBinary) value).getData(); + } else if (value instanceof BsonObjectId) { + return ((BsonObjectId) value).getValue(); + } else if (value instanceof BsonArray) { + return convertBsonArrayToList((BsonArray) value); + } else if (value instanceof BsonDocument) { + return convertBsonDocumentToMap((BsonDocument) value); + } else if (value instanceof Document) { + return value; + } else { + return value; + } + } + + @Nonnull + public static List convertBsonArrayToList(@Nonnull BsonArray array) { + List list = new ArrayList<>(array.size()); + for (BsonValue value : array) { + list.add(unpackBsonElement(value)); + } + return list; + } + + @Nonnull + public static Map convertBsonDocumentToMap(@Nonnull BsonDocument document) { + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + map.put(entry.getKey(), unpackBsonElement(entry.getValue())); + } + return map; + } + + @Nonnull + public static BsonValue convertObjectToBsonElement(@Nullable Object value) { + if (value == null) { + return BsonNull.VALUE; + } else if (value instanceof BsonValue) { + return (BsonValue) value; + } else if (value instanceof Bson) { + return convertBsonToBsonDocument((Bson) value); + } else if (value instanceof String) { + return new BsonString((String) value); + } else if (value instanceof Boolean) { + return new BsonBoolean((Boolean) value); + } else if (value instanceof ObjectId) { + return new BsonObjectId((ObjectId) value); + } else if (value instanceof Double) { + return new BsonDouble((Double) value); + } else if (value instanceof Float) { + return new BsonDouble((Float) value); + } else if (value instanceof Long) { + return new BsonInt64((Long) value); + } else if (value instanceof Integer) { + return new BsonInt32((Integer) value); + } else if (value instanceof Number) { + return new BsonInt32(((Number) value).intValue()); + } else if (value instanceof byte[]) { + return new BsonBinary((byte[]) value); + } else if (value instanceof Iterable) { + return convertIterableToBsonArray((Iterable) value); + } else if (value.getClass().isArray()) { + return convertArrayToBsonArray(value); + } else if (value instanceof Map) { + BsonDocument document = new BsonDocument(); + setDocumentProperties(document, (Map) value); + return document; + } else { + logger.error("Could not serialize " + value.getClass().getName() + " to BsonValue"); + return BsonNull.VALUE; + } + } + + public static void setDocumentProperties(@Nonnull BsonDocument document, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + document.put(entry.getKey(), convertObjectToBsonElement(value)); + } + } + + @Nonnull + public static BsonArray convertIterableToBsonArray(@Nonnull Iterable iterable) { + BsonArray bsonArray = new BsonArray(); + iterable.forEach(object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + + @Nonnull + public static BsonArray convertArrayToBsonArray(@Nonnull Object array) { + BsonArray bsonArray = new BsonArray(); + ReflectionUtils.forEachInArray(array, object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java new file mode 100644 index 000000000..d0c2c4a37 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Sorts; +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +public final class MongoUtils { + + private MongoUtils() { + } + + public static void applyWhere(@Nonnull FindIterable iterable, @Nonnull Map where) { + for (Entry entry : where.entrySet()) { + MongoDBWhere value = entry.getValue(); + iterable.filter(value.toBson()); + + Collation collation = value.getCollation(); + if (collation != null) + iterable.collation(collation); + } + } + + public static void applyOrder(@Nonnull FindIterable iterable, @Nullable String orderBy, @Nullable Order order) { + if (order == null || orderBy == null) return; + switch (order) { + case HIGHEST: + iterable.sort(Sorts.descending(orderBy)); + break; + case LOWEST: + iterable.sort(Sorts.ascending(orderBy)); + break; + } + } + + @Nullable + public static Object packObject(@Nullable Object value) { + if (value == null) { + return null; + } else if (value instanceof Json) { + String json = ((Json) value).toJson(); + return Document.parse(json); + } else if (BukkitReflectionSerializationUtils.isSerializable(value.getClass())) { + Map values = BukkitReflectionSerializationUtils.serializeObject(value); + if (values == null) return null; + BsonDocument bson = new BsonDocument(); + BsonUtils.setDocumentProperties(bson, values); + return bson; + } else if (value instanceof UUID) { + return ((UUID) value).toString(); + } else { + return value; + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java new file mode 100644 index 000000000..e6789feda --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java @@ -0,0 +1,148 @@ +package net.codingarea.commons.database.mongodb; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.mongodb.count.MongoDBCountEntries; +import net.codingarea.commons.database.mongodb.deletion.MongoDBDeletion; +import net.codingarea.commons.database.mongodb.insertion.MongoDBInsertion; +import net.codingarea.commons.database.mongodb.insertorupdate.MongoDBInsertionOrUpdate; +import net.codingarea.commons.database.mongodb.list.MongoDBListTables; +import net.codingarea.commons.database.mongodb.query.MongoDBQuery; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class MongoDBDatabase extends AbstractDatabase { + + static { + Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); + } + + protected MongoClient client; + protected MongoDatabase database; + + public MongoDBDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void connect0() throws Exception { + MongoCredential credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabase(), config.getPassword().toCharArray()); + MongoClientSettings settings = MongoClientSettings.builder() + .retryReads(false).retryReads(false) + .credential(credential) + .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress(config.getHost(), config.isPortSet() ? config.getPort() : ServerAddress.defaultPort())))) + .build(); + client = MongoClients.create(settings); + database = client.getDatabase(config.getDatabase()); + } + + @Override + public void disconnect0() throws Exception { + client.close(); + client = null; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + checkConnection(); + + boolean collectionExists = listTables().execute().contains(name); + if (collectionExists) return; + + try { + database.createCollection(name); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MongoDBListTables(this); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new MongoDBCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new MongoDBQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new MongoDBQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new MongoDBUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new MongoDBInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new MongoDBInsertion(this, table, new Document(values)); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Document document) { + return new MongoDBInsertion(this, table, document); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new MongoDBInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new MongoDBDeletion(this, table); + } + + @Nonnull + public MongoCollection getCollection(@Nonnull String collection) { + return database.getCollection(collection); + } + + @Nonnull + public MongoDatabase getDatabase() { + return database; + } + + @Override + public boolean isConnected() { + return client != null && database != null; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java new file mode 100644 index 000000000..e1b185de5 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.mongodb.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class MongoDBCountEntries implements DatabaseCountEntries { + + protected final MongoDBDatabase database; + protected final String table; + + public MongoDBCountEntries(@Nonnull MongoDBDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + return database.getCollection(table).countDocuments(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBCountEntries that = (MongoDBCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java new file mode 100644 index 000000000..3073dbb40 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.database.mongodb.deletion; + +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.DeleteOptions; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class MongoDBDeletion implements DatabaseDeletion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where = new HashMap<>(); + + public MongoDBDeletion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::ne)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + DeleteOptions options = new DeleteOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + collection.deleteMany(filter, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBDeletion that = (MongoDBDeletion) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java new file mode 100644 index 000000000..10e38cfc6 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.database.mongodb.insertion; + +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class MongoDBInsertion implements DatabaseInsertion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Document values; + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.values = new Document(); + } + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Document values) { + this.database = database; + this.collection = collection; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + database.getCollection(collection).insertOne(values); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBInsertion that = (MongoDBInsertion) o; + return database.equals(that.database) && collection.equals(that.collection) && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java new file mode 100644 index 000000000..295751f3d --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.mongodb.insertorupdate; + +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map.Entry; + +public class MongoDBInsertionOrUpdate extends MongoDBUpdate implements DatabaseInsertionOrUpdate { + + public MongoDBInsertionOrUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + super(database, collection); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + super.where(field, value, ignoreCase); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value) { + super.whereNot(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value) { + super.set(field, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(collection, where).execute().isSet()) { + return super.execute(); + } else { + Document document = new Document(values); + for (Entry entry : where.entrySet()) { + BsonDocument bson = BsonUtils.convertBsonToBsonDocument(entry.getValue().toBson()); + document.putAll(bson); + } + + database.insert(collection, document).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java new file mode 100644 index 000000000..987eba440 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.mongodb.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public class MongoDBListTables implements DatabaseListTables { + + protected final MongoDBDatabase database; + + public MongoDBListTables(@Nonnull MongoDBDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + return database.getDatabase().listCollectionNames().into(new ArrayList<>()); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java new file mode 100644 index 000000000..e1e11832b --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java @@ -0,0 +1,128 @@ +package net.codingarea.commons.database.mongodb.query; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public class MongoDBQuery implements DatabaseQuery { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected Order order; + protected String orderBy; + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + } + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where) { + this.database = database; + this.collection = collection; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + FindIterable iterable = database.getCollection(collection).find(); + MongoUtils.applyWhere(iterable, where); + MongoUtils.applyOrder(iterable, orderBy, order); + + List documents = iterable.into(new ArrayList<>()); + return createExecutedQuery(documents); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull List documents) { + List results = new ArrayList<>(documents.size()); + for (Document document : documents) { + results.add(new MongoDBResult(document)); + } + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBQuery that = (MongoDBQuery) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where) && order == that.order && Objects.equals(orderBy, that.orderBy); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, order, orderBy); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java new file mode 100644 index 000000000..c65457f05 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.mongodb.query; + +import net.codingarea.commons.common.config.document.BsonDocument; + +import javax.annotation.Nonnull; + +public final class MongoDBResult extends BsonDocument { + + public MongoDBResult(@Nonnull org.bson.Document bsonDocument) { + super(bsonDocument); + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java new file mode 100644 index 000000000..6e30f14f4 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.database.mongodb.update; + +import com.mongodb.BasicDBObject; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; + +public class MongoDBUpdate implements DatabaseUpdate { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected final Map values; + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.collection = collection; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + UpdateOptions options = new UpdateOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + Document newDocument = new Document(); + for (Entry entry : values.entrySet()) { + newDocument.put(entry.getKey(), MongoUtils.packObject(entry.getValue())); + } + + BasicDBObject update = new BasicDBObject(); + update.put("$set", newDocument); + + collection.updateMany(filter, update, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBUpdate that = (MongoDBUpdate) o; + return database.equals(that.database) + && collection.equals(that.collection) + && where.equals(that.where) + && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java new file mode 100644 index 000000000..64a41b89e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface MongoDBWhere { + + @Nonnull + Bson toBson(); + + @Nullable + Collation getCollation(); + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java new file mode 100644 index 000000000..84852ffb2 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import net.codingarea.commons.common.misc.MongoUtils; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.BiFunction; + +public class ObjectWhere implements MongoDBWhere { + + protected final String field; + protected final Object value; + protected final BiFunction creator; + + public ObjectWhere(@Nonnull String field, @Nullable Object value, @Nonnull BiFunction creator) { + this.field = field; + this.value = MongoUtils.packObject(value); + this.creator = creator; + } + + @Nonnull + @Override + public Bson toBson() { + return creator.apply(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return field.equals(that.field) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..d7e875f8e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.CollationStrength; +import com.mongodb.client.model.Filters; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements MongoDBWhere { + + protected final String field; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String field, @Nonnull String value) { + this.field = field; + this.value = value; + } + + @Nonnull + @Override + public Bson toBson() { + return Filters.eq(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return field.equals(that.field) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/plugin/pom.xml b/plugin/pom.xml index 1e1785238..edfeaadca 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc @@ -27,11 +34,6 @@ ${spigot.version} provided - - com.github.anweisen.Utility - bukkit-utils - ${utilities.version} - com.mojang authlib @@ -59,18 +61,6 @@ provided - - - com.github.anweisen.Utility - database-api - ${utilities.version} - - - com.github.anweisen.Utility - database-sql - ${utilities.version} - - org.projectlombok @@ -88,12 +78,6 @@ - - - jitpack.io - https://jitpack.io - - spigot-repo @@ -171,11 +155,7 @@ - com.github.anweisen.Utility:commons - com.github.anweisen.Utility:common-utils - com.github.anweisen.Utility:bukkit-utils - com.github.anweisen.Utility:database-api - com.github.anweisen.Utility:database-sql + net.kyori:adventure-api diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 08ba1633e..1cec3de1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin; import lombok.Getter; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index e0f17ae5a..e8a2e9237 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 117bead96..1cc84980d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 586ff2b89..d808902a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index a452f268a..22194c0dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import java.util.Map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index fc56b49a4..20915daf0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 2180fcc5e..bb6e2ecf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 8044df01f..76de8e406 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index 71165a4c1..f370a9651 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index 6e835fdcc..bd618a663 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -31,8 +31,8 @@ public void executeFor(Entity entity, Map subActions) { livingEntity.addPotionEffect(effect); } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Error while adding potion effect to player"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().severe("Error while adding potion effect to player"); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index 036b63421..f51cddf9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index f84400c0a..1c967aab1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 9e549f65d..76dbdf823 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.impl.MessageManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 99db78f06..2ba7ab835 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; public abstract class ValueSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 6e28dfb55..5ed694708 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -2,7 +2,7 @@ import com.google.common.collect.Lists; import lombok.Getter; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index f8702057c..48623e544 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index 8b68286e1..93269312d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.type.IModifier; @@ -86,9 +86,9 @@ public int getIntValue(String value) { try { return Integer.parseInt(value); } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Something went wrong while parsing the " + Challenges.getInstance().getILogger().severe("Something went wrong while parsing the " + "value of subsetting " + getKey() + " with value " + value); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return 0; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index fb20cdc25..a0ca61a73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 1ed8be435..01256bb88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index cdffe4629..3a394f7c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.implementation.setting.MaxHealthSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 53f3059fa..b1688facf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 7b1642b87..1fe1e8ac6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 320d562d6..24614d601 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 5c9ce881f..5c5e8222f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 677f1af99..67f64d91f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 47e5c80fa..39056f367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 91e7dc361..9857ad5a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index fc4ca4027..30b0a6d39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 637ce9f8b..b140744a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 14eec8b49..5b7ebeaa8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index a75beacdb..5b15d051e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index f9f6943a8..f7ed9e957 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index a60f5a536..01cb2af32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 862aab974..e82b06d22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index b5c05902a..0d9df9a5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index de20c8bae..064c9b2c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 86dbb758e..e87867380 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 2bce869e2..b11f85864 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 630d0ce7d..08491be15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 60229a8b0..f91b95b93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index dd68e68e9..bfa6fc65d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index cf65586a8..26a31ea9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 8d60cccb2..85ae08737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 838947644..fd61eda4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 7bcd5ab9f..261f26e45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index a726d2019..47074dea0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 56fb97ae6..8e7ad6ab9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -1,10 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -15,7 +16,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.md_5.bungee.api.chat.BaseComponent; @@ -197,7 +197,7 @@ private Tuple generateMissingItemsInventory(@Nonnull ItemSta inventory.setItem(slot, getRandomItem(itemStack)); } catch (Exception exception) { inventory.setItem(slot, new ItemStack(Material.BARRIER)); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index e086bd6ed..3a9dbd54e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 762143d4a..fe6b3f63c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 52747ff62..6b86b70af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index dca729ffa..486f05d40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 47e33eabd..7c3ddab89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index cfd3921b5..899c446cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 8f1df0fb9..d43893978 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 772f3e71f..5c22246d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 2bafe978f..5cf2c4414 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index d62b3dfcc..188c7dbb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 5b7f33b5e..5f2beb3a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index e69bb3116..c56645114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 68310cd3d..25ec885dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -57,7 +57,7 @@ public void onLootGenerate(LootGenerateEvent event) { Challenges.getInstance().registerListener(listener); } catch (NoClassDefFoundError noClassDefFoundError) { - Challenges.getInstance().getLogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); + Challenges.getInstance().getILogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); } @@ -176,7 +176,7 @@ public void loadGameState(@NotNull Document document) { } catch (IllegalArgumentException exception) { plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " + "key '" + key + "' is not a valid uuid"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 3e7c18af7..8b1b57f9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index a85e9bcc3..bc8eb2b81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 40caffe17..779262f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 9d63f1bd2..fb7817f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index cbbf640d3..7b3a20314 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index e540ea849..90b44a7e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; @@ -15,7 +15,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 7dabca933..ae3433268 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index a4ea3360c..72628c416 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index a0b258204..659d6be31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 004217c96..32c31c8f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index d454c4c65..aff8383d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; @@ -207,7 +207,7 @@ private int getSpawnLimit(@Nonnull World world) { try { return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); } catch (Throwable throwable) { - Challenges.getInstance().getLogger().error("", throwable); + Challenges.getInstance().getILogger().error("", throwable); } } case WATER_ANIMAL: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index c5c5e477e..16f8537a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index e876a7287..f378b2c0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 7e897854d..55820aaee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomItemAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index bb87ca313..b7e3a964e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 94d4b7ec5..cf96f92f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index f20c39856..33ded8246 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index 007749f92..cdc626c77 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 8dd334665..b1686d8a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Color; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index b76cfe7c1..fcd1ae478 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index f8f582a8b..515636263 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index a2a6021aa..116e3760e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index b6ee091f0..9ea5570da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 79eb21ac8..00369062f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index fa448c186..61a77a830 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f61e93990..f86204b47 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index c2e0120a4..2e1c5c8a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index b730729d6..b17959b79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 93c033f50..b3c46958b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 5a66768cb..e615d4b96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 72ab023d9..000dea1ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,7 +13,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index 6588aa766..a0b2dc226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 4af53408c..28ae22550 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 50fcc15d6..92e6e160c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 5e8518a16..127b856eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index d7e86c3ec..ee0c8ee49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 5c86340c9..303b56631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -1,10 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 4e80c2757..ff3a3e747 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 42cbc8f41..1631103ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 449d3d2e5..e2e7cbffe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index a1acc29bf..2e710b704 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index d9145b4c8..1e28b334f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index 5fa0758ad..c371f63f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 2a5a98552..d0c36d32b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 6fbb0a0ca..8027dc78b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index e90d6996e..2fa73fcf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 3c6ce547b..e84756f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index 035471b55..00a768f51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 94644d28d..394272035 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index b5dede66f..bd79ebbed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 0474468bf..aa3ed1570 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 149be26d3..170fb80ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 06c17811c..376d625c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 86c667581..0b97d4274 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index d8ae5cfcd..eed2c9d87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index 02650f3b6..4a1cb5ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 1b1290707..3aa197d2f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index d2d062dda..f84395c18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index d45086267..6fd97c7be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index 1059a1d3a..e98c71fbf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 6bf8f41fc..551b46b8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index 3aa89c5a3..0834bea22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index a834abae8..16a7bb90f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index abe805f0d..e27fb4c3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 98f0b326b..b4405e994 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 8f1e96643..d63c7a93f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 27a6b402e..ed4f63bf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 711414e17..7e8908424 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index 9290b0d2b..bd9a823b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 3010f5a48..783e07722 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BiomeTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 1ecf964ab..b2764d8ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 64896b11d..9f5519808 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.DamageTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index e454d07e0..399dbb267 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.HeightTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index bec126bed..826021f01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index be2caa7ec..3325a2396 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 885f1ceda..5e9a2c85e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 51ed23a66..088da9146 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -3,9 +3,9 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index 5b2b1d526..d775f5a09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 7d5012c5a..524057bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 34bed85b8..3b02b1a14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -118,7 +118,7 @@ protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Non if (value == null) return; BukkitSerialization.fromBase64(inventory, value); } catch (IOException exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index bc31d6d29..3c062bb33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index dc5e9aea1..c30223490 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 8e029ac56..303ddf53a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 6f5c14d5f..f0e163278 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 55c7a7a51..f6368a423 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 659aaeec7..551859310 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 748011a2d..f4abafbc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 55176e6ed..e1134eb6c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -67,7 +67,7 @@ private void show(@Nonnull Player player) { try { objective.setRenderType(RenderType.HEARTS); } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); + Challenges.getInstance().getILogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); // In some versions of spigot RenderType does not exist } @@ -82,7 +82,7 @@ private void hide(@Nonnull Player player) { try { objective.unregister(); } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Error while unregistering tablist hearts objective"); + Challenges.getInstance().getILogger().severe("Error while unregistering tablist hearts objective"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index fa6eb8e24..088db39dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index f460ecd9d..68ca3bde3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.item.MaterialWrapper; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 0e0b09421..23be5b36a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 3fa5c2747..054dd292d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 98529fca2..c1b1ce733 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 635874ed7..4be83995e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 3627347ee..6b3f76e71 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 60e150200..3881c0cc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 4333b5525..da91a8eef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 36e89c03c..c4bc864bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 0d5e1a187..627bd099e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 2199b8451..74bd86114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index b96458fd0..4ef7440cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 708f9e99e..506d29f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index c3943a7a4..6f597140d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 929fd8e19..35838577d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -2,9 +2,9 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.common.annotations.DeprecatedSince; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index 65ab3cde8..102977b53 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 3e155e5a3..2ad3bacf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 24c3742b1..0c2ef8b48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 721c5a343..4c29f8444 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index 694afe425..b92624eed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 8aa1b47ed..0ff8f60b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 301d87772..aeec44b76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 6b772881a..5b10af2c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index 34a101526..11da3d1d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index cee709060..b2d8270ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.EmptyMenuPosition; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 1c7edca94..e6676859a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -68,7 +68,7 @@ public void setValue(int value) { try { if (isEnabled()) onValueChange(); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); } updateItems(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 4a71765d2..c656d0ff7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 33b52d8a5..5fc09751b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index d37d3abc7..58a57c890 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index f625256b8..29a6f6e87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 33804057c..3539e476a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -76,7 +76,7 @@ public void setEnabled(boolean enabled) { if (enabled) onEnable(); else onDisable(); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); } updateItems(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index d969538ca..92721607a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 59c5c6f4b..7d407578f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index a29db2230..75f07e057 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 841c6e433..aab2ddca6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 2c527f4a4..a4255303a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 3b7a6253e..6e57cc5c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index a99261bce..cc59d1b49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 79a3b346d..7cfd70ce4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index e567f1e48..1051d797c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 1f10fa067..f4dfa9226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 11e321c84..9ea299e7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.misc.ColorConversions; import org.bukkit.ChatColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index 2d5082f33..a7266d1a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index 5c888eec8..bbef01e1d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content.impl; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 556bab187..fc34aca48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -5,12 +5,12 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; -import net.anweisen.utilities.common.misc.GsonUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; @@ -147,7 +147,7 @@ private void download() { Logger.debug("Writing language {} to {}", name, file); verifyLanguage(language, file, name); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 9b9a8952d..05a44760a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index 4cd3d8f02..0cf9321b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.content.Prefix; import java.io.File; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index bec84bcee..129814eb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.content.loader; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 8f639b03f..6d9734968 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.blocks; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.implementation.setting.CutCleanSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting.SubSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 733f50598..92bd18d14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.bstats; -import net.anweisen.utilities.bukkit.utils.bstats.Metrics; -import net.anweisen.utilities.bukkit.utils.bstats.chart.AdvancedPie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SimplePie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SingleLineChart; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.bstats.Metrics; +import net.codingarea.commons.bukkit.utils.bstats.chart.AdvancedPie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SimplePie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SingleLineChart; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.misc.MemoryConverter; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index adafa7d83..cf5b7a59a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 7938c1f73..da5245eac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.wrapper.FileDocumentWrapper; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 849b9d866..4696a756d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.challenges; import lombok.Getter; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; @@ -70,8 +70,8 @@ public void loadCustomChallengesFrom(@Nonnull Document document) { challenge.setEnabled(doc.getBoolean("enabled")); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index c04f78eb5..28950d530 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 67c14cba2..3f76cf0df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges.annotations; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import javax.annotation.Nonnull; import java.lang.annotation.ElementType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 4f24c0ff8..58f269cee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges.entities; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index cc98c7bc8..ff36638d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.cloud; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.cloud.support.CloudNet2Support; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index 36019f377..1ff4612f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -1,19 +1,19 @@ package net.codingarea.challenges.plugin.management.database; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.database.Database; -import net.anweisen.utilities.database.DatabaseConfig; -import net.anweisen.utilities.database.SQLColumn; -import net.anweisen.utilities.database.action.ExecutedQuery; -import net.anweisen.utilities.database.exceptions.DatabaseException; -import net.anweisen.utilities.database.internal.sql.abstraction.AbstractSQLDatabase; -import net.anweisen.utilities.database.internal.sql.mysql.MySQLDatabase; -import net.anweisen.utilities.database.internal.sql.sqlite.SQLiteDatabase; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.MySQLDatabase; +import net.codingarea.commons.database.sql.sqlite.SQLiteDatabase; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -107,10 +107,10 @@ private void loadMigration() { } catch (DatabaseException databaseException) { try { sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); - Challenges.getInstance().getLogger().info("Creating not existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getILogger().info("Creating not existing column 'custom_challenges' in SQL Database"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 6b589a3e2..73ad01456 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.management.files; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.YamlDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -73,7 +73,7 @@ public YamlConfiguration getDefaultConfig() { return defaultConfig; } catch (IOException | NullPointerException | InvalidConfigurationException exception) { plugin.getLogger().severe("Error while checking missing keys in the current config"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 331ba48f4..e2c86f35f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.inventory; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index ad1b72506..f4f63b65e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index d5bb0eaa4..6996e9588 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu.generator; import com.google.common.collect.ImmutableList; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index 4a651f33e..b268c8558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 1cffe6938..8efcc07f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index d63a57f47..5fadbe3f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -2,8 +2,8 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 79798c9e8..e0a398b3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index fe49411ca..42bcb88e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.menu.generator; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 44ff6898c..865652da3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 7b3334c6b..02585fecf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 36c597f33..194f6e778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 0e5abe92e..0700ff5bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 3286ecd78..2f5417ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index 46ef222e5..ff40c7b97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index ceff6e5cd..53b285c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.info; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 3fcbcb702..694b9463f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.position; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index 1e77f5ddf..eecf8b281 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index cac8bf196..9c3c5e88b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index c3cddbee6..44d2789c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index d06b1fcf4..f96662dbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index 3c459357b..fa4c045dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.spigot.generator.VoidMapGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 167230187..6d192f443 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import org.bukkit.Location; @@ -61,8 +61,8 @@ public void loadGameState(@NotNull Document document) { UUID uuid = UUID.fromString(key); lastWorldLocations.put(uuid, location); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Couldn't load last location of: " + key); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Couldn't load last location of: " + key); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 635ca5ad2..a94da3f0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 5f9049f44..e27a364d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server; import lombok.Getter; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 2a995251f..2d7435838 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 5cd463aa5..a1f7d0ba8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server.scoreboard; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 2df8a1d38..d61318aee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -2,8 +2,8 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index 323ab33ec..32f93b00f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; import java.util.EnumMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index 1768554da..c577f2b18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import javax.annotation.Nonnull; import java.util.function.Function; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index a38572dc3..6a83e2f97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.stats; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a79e00ec1..a633ec0d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.team; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 69d1d4da7..987cc8bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 9fbeb77f5..ae464b130 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 664b388d3..314ba6555 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 85cfe3f5f..e32682f0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 8f9752051..605a0a634 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 88cb3bc79..e463a4d51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -69,7 +69,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { try { seed = Long.parseLong(seedInput); } catch (NumberFormatException exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index 0c9313f58..c5f7ef062 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 1248a6519..1997de2b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 5e222ab6d..d14ea9e61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index a202e72c5..de37a99cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index 2a451558d..c1a6a2e8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index f4a514e70..41b8f4d89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index ce34a1044..387af43cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.generator; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -36,7 +36,7 @@ public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, } // if (portalChunk.chunkX == x && portalChunk.chunkZ == z) { -// Challenges.getInstance().getLogger().info("Generating End Portal"); +// Challenges.getInstance().getILogger().info("Generating End Portal"); // generateEndPortal(chunkData); // break; // } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index 1a82f62ba..8457776c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.GameMode; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 00b11602f..00de88ed9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 05e6668f2..82dfe55ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.spigot.events.*; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index f8a2f62f1..22ef71374 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -127,7 +127,7 @@ public void onQuit(@Nonnull PlayerQuitEvent event) { Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while handling disconnect", exception); + Challenges.getInstance().getILogger().error("Error while handling disconnect", exception); } if (Bukkit.getOnlinePlayers().size() <= 1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index a2f83c357..650a3e5f7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 924e681a0..776df6c8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index 10294e07c..f403eeceb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index c0d460d35..fe582fe7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index a41712252..c5f73691e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.logging.ILogger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; import net.codingarea.challenges.plugin.content.Prefix; import net.md_5.bungee.api.chat.*; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java deleted file mode 100644 index 2077593a8..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import org.bukkit.Bukkit; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; - -public enum MinecraftVersion implements Version { - - V1_0, // 1.0 - V1_1, // 1.1 - V1_2_1, // 1.2.1 - V1_3_1, // 1.3.1 - V1_4_2, // 1.4.2 - V1_5, // 1.5 - V1_6, // 1.6 - V1_7, // 1.7 - V1_7_2, // 1.7.2 - V1_8, // 1.8 - V1_9, // 1.9 - V1_10, // 1.10 - V1_11, // 1.11 - V1_12, // 1.12 - V1_13, // 1.13 - V1_14, // 1.14 - V1_15, // 1.15 - V1_16, // 1.16 - V1_16_5, // 1.16.5 - V1_17, // 1.17 - V1_18, // 1.18 - V1_19, // 1.19 - V1_20, // 1.20 - V1_20_1, // 1.20.1 - V1_20_2, // 1.20.2 - V1_20_3, // 1.20.3 - V1_20_4, // 1.20.4 - V1_20_5, // 1.20.5 - V1_21, // 1.21 - V1_21_1, // 1.21.1 - V1_21_2, // 1.21.2 - V1_21_3, // 1.21.3 - V1_21_4, // 1.21.4 - V1_21_5 // 1.21.5 - ; - - private final int major, minor, revision; - - MinecraftVersion() { - - String name = this.name().substring(1); - String[] version = name.split("_"); - - if (version.length != 2 && version.length != 3) - throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); - - major = Integer.parseInt(version[0]); - minor = Integer.parseInt(version[1]); - revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; - - } - - @Override - public int getMajor() { - return major; - } - - @Override - public int getMinor() { - return minor; - } - - @Override - public int getRevision() { - return revision; - } - - @Override - public String toString() { - return this.format(); - } - - @Nonnull - @CheckReturnValue - public static Version parseExact(@Nonnull String bukkitVersion) { - bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); - return Version.parse(bukkitVersion); - } - - @Nonnull - @CheckReturnValue - public static Version findNearest(@Nonnull Version realVersion) { - return Version.findNearest(realVersion, values()); - } - - private static Version currentExact; - private static Version current; - - @Nonnull - @CheckReturnValue - public static Version currentExact() { - if (currentExact == null) - currentExact = parseExact(Bukkit.getBukkitVersion()); - return currentExact; - } - - @Nonnull - @CheckReturnValue - public static Version current() { - if (current == null) - current = findNearest(currentExact()); - return current; - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java deleted file mode 100644 index e21567f10..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java +++ /dev/null @@ -1,105 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import net.anweisen.utilities.common.annotations.Since; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.*; - -public interface Version { - @Nonnegative - int getMajor(); - - @Nonnegative - int getMinor(); - - @Nonnegative - int getRevision(); - - default boolean isNewerThan(@Nonnull Version other) { - return this.intValue() > other.intValue(); - } - - default boolean isNewerOrEqualThan(@Nonnull Version other) { - return this.intValue() >= other.intValue(); - } - - default boolean isOlderThan(@Nonnull Version other) { - return this.intValue() < other.intValue(); - } - - default boolean isOlderOrEqualThan(@Nonnull Version other) { - return this.intValue() <= other.intValue(); - } - - default boolean equals(@Nonnull Version other) { - return this.intValue() == other.intValue(); - } - - @Nonnull - default String format() { - int revision = this.getRevision(); - return revision > 0 ? String.format("%s.%s.%s", this.getMajor(), this.getMinor(), revision) : String.format("%s.%s", this.getMajor(), this.getMinor()); - } - - default int intValue() { - int major = this.getMajor(); - int minor = this.getMinor(); - int revision = this.getRevision(); - if (major > 99) { - throw new IllegalStateException("Malformed version: major is greater than 99"); - } else if (minor > 99) { - throw new IllegalStateException("Malformed version: minor is greater than 99"); - } else if (revision > 99) { - throw new IllegalStateException("Malformed version: revision is greater than 99"); - } else { - return revision + minor * 100 + major * 10000; - } - } - - @Nonnull - @CheckReturnValue - static Version parse(@Nullable String input) { - return parse(input, new VersionInfo(1, 0, 0)); - } - - @CheckReturnValue - static Version parse(@Nullable String input, Version def) { - return VersionInfo.parse(input, def); - } - - @Nonnull - @CheckReturnValue - static Version parseExceptionally(@Nullable String input) { - return VersionInfo.parseExceptionally(input); - } - - @Nonnull - @CheckReturnValue - static Version getAnnotatedSince(@Nonnull Object object) { - return (Version) (!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(object.getClass().getAnnotation(Since.class).value())); - } - - @Nonnull - @CheckReturnValue - static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { - List versions = new ArrayList(Arrays.asList(sortedVersionsArray)); - Collections.reverse(versions); - - for (V version : versions) { - if (!version.isNewerThan(target)) { - return version; - } - } - - throw new IllegalArgumentException("No version found for '" + target + "'"); - } - - @Nonnull - @CheckReturnValue - static Comparator comparator() { - return new VersionComparator(); - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java deleted file mode 100644 index 3f937009f..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import javax.annotation.Nonnull; -import java.util.Comparator; - -public class VersionComparator implements Comparator { - public VersionComparator() { - } - - public int compare(@Nonnull Version v1, @Nonnull Version v2) { - return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java deleted file mode 100644 index af9f78e34..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import lombok.Getter; -import net.anweisen.utilities.common.logging.ILogger; - -import javax.annotation.Nullable; -import java.util.Objects; - -@Getter -public class VersionInfo implements Version { - protected static final ILogger logger = ILogger.forThisClass(); - private final int major; - private final int minor; - private final int revision; - - public VersionInfo() { - this(1, 0, 0); - } - - public VersionInfo(int major, int minor, int revision) { - this.major = major; - this.minor = minor; - this.revision = revision; - } - - public boolean equals(Object other) { - if (this == other) { - return true; - } else { - return other instanceof Version && this.equals(other); - } - } - - public int hashCode() { - return Objects.hash(this.major, this.minor, this.revision); - } - - public String toString() { - return this.format(); - } - - public static Version parseExceptionally(@Nullable String input) { - if (input == null) { - throw new IllegalArgumentException("Version cannot be null"); - } else { - String[] array = input.split("\\."); - if (array.length == 0) { - throw new IllegalArgumentException("Version cannot be empty"); - } else { - try { - int major = Integer.parseInt(array[0]); - int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; - int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; - return new VersionInfo(major, minor, revision); - } catch (Exception ex) { - throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); - } - } - } - } - - public static Version parse(@Nullable String input, Version def) { - try { - return parseExceptionally(input); - } catch (Exception ex) { - logger.error("Could not parse version for input {}", ex.getMessage()); - return def; - } - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 66995d593..4b941e688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.*; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.BorderPacketFactory_1_17; @@ -48,7 +48,7 @@ public static WorldServer createWorldServer(World world) { return new WorldServer_1_13(world); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); } @@ -68,7 +68,7 @@ public static CraftPlayer createCraftPlayer(Player player) { return new CraftPlayer_1_13(player); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); } @@ -88,7 +88,7 @@ public static PlayerConnection createPlayerConnection(CraftPlayer player) { return new PlayerConnection_1_13(player.getPlayerConnectionObject()); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java index ec89489cc..65ac625ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java @@ -20,7 +20,7 @@ public static void setEntityName(Entity entity, BaseComponent baseComponent) { Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{componentClass}, new Object[]{componentObject}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } @@ -33,7 +33,7 @@ public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{getComponentClass()}, new Object[]{component}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } @@ -44,7 +44,7 @@ public static Object toIChatBaseComponent(BaseComponent baseComponent) { Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; } @@ -63,7 +63,7 @@ public static Class getClass(String path) { return ReflectionUtil.getNmsClass(className); } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index e3aa8212c..b989752b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -76,7 +76,7 @@ public class ReflectionUtil { } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { - Challenges.getInstance().getLogger().error("Failed to initialize the ReflectionUtil:", e); + Challenges.getInstance().getILogger().error("Failed to initialize the ReflectionUtil:", e); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index ab832b11c..325144b6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -39,7 +39,7 @@ private Object createPacket(PacketBorder packetBorder, String worldBorderAction) } } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet for action {}:", worldBorderAction, exception); + Challenges.getInstance().getILogger().error("Failed to create packet for action {}:", worldBorderAction, exception); } return null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java index 056bdf485..efaefb83c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java @@ -25,7 +25,7 @@ public Object get(Player player) { try { craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer:", exception); + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer:", exception); craftPlayer = null; } return craftPlayer; @@ -39,7 +39,7 @@ public Object getPlayerConnectionObject() { try { return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get the playerConnection object:", exception); + Challenges.getInstance().getILogger().error("Failed to get the playerConnection object:", exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java index de25d60f0..1cb6959a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java @@ -41,7 +41,7 @@ protected Object createWorldBorder() { try { return ReflectionUtil.invokeConstructor(nmsClass); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); + Challenges.getInstance().getILogger().error("Failed to create world border:", exception); return null; } } @@ -56,7 +56,7 @@ protected void setWorld(World world) { try { ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set world:", exception); + Challenges.getInstance().getILogger().error("Failed to set world:", exception); } } @@ -65,7 +65,7 @@ protected void setSizeField(double size) { try { ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[]{double.class}, new Object[]{size}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } } @@ -74,7 +74,7 @@ protected void transitionSizeBetween(double oldSize, double newSize, long animat try { ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } } @@ -83,7 +83,7 @@ protected void setCenterField(double x, double z) { try { ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[]{double.class, double.class}, new Object[]{x, z}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border center:", exception); + Challenges.getInstance().getILogger().error("Failed to set border center:", exception); } } @@ -92,7 +92,7 @@ protected void setWarningTimeField(int warningTime) { try { ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[]{int.class}, new Object[]{warningTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning time:", exception); + Challenges.getInstance().getILogger().error("Failed to set border warning time:", exception); } } @@ -101,7 +101,7 @@ protected void setWarningDistanceField(int warningDistance) { try { ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[]{int.class}, new Object[]{warningDistance}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning distance:", exception); + Challenges.getInstance().getILogger().error("Failed to set border warning distance:", exception); } } @@ -112,7 +112,7 @@ public void send(Player player, UpdateType updateType) { CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); craftPlayer.getConnection().sendPacket(packet); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); + Challenges.getInstance().getILogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java index c336ab8c4..6166e17ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java @@ -15,7 +15,7 @@ public void sendPacket(Object packet) { try { ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java index 1b85a2ee4..353622778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java @@ -26,7 +26,7 @@ public Object get(World world) { try { worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get WorldServer:", exception); + Challenges.getInstance().getILogger().error("Failed to get WorldServer:", exception); worldServer = null; } return worldServer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java index 3159aa309..07fc1f75c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java @@ -33,7 +33,7 @@ private Object createPacket(PacketBorder packetBorder, String className) { try { return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet {}:", className, exception); + Challenges.getInstance().getILogger().error("Failed to create packet {}:", className, exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java index 1fe13159b..0b816a0c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java @@ -22,7 +22,7 @@ public Object get(Player player) { try { craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get CraftPlayer:", exception); + Challenges.getInstance().getILogger().error("Failed to get CraftPlayer:", exception); craftPlayer = null; } return craftPlayer; @@ -33,7 +33,7 @@ public Object getPlayerConnectionObject() { try { return ReflectionUtil.getObject(this.nmsObject, "b"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get player connection object:", exception); + Challenges.getInstance().getILogger().error("Failed to get player connection object:", exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java index 0e39fdbc8..f812aad10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java @@ -16,7 +16,7 @@ protected void setCenterField(double x, double z) { try { ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{double.class, double.class}, new Object[]{x, z}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set center:", exception); + Challenges.getInstance().getILogger().error("Failed to set center:", exception); } } @@ -25,7 +25,7 @@ protected void setSizeField(double size) { try { ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class}, new Object[]{size}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } } @@ -34,7 +34,7 @@ protected void setWarningDistanceField(int warningDistance) { try { ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{int.class}, new Object[]{warningDistance}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning distance:", exception); + Challenges.getInstance().getILogger().error("Failed to set warning distance:", exception); } } @@ -43,7 +43,7 @@ protected void setWarningTimeField(int warningTime) { try { ReflectionUtil.invokeMethod(worldBorder, "b", new Class[]{int.class}, new Object[]{warningTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning time:", exception); + Challenges.getInstance().getILogger().error("Failed to set warning time:", exception); } } @@ -52,7 +52,7 @@ protected void transitionSizeBetween(double oldSize, double newSize, long animat try { ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java index d96c4c3ec..c254cc8d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java @@ -15,7 +15,7 @@ public void sendPacket(Object packet) { try { ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 683ef1c80..b457a897e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -2,7 +2,7 @@ import com.google.gson.JsonParser; import lombok.NonNull; -import net.anweisen.utilities.bukkit.utils.item.BannerPattern; +import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.*; @@ -27,7 +27,7 @@ import java.util.List; import java.util.UUID; -public class ItemBuilder extends net.anweisen.utilities.bukkit.utils.item.ItemBuilder { +public class ItemBuilder extends net.codingarea.commons.bukkit.utils.item.ItemBuilder { public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java deleted file mode 100644 index ce75b81eb..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.codingarea.challenges.plugin.utils.item; - -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; - -import javax.annotation.Nonnull; - -public class ItemUtils { - - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { - try { - return Material.valueOf("COOKED_" + material.name()); - } catch (Exception ex) { - return material; // No cooked material is available - } - } - - public static boolean isObtainableInSurvival(@Nonnull Material material) { - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.endsWith("_SPAWN_EGG")) return false; - if (name.startsWith("INFESTED_")) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "BEDROCK": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL_FRAME": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "LAVA": - case "WATER": - case "LARGE_FERN": - case "TALL_GRASS": - case "TALL_SEAGRASS": - case "PATH_BLOCK": - case "CHORUS_PLANT": - case "PETRIFIED_OAK_SLAB": - case "FARMLAND": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "SPAWNER": - case "AMETHYST_CLUSTER": - case "BUDDING_AMETHYST": - case "POWDER_SNOW": - case "LIGHT": - case "BUNDLE": - case "REINFORCED_DEEPSLATE": - case "FROGSPAWN": - return false; - } - - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - return !name.equals("SCULK_SENSOR"); - } - - return true; - } - - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { - if (!material.isBlock()) return false; - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "PETRIFIED_OAK_SLAB": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "LIGHT": - case "BUNDLE": - return false; - } - - return true; - } - - public static void damageItem(@Nonnull ItemStack item) { - damageItem(item, 1); - } - - public static void damageItem(@Nonnull ItemStack item, int amount) { - ItemMeta meta = item.getItemMeta(); - if (meta == null) return; - if (!(meta instanceof Damageable)) return; - Damageable damageable = (Damageable) meta; - damageable.setDamage(damageable.getDamage() + amount); - item.setItemMeta(meta); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 6f4382d40..771eb1737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.logging; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index 6bba078ef..348a43631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -3,8 +3,8 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.GameProfileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index adbdcc26c..56c365fd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index 5e8ff0de1..cf6e7c1f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import java.util.*; @@ -37,7 +37,7 @@ public static Map createSubSettingsMapFromDocument(Document do try { map.put(entry.getKey(), document.getStringArray(entry.getKey())); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 4952998f1..023f90fa7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import org.bukkit.Material; import org.bukkit.Particle; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 8d8d9d524..985a65410 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 96fad9239..18fe9135a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index c98b80ee8..c4df7e13a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java new file mode 100644 index 000000000..c90eea42b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -0,0 +1,375 @@ +package net.codingarea.commons.bukkit.core; + +import com.google.common.base.Charsets; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.wrapper.ActionListener; +import net.codingarea.commons.bukkit.utils.wrapper.SimpleEventExecutor; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.internal.BukkitLoggerWrapper; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import java.util.logging.Level; + +public abstract class BukkitModule extends JavaPlugin { + + private static volatile BukkitModule firstInstance; + private static boolean setFirstInstance = true; + private static boolean wasShutdown; + + private final Map commands = new HashMap<>(); + private final List listeners = new ArrayList<>(); + private final SimpleConfigManager configManager = new SimpleConfigManager(this); + + private JavaILogger logger; + private ExecutorService executorService; + private Document config, pluginConfig; + private Version version; + private boolean devMode; + private boolean firstInstall; + private boolean isReloaded; + private boolean isLoaded; + + private boolean requirementsMet = true; + + @Override + public final void onLoad() { + isLoaded = true; + + if (!requirementsMet || !(requirementsMet = new RequirementsChecker(this).checkBoolean(getPluginDocument().getDocument("require")))) + return; + + if (setFirstInstance || firstInstance == null) { + setFirstInstance(this); + } + + ILogger.setConstantFactory(this.getILogger()); + trySaveDefaultConfig(); + if (wasShutdown) isReloaded = true; + if (firstInstall = !getDataFolder().exists()) { + getILogger().info("Detected first install!"); + } + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + getILogger().setLevel(Level.ALL); + getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); + } else { + getILogger().setLevel(Level.INFO); + } + + injectInstance(); + + try { + handleLoad(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onEnable() { + if (!requirementsMet) return; + + commands.forEach((name, executor) -> registerCommand0(executor, name)); + listeners.forEach(this::registerListener); + + + try { + handleEnable(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onDisable() { + Throwable error = null; + try { + handleDisable(); + } catch (Throwable ex) { + error = ex; + } + + setFirstInstance = true; + wasShutdown = true; + isLoaded = false; + commands.clear(); + listeners.clear(); + + if (executorService != null) + executorService.shutdown(); + + for (Player player : Bukkit.getOnlinePlayers()) { + InventoryView view = player.getOpenInventory(); + Inventory inventory = view.getTopInventory(); + if (inventory.getHolder() == MenuPosition.HOLDER) + view.close(); + } + + if (error != null) + throw new WrappedException(error); + } + + protected void handleLoad() throws Exception {} + protected void handleEnable() throws Exception {} + protected void handleDisable() throws Exception {} + + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { + return firstInstall; + } + + public final boolean isReloaded() { + return isReloaded; + } + + public final boolean isLoaded() { + return isLoaded; + } + + public final boolean isFirstInstance() { + return firstInstance == this; + } + + @Nonnull + public JavaILogger getILogger() { + return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); + } + + @Nonnull + public Document getConfigDocument() { + checkLoaded(); + return config != null ? config : (config = new YamlDocument(super.getConfig())); + } + + @Override + public void reloadConfig() { + config = null; + super.reloadConfig(); + } + + /** + * @return the plugin configuration (plugin.yml) as document + */ + @Nonnull + public Document getPluginDocument() { + return pluginConfig != null ? pluginConfig : + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + } + + @Nonnull + public FileDocument getConfig(@Nonnull String filename) { + return configManager.getDocument(filename); + } + + @Nonnull + public Version getVersion() { + return version != null ? version : (version = Version.parse(getDescription().getVersion())); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.current()") + public MinecraftVersion getServerVersion() { + return MinecraftVersion.current(); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.currentExact()") + public Version getServerVersionExact() { + return MinecraftVersion.currentExact(); + } + + @Nonnull + @Override + @Deprecated + @ReplaceWith("getConfigDocument()") + public FileConfiguration getConfig() { + return super.getConfig(); + } + + @Override + @Deprecated + public void saveConfig() { + super.saveConfig(); + } + + public void setRequirementsFailed() { + this.requirementsMet = false; + } + + public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { + registerCommand(listenerAndExecutor, names); + registerListener(listenerAndExecutor); + } + + public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { + for (String name : names) { + if (isEnabled()) { + registerCommand0(executor, name); + } else { + commands.put(name, executor); + } + } + } + + private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { + PluginCommand command = getCommand(name); + if (command == null) { + getILogger().warn("Tried to register invalid command '{}'", name); + } else { + command.setExecutor(executor); + } + } + + public final void registerListener(@Nonnull Listener... listeners) { + if (isEnabled()) { + for (Listener listener : listeners) { + registerListener0(listener); + } + } else { + this.listeners.addAll(Arrays.asList(listeners)); + } + } + + private void registerListener0(@Nonnull Listener listener) { + if (listener instanceof ActionListener) { + ActionListener actionListener = (ActionListener) listener; + getServer().getPluginManager().registerEvent( + actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), + new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() + ); + } else { + getServer().getPluginManager().registerEvents(listener, this); + } + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + on(classOfEvent, EventPriority.NORMAL, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { + on(classOfEvent, priority, false, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { + registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); + } + + public final void disablePlugin() { + getServer().getPluginManager().disablePlugin(this); + } + + @Nonnull + public final File getDataFile(@Nonnull String filename) { + return new File(getDataFolder(), filename); + } + + @Nonnull + public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { + return new File(getDataFile(subfolder), filename); + } + + @Nonnull + public ExecutorService getExecutor() { + return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); + } + + public void runAsync(@Nonnull Runnable task) { + getExecutor().submit(task); + } + + public final void checkLoaded() { + if (!isLoaded()) + throw new IllegalStateException("Plugin (" + getName() + ") is not loaded yet"); + } + + public final void checkEnabled() { + if (!isEnabled()) + throw new IllegalStateException("Plugin (" + getName() + ") is not enabled yet"); + } + + private void registerAsFirstInstance() { + getILogger().info(getName() + " was loaded as the first BukkitModule"); + registerListener( + new MenuPositionListener() + ); + getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); + } + + private void trySaveDefaultConfig() { + try { + saveDefaultConfig(); + } catch (IllegalArgumentException ex) { + // No default config exists + } + } + + private void injectInstance() { + try { + Field instanceField = this.getClass().getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, this); + } catch (Throwable ex) { + } + } + + @Nonnull + public static BukkitModule getFirstInstance() { + if (firstInstance == null) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException("No BukkitModule was initialized yet & BukkitModule class was not loaded by a BukkitModule"); + firstInstance = (BukkitModule) provider; + } + + return firstInstance; + } + + private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { + setFirstInstance = false; + firstInstance = module; + module.registerAsFirstInstance(); + } + + @Nonnull + public static BukkitModule getProvidingModule(@Nonnull Class clazz) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); + return (BukkitModule) provider; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java new file mode 100644 index 000000000..87cae1721 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -0,0 +1,94 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.Nonnull; + +public final class RequirementsChecker { + + private final BukkitModule module; + + public RequirementsChecker(@Nonnull BukkitModule module) { + this.module = module; + } + + public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { + if (requirements.getBoolean("spigot")) requireSpigot(); + if (requirements.getBoolean("paper")) requirePaper(); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + } + + public boolean checkBoolean(@Nonnull Document requirements) { + try { + checkExceptionally(requirements); + return true; + } catch (IllegalStateException ex) { + return false; + } + } + + private void requireSpigot() { + try { + Bukkit.spigot(); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of Spigot (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Spigot or Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requirePaper() { + try { + Class.forName("com.destroystokyo.paper.VersionHistoryManager"); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of PaperMC (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requireVersion(@Nonnull Version required) { + if (MinecraftVersion.currentExact().isOlderThan(required)) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("This plugin requires the server version {} (You have: {})", required.format(), MinecraftVersion.currentExact().format()); + log("Please use this version (or an newer version) to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void log(@Nonnull String line, @Nonnull Object... args) { + module.getILogger().error(line, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java new file mode 100644 index 000000000..a4570ad3f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; + +import javax.annotation.Nonnull; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class SimpleConfigManager { + + protected final Map configs = new HashMap<>(); + protected final BukkitModule module; + + public SimpleConfigManager(@Nonnull BukkitModule module) { + this.module = module; + } + + @Nonnull + public FileDocument getDocument(@Nonnull String filename) { + if (!filename.contains(".")) filename += ".json"; + return getDocument(module.getDataFile(filename)); + } + + public synchronized FileDocument getDocument(@Nonnull File file) { + String extension = FileUtils.getFileExtension(file); + return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); + } + + @Nonnull + public static Class resolveType(@Nonnull String extension) { + switch (extension.toLowerCase()) { + case "json": return GsonDocument.class; + case "yml": + case "yaml": return YamlDocument.class; + default: throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java new file mode 100644 index 000000000..3bd67d790 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -0,0 +1,168 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +public class AnimatedInventory { + + private final List frames = new ArrayList<>(); + private final InventoryHolder holder; + private final int size; + private final String title; + private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; + private int frameDelay = 1; + + public AnimatedInventory(@Nonnull String title, int size) { + this(title, size, null); + } + + public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { + this.title = title; + this.size = size; + this.holder = holder; + } + + public void open(@Nonnull Player player) { + open(player, BukkitModule.getFirstInstance()); + } + + public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); + return; + } + + Inventory inventory = createInventory(); + applyFrame(inventory, 0, player); + player.openInventory(inventory); + + AtomicInteger index = new AtomicInteger(1); + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + + boolean opened = inventory.getViewers().contains(player); + if (index.get() >= frames.size() || !opened) { + task.cancel(); + return; + } + + applyFrame(inventory, index.get(), player); + + index.incrementAndGet(); + + }, frameDelay, frameDelay); + + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound) { + openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); + return; + } + + Inventory inventory = createInventory(); + + if (!frames.isEmpty()) { + AnimationFrame frame = getLastFrame(); + inventory.setContents(frame.getContent()); + } + + player.openInventory(inventory); + + if (playSound && endSound != null) endSound.play(player); + + } + + private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { + AnimationFrame frame = frames.get(index); + inventory.setContents(frame.getContent()); + + if (index == frames.size() - 1 && endSound != null) endSound.play(viewer); + else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); + } + + @Nonnull + public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { + if (size != frame.getSize()) throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); + frames.add(frame); + return this; + } + + @Nonnull + public AnimationFrame createAndAdd() { + AnimationFrame frame = new AnimationFrame(size); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getFrame(int index) { + return frames.get(index); + } + + @Nonnull + public AnimationFrame getOrCreateFrame(int index) { + while (frames.size() <= index) { + cloneLastAndAdd(); + } + return getFrame(index); + } + + @Nonnull + public AnimationFrame cloneAndAdd(int index) { + AnimationFrame frame = getFrame(index).clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getLastFrame() { + if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); + return getFrame(frames.size() - 1); + } + + @Nonnull + public AnimationFrame cloneLastAndAdd() { + AnimationFrame frame = getLastFrame().clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { + this.endSound = endSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { + this.frameSound = frameSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameDelay(int delay) { + if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); + this.frameDelay = delay; + return this; + } + + @Nonnull + private Inventory createInventory() { + return Bukkit.createInventory(holder, size, title); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java new file mode 100644 index 000000000..130785522 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -0,0 +1,84 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.utils.item.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public class AnimationFrame implements Cloneable { + + private final ItemStack[] content; + private boolean sound = true; + + public AnimationFrame(@Nonnull ItemStack[] content) { + this.content = Arrays.copyOf(content, content.length); + } + + public AnimationFrame(int size) { + this.content = new ItemStack[size]; + } + + @Nonnull + public AnimationFrame fill(@Nonnull ItemStack item) { + Arrays.fill(content, item); + return this; + } + + @Nonnull + public AnimationFrame setAccent(int... slots) { + for (int slot : slots) { + content[slot] = ItemBuilder.FILL_ITEM_2; + } + return this; + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { + return setItem(slot, item.build()); + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { + content[slot] = item; + return this; + } + + @Nonnull + public AnimationFrame setSound(boolean play) { + this.sound = play; + return this; + } + + @Nullable + public ItemStack getItem(int slot) { + return content[slot]; + } + + @Nullable + public Material getItemType(int slot) { + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + } + + @Nonnull + public ItemStack[] getContent() { + return content; + } + + public boolean shouldPlaySound() { + return sound; + } + + public int getSize() { + return content.length; + } + + @Nonnull + @Override + public AnimationFrame clone() { + return new AnimationFrame(content); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java new file mode 100644 index 000000000..8991960e0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -0,0 +1,113 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public final class SoundSample { + + public static final SoundSample + CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), + BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), + BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), + PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), + KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), + LEVEL_UP = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 1.1f), + PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 2), + LOW_PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 1.3f), + DEATH = new SoundSample().addSound(Sound.ENTITY_BAT_DEATH, 0.7F), + TELEPORT = new SoundSample().addSound(Sound.ITEM_CHORUS_FRUIT_TELEPORT, 0.9F), + OPEN = new SoundSample().addSound(KLING).addSound(PLOP), + EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), + BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), + BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), + WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), + DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); + + public static void playStatusSound(@Nonnull Player player, boolean enabled) { + (enabled ? BASS_ON : BASS_OFF).play(player); + } + + private static final class SoundFrame { + + private final float pitch, volume; + private final Sound sound; + + public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { + this.volume = volume; + this.pitch = pitch; + this.sound = sound; + } + + public SoundFrame(@Nonnull Sound sound, float volume) { + this(sound, volume, 1); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + player.playSound(location, sound, volume, pitch); + } + + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull + public Sound getSound() { + return sound; + } + + } + + private final List frames = new ArrayList<>(); + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { + frames.add(new SoundFrame(sound, volume, pitch)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume) { + frames.add(new SoundFrame(sound, volume)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull SoundSample sound) { + frames.addAll(sound.frames); + return this; + } + + public void play(@Nonnull Player player) { + play(player, player.getLocation()); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + for (SoundFrame frame : frames) { + frame.play(player, location); + } + } + + public void playIfPlayer(@Nonnull Object target) { + if (target instanceof Player) + play((Player) target); + } + + public void broadcast() { + Bukkit.getOnlinePlayers().forEach(this::play); + } + + public void broadcast(@Nonnull Location location) { + Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java new file mode 100644 index 000000000..172e2e4ff --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -0,0 +1,210 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ +public class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java new file mode 100644 index 000000000..60574d3fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java @@ -0,0 +1,333 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import net.codingarea.commons.bukkit.utils.bstats.chart.CustomChart; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +public class Metrics { + + private final Plugin plugin; + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + true, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "2.2.1"; + + private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final String platform; + private final String serverUuid; + private final int serviceId; + private final Consumer appendPlatformDataConsumer; + private final Consumer appendServiceDataConsumer; + private final Consumer submitTaskConsumer; + private final Supplier checkServiceEnabledSupplier; + private final BiConsumer errorLogger; + private final Consumer infoLogger; + private final boolean logErrors; + private final boolean logSentData; + private final boolean logResponseStatusText; + private final Set customCharts = new HashSet<>(); + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution + // of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial + // and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or + // frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + sendData(data); + } catch (Exception e) { + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little + // "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong package + // names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java new file mode 100644 index 000000000..48063d475 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java new file mode 100644 index 000000000..afdba71ee --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java new file mode 100644 index 000000000..3897be5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.function.BiConsumer; + +public abstract class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObject getChartData() throws Exception; +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java new file mode 100644 index 000000000..d0cb2ff19 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java @@ -0,0 +1,51 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java new file mode 100644 index 000000000..0d62864af --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java new file mode 100644 index 000000000..aa7d49220 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java new file mode 100644 index 000000000..e42f4a5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java new file mode 100644 index 000000000..8e4d91259 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java new file mode 100644 index 000000000..4901ae38d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -0,0 +1,64 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.block.banner.PatternType; + +import javax.annotation.Nonnull; + +public enum BannerPattern { + + BASE_DEXTER_CANTON(PatternType.SQUARE_BOTTOM_LEFT), + BASE_SINISTER_CANTON(PatternType.SQUARE_BOTTOM_RIGHT), + CHIEF_DEXTER_CANTON(PatternType.SQUARE_TOP_LEFT), + CHIEF_SINISTER_CANTON(PatternType.SQUARE_TOP_RIGHT), + BASE(PatternType.STRIPE_BOTTOM), + CHIEF(PatternType.STRIPE_TOP), + PALE_DEXTER(PatternType.STRIPE_LEFT), + PALE_SINISTER(PatternType.STRIPE_RIGHT), + PALE(PatternType.STRIPE_CENTER), + FESS(PatternType.STRIPE_MIDDLE), + BEND(PatternType.STRIPE_DOWNRIGHT), + BEND_SINISTER(PatternType.STRIPE_DOWNLEFT), + PALY(PatternType.SMALL_STRIPES), + SALTIRE(PatternType.CROSS), + CROSS(PatternType.STRAIGHT_CROSS), + CHEVRON(PatternType.TRIANGLE_BOTTOM), + INVERTED_CHEVRON(PatternType.TRIANGLE_TOP), + BASE_INDENTED(PatternType.TRIANGLES_BOTTOM), + CHIEF_INDENTED(PatternType.TRIANGLES_TOP), + PER_BEND_SINISTER(PatternType.DIAGONAL_LEFT), + PER_BEND_SINISTER_INVERTED(PatternType.DIAGONAL_RIGHT), + PER_BEND_INVERTED(PatternType.DIAGONAL_UP_LEFT), + PER_BEND(PatternType.DIAGONAL_UP_RIGHT), + ROUNDEL(PatternType.CIRCLE), + LOZENGE(PatternType.STRIPE_MIDDLE), + PER_PALE(PatternType.HALF_VERTICAL), + PER_FESS(PatternType.HALF_HORIZONTAL), + PER_PALE_INVERTED(PatternType.HALF_VERTICAL_RIGHT), + PER_FESS_INVERTED(PatternType.HALF_HORIZONTAL_BOTTOM), + BORDURE(PatternType.BORDER), + BORDURE_INDENTED(PatternType.CURLY_BORDER), + GRADIENT(PatternType.GRADIENT), + BASE_GRADIENT(PatternType.GRADIENT_UP), + FIELD_MASONED(PatternType.BRICKS), + CREEPER_CHARGE(PatternType.CREEPER), + SKULL_CHARGE(PatternType.SKULL), + FLOWER_CHARGE(PatternType.FLOWER), + MOJANG(PatternType.MOJANG); + + private final PatternType patternType; + + BannerPattern(@Nonnull PatternType patternType) { + this.patternType = patternType; + } + + @Nonnull + public PatternType getPatternType() { + return patternType; + } + + @Nonnull + public String getIdentifier() { + return patternType.getKeyOrThrow().getKey(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java new file mode 100644 index 000000000..339bbaba2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -0,0 +1,424 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.PotionEffect; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public class ItemBuilder { + + public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), + FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), + BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), + AIR = new ItemStack(Material.AIR); + + protected ItemStack item; + protected ItemMeta meta; + + public ItemBuilder(@Nonnull ItemStack item) { + this(item, item.getItemMeta()); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + this.item = item; + this.meta = meta; + } + + public ItemBuilder(@Nonnull Material material) { + this(new ItemStack(material)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + this(material); + setName(name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + this(material); + setName(name); + setLore(lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + this(material); + setName(name); + setAmount(amount); + } + + @Nonnull + public ItemMeta getMeta() { + return getCastedMeta(); + } + + @Nonnull + @SuppressWarnings("unchecked") + public final M getCastedMeta() { + return (M) (meta == null ? meta = item.getItemMeta() : meta); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + getMeta().setLore(lore); + return this; + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return setLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return appendLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + List newLore = getMeta().getLore(); + if (newLore == null) newLore = new ArrayList<>(); + newLore.addAll(lore); + setLore(newLore); + return this; + } + + @Nonnull + public ItemBuilder lore(@Nonnull String... lore) { + return setLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + getMeta().setDisplayName(name); + return this; + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return setName(name == null ? null : name.toString()); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + if (content.length > 0) setName(content[0]); + if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); + return this; + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + String name = getMeta().getDisplayName(); + return setName(name + sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return setName(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return setName(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + getMeta().addEnchant(enchantment, level, true); + return this; + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + getMeta().addItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder flag(@Nonnull ItemFlag... flags) { + return addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + getMeta().removeItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder hideAttributes() { + return addFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder showAttributes() { + return removeFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + getMeta().setUnbreakable(unbreakable); + return this; + } + + @Nonnull + public ItemBuilder unbreakable() { + return setUnbreakable(true); + } + + @Nonnull + public ItemBuilder breakable() { + return setUnbreakable(false); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + item.setAmount(Math.min(Math.max(amount, 0), 64)); + return this; + } + + @Nonnull + public ItemBuilder amount(int amount) { + return setAmount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + this.getCastedMeta().setDamage(damage); + return this; + } + + @Nonnull + public ItemBuilder damage(int damage) { + return setDamage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + item.setType(material); + meta = item.getItemMeta(); + return this; + } + + @Nonnull + public String getName() { + return getMeta().getDisplayName(); + } + + @Nonnull + public List getLore() { + List lore = getMeta().getLore(); + return lore == null ? new ArrayList<>() : lore; + } + + @Nonnull + public Material getType() { + return item.getType(); + } + + public int getAmount() { + return item.getAmount(); + } + + public int getDamage() { + return this.getCastedMeta().getDamage(); + } + + @Nonnull + public ItemStack build() { + item.setItemMeta(getMeta()); // Call to getter to prevent null value + return item; + } + + @Nonnull + public ItemStack toItem() { + return build(); + } + + @Override + public ItemBuilder clone() { + return new ItemBuilder(item.clone(), getMeta().clone()); + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(@Nonnull String owner) { + super(Material.PLAYER_HEAD); + setOwner(owner); + } + + public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + super(Material.PLAYER_HEAD, name, lore); + setOwner(owner); + } + + public SkullBuilder setOwner(@Nonnull String owner) { + getMeta().setOwner(owner); + return this; + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java new file mode 100644 index 000000000..e967429a8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -0,0 +1,117 @@ +package net.codingarea.commons.bukkit.utils.item; + +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import javax.annotation.Nonnull; + +public class ItemUtils { + + @Nonnull + public static Material convertFoodToCookedFood(@Nonnull Material material) { + try { + return Material.valueOf("COOKED_" + material.name()); + } catch (Exception ex) { + return material; // No cooked material is available + } + } + + public static boolean isObtainableInSurvival(@Nonnull Material material) { + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.endsWith("_SPAWN_EGG")) return false; + if (name.startsWith("INFESTED_")) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "BEDROCK": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL_FRAME": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "LAVA": + case "WATER": + case "LARGE_FERN": + case "TALL_GRASS": + case "TALL_SEAGRASS": + case "PATH_BLOCK": + case "CHORUS_PLANT": + case "PETRIFIED_OAK_SLAB": + case "FARMLAND": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "SPAWNER": + case "AMETHYST_CLUSTER": + case "BUDDING_AMETHYST": + case "POWDER_SNOW": + case "LIGHT": + case "BUNDLE": + case "REINFORCED_DEEPSLATE": + case "FROGSPAWN": + return false; + } + + if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { + return !name.equals("SCULK_SENSOR"); + } + + return true; + } + + public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + if (!material.isBlock()) return false; + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "PETRIFIED_OAK_SLAB": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "LIGHT": + case "BUNDLE": + return false; + } + + return true; + } + + public static void damageItem(@Nonnull ItemStack item) { + damageItem(item, 1); + } + + public static void damageItem(@Nonnull ItemStack item, int amount) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + if (!(meta instanceof Damageable)) return; + Damageable damageable = (Damageable) meta; + damageable.setDamage(damageable.getDamage() + amount); + item.setItemMeta(meta); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java new file mode 100644 index 000000000..ac6f766f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.bukkit.utils.logging; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public final class Logger { + + private Logger() {} + + @Nonnull + public static ILogger getInstance() { + return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); + } + + public static void error(@Nullable Object message, @Nonnull Object... args) { + getInstance().error(message, args); + } + + public static void warn(@Nullable Object message, @Nonnull Object... args) { + getInstance().warn(message, args); + } + + public static void info(@Nullable Object message, @Nonnull Object... args) { + getInstance().info(message, args); + } + + public static void debug(@Nullable Object message, @Nonnull Object... args) { + getInstance().debug(message, args); + } + + public static void trace(@Nullable Object message, @Nonnull Object... args) { + getInstance().trace(message, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java new file mode 100644 index 000000000..5753ad174 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -0,0 +1,75 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class MenuClickInfo { + + protected final Player player; + protected final Inventory inventory; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; + + public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { + this.player = player; + this.inventory = inventory; + this.shiftClick = shiftClick; + this.rightClick = rightClick; + this.slot = slot; + } + + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } + + public boolean isRightClick() { + return rightClick; + } + + public boolean isLeftClick() { + return !rightClick; + } + + public boolean isShiftClick() { + return shiftClick; + } + + public int getSlot() { + return slot; + } + + @Nullable + public ItemStack getClickedItem() { + return inventory.getItem(slot); + } + + @Nonnull + public Material getClickedMaterial() { + return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); + } + + @Override + public String toString() { + return "MenuClickInfo{" + + "player=" + player + + ", inventory=" + inventory + + ", shiftClick=" + shiftClick + + ", rightClick=" + rightClick + + ", slot=" + slot + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java new file mode 100644 index 000000000..527cc844f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@FunctionalInterface +public interface MenuPosition { + + final class Holder { + + private Holder() {} + + private static final Map positions = new ConcurrentHashMap<>(); + + } + + InventoryHolder HOLDER = new MenuPositionHolder(); + + static void set(@Nonnull Player player, @Nullable MenuPosition position) { + Holder.positions.put(player, position); + } + + static void remove(@Nonnull Player player) { + Holder.positions.remove(player); + } + + @Nullable + static MenuPosition get(@Nonnull Player player) { + return Holder.positions.get(player); + } + + static void setEmpty(@Nonnull Player player) { + set(player, new EmptyMenuPosition()); + } + + void handleClick(@Nonnull MenuClickInfo info); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java new file mode 100644 index 000000000..669b1367f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; + +class MenuPositionHolder implements InventoryHolder { + + @Nonnull + @Override + public Inventory getInventory() { + return null; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java new file mode 100644 index 000000000..8addddaca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; + +import javax.annotation.Nonnull; + +public final class MenuPositionListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { + + HumanEntity human = event.getWhoClicked(); + if (!(human instanceof Player)) return; + Player player = (Player) human; + + Inventory inventory = event.getClickedInventory(); + if (inventory == null) return; + + if (inventory == CompatibilityUtils.getTopInventory(event)) { + + if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + MenuPosition position = MenuPosition.get(player); + if (position == null) return; // Currently in no menu + + event.setCancelled(true); + position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); + + } else if (event.isShiftClick()) { // Player inventory was clicked + + Inventory topInventory = event.getInventory(); + if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + event.setCancelled(true); + + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java new file mode 100644 index 000000000..dfe653abf --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; + +import javax.annotation.Nonnull; + +public class EmptyMenuPosition implements MenuPosition { + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java new file mode 100644 index 000000000..8ea854148 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +public class SlottedMenuPosition implements MenuPosition { + + protected final Map> actions = new HashMap<>(); + protected boolean emptySound = true; + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + Consumer action = actions.get(info.getSlot()); + if (action == null) { + if (emptySound) SoundSample.CLICK.play(info.getPlayer()); + return; + } + + action.accept(info); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { + actions.put(slot, action); + return this; + } + + @Nonnull + public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { + return setAction(slot, info -> action.accept(info.getPlayer())); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { + return setAction(slot, info -> action.run()); + } + + public SlottedMenuPosition setEmptySound(boolean playSound) { + this.emptySound = playSound; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java new file mode 100644 index 000000000..36284f5e3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -0,0 +1,170 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Method; +import java.util.regex.Pattern; + +/** + * This class gives access to + * - api functions which are not directly implemented in some versions of bukkit or spigot + * - some basic nms functionality. + */ +public final class BukkitReflectionUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private BukkitReflectionUtils() { + } + + public static double getAbsorptionAmount(@Nonnull Player player) { + Class classOfPlayer = player.getClass(); + + try { + return player.getAbsorptionAmount(); + } catch (Throwable ignored) { + } + + try { + Method getHandleMethod = classOfPlayer.getMethod("getHandle"); + getHandleMethod.setAccessible(true); + + Object handle = getHandleMethod.invoke(player); + Class classOfHandle = handle.getClass(); + + Method getAbsorptionMethod = classOfHandle.getMethod("getAbsorptionHearts"); + getAbsorptionMethod.setAccessible(true); + return (double) (float) getAbsorptionMethod.invoke(handle); + } catch (Throwable ignored) { + } + + logger.warn("Could not get absorption amount for player of class {}", classOfPlayer.getName()); + return 0; + } + + public static boolean isAir(@Nonnull Material material) { + try { + return material.isAir(); + } catch (Throwable ignored) { + } + + switch (material.name()) { + case "AIR": + case "VOID_AIR": + case "CAVE_AIR": + case "LEGACY_AIR": + return true; + default: + return false; + } + } + + public static int getMinHeight(@Nonnull World world) { + try { + return world.getMinHeight(); + } catch (Throwable ignored) { + } + + return 0; + } + + /** + * @return if the entity is in water, {@code false} otherwise or if not implemented + * @deprecated not implemented in all forks of bukkit + */ + @Deprecated + public static boolean isInWater(@Nonnull Entity entity) { + try { + return entity.isInWater(); + } catch (Throwable ignored) { + } + + return false; + } + + private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); + + /** + * Get a NamespacedKey from the supplied string. + * + * The default namespace will be Minecraft's (i.e. + * {@link NamespacedKey#minecraft(String)}). + * + * @param key the key to convert to a NamespacedKey + * @return the created NamespacedKey. null if invalid + * @see #fromString(String, Plugin) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String key) { + return fromString(key, null); + } + + /** + * Does not exists in versions prior to 1.14 + * + * Get a NamespacedKey from the supplied string with a default namespace if + * a namespace is not defined. This is a utility method meant to fetch a + * NamespacedKey from user input. Please note that casing does matter and + * any instance of uppercase characters will be considered invalid. The + * input contract is as follows: + *

+	 * fromString("foo", plugin) -{@literal >} "plugin:foo"
+	 * fromString("foo:bar", plugin) -{@literal >} "foo:bar"
+	 * fromString(":foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("Foo", plugin) -{@literal >} null
+	 * fromString(":Foo", plugin) -{@literal >} null
+	 * fromString("foo:bar:bazz", plugin) -{@literal >} null
+	 * fromString("", plugin) -{@literal >} null
+	 * 
+ * + * @param string the string to convert to a NamespacedKey + * @param defaultNamespace the default namespace to use if none was + * supplied. If null, the {@code minecraft} namespace + * ({@link NamespacedKey#minecraft(String)}) will be used + * @return the created NamespacedKey. null if invalid key + * @see #fromString(String) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + + String[] components = string.split(":", 3); + if (components.length > 2) { + return null; + } + + String key = (components.length == 2) ? components[1] : ""; + if (components.length == 1) { + String value = components[0]; + if (value.isEmpty() || !VALID_KEY.matcher(value).matches()) { + return null; + } + + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, value) : NamespacedKey.minecraft(value); + } else if (components.length == 2 && !VALID_KEY.matcher(key).matches()) { + return null; + } + + String namespace = components[0]; + if (namespace.isEmpty()) { + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, key) : NamespacedKey.minecraft(key); + } + + if (!VALID_KEY.matcher(namespace).matches()) { + return null; + } + + return new NamespacedKey(namespace, key); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java new file mode 100644 index 000000000..47cd94c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/* + * In API version 1.20.6 and earlier, InventoryView is an abstract class + * In API version 1.21, InventoryView is an interface + */ +public class CompatibilityUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + private static final Logger log = LoggerFactory.getLogger(CompatibilityUtils.class); + + private CompatibilityUtils() { + } + + public static Inventory getTopInventory(@Nonnull Player player) { + InventoryView view = player.getOpenInventory(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } + + public static Inventory getTopInventory(@Nonnull InventoryClickEvent event) { + InventoryView view = event.getView(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java new file mode 100644 index 000000000..44d8d380f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java @@ -0,0 +1,91 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.SkullMeta; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.UUID; + +public final class GameProfileUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private GameProfileUtils() {} + + @Nonnull + public static GameProfile getGameProfile(@Nonnull Player player) { + try { + + Class classOfPlayer = player.getClass(); + + Method getProfileMethod = classOfPlayer.getMethod("getProfile"); + getProfileMethod.setAccessible(true); + return (GameProfile) getProfileMethod.invoke(player); + + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { + applyTextures(meta, uuid, name, texture, null); + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { + if (texture == null || texture.isEmpty()) return; + + GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); + profile.getProperties().put("textures", new Property("textures", texture, signature)); + + Class classOfMeta = meta.getClass(); + try { + Method setProfileMethod = classOfMeta.getDeclaredMethod("setProfile", GameProfile.class); + setProfileMethod.setAccessible(true); + setProfileMethod.invoke(meta, profile); + return; + } catch (Exception ignored) { + } + + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + field.set(meta, profile); + + // This field is not implemented in every version + try { + field = classOfMeta.getDeclaredField("serializedProfile"); + field.setAccessible(true); + field.set(meta, profile); + } catch (Exception ignored) { + } + + return; + } catch (Exception ignored) { + } + + logger.warn("Unable to apply textures to item"); + + } + + @Nonnull + public static GameProfile getTextures(@Nonnull SkullMeta meta) { + + Class classOfMeta = meta.getClass(); + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + return (GameProfile) field.get(meta); + } catch (Exception ex) { + throw new WrappedException(ex); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java new file mode 100644 index 000000000..16e369a67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -0,0 +1,115 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public enum MinecraftVersion implements Version { + + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static MinecraftVersion current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java new file mode 100644 index 000000000..8faa0993b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -0,0 +1,57 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.Consumer; + +public final class ActionListener implements Listener { + + private final Class classOfEvent; + private final Consumer listener; + private final EventPriority priority; + private final boolean ignoreCancelled; + + public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { + this.classOfEvent = classOfEvent; + this.listener = listener; + this.priority = priority; + this.ignoreCancelled = ignoreCancelled; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ActionListener that = (ActionListener) o; + return listener.equals(that.listener); + } + + @Override + public int hashCode() { + return Objects.hash(listener); + } + + @Nonnull + public Consumer getListener() { + return listener; + } + + @Nonnull + public EventPriority getPriority() { + return priority; + } + + @Nonnull + public Class getClassOfEvent() { + return classOfEvent; + } + + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java similarity index 80% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java rename to plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java index 5b5abbdb8..ea2a13e3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java @@ -1,6 +1,6 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper; +package net.codingarea.commons.bukkit.utils.wrapper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.attribute.Attribute; public class AttributeWrapper { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java new file mode 100644 index 000000000..d073dd81f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.bukkit.Material; + +import javax.annotation.Nonnull; + +/** + * This class allows you to use materials, whose names are changed at some point, in most versions. + * For example the red dye was first named {@code ROSE_RED} but then renamed to {@code RED_DYE}. + * To prevent unwanted {@link NoSuchFieldError NoSuchFieldErrors}, you should use this wrapper instead of a direct call to the material enum {@link Material}. + */ +public final class MaterialWrapper { + + private MaterialWrapper() {} + + public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); + public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); + public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); + public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); + + @Nonnull + private static Material getMaterialByNames(@Nonnull String... names) { + return ReflectionUtils.getFirstEnumByNames(Material.class, names); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java new file mode 100644 index 000000000..2b3055417 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.bukkit.plugin.EventExecutor; + +import javax.annotation.Nonnull; +import java.util.function.Consumer; + +public class SimpleEventExecutor implements EventExecutor { + + private final Class classOfEvent; + private final Consumer action; + + public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + this.classOfEvent = classOfEvent; + this.action = action; + } + + @Override + public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { + if (!classOfEvent.isAssignableFrom(event.getClass())) return; + try { + action.accept(event); + } catch (Throwable ex) { + throw new EventException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java new file mode 100644 index 000000000..685852b83 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * Used to declare alternate names which are used in used or similar libraries. + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) +public @interface AlsoKnownAs { + + @Nonnull + String[] value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java new file mode 100644 index 000000000..72fb1e113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface DeprecatedSince { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java new file mode 100644 index 000000000..469355d3b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface ReplaceWith { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java new file mode 100644 index 000000000..0f27a0c69 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +@Documented +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PACKAGE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Since { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java new file mode 100644 index 000000000..23ba208f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java @@ -0,0 +1,56 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.lang.reflect.Array; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.function.Consumer; + +public class ArrayWalker implements Iterable { + + protected final Object array; + protected final int length; + + protected ArrayWalker(@Nonnull Object array) { + if (!array.getClass().isArray()) throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); + this.array = array; + this.length = Array.getLength(array); + } + + public static ArrayWalker walk(@Nonnull Object array) { + return new ArrayWalker<>(array); + } + + public static ArrayWalker walk(@Nonnull T... array) { + return new ArrayWalker<>(array); + } + + @Override + public Iterator iterator() { + return new Iterator() { + + private int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < length; + } + + @Override + @SuppressWarnings("unchecked") + public T next() { + if (!hasNext()) throw new NoSuchElementException(); + return (T) Array.get(array, cursor++); + } + + }; + } + + @Override + @SuppressWarnings("unchecked") + public void forEach(Consumer action) { + for (int i = 0; i < length; i++) { + action.accept((T) Array.get(array, i)); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java new file mode 100644 index 000000000..d71f0df71 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -0,0 +1,65 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.*; + +/** + * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java + */ +public class ClassWalker implements Iterable> { + + protected final Class clazz; + protected final Class end; + + protected ClassWalker(@Nonnull Class clazz) { + this(clazz, Object.class); + } + + protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { + this.clazz = clazz; + this.end = end; + } + + public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { + return new ClassWalker(start, end); + } + + public static ClassWalker walk(@Nonnull Class start) { + return new ClassWalker(start); + } + + @Nonnull + @Override + public Iterator> iterator() { + return new Iterator>() { + + private final Set> done = new HashSet<>(); + private final Deque> work = new LinkedList<>(); + + { + work.addLast(clazz); + done.add(end); + } + + @Override + public boolean hasNext() { + return !work.isEmpty(); + } + + @Override + public Class next() { + Class current = work.removeFirst(); + done.add(current); + for (Class parent : current.getInterfaces()) { + if (!done.contains(parent)) + work.addLast(parent); + } + + Class parent = current.getSuperclass(); + if (parent != null && !done.contains(parent)) + work.addLast(parent); + return current; + } + }; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java new file mode 100644 index 000000000..dc7950c10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; + +import static java.awt.Color.decode; + +public final class Colors { + + private Colors() {} + + public static final Color + ONLINE = decode("#40AC7B"), + DO_NOT_DISTURB = decode("#E84444"), + IDLE = decode("#F09F19"), + OFFLINE = decode("#747F8D"), + STREAMING = decode("#573591"), + + EMBED = decode("#2F3136"), + NO_RANK = decode("#CCD8DE"), + + LIGHT_BLACK = decode("#1c1c1c") + ; + + @Nonnull + @CheckReturnValue + public static String asHex(@Nonnull Color color) { + String red = Integer.toHexString(color.getRed()); + String green = Integer.toHexString(color.getGreen()); + String blue = Integer.toHexString(color.getBlue()); + return "#" + (red.length() == 1 ? "0" + red : red) + + (green.length() == 1 ? "0" + green : green) + + (blue.length() == 1 ? "0" + blue : blue); + } + + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java new file mode 100644 index 000000000..4625c3347 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java @@ -0,0 +1,93 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.Objects; + +public class FontBuilder { + + private Font font; + + public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { + this(file, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, file); + } + + public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { + this(resource, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); + } + + @Nonnull + @CheckReturnValue + public FontBuilder bold() { + return style(Font.BOLD); + } + + @Nonnull + @CheckReturnValue + public FontBuilder italic() { + return style(Font.ITALIC); + } + + @Nonnull + @CheckReturnValue + public FontBuilder style(int style) { + font = font.deriveFont(style); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder size(float size) { + font = font.deriveFont(size); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder derive(int style, float size) { + font = font.deriveFont(style, size); + return this; + } + + @Nonnull + public Font build() { + registerFont(font); + return font; + } + + public static void registerFont(@Nonnull Font font) { + GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromFile(@Nonnull String filename) { + try { + return new FontBuilder(new File(filename)); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromResource(@Nonnull String resource) { + try { + return new FontBuilder(resource); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java new file mode 100644 index 000000000..54c8675fe --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java @@ -0,0 +1,43 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public final class IOUtils { + + private IOUtils() {} + + public static String toString(@Nonnull String url) throws IOException { + return toString(new URL(url)); + } + + public static String toString(@Nonnull URL url) throws IOException { + InputStream input = url.openStream(); + String string = toString(input); + input.close(); + return string; + } + + public static String toString(@Nonnull InputStream input) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); + reader.lines().forEach(builder::append); + return builder.toString(); + } + + @Nonnull + @CheckReturnValue + public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return connection; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java new file mode 100644 index 000000000..cfd4a96bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -0,0 +1,152 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public interface IRandom { + + @Nonnull + @CheckReturnValue + static IRandom create() { + return new SeededRandomWrapper(); + } + + @Nonnull + @CheckReturnValue + static IRandom create(long seed) { + return new SeededRandomWrapper(seed); + } + + @Nonnull + @CheckReturnValue + static IRandom wrap(@Nonnull Random random) { + return new RandomWrapper(random); + } + + @Nonnull + @CheckReturnValue + static IRandom threadLocal() { + return wrap(ThreadLocalRandom.current()); + } + + @Nonnull + @CheckReturnValue + static IRandom secure() { + return wrap(new SecureRandom()); + } + + @Nonnull + @CheckReturnValue + static IRandom singleton() { + return SingletonRandom.INSTANCE; + } + + long getSeed(); + + void setSeed(long seed); + + void nextBytes(@Nonnull byte[] bytes); + + boolean nextBoolean(); + + int nextInt(); + + int nextInt(int bound); + + @Nonnull + @CheckReturnValue + IntStream ints(); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + IntStream ints(int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(); + + long nextLong(); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + LongStream longs(long randomNumberOrigin, long randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); + + double nextDouble(); + + double nextGaussian(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); + + float nextFloat(); + + default T choose(@Nonnull T... array) { + return array[nextInt(array.length)]; + } + + default T choose(@Nonnull List list) { + return list.get(nextInt(list.size())); + } + + default T choose(@Nonnull Collection collection) { + return choose(new ArrayList<>(collection)); + } + + default void shuffle(@Nonnull List list) { + Collections.shuffle(list, asRandom()); + } + + default int around(int value, @Nonnegative int range) { + return range(value - range, value + range); + } + + default int range(int min, int max) { + if (min >= max) throw new IllegalArgumentException("min >= max"); + return nextInt(max - min) + min; + } + + @Nonnull + @CheckReturnValue + default Random asRandom() { + if (!(this instanceof Random)) + throw new IllegalStateException(this.getClass().getName() + " cannot be converted a java.util.Random"); + return (Random) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java new file mode 100644 index 000000000..624f2508f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntFunction; + +public class NamedThreadFactory implements ThreadFactory { + + private static final AtomicInteger poolNumber = new AtomicInteger(1); + + protected final int id = poolNumber.getAndIncrement(); + protected final IntFunction nameFunction; + protected final ThreadGroup group; + protected final AtomicInteger threadNumber = new AtomicInteger(1); + + public NamedThreadFactory(@Nonnull IntFunction nameFunction) { + SecurityManager securityManager = System.getSecurityManager(); + this.group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); + this.nameFunction = nameFunction; + } + + public NamedThreadFactory(@Nonnull String prefix) { + this(id -> prefix + "-" + id); + } + + @Override + public Thread newThread(@Nonnull Runnable task) { + Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); + if (thread.isDaemon()) + thread.setDaemon(false); + if (thread.getPriority() != Thread.NORM_PRIORITY) + thread.setPriority(Thread.NORM_PRIORITY); + return thread; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java new file mode 100644 index 000000000..4a734b55b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -0,0 +1,357 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.function.Consumer; + +public interface NumberFormatter { + + @Nonnull + @CheckReturnValue + String format(double value); + + @Nonnull + @CheckReturnValue + default String format(float value) { + return format(Float.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(long value) { + return format(Long.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(int value) { + return format(Integer.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(short value) { + return format(Short.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(byte value) { + return format(Byte.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(@Nonnull Number number) { + return format(number.doubleValue()); + } + + public static final NumberFormatter + DEFAULT = fromPattern("0.##", null, false), + INTEGER = value -> (int) value + "", + SPACE_SPLIT = fromPattern("###,##0.###############", null, false, + init -> updateSymbols(init, symbols -> symbols.setGroupingSeparator(' '))), + FLOATING_POINT = fromPattern("0.0", null, false), + DOUBLE_FLOATING_POINT = fromPattern("0.00", null, false), + BIG_FLOATING_POINT = fromPattern("###,##0.00000", null, false), + PERCENTAGE = fromPattern("0.##", "%", true), + FLOATING_PERCENTAGE = fromPattern("0.00", "%", true), + MIDDLE_NUMBER = fromPattern("###,###,##0.#", null, false), + + /** + * days, hours, minutes, seconds + */ + TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 ? minutes + "m " : "") + + (seconds > 0 || (years == 0 && days == 0 && hours == 0 && minutes == 0) ? seconds + "s" : "")).trim(); + + }, + + /** + * days, hours, minutes + */ + BIG_TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 || (years == 0 && days == 0 && hours == 0) ? minutes + "m " : "")).trim(); + + }, + + /** + * input: millis + * 1 Tag, H:M:S + */ + GERMAN_TIME = value -> { + + DecimalFormat format = new DecimalFormat("00"); + + long millis = (long) value; + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + seconds %= 60; + minutes %= 60; + hours %= 24; + + return (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? format.format(hours) + ":" : "") + + format.format(minutes) + ":" + + format.format(seconds); + + }, + /** + * input: seconds + * 1 Tag, H:M:S + */ + FULL_GERMAN_TIME_HOURS = value -> { + + long seconds = (long) (value); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); + }, + + FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "") + + (seconds > 0 || years == 0 && hours == 0 && minutes == 0 ? (seconds == 1 ? "1 Sekunde" : seconds + " Sekunden") : "")).trim(); + + }, + + NORMAL_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 || value == 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "")).trim(); + + }, + + BIG_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 || years == 0 && days == 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : "")).trim(); + + }, + + /** + * billion, million, thousand, number + */ + BIG_NUMBER = value -> { + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending = ""; + + // Normal number + if (value < 1000) { + divide = 1; + format = new DecimalFormat("0.#"); + // Thousand + } else if (value < 1000000) { + divide = 1000; + ending = "k"; + // Million + } else if (value < 1000000000) { + divide = 1000000; + ending = "m"; + // Billion (Milliarde) + } else if (value < 1000000000000D) { + divide = 1000000000; + ending = "b"; + // Trillion (Billion) + } else { + divide = 1000000000000D; + ending = "t"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * kilobyte, megabyte, gigabyte, terrabyte + */ + DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // KiloByte + if (value < 1000000L) { + divide = 1000; + format = new DecimalFormat("0.#"); + ending = "KB"; + } else if (value < 1000000000L) { + // MegaByte + divide = 1000000L; + ending = "MB"; + // GigaByte + } else if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else { + divide = 1000000000000L; + ending = "TB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * gigabyte, terrabyte, petabyte + */ + BIG_DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // GigaByte + if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else if (value < 1000000000000000L) { + divide = 1000000000000L; + ending = "TB"; + // PetaByte + } else { + divide = 1000000000000000L; + ending = "PB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + ORDINAL = value -> { + + String string = String.valueOf(((long) value)); + int number = Integer.parseInt(string.substring(string.length() - 1)); + String ending = "th"; + + if (value != 11 && value != 12 && value != 13) { + switch (number) { + case 1: + ending = "st"; + break; + case 2: + ending = "nd"; + break; + case 3: + ending = "rd"; + break; + } + } + + return string + ending; + + }, + GERMAN_ORDINAL = fromPattern("0", ".", false); + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + return fromPattern(pattern, ending, positive, null); + } + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + DecimalFormat format = new DecimalFormat(pattern); + if (init != null) init.accept(format); + return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); + } + + @Nonnull + @CheckReturnValue + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + action.accept(symbols); + return symbols; + } + + @CheckReturnValue + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java new file mode 100644 index 000000000..b561b6bf8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; + +public class PublicSecurityManager extends SecurityManager { + + @Nonnull + public Class[] getPublicClassContext() { + return getClassContext(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java new file mode 100644 index 000000000..a845fbc10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java @@ -0,0 +1,149 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.Random; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public class RandomWrapper implements IRandom { + + private final Random random; + + public RandomWrapper(@Nonnull Random random) { + this.random = random; + } + + @Override + public long getSeed() { + throw new UnsupportedOperationException("Random.getSeed()"); + } + + @Override + public void setSeed(long seed) { + random.setSeed(seed); + } + + @Override + public void nextBytes(@Nonnull byte[] bytes) { + random.nextBytes(bytes); + } + + @Override + public boolean nextBoolean() { + return random.nextBoolean(); + } + + @Override + public int nextInt() { + return random.nextInt(); + } + + @Override + public int nextInt(int bound) { + return random.nextInt(bound); + } + + @Nonnull + @Override + public IntStream ints() { + return random.ints(); + } + + @Nonnull + @Override + public IntStream ints(long streamSize) { + return random.ints(streamSize); + } + + @Nonnull + @Override + public IntStream ints(int randomNumberOrigin, int randomNumberBound) { + return random.ints(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { + return random.ints(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs() { + return random.longs(); + } + + @Override + public long nextLong() { + return random.nextLong(); + } + + @Nonnull + @Override + public LongStream longs(long streamSize) { + return random.longs(streamSize); + } + + @Nonnull + @Override + public LongStream longs(long randomNumberOrigin, long randomNumberBound) { + return random.longs(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { + return random.longs(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public double nextDouble() { + return random.nextDouble(); + } + + @Override + public double nextGaussian() { + return random.nextGaussian(); + } + + @Nonnull + @Override + public DoubleStream doubles() { + return random.doubles(); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize) { + return random.doubles(streamSize); + } + + @Nonnull + @Override + public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { + return random.doubles(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { + return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public float nextFloat() { + return random.nextFloat(); + } + + @Nonnull + @Override + public Random asRandom() { + return random; + } + + @Override + public String toString() { + return "Random[wrapped=" + random.getClass().getSimpleName() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java new file mode 100644 index 000000000..e1401ba5e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TreeMap; + +public final class RomanNumerals { + + public static final class IllegalRomanNumeralException extends IllegalArgumentException { + + private IllegalRomanNumeralException(int number) { + super("Number " + number + " out of bounds for 0 to 3999"); + } + + } + + private static final TreeMap values = new TreeMap<>(); + + static { + values.put(1000, "M" ); + values.put(900, "CM"); + values.put(500, "D" ); + values.put(400, "CD"); + values.put(100, "C" ); + values.put(90, "XC"); + values.put(50, "L" ); + values.put(40, "XL"); + values.put(10, "X" ); + values.put(9, "IX"); + values.put(5, "V" ); + values.put(4, "IV"); + values.put(1, "I" ); + } + + private RomanNumerals() {} + + @Nonnull + public static String forNumber(int number) { + if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); + if (number == 0) return ""; + int i = values.floorKey(number); + if (number == i) { + return values.get(number); + } + return values.get(i) + forNumber(number - i); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java new file mode 100644 index 000000000..540c375f1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TimerTask; + +public class RunnableTimerTask extends TimerTask { + + protected final Runnable action; + + public RunnableTimerTask(@Nonnull Runnable action) { + this.action = action; + } + + @Override + public void run() { + action.run(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java new file mode 100644 index 000000000..a9fcb48f2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -0,0 +1,35 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +/** + * Since there is no way of getting the seed of a {@link Random} we create a wrapper + * which will save seed. This allows us to save randomization and reload it. + */ +public class SeededRandomWrapper extends Random implements IRandom { + + protected long seed; + + public SeededRandomWrapper() { + super(); + } + + public SeededRandomWrapper(long seed) { + super(seed); + } + + @Override + public void setSeed(long seed) { + super.setSeed(seed); + this.seed = seed; + } + + public long getSeed() { + return seed; + } + + @Override + public String toString() { + return "Random[seed=" + seed + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java new file mode 100644 index 000000000..93a2ce6ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +public class SingletonRandom extends RandomWrapper { + + public static final SingletonRandom INSTANCE = new SingletonRandom(); + + private SingletonRandom() { + super(new Random()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java new file mode 100644 index 000000000..2d0e45d21 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.io.PrintWriter; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderPrintWriter extends PrintWriter { + + protected final StringBuilderWriter writer; + + public StringBuilderPrintWriter() { + super(new StringBuilderWriter()); + writer = (StringBuilderWriter) out; + } + + @Nonnull + public StringBuilder getBuilder() { + return writer.getBuilder(); + } + + @Override + public String toString() { + return getBuilder().toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java new file mode 100644 index 000000000..5ad40651c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java @@ -0,0 +1,68 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.Writer; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderWriter extends Writer { + + private final StringBuilder builder; + + public StringBuilderWriter() { + this.builder = new StringBuilder(); + } + + public StringBuilderWriter(int capacity) { + this.builder = new StringBuilder(capacity); + } + + public StringBuilderWriter(@Nullable StringBuilder builder) { + this.builder = builder != null ? builder : new StringBuilder(); + } + + public Writer append(char value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value, int start, int end) { + builder.append(value, start, end); + return this; + } + + public void close() { + } + + public void flush() { + } + + public void write(@Nonnull String value) { + builder.append(value); + } + + public void write(@Nullable char[] value, int offset, int length) { + if (value != null) { + builder.append(value, offset, length); + } + } + + @Nonnull + public StringBuilder getBuilder() { + return this.builder; + } + + @Override + public String toString() { + return this.builder.toString(); + } + +} + diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java new file mode 100644 index 000000000..b480031d2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java @@ -0,0 +1,20 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +@Deprecated +public class Triple extends net.codingarea.commons.common.collection.pair.Triple { + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + super(first, second, third); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java new file mode 100644 index 000000000..8e9077907 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + */ +@Deprecated +public class Tuple extends net.codingarea.commons.common.collection.pair.Tuple { + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + super(first, second); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java new file mode 100644 index 000000000..1e8999988 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * This class is used to rethrow signed exception as unsigned exceptions. + */ +public class WrappedException extends RuntimeException { + + public static class SilentWrappedException extends WrappedException { + + public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public SilentWrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + } + + public WrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public WrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Nonnull + @Override + public Throwable getCause() { + return super.getCause(); + } + + @Nonnull + public static RuntimeException rethrow(@Nonnull Throwable ex) { + if (ex instanceof Error) + throw (Error) ex; + if (ex instanceof RuntimeException) + throw (RuntimeException) ex; + throw silent(ex); + } + + @Nonnull + public static WrappedException silent(@Nonnull Throwable cause) { + return new SilentWrappedException(cause); + } + + @Nonnull + public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { + return new SilentWrappedException(message, cause); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java new file mode 100644 index 000000000..bb4c23a4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Tuple + * @see Triple + * @see Quadro + */ +public interface Pair { + + /** + * @return The amount of values + */ + @Nonnegative + int amount(); + + @Nonnull + Object[] values(); + + /** + * @return {@code true} when all of the values are null, {@code false} otherwise + */ + boolean allNull(); + + /** + * @return {@code true} when none of the values are null, {@code false} otherwise + */ + boolean noneNull(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java new file mode 100644 index 000000000..df07b890d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + * @param The type of the fourth value + */ +public class Quadro implements Pair { + + protected F first; + protected S second; + protected T third; + protected FF fourth; + + public Quadro() { + } + + public Quadro(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + this.first = first; + this.second = second; + this.third = third; + this.fourth = fourth; + } + + @Override + public final int amount() { + return 4; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third, first }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + public void setFourth(@Nullable FF fourth) { + this.fourth = fourth; + } + + @Nonnull + @CheckReturnValue + public Quadro map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper, + @Nonnull Function fourthMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); + } + + public boolean noneNull() { + return first != null && second != null && third != null && fourth != null; + } + + public boolean allNull() { + return first == null && second == null && third == null && fourth != null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quadro quadro = (Quadro) o; + return Objects.equals(first, quadro.first) && Objects.equals(second, quadro.second) && Objects.equals(third, quadro.third) && Objects.equals(fourth, quadro.fourth); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third, fourth); + } + + @Override + public String toString() { + return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; + } + + @Nonnull + public static Quadro ofFirst(@Nullable F first) { + return of(first, null, null, null); + } + + @Nonnull + public static Quadro ofSecond(@Nullable S second) { + return of(null, second, null, null); + } + + @Nonnull + public static Quadro ofThird(@Nullable T third) { + return of(null, null, third, null); + } + + @Nonnull + public static Quadro ofFourth(@Nullable FF fourth) { + return of(null, null, null, fourth); + } + + @Nonnull + public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + return new Quadro<>(first, second, third, fourth); + } + + @Nonnull + public static Quadro empty() { + return new Quadro<>(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java new file mode 100644 index 000000000..48c8dfcde --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -0,0 +1,123 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +public class Triple implements Pair { + + protected F first; + protected S second; + protected T third; + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + this.first = first; + this.second = second; + this.third = third; + } + + @Override + public final int amount() { + return 3; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + @Nonnull + @CheckReturnValue + public Triple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); + } + + public boolean noneNull() { + return first != null && second != null && third != null; + } + + public boolean allNull() { + return first == null && second == null && third == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Triple triple = (Triple) o; + return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third); + } + + @Override + public String toString() { + return "Triple[" + first + ", " + second + ", " + third + "]"; + } + + @Nonnull + public static Triple ofFirst(@Nullable F first) { + return of(first, null, null); + } + + @Nonnull + public static Triple ofSecond(@Nullable S second) { + return of(null, second, null); + } + + @Nonnull + public static Triple ofThird(@Nullable T third) { + return of(null, null, third); + } + + @Nonnull + public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { + return new Triple<>(first, second, third); + } + + @Nonnull + public static Triple empty() { + return new Triple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java new file mode 100644 index 000000000..9d320ba6e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -0,0 +1,106 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + */ +public class Tuple implements Pair { + + protected F first; + protected S second; + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + this.first = first; + this.second = second; + } + + @Override + public final int amount() { + return 2; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + @Nonnull + @CheckReturnValue + public Tuple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second)); + } + + public boolean noneNull() { + return first != null && second != null; + } + + public boolean allNull() { + return first == null && second == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Tuple tuple = (Tuple) o; + return Objects.equals(first, tuple.first) && Objects.equals(second, tuple.second); + } + + @Override + public int hashCode() { + return Objects.hash(first, second); + } + + @Override + public String toString() { + return "Tuple[" + first + ", " + second + "]"; + } + + @Nonnull + public static Tuple ofFirst(@Nullable F frist) { + return new Tuple<>(frist, null); + } + + @Nonnull + public static Tuple ofSecond(@Nullable S second) { + return new Tuple<>(null, second); + } + + @Nonnull + public static Tuple of(@Nullable F first, @Nullable S second) { + return new Tuple<>(first, second); + } + + @Nonnull + public static Tuple empty() { + return new Tuple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java new file mode 100644 index 000000000..87bf70c77 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java @@ -0,0 +1,118 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; + +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public class CleanAndWriteDatabaseCache implements DatabaseCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final Predicate check; + protected final Function query; + protected final Function fallback; + protected final BiConsumer writer; + protected final long unusedTimeBeforeClean; + protected final long cleanAndWriteInterval; + protected final ILogger logger; + + public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, + @Nonnull Predicate check, @Nonnull Function fallback, + @Nonnull Function query, @Nonnull BiConsumer writer) { + this.logger = logger; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + this.cleanAndWriteInterval = cleanAndWriteInterval; + this.check = check; + this.query = query; + this.fallback = fallback; + this.writer = writer; + + EXECUTOR.scheduleAtFixedRate(this::writeCache, cleanAndWriteInterval, cleanAndWriteInterval, TimeUnit.MILLISECONDS); + Runtime.getRuntime().addShutdownHook(new Thread(this::writeCache)); + } + + public void writeCache() { + if (logger != null ) logger.debug("Writing & Cleaning cache"); + cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); + } + + @Nonnull + @Override + public V getData(@Nonnull K key) { + Tuple cached = cache.get(key); + if (cached != null) { + cached.setFirst(System.currentTimeMillis()); + return cached.getSecond(); + } + + try { + V data = query.apply(key); + if (logger != null ) logger.trace("Queried data {} for {}", data, key); + cache.put(key, new Tuple<>(System.currentTimeMillis(), data)); + return data; + } catch (Exception ex) { + if (logger != null ) logger.error("Could not get data for {}", key, ex); + return fallback.apply(key); + } + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, + @Nonnull Predicate check, @Nonnull BiConsumer writer) { + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + try { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + + V value = pair.getSecond(); + if (!check.test(value)) return; + + if (logger != null ) logger.trace("Writing {}", value); + writer.accept(key, value); + } catch (Exception ex) { + if (logger != null ) logger.error("Unable to write cache for {}", key, ex); + } + }); + remove.forEach(cache::remove); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java new file mode 100644 index 000000000..6cf0779c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public class CleanWriteableCache implements WriteableCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final long cleanInterval; + protected final long unusedTimeBeforeClean; + + public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { + this.logger = logger; + this.cleanInterval = cleanInterval; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + + EXECUTOR.scheduleAtFixedRate(this::cleanCache, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS); + } + + public void cleanCache() { + if (logger != null ) logger.debug("Cleaning cache"); + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + @Nullable + @Override + public V getData(@Nonnull K key) { + Tuple pair = cache.get(key); + if (pair == null) return null; + pair.setFirst(System.currentTimeMillis()); + return pair.getSecond(); + } + + @Override + public void setData(@Nonnull K key, @Nullable V value) { + cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java new file mode 100644 index 000000000..1279ae1f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.collection.RunnableTimerTask; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Timer; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.ToLongFunction; + +public class CoolDownCache { + + protected final Map cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final ToLongFunction cooldownTime; + protected final long cleanInterval; + + public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { + this.logger = logger; + this.cooldownTime = cooldownTime; + this.cleanInterval = cleanInterval; + + new Timer(taskName).schedule(new RunnableTimerTask(this::cleanCache), cleanInterval, cleanInterval); + } + + public void cleanCache() { + logger.debug("Cleaning cooldown cache"); + + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, time) -> { + if (time == null || !isOnCoolDown(now, time, key)) { + logger.trace("Removing {} from cooldown cache", key); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { + long difference = now - suspect; + return difference < getCoolDownTime(key); + } + + public boolean isOnCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return false; + return isOnCoolDown(System.currentTimeMillis(), time, key); + } + + public boolean checkCoolDown(@Nonnull K key) { + boolean cooldown = isOnCoolDown(key); + if (!cooldown) setOnCoolDown(key); + return cooldown; + } + + public void setOnCoolDown(@Nonnull K key) { + cache.put(key, System.currentTimeMillis()); + } + + public long getCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return 0; + return System.currentTimeMillis() - time; + } + + public float getCoolDownSeconds(@Nonnull K key) { + return getCoolDown(key) / 1000f; + } + + public long getCoolDownTime(@Nonnull K key) { + return cooldownTime.applyAsLong(key); + } + + public int size() { + return cache.size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java new file mode 100644 index 000000000..5afc4e461 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; + +/** + * @deprecated Use {@link com.google.common.cache.LoadingCache} instead + * + * @see com.google.common.cache.LoadingCache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public interface DatabaseCache extends ICache { + + @Nonnull + V getData(@Nonnull K key); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java new file mode 100644 index 000000000..4a6b49f7f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.BiConsumer; + +/** + * @deprecated Use {@link com.google.common.cache.Cache} instead + * + * @see com.google.common.cache.Cache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface ICache { + + ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); + + boolean contains(@Nonnull K key); + + int size(); + + default boolean isEmpty() { + return size() == 0; + } + + void clear(); + + @Nonnull + Map values(); + + default void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java new file mode 100644 index 000000000..a2c887e25 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface WriteableCache extends ICache { + + @Nullable + V getData(@Nonnull K key); + + void setData(@Nonnull K key, @Nullable V value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java new file mode 100644 index 000000000..37b71703f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -0,0 +1,169 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletableTask implements Task { + + static final ExecutorService SERVICE = Executors.newCachedThreadPool(new NamedThreadFactory("TaskProcessor")); + + private final Collection> listeners = new ArrayList<>(); + private final CompletableFuture future; + + private Throwable failure; + + public CompletableTask() { + this(new CompletableFuture<>()); + } + + private CompletableTask(@Nonnull CompletableFuture future) { + this.future = future; + this.future.exceptionally(ex -> { + this.failure = ex; + return null; + }); + } + + @Nonnull + public static Task callAsync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + SERVICE.execute(() -> { + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + }); + return task; + } + + @Nonnull + public static Task callSync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + return task; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (future.isDone()) { + V value = future.getNow(null); + if (future.isCancelled() || value != null) { + listener.onCancelled(this); + } else if (failure != null) { + listener.onFailure(this, failure); + } else { + listener.onComplete(this, value); + } + return this; + } + + listeners.add(listener); + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + this.listeners.clear(); + return this; + } + + public void fail(Throwable throwable) { + this.failure = throwable; + this.future.completeExceptionally(throwable); + for (TaskListener listener : this.listeners) { + listener.onFailure(this, throwable); + } + } + + @Override + public V call() { + if (this.future.isDone()) { + return this.future.getNow(null); + } + throw new UnsupportedOperationException("Use #complete in the CompletableTask"); + } + + public void complete(@Nullable V value) { + future.complete(value); + if (value != null) { + for (TaskListener listener : listeners) { + listener.onComplete(this, value); + } + } else { + for (TaskListener listener : listeners) { + listener.onCancelled(this); + } + } + + } + + @Override + public boolean cancel(boolean b) { + if (this.future.isCancelled()) { + return false; + } + + if (this.future.cancel(b)) { + for (TaskListener listener : this.listeners) { + listener.onCancelled(this); + } + return true; + } + return false; + } + + @Override + public boolean isCancelled() { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() { + return this.future.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + CompletableTask task = new CompletableTask<>(); + this.future.thenAccept(v -> { + try { + task.complete(mapper == null ? null : mapper.apply(v)); + } catch (Throwable ex) { + task.fail(ex); + } + }); + this.onFailure(task.future::completeExceptionally); + this.onCancelled(otherTask -> task.cancel(true)); + return task; + } + + @Nonnull + @Override + public CompletionStage stage() { + return future; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java new file mode 100644 index 000000000..aed5684ba --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletedTask implements Task { + + private final V value; + private final Throwable failure; + + private CompletableFuture future; + + public CompletedTask(@Nullable V value) { + this.value = value; + this.failure = null; + } + + public CompletedTask(@Nullable Throwable failure) { + this.value = null; + this.failure = failure; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (failure != null) { + listener.onFailure(this, failure); + } else if (value != null) { + listener.onComplete(this, value); + } else { + listener.onCancelled(this); + } + + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + return this; + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + if (failure != null) + return new CompletedTask<>(failure); + + return new CompletedTask<>(value == null || mapper == null ? null : mapper.apply(value)); + } + + @Override + public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + if (value != null) + return value; + + return def; + } + + @Override + public V call() throws Exception { + return value; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return value; + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return value; + } + + @Nonnull + @Override + public CompletionStage stage() { + if (future == null) { + future = new CompletableFuture<>(); + + if (failure != null) { + future.completeExceptionally(failure); + } else { + future.complete(value); + } + } + + return future; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java new file mode 100644 index 000000000..8b43122ec --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java @@ -0,0 +1,228 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyFunction; +import net.codingarea.commons.common.function.ExceptionallyRunnable; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * A task that may complete (done / failed / cancelled) in the future or may already be done. + * + * For the completion can be listened by calling {@link #onComplete(Consumer)}, for the cancellation by {@link #onCancelled(Runnable)} and for failure by {@link #onFailure(Consumer)}. + * + * @see #asyncCall(Callable) + * @see #completed(Object) + */ +public interface Task extends Future, Callable { + + @Nonnull + static ExecutorService getAsyncExecutor() { + return CompletableTask.SERVICE; + } + + @Nonnull + static Task empty() { + return completed(null); + } + + @Nonnull + static Task completed(@Nullable V value) { + return new CompletedTask<>(value); + } + + @Nonnull + static Task completedVoid() { + return empty(); + } + + @Nonnull + static Task failed(@Nonnull Throwable failure) { + return new CompletedTask<>(failure); + } + + @Nonnull + static CompletableTask completable() { + return new CompletableTask<>(); + } + + @Nonnull + static Task asyncCall(@Nonnull Callable callable) { + return CompletableTask.callAsync(callable); + } + + @Nonnull + static Task asyncSupply(@Nonnull Supplier supplier) { + return asyncCall(supplier::get); + } + + @Nonnull + static Task asyncRun(@Nonnull Runnable runnable) { + return asyncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return asyncRun(runnable); + } + + @Nonnull + static Task syncCall(@Nonnull Callable callable) { + return CompletableTask.callSync(callable); + } + + @Nonnull + static Task syncSupply(@Nonnull Supplier supplier) { + return syncCall(supplier::get); + } + + @Nonnull + static Task syncRun(@Nonnull Runnable runnable) { + return syncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return syncRun(runnable); + } + + @Nonnull + default Task onComplete(@Nonnull Runnable action) { + return onComplete(v -> action.run()); + } + + @Nonnull + default Task onComplete(@Nonnull Consumer action) { + return onComplete((task, value) -> action.accept(value)); + } + + @Nonnull + default Task onComplete(@Nonnull BiConsumer, ? super V> action) { + return addListener(new TaskListener() { + @Override + public void onComplete(@Nonnull Task task, @Nonnull V value) { + action.accept(task, value); + } + }); + } + + @Nonnull + default Task onFailure(@Nonnull Runnable action) { + return onFailure(ex -> action.run()); + } + + @Nonnull + default Task onFailure(@Nonnull Consumer action) { + return onFailure((task, ex) -> action.accept(ex)); + } + + @Nonnull + default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { + return addListener(new TaskListener() { + @Override + public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + action.accept(task, ex); + } + }); + } + + @Nonnull + default Task throwOnFailure() { + return onFailure(ex -> ex.printStackTrace()); + } + + @Nonnull + default Task onCancelled(@Nonnull Runnable action) { + return onCancelled(task -> action.run()); + } + + @Nonnull + default Task onCancelled(@Nonnull Consumer> action) { + return addListener(new TaskListener() { + @Override + public void onCancelled(@Nonnull Task task) { + action.accept(task); + } + }); + } + + @Nonnull + default Task addListeners(@Nonnull TaskListener... listeners) { + for (TaskListener listener : listeners) + addListener(listener); + + return this; + } + + @Nonnull + Task addListener(@Nonnull TaskListener listener); + + @Nonnull + Task clearListeners(); + + @Override + V get() throws InterruptedException, ExecutionException; + + @Override + V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + + default V getOrDefault(V def) { + try { + return get(); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException ex) { + return def; + } + } + + default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + try { + return this.get(timeout, unit); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException | TimeoutException ex) { + return def; + } + } + + default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { + try { + return get(timeout, unit); + } catch (ExecutionException | InterruptedException ex) { + throw new WrappedException(ex); + } catch (TimeoutException ex) { + throw new IllegalStateException("Operation timed out (" + timeout + " " + unit + ")"); + } + } + + @Nonnull + Task map(@Nullable Function mapper); + + @Nonnull + default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { + return map(mapper); + } + + @Nonnull + default Task mapVoid() { + return map(v -> null); + } + + @Nonnull + default Task map(@Nonnull Class target) { + return map(target::cast); + } + + @Nonnull + @CheckReturnValue + CompletionStage stage(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java new file mode 100644 index 000000000..f800ae95a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; + +public interface TaskListener { + + default void onComplete(@Nonnull Task task, @Nonnull T value) { + } + + default void onCancelled(@Nonnull Task task) { + } + + default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java new file mode 100644 index 000000000..54462d54a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java @@ -0,0 +1,97 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.function.Consumer; + +/** + * @see Document + */ +public interface Config extends Propertyable { + + /** + * Sets the value at the given path. + * + * Setting a value to {@code null} has the same effect as {@link #remove(String) removing} it. + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @param value The value to change to, {@code null} to remove + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config set(@Nonnull String path, @Nullable Object value); + + /** + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config clear(); + + /** + * Removing a value has the same effect as {@link #set(String, Object) setting} it to {@code null} + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config remove(@Nonnull String path); + + boolean isReadonly(); + + /** + * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} + */ + @Nonnull + @CheckReturnValue + Config readonly(); + + @Nonnull + @Override + default Config apply(@Nonnull Consumer action) { + return (Config) Propertyable.super.apply(action); + } + + @Nonnull + @Override + default Config applyIf(boolean expression, @Nonnull Consumer action) { + return (Config) Propertyable.super.applyIf(expression, action); + } + + @Nonnull + default Config increment(@Nonnull String path, double amount) { + return set(path, getDouble(path) + amount); + } + + @Nonnull + default Config decrement(@Nonnull String path, double amount) { + return set(path, getDouble(path) - amount); + } + + @Nonnull + default Config multiply(@Nonnull String path, double factor) { + return set(path, getDouble(path) * factor); + } + + @Nonnull + default Config divide(@Nonnull String path, double divisor) { + return set(path, getDouble(path) / divisor); + } + + @Nonnull + default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + if (!contains(path)) + set(path, defaultValue); + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java new file mode 100644 index 000000000..17c4a0b4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -0,0 +1,345 @@ +package net.codingarea.commons.common.config; + +import com.google.gson.JsonArray; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +public interface Document extends Config, Json { + + /** + * Gets the document located at the given path. + * If there is no document assigned to this path, + * a new document is being created and assigned to this path. + * + * @return the document assigned to this path + */ + @Nonnull + Document getDocument(@Nonnull String path); + + /** + * Returns the list of documents located at the given path. + * The returned list will not contain any null elements. + * If there are no documents, the list will be empty. + * Elements which are no documents in the original list will be skipped. + * If an element is {@code null} an empty document will be added + * if this document is not {@link #isReadonly() readonly}. + * + * @return the list of documents assigned to this path + */ + @Nonnull + List getDocumentList(@Nonnull String path); + + @Nonnull + default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { + List documents = getDocumentList(path); + List result = new ArrayList<>(documents.size()); + for (Document document : documents) { + result.add(document.toInstanceOf(classOfT)); + } + return result; + } + + @Nonnull + List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + T getSerializable(@Nonnull String path, @Nonnull Class classOfT); + + @Nonnull + T getSerializable(@Nonnull String path, @Nonnull T def); + + @Nonnull + Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + R mapDocument(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + T toInstanceOf(@Nonnull Class classOfT); + + /** + * Returns the parent document of this document. + * If {@code this} is the {@link #getRoot() root} this method will return {@code null}. + * + * @return the parent document of this document + */ + @Nullable + Document getParent(); + + /** + * Returns the root document of this document. + * If the {@link #getParent() parent} is {@code null} this will return {@code this}. + * + * @return the root document of this document + */ + @Nonnull + Document getRoot(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document apply(@Nonnull Consumer action) { + return (Document) Config.super.apply(action); + } + + @Nonnull + @Override + default Document applyIf(boolean expression, @Nonnull Consumer action) { + return (Document) Config.super.applyIf(expression, action); + } + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (Document) Config.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + Document set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + @CheckReturnValue + Document readonly(); + + @Nonnull + Map children(); + + boolean isDocument(@Nonnull String path); + + boolean hasChildren(@Nonnull String path); + + void write(@Nonnull Writer writer) throws IOException; + + default void saveToFile(@Nonnull File file) throws IOException { + FileUtils.createFilesIfNecessary(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + default void saveToFile(@Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull File file) { + return (this instanceof FileDocument && ((FileDocument)this).getFile().equals(file)) + ? (FileDocument) this : FileDocument.wrap(this, file); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull Path file) { + return asFileDocument(file.toFile()); + } + + @Nonnull + @CheckReturnValue + default Document copyJson() { + Document document = create(); + this.forEach(document::set); + return document; + } + + /** + * @return an empty and immutable document + * + * @see EmptyDocument + */ + @Nonnull + @CheckReturnValue + static Document empty() { + return EmptyDocument.ROOT; + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + try { + if (file.exists()) { + Constructor constructor = classOfDocument.getConstructor(File.class); + return constructor.newInstance(file); + } else { + Constructor constructor = classOfDocument.getConstructor(); + return constructor.newInstance(); + } + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException ex) { + throw new UnsupportedOperationException(classOfDocument.getName() + " does not support File creation"); + } catch (InvocationTargetException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return readFile(classOfDocument, file.toFile()); + } + + /** + * @return a json document parsed by the input + * + * @see GsonDocument + */ + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull String jsonInput) { + return new GsonDocument(jsonInput); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull Reader reader) throws IOException { + return new GsonDocument(reader); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull InputStream input) throws IOException { + return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); + } + + @Nonnull + @CheckReturnValue + static List parseJsonArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + @Nonnull + @CheckReturnValue + static List parseStringArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); + (GsonDocument.isWritePrettyJson() ? GsonDocument.GSON_PRETTY_PRINT : GsonDocument.GSON).toJson(array, writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull Path file) { + return readJsonFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static List readJsonArrayFile(@Nonnull Path file) { + try { + JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + array.forEach(element -> documents.add(new GsonDocument(element.getAsJsonObject()))); + return documents; + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull Path file) { + return readPropertiesFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static Document create() { + return new GsonDocument(); + } + + @Nonnull + @CheckReturnValue + static Document of(@Nonnull Object object) { + return new GsonDocument(object); + } + + @Nullable + @CheckReturnValue + static Document ofNullable(@Nullable Object object) { + return object == null ? null : of(object); + } + + @Nonnull + @CheckReturnValue + static List arrayOf(@Nonnull Collection objects) { + List documents = new ArrayList<>(objects.size()); + objects.forEach(object -> documents.add(Document.of(object))); + return documents; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java new file mode 100644 index 000000000..b6d73f26b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java @@ -0,0 +1,172 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.function.Consumer; + +public interface FileDocument extends Document { + + /** + * Logger used to log errors which are caught in the safe version of an exceptionally method + */ + ILogger LOGGER = ILogger.forThisClass(); + + default void saveExceptionally() throws IOException { + saveToFile(getFile()); + } + + /** + * Executes {@link #saveExceptionally()} and prints all caught errors to {@link #LOGGER} + * + * @see #saveExceptionally() + */ + default void save() { + try { + saveExceptionally(); + } catch (IOException ex) { + LOGGER.error("Could not save config to file \"{}\"", getFile(), ex); + } + } + + @Nonnull + default Task saveAsync() { + return Task.asyncRunExceptionally(this::save); + } + + /** + * @param async whether this should be saved asynchronously or synchronously + * + * @see #save() + * @see #saveAsync() + */ + default void save(boolean async) { + if (async) saveAsync(); + else save(); + } + + @Nonnull + File getFile(); + + @Nonnull + Path getPath(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default FileDocument apply(@Nonnull Consumer action) { + return (FileDocument) Document.super.apply(action); + } + + @Nonnull + @Override + default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (FileDocument) Document.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + @Override + default FileDocument increment(@Nonnull String path, double amount) { + return (FileDocument) Document.super.increment(path, amount); + } + + @Nonnull + @Override + default FileDocument decrement(@Nonnull String path, double amount) { + return (FileDocument) Document.super.decrement(path, amount); + } + + @Nonnull + @Override + default FileDocument multiply(@Nonnull String path, double factor) { + return (FileDocument) Document.super.multiply(path, factor); + } + + @Nonnull + @Override + default FileDocument divide(@Nonnull String path, double divisor) { + return (FileDocument) Document.super.divide(path, divisor); + } + + @Nonnull + @CheckReturnValue + static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { + return new FileDocumentWrapper(file, document); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull Path file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull Path file) { + return readFile(PropertiesDocument.class, file); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java new file mode 100644 index 000000000..efcfb495c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java @@ -0,0 +1,48 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Supplier; + +/** + * @see Document + */ +public interface Json { + + @Nonnull + String toJson(); + + @Nonnull + String toPrettyJson(); + + @Nonnull + @CheckReturnValue + static Json empty() { + return constant("{}", "{}"); + } + + @Nonnull + @CheckReturnValue + static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { + return new Json() { + @Nonnull + @Override + public String toJson() { + return normal.get(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return pretty.get(); + } + }; + } + + @Nonnull + @CheckReturnValue + static Json constant(@Nonnull String json, @Nonnull String prettyJson) { + return supply(() -> json, () -> prettyJson); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java new file mode 100644 index 000000000..bab183bc2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.Nullable; +import java.awt.*; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +public final class PropertyHelper { + + private PropertyHelper() {} + + private static final Map> getters = new HashMap<>(); + + static { + getters.put(Character.class, Propertyable::getChar); + getters.put(Boolean.class, Propertyable::getBoolean); + getters.put(Byte.class, Propertyable::getByte); + getters.put(Short.class, Propertyable::getShort); + getters.put(Integer.class, Propertyable::getInt); + getters.put(Long.class, Propertyable::getLong); + getters.put(Float.class, Propertyable::getFloat); + getters.put(Double.class, Propertyable::getDouble); + getters.put(String.class, Propertyable::getString); + getters.put(CharSequence.class, Propertyable::getString); + getters.put(List.class, Propertyable::getStringList); + getters.put(Document.class, (BiFunction) Document::getDocument); + getters.put(String[].class, Propertyable::getStringArray); + getters.put(Date.class, Propertyable::getDate); + getters.put(OffsetDateTime.class, Propertyable::getDateTime); + getters.put(Color.class, Propertyable::getColor); + getters.put(byte[].class, Propertyable::getBinary); + } + + @Nullable + public static Date parseDate(@Nullable String string) { + try { + return DateFormat.getDateTimeInstance().parse(string); + } catch (Exception ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java new file mode 100644 index 000000000..1149b7be1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java @@ -0,0 +1,199 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * @see Document + * @see Config + */ +public interface Propertyable { + + T getInstance(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + Object getObject(@Nonnull String path); + + @Nonnull + Object getObject(@Nonnull String path, @Nonnull Object def); + + @Nonnull + @SuppressWarnings("unchecked") + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.ofNullable(extractor.apply((O) this, key)); + } + + @Nonnull + @SuppressWarnings("unchecked") + default Propertyable apply(@Nonnull Consumer action) { + action.accept((O) this); + return this; + } + + @Nonnull + default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { + if (expression) + apply(action); + return this; + } + + @Nullable + String getString(@Nonnull String path); + + @Nonnull + String getString(@Nonnull String path, @Nonnull String def); + + @Nullable + byte[] getBinary(@Nonnull String path); + + char getChar(@Nonnull String path); + + char getChar(@Nonnull String path, char def); + + long getLong(@Nonnull String path); + + long getLong(@Nonnull String path, long def); + + int getInt(@Nonnull String path); + + int getInt(@Nonnull String path, int def); + + short getShort(@Nonnull String path); + + short getShort(@Nonnull String path, short def); + + byte getByte(@Nonnull String path); + + byte getByte(@Nonnull String path, byte def); + + float getFloat(@Nonnull String path); + + float getFloat(@Nonnull String path, float def); + + double getDouble(@Nonnull String path); + + double getDouble(@Nonnull String path, double def); + + boolean getBoolean(@Nonnull String path); + + boolean getBoolean(@Nonnull String path, boolean def); + + @Nonnull + List getStringList(@Nonnull String path); + + @Nonnull + String[] getStringArray(@Nonnull String path); + + @Nonnull + > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + List getUUIDList(@Nonnull String path); + + @Nonnull + List getCharacterList(@Nonnull String path); + + @Nonnull + List getByteList(@Nonnull String path); + + @Nonnull + List getShortList(@Nonnull String path); + + @Nonnull + List getIntegerList(@Nonnull String path); + + @Nonnull + List getLongList(@Nonnull String path); + + @Nonnull + List getFloatList(@Nonnull String path); + + @Nonnull + List getDoubleList(@Nonnull String path); + + @Nullable + UUID getUUID(@Nonnull String path); + + @Nonnull + UUID getUUID(@Nonnull String path, @Nonnull UUID def); + + @Nullable + OffsetDateTime getDateTime(@Nonnull String path); + + @Nonnull + OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); + + @Nullable + Date getDate(@Nonnull String path); + + @Nonnull + Date getDate(@Nonnull String path, @Nonnull Date def); + + @Nullable + Color getColor(@Nonnull String path); + + @Nonnull + Color getColor(@Nonnull String path, @Nonnull Color def); + + @Nullable + > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + > E getEnum(@Nonnull String path, @Nonnull E def); + + @Nullable + Class getClass(@Nonnull String path); + + @Nonnull + Class getClass(@Nonnull String path, @Nonnull Class def); + + @Nullable + Version getVersion(@Nonnull String path); + + @Nonnull + Version getVersion(@Nonnull String path, @Nonnull Version def); + + boolean isList(@Nonnull String path); + + boolean isObject(@Nonnull String path); + + boolean contains(@Nonnull String path); + + boolean isEmpty(); + + @Nonnegative + int size(); + + @Nonnull + Map values(); + + @Nonnull + Map valuesAsStrings(); + + @Nonnull + Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + List mapList(@Nonnull String path, @Nonnull Function mapper); + + @Nonnull + Collection keys(); + + @Nonnull + Set> entrySet(); + + void forEach(@Nonnull BiConsumer action); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java new file mode 100644 index 000000000..cce0be2e8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -0,0 +1,278 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Config; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.function.Supplier; + +public abstract class AbstractConfig implements Config { + + protected static final ILogger logger = ILogger.forThisClass(); + + @Nonnull + protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { + T value = getter.get(); + return value == null ? def : value; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = getObject(path); + return value == null ? def : value; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return getDef(def, () -> getString(path)); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | IndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return getDouble(path, 0); + } + + @Override + public float getFloat(@Nonnull String path) { + return getFloat(path, 0); + } + + @Override + public long getLong(@Nonnull String path) { + return getLong(path, 0); + } + + @Override + public int getInt(@Nonnull String path) { + return getInt(path, 0); + } + + @Override + public short getShort(@Nonnull String path) { + return getShort(path, (short) 0); + } + + @Override + public byte getByte(@Nonnull String path) { + return getByte(path, (byte) 0); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return getBoolean(path, false); + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getDef(def, () -> getUUID(path)); + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getDef(def, () -> getDateTime(path)); + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return getDef(def, () -> getDate(path)); + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return getDef(def, () -> getColor(path)); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + E value = getEnum(path, def.getDeclaringClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + try { + return Class.forName(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return getDef(def, () -> getClass(path)); + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return Version.parse(getString(path), null); + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getDef(def, () -> getVersion(path)); + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + String string = getString(path); + if (string == null) return null; + return Base64.getDecoder().decode(string); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return getStringList(path).toArray(new String[0]); + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return mapList(path, UUID::fromString); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return mapList(path, Byte::parseByte); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return mapList(path, Short::parseShort); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return mapList(path, Integer::parseInt); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return mapList(path, Long::parseLong); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return mapList(path, Float::parseFloat); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return mapList(path, Double::parseDouble); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + List list = getStringList(path); + List result = new ArrayList<>(list.size()); + for (String string : list) { + try { + result.add(mapper.apply(string)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'", string, ex); + } + } + return result; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Nonnull + @Override + public Map valuesAsStrings() { + Map map = new HashMap<>(); + values().forEach((key, value) -> map.put(key, String.valueOf(value))); + return map; + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(valuesAsStrings(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public Set> entrySet() { + return values().entrySet(); + } + + @Nonnull + public Map map(@Nonnull Map values, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + values.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'='{}'", key, value, ex); + } + }); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java new file mode 100644 index 000000000..6f13c5f75 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java @@ -0,0 +1,162 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.readonly.ReadOnlyDocumentWrapper; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class AbstractDocument extends AbstractConfig implements Document { + + protected final Document root, parent; + + public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public AbstractDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + T value = getSerializable(path, (Class) def.getClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + if (!contains(path)) return null; + return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getDocumentList(path).stream() + .map(Document::values) + .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) + .collect(Collectors.toList()); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(children(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + Document document = getDocument(path); + return mapper.apply(document); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + if (!contains(path)) return null; + return mapDocument(path, mapper); + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + Document document = getDocument0(path, root, this); + return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + if (value instanceof byte[]) + value = Base64.getEncoder().encodeToString((byte[]) value); + + set0(path, value); + return this; + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + Document.of(object).forEach(this::set); + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + if (isReadonly()) throw new ConfigReadOnlyException("remove"); + remove0(path); + return this; + } + + @Nonnull + @Override + public Document clear() { + if (isReadonly()) throw new ConfigReadOnlyException("clear"); + clear0(); + return this; + } + + @Nonnull + @CheckReturnValue + public Document readonly() { + return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); + } + + @Nonnull + protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); + + protected abstract void set0(@Nonnull String path, @Nullable Object value); + + protected abstract void remove0(@Nonnull String path); + + protected abstract void clear0(); + + @Nonnull + @Override + public Map children() { + Map map = new HashMap<>(); + keys().forEach(key -> { + if (!isDocument(key)) return; + map.put(key, getDocument(key)); + }); + return map; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return !getDocument(path).isEmpty(); + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java new file mode 100644 index 000000000..21deb8ae5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java @@ -0,0 +1,518 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class EmptyDocument implements Document { + + public static final EmptyDocument ROOT = new EmptyDocument(); + + protected final Document root, parent; + + public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public EmptyDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + return new EmptyDocument(); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return mapper.apply(Document.empty()); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return null; + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document set(@Nonnull Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document clear() { + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + return this; + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); + } + + @Override + public void saveToFile(@Nonnull File file) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.save(File)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + return def; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + throw new UnsupportedOperationException(); + } + + @Nonnull + @Override + public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.empty(); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return def; + } + + @Override + public char getChar(@Nonnull String path) { + return 0; + } + + @Override + public char getChar(@Nonnull String path, char def) { + return def; + } + + @Override + public long getLong(@Nonnull String path) { + return 0; + } + + @Override + public long getLong(@Nonnull String path, long def) { + return def; + } + + @Override + public int getInt(@Nonnull String path) { + return 0; + } + + @Override + public int getInt(@Nonnull String path, int def) { + return def; + } + + @Override + public short getShort(@Nonnull String path) { + return 0; + } + + @Override + public short getShort(@Nonnull String path, short def) { + return def; + } + + @Override + public byte getByte(@Nonnull String path) { + return 0; + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return def; + } + + @Override + public float getFloat(@Nonnull String path) { + return 0; + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return def; + } + + @Override + public double getDouble(@Nonnull String path) { + return 0; + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return def; + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return false; + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return def; + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return new String[0]; + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return def; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return def; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return def; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return def; + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return null; + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + return def; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + return def; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return def; + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return def; + } + + @Override + public boolean contains(@Nonnull String path) { + return false; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return false; + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return false; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return 0; + } + + @Nonnull + @Override + public Map values() { + return Collections.emptyMap(); + } + + @Nonnull + @Override + public Map valuesAsStrings() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map children() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Collection keys() { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + } + + @Nonnull + @Override + public String toJson() { + return "{}"; + } + + @Nonnull + @Override + public String toPrettyJson() { + return "{}"; + } + + @Nonnull + @Override + public String toString() { + return "{}"; + } + + @Override + public boolean isReadonly() { + return true; + } + + @Nonnull + @Override + public Document readonly() { + return this; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java new file mode 100644 index 000000000..50262eaf0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -0,0 +1,508 @@ +package net.codingarea.commons.common.config.document; + +import com.google.gson.*; +import com.google.gson.internal.LazilyParsedNumber; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.gson.*; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class GsonDocument extends AbstractDocument { + + static { + GsonBuilder builder = new GsonBuilder() + .disableHtmlEscaping() + .registerTypeAdapterFactory(GsonTypeAdapter.newPredictableFactory(BukkitReflectionSerializationUtils::isSerializable, new BukkitReflectionSerializableTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Document.class, new DocumentTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Pair.class, new PairTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Class.class, new ClassTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Color.class, new ColorTypeAdapter())) + ; + + GSON = builder.create(); + GSON_PRETTY_PRINT = builder.setPrettyPrinting().create(); + } + + // Not implemented in some versions of gson + TypeAdapter NUMBER = new TypeAdapter() { + @Override + public void write(JsonWriter out, Number value) throws IOException { + out.value(value); + } + @Override + public Number read(JsonReader in) throws IOException { + JsonToken jsonToken = in.peek(); + switch (jsonToken) { + case NUMBER: + case STRING: + return new LazilyParsedNumber(in.nextString()); + case BOOLEAN: + default: + throw new JsonSyntaxException("Expecting number, got: " + jsonToken); + case NULL: + in.nextNull(); + return null; + } + } + }; + + public static final Gson GSON, GSON_PRETTY_PRINT; + + private static boolean cleanupEmptyObjects = false; + private static boolean cleanupEmptyArrays = false; + private static boolean writePrettyJson = true; + + public static void setCleanupEmptyArrays(boolean clean) { + cleanupEmptyArrays = clean; + } + + public static void setCleanupEmptyObjects(boolean clean) { + cleanupEmptyObjects = clean; + } + + public static void setWritePrettyJson(boolean pretty) { + writePrettyJson = pretty; + } + + public static boolean isWritePrettyJson() { + return writePrettyJson; + } + + @Nonnull + public static List convertArrayToDocuments(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(new GsonDocument(element.getAsJsonObject())); + } + return list; + } + + @Nonnull + public static List convertArrayToStrings(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(element.getAsString()); + } + return list; + } + + protected JsonObject jsonObject; + + public GsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public GsonDocument(@Nonnull Reader reader) throws IOException { + this(new BufferedReader(reader)); + } + + public GsonDocument(@Nonnull BufferedReader reader) throws IOException { + this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); + } + + public GsonDocument(@Nonnull String json) { + this(GSON.fromJson(json, JsonObject.class)); + } + + public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { + this(GSON.fromJson(json, JsonObject.class), root, parent); + } + + public GsonDocument(@Nullable JsonObject jsonObject) { + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nonnull Map values) { + this(); + GsonUtils.setDocumentProperties(GSON, jsonObject, values); + } + + public GsonDocument() { + this(new JsonObject()); + } + + public GsonDocument(@Nonnull Object object) { + this(GSON.toJsonTree(object).getAsJsonObject()); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.convertJsonElementToString(element); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.unpackJsonElement(element); + } + + @Nullable + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { + JsonElement element = getElement(path).orElse(null); + return GSON.fromJson(element, classOfType); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + if (isEmpty()) return null; + return GSON.fromJson(jsonObject, classOfT); + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getInstance(path, classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + JsonElement element = getElement(path).orElse(null); + if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); + return new GsonDocument(element.getAsJsonObject(), root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(new JsonArray()); + if (element.isJsonNull()) return new ArrayList<>(); + JsonArray array = element.getAsJsonArray(); + List documents = new ArrayList<>(array.size()); + for (JsonElement current : array) { + if (current == null || current.isJsonNull()) documents.add(new GsonDocument((JsonObject) null, root, this)); + else if (current.isJsonObject()) documents.add(new GsonDocument(current.getAsJsonObject(), root, this)); + } + return documents; + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + if (element == null || element.isJsonNull()) return new ArrayList<>(); + if (element.isJsonPrimitive()) return new ArrayList<>(Collections.singletonList(GsonUtils.convertJsonElementToString(element))); + if (element.isJsonObject()) throw new IllegalStateException("Cannot extract list out of json object at '" + path + "'"); + return GsonUtils.convertJsonArrayToStringList(element.getAsJsonArray()); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return getInstance(path, UUID.class); + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return getInstance(path, Date.class); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return getInstance(path, OffsetDateTime.class); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return getInstance(path, Color.class); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getInstance(path, classOfEnum); + } + + @Override + public boolean isList(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonArray); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonObject); + } + + @Override + public boolean isObject(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonPrimitive); + } + + private boolean checkElement(@Nonnull String path, @Nonnull Function check) { + return getElement(path).map(check).orElse(false); + } + + @Override + public boolean contains(@Nonnull String path) { + return getElement(path).isPresent(); + } + + @Override + public int size() { + return GsonUtils.getSize(jsonObject); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + setElement(path, value); + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); + for (Entry entry : json.entrySet()) { + jsonObject.add(entry.getKey(), entry.getValue()); + } + return this; + } + + @Override + public void clear0() { + jsonObject = new JsonObject(); + } + + @Override + public void remove0(@Nonnull String path) { + setElement(path, null); + } + + @Nonnull + @Override + public Map values() { + return GsonUtils.convertJsonObjectToMap(jsonObject); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Nonnull + @Override + public Collection keys() { + Collection keys = new ArrayList<>(size()); + for (Entry entry : jsonObject.entrySet()) { + keys.add(entry.getKey()); + } + return keys; + } + + @Nonnull + private Optional getPrimitive(@Nonnull String path) { + return getElement(path) + .filter(JsonPrimitive.class::isInstance) + .map(JsonPrimitive.class::cast); + } + + @Nonnull + private Optional getElement(@Nonnull String path) { + return getElement(path, jsonObject); + } + + @Nonnull + private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { + + JsonElement fullPathElement = object.get(path); + if (fullPathElement != null) return Optional.of(fullPathElement); + + int index = path.indexOf('.'); + if (index == -1) return Optional.empty(); + + String child = path.substring(0, index); + String newPath = path.substring(index + 1); + + JsonElement element = object.get(child); + if (element == null || element.isJsonNull()) return Optional.empty(); + + return getElement(newPath, element.getAsJsonObject()); + + } + + private void setElement(@Nonnull String path, @Nullable Object value) { + + LinkedList paths = determinePath(path); + JsonObject object = jsonObject; + + for (int i = 0; i < paths.size() - 1; i++) { + + String current = paths.get(i); + JsonElement element = object.get(current); + if (element == null || element.isJsonNull()) { + if (value == null) return; // There's noting to remove + object.add(current, element = new JsonObject()); + } + + if (!element.isJsonObject()) throw new IllegalArgumentException("Cannot replace '" + current + "' on '" + path + "'; It's not an object (" + element.getClass().getName() + ")"); + object = element.getAsJsonObject(); + + } + + String lastPath = paths.getLast(); + JsonElement jsonValue = + value instanceof JsonElement ? (JsonElement) value + : value == null ? JsonNull.INSTANCE + : value instanceof Number ? NUMBER.toJsonTree((Number) value) + : value instanceof Boolean ? TypeAdapters.BOOLEAN.toJsonTree((boolean) value) + : value instanceof Character ? TypeAdapters.CHARACTER.toJsonTree((char) value) + : GSON.toJsonTree(value); + object.add(lastPath, jsonValue); + + } + + @Nonnull + private LinkedList determinePath(@Nonnull String path) { + + LinkedList paths = new LinkedList<>(); + String pathCopy = path; + int index; + while ((index = pathCopy.indexOf('.')) != -1) { + String child = pathCopy.substring(0, index); + pathCopy = pathCopy.substring(index + 1); + paths.add(child); + } + paths.add(pathCopy); + + return paths; + + } + + @Nonnull + @Override + public String toJson() { + return GSON.toJson(jsonObject); + } + + @Nonnull + @Override + public String toPrettyJson() { + return GSON_PRETTY_PRINT.toJson(jsonObject); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GsonDocument that = (GsonDocument) o; + return jsonObject.equals(that.jsonObject); + } + + @Override + public int hashCode() { + return jsonObject.hashCode(); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + cleanup(); + (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); + } + + @Nonnull + public JsonObject getJsonObject() { + return jsonObject; + } + + @Override + public boolean isReadonly() { + return false; + } + + public void cleanup() { + cleanup(jsonObject); + } + + public static void cleanup(@Nonnull JsonObject jsonObject) { + Iterator> iterator = jsonObject.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + JsonElement value = entry.getValue(); + if (value.isJsonObject()) cleanup(value.getAsJsonObject()); +// if (cleanupNulls && value.isJsonNull()) iterator.remove(); + if (cleanupEmptyObjects && value.isJsonObject() && GsonUtils.getSize(value.getAsJsonObject()) == 0) iterator.remove(); + if (cleanupEmptyArrays && value.isJsonArray() && value.getAsJsonArray().size() == 0) iterator.remove(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java new file mode 100644 index 000000000..b0b194d05 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -0,0 +1,292 @@ +package net.codingarea.commons.common.config.document; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonArray; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +/** + * This class is not thread safe. + * Documents of this type are not able to be saved or loaded. + */ +public class MapDocument extends AbstractDocument { + + private final Map values; + + public MapDocument(@Nonnull Map values) { + Preconditions.checkNotNull(values, "Map cannot be null"); + this.values = values; + } + + public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.values = values; + } + + public MapDocument() { + this(new LinkedHashMap<>()); + } + + @Override + public boolean isReadonly() { + return false; + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); + if (value instanceof Map) return new MapDocument((Map) value, root, parent); + if (value instanceof Document) return (Document) value; + if (value instanceof String) return new GsonDocument((String) value, root, parent); + throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List documents = new ArrayList<>(); + Object value = values.get(path); + if (value instanceof List) { + List list = (List) value; + for (Object object : list) { + if (object instanceof Map) documents.add(new MapDocument((Map) object, root, parent)); + if (object instanceof Document) documents.add((Document) object); + if (object instanceof String) documents.add(new GsonDocument((String) object, root, this)); + } + } + return documents; + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + values.put(path, value); + } + + @Override + public void clear0() { + values.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + values.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + new GsonDocument(values).write(writer); + } + + @Nonnull + @Override + public String toJson() { + return new GsonDocument(values).toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return new GsonDocument(values).toPrettyJson(); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return values.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = values.get(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + if (!contains(path)) return def; + switch (getString(path).toLowerCase()) { + case "true": + case "1": + return true; + default: + return false; + } + } catch (Exception ex) { + return def; + } + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + Object object = getObject(path); + if (object == null) return Collections.emptyList(); + if (object instanceof Iterable) return StreamSupport.stream(((Iterable)object).spliterator(), false).map(String::valueOf).collect(Collectors.toList()); + if (object instanceof String) return GsonUtils.convertJsonArrayToStringList(GsonDocument.GSON.fromJson((String) object, JsonArray.class)); + throw new IllegalStateException("Cannot convert " + object.getClass() + " to a list"); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object object = getObject(path); + if (object instanceof UUID) return (UUID) object; + return UUID.fromString(String.valueOf(object)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof String) return PropertyHelper.parseDate((String) object); + if (object instanceof Date) return (Date) object; + return null; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); + if (object instanceof OffsetDateTime) return (OffsetDateTime) object; + return null; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof Color) return (Color) object; + if (object instanceof String) return Color.decode((String) object); + return null; + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Map || value instanceof Document; + } + + @Override + public boolean contains(@Nonnull String path) { + return values.containsKey(path); + } + + @Override + public int size() { + return values.size(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(values); + } + + @Nonnull + @Override + public Collection keys() { + return values.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values.forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java new file mode 100644 index 000000000..58fa7b100 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -0,0 +1,285 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.collection.Colors; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.PropertiesUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; + +/** + * This document only supports basic objects like {@link Number numbers}, {@link String strings}, {@link Character characters} and {@link Boolean booleans}. + * You may use more advanced documents which are fully supported like {@link GsonDocument} + */ +public class PropertiesDocument extends AbstractDocument { + + protected final Properties properties; + + public PropertiesDocument(@Nullable Properties properties) { + this.properties = properties == null ? new Properties() : properties; + } + + public PropertiesDocument(@Nonnull File file) throws IOException { + properties = new Properties(); + properties.load(FileUtils.newBufferedReader(file)); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return properties.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return properties.getProperty(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + if (!contains(path)) return def; + return Boolean.parseBoolean(getString(path)); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return PropertyHelper.parseDate(getString(path)); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + String string = getString(path); + return string == null ? null : Color.decode(string); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean contains(@Nonnull String path) { + return properties.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return true; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return properties.size(); + } + + @Nonnull + @Override + public Map values() { + Map map = new LinkedHashMap<>(); + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + return map; + } + + @Nonnull + @Override + public Collection keys() { + return properties.stringPropertyNames(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + final String asString; + if (value instanceof Color) { + asString = Colors.asHex((Color) value); + } else { + asString = String.valueOf(value); + } + + properties.setProperty(path, asString); + } + + @Override + public void clear0() { + properties.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + properties.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + properties.store(writer, null); + } + + @Nonnull + public Properties getProperties() { + return properties; + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Nonnull + @Override + public Document copyJson() { + Map map = new HashMap<>(); + PropertiesUtils.setProperties(properties, map); + return new GsonDocument(map); + } + + @Override + public boolean isReadonly() { + return false; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java new file mode 100644 index 000000000..03bdf14d3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -0,0 +1,355 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.file.YamlConstructor; +import org.bukkit.configuration.file.YamlRepresenter; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.representer.Representer; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class YamlDocument extends AbstractDocument { + + protected final ConfigurationSection config; + + public YamlDocument() { + this.config = new YamlConfiguration(); + } + + public YamlDocument(@Nonnull ConfigurationSection config) { + this.config = config; + } + + public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.config = config; + } + + public YamlDocument(@Nonnull File file) { + this(YamlConfiguration.loadConfiguration(file)); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return config.getString(path); + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + String string = config.getString(path, def); + return string == null ? def : string; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return config.get(path); + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = config.get(path, def); + return value == null ? def : value; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + ConfigurationSection section = config.getConfigurationSection(path); + if (section == null) section = config.createSection(path); + return new YamlDocument(section, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List> maps = config.getMapList(path); + List documents = new ArrayList<>(maps.size()); + for (Map map : maps) { + documents.add(new MapDocument((Map) map, root, this)); + } + return documents; + } + + @Override + public long getLong(@Nonnull String path) { + return config.getLong(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return config.getLong(path, def); + } + + @Override + public int getInt(@Nonnull String path) { + return config.getInt(path); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return config.getInt(path, def); + } + + @Override + public short getShort(@Nonnull String path) { + return (short) config.getInt(path); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return (short) config.getInt(path, def); + } + + @Override + public byte getByte(@Nonnull String path) { + return (byte) config.getInt(path); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return (byte) config.getInt(path, def); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | StringIndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return config.getDouble(path); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return config.getDouble(path, def); + } + + @Override + public float getFloat(@Nonnull String path) { + return (float) config.getDouble(path); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return (float) config.getDouble(path, def); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return config.getBoolean(path); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return config.getBoolean(path, def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return config.getStringList(path); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + try { + return DateFormat.getDateTimeInstance().parse(path); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + try { + return Color.decode(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean isList(@Nonnull String path) { + return config.isList(path); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return config.get(path) instanceof ConfigurationSection; + } + + @Override + public boolean contains(@Nonnull String path) { + return config.contains(path, true); + } + + @Override + public int size() { + return config.getValues(false).size(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + if (value instanceof Enum) { + Enum enun = (Enum) value; + value = enun.name(); + } + config.set(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + config.set(path, null); + } + + @Override + public void clear0() { + for (String key : config.getKeys(true)) { + config.set(key, null); + } + } + + @Nonnull + @Override + public Map values() { + return config.getValues(true); + } + + @Nonnull + @Override + public Collection keys() { + return config.getKeys(false); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public String toString() { + + DumperOptions yamlOptions = new DumperOptions(); + LoaderOptions loaderOptions = new LoaderOptions(); + Representer yamlRepresenter = new YamlRepresenter(); + Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions, loaderOptions); + + yamlOptions.setIndent(2); + yamlOptions.setDefaultFlowStyle(FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(FlowStyle.BLOCK); + String dump = yaml.dump(config.getValues(false)); + if (dump.equals("{}\n")) { + dump = ""; + } + + return dump; + + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + writer.write(toString()); + } + + @Nonnull + @Override + public Document copyJson() { + return new GsonDocument(values()); + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java new file mode 100644 index 000000000..ed36fd787 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -0,0 +1,60 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.Map; +import java.util.Optional; + +public class BukkitReflectionSerializableTypeAdapter implements GsonTypeAdapter { + + public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { + + Map map = BukkitReflectionSerializationUtils.serializeObject(object); + if (map == null) return; + + JsonObject json = new JsonObject(); + json.addProperty(KEY, BukkitReflectionSerializationUtils.getSerializationName(object.getClass())); + GsonUtils.setDocumentProperties(gson, json, map); + TypeAdapters.JSON_ELEMENT.write(writer, json); + + } + + @Override + public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + + JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); + if (element == null || !element.isJsonObject()) return null; + + JsonObject json = element.getAsJsonObject(); + String classOfType = Optional.ofNullable(findClassContainer(json)).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString).orElse(null); + + Class clazz = null; + try { + clazz = Class.forName(classOfType); + } catch (ClassNotFoundException | NullPointerException ex) { + } + + Map map = GsonUtils.convertJsonObjectToMap(json); + return BukkitReflectionSerializationUtils.deserializeObject(map, clazz); + + } + + private JsonElement findClassContainer(@Nonnull JsonObject json) { + if (json.has(ALTERNATE_KEY)) + return json.get(ALTERNATE_KEY); + return json.get(KEY); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java new file mode 100644 index 000000000..3b85bbd16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class ClassTypeAdapter implements GsonTypeAdapter> { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { + TypeAdapters.STRING.write(writer, object.getName()); + } + + @Override + public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + try { + + String value = reader.nextString(); + if (value == null) return null; + + return Class.forName(value); + + } catch (ClassNotFoundException ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java new file mode 100644 index 000000000..6a172a83f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.Colors; + +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.IOException; + +public class ColorTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { + TypeAdapters.STRING.write(writer, Colors.asHex(color)); + } + + @Override + public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + String value = TypeAdapters.STRING.read(reader); + if (value == null) return null; + return Color.decode(value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java new file mode 100644 index 000000000..fffa43204 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java @@ -0,0 +1,46 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class DocumentTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { + if (document instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) document; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + Document copiedDocument = document.copyJson(); + if (copiedDocument instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) copiedDocument; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + GsonDocument gsonDocument = new GsonDocument(document.values()); + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + + } + + @Override + public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); + if (jsonElement != null && jsonElement.isJsonObject()) { + return new GsonDocument(jsonElement.getAsJsonObject()); + } else { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java new file mode 100644 index 000000000..e8f72f78b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.function.Predicate; + +@SuppressWarnings("unchecked") +public interface GsonTypeAdapter { + + void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; + + T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; + + default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { + return new TypeAdapter() { + @Override + public void write(JsonWriter writer, T object) throws IOException { + if (object == null) { + writer.nullValue(); + return; + } + GsonTypeAdapter.this.write(gson, writer, object); + } + + @Override + public T read(JsonReader reader) throws IOException { + return GsonTypeAdapter.this.read(gson, reader); + } + }; + } + + @Nonnull + static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken token) { + Class requestedType = token.getRawType(); + if (!clazz.isAssignableFrom(requestedType)) return null; + + return (TypeAdapter) adapter.toTypeAdapter(gson); + } + }; + } + + @Nonnull + static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + return predicate.test(type.getRawType()) ? (TypeAdapter) adapter.toTypeAdapter(gson) : null; + } + }; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java new file mode 100644 index 000000000..6b4b393d0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.collection.pair.Quadro; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.collection.pair.Tuple; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class PairTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { + Object[] values = object.values(); + JsonArray array = new JsonArray(values.length); + for (Object value : values) { + array.add(gson.toJsonTree(value)); + } + } + + @Override + public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonArray array = gson.fromJson(reader, JsonArray.class); + int size = array.size(); + switch (size) { + case 2: return Tuple.of(array.get(0), array.get(1)); + case 3: return Triple.of(array.get(0), array.get(1), array.get(2)); + case 4: return Quadro.of(array.get(0), array.get(1), array.get(2), array.get(3)); + default:throw new IllegalStateException("No Pair known for amount of " + size); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java new file mode 100644 index 000000000..4267a567c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.common.config.document.readonly; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.wrapper.WrappedDocument; + +import javax.annotation.Nonnull; + +public final class ReadOnlyDocumentWrapper implements WrappedDocument { + + private final Document document; + + public ReadOnlyDocumentWrapper(@Nonnull Document document) { + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java new file mode 100644 index 000000000..4cbb0a0f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.wrapper; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.nio.file.Path; + +public class FileDocumentWrapper implements WrappedDocument, FileDocument { + + protected final Document document; + protected final File file; + + public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { + this.file = file; + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Nonnull + @Override + public File getFile() { + return file; + } + + @Nonnull + @Override + public Path getPath() { + return file.toPath(); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull String path, @Nullable Object value) { + return WrappedDocument.super.set(path, value); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull Object value) { + return WrappedDocument.super.set(value); + } + + @Nonnull + @Override + public FileDocument clear() { + return WrappedDocument.super.clear(); + } + + @Nonnull + @Override + public FileDocument remove(@Nonnull String path) { + return WrappedDocument.super.remove(path); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java new file mode 100644 index 000000000..989c393e4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java @@ -0,0 +1,510 @@ +package net.codingarea.commons.common.config.document.wrapper; + + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public interface WrappedDocument extends Document { + + Document getWrappedDocument(); + + @Override + default boolean isReadonly() { + return getWrappedDocument().isReadonly(); + } + + @Nonnull + @Override + default Document getDocument(@Nonnull String path) { + return getWrappedDocument().getDocument(path); + } + + @Nonnull + @Override + default List getDocumentList(@Nonnull String path) { + return getWrappedDocument().getDocumentList(path); + } + + @Nonnull + @Override + default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializableList(path, classOfT); + } + + @Nonnull + @Override + default D set(@Nonnull String path, @Nullable Object value) { + getWrappedDocument().set(path, value); + return self(); + } + + @Nonnull + @Override + default D set(@Nonnull Object value) { + getWrappedDocument().set(value); + return self(); + } + + @Nonnull + @Override + default D clear() { + getWrappedDocument().clear(); + return self(); + } + + @Nonnull + @Override + default D remove(@Nonnull String path) { + getWrappedDocument().remove(path); + return self(); + } + + @Override + default void write(@Nonnull Writer writer) throws IOException { + getWrappedDocument().write(writer); + } + + @Override + default void saveToFile(@Nonnull File file) throws IOException { + getWrappedDocument().saveToFile(file); + } + + @Nonnull + @Override + default String toJson() { + return getWrappedDocument().toJson(); + } + + @Nonnull + @Override + default String toPrettyJson() { + return getWrappedDocument().toPrettyJson(); + } + + @Override + default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getInstance(path, classOfT); + } + + @Override + default T toInstanceOf(@Nonnull Class classOfT) { + return getWrappedDocument().toInstanceOf(classOfT); + } + + @Nullable + @Override + default Object getObject(@Nonnull String path) { + return getWrappedDocument().getObject(path); + } + + @Nonnull + @Override + default Object getObject(@Nonnull String path, @Nonnull Object def) { + return getWrappedDocument().getObject(path, def); + } + + @Nonnull + @Override + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return getWrappedDocument().getOptional(key, extractor); + } + + @Nullable + @Override + default String getString(@Nonnull String path) { + return getWrappedDocument().getString(path); + } + + @Nonnull + @Override + default String getString(@Nonnull String path, @Nonnull String def) { + return getWrappedDocument().getString(path, def); + } + + @Override + default char getChar(@Nonnull String path) { + return getWrappedDocument().getChar(path); + } + + @Override + default char getChar(@Nonnull String path, char def) { + return getWrappedDocument().getChar(path, def); + } + + @Override + default long getLong(@Nonnull String path) { + return getWrappedDocument().getLong(path); + } + + @Override + default long getLong(@Nonnull String path, long def) { + return getWrappedDocument().getLong(path, def); + } + + @Override + default int getInt(@Nonnull String path) { + return getWrappedDocument().getInt(path); + } + + @Override + default int getInt(@Nonnull String path, int def) { + return getWrappedDocument().getInt(path, def); + } + + @Override + default short getShort(@Nonnull String path) { + return getWrappedDocument().getShort(path); + } + + @Override + default short getShort(@Nonnull String path, short def) { + return getWrappedDocument().getShort(path, def); + } + + @Override + default byte getByte(@Nonnull String path) { + return getWrappedDocument().getByte(path); + } + + @Override + default byte getByte(@Nonnull String path, byte def) { + return getWrappedDocument().getByte(path, def); + } + + @Override + default float getFloat(@Nonnull String path) { + return getWrappedDocument().getFloat(path); + } + + @Override + default float getFloat(@Nonnull String path, float def) { + return getWrappedDocument().getFloat(path, def); + } + + @Override + default double getDouble(@Nonnull String path) { + return getWrappedDocument().getDouble(path); + } + + @Override + default double getDouble(@Nonnull String path, double def) { + return getWrappedDocument().getDouble(path, def); + } + + @Override + default boolean getBoolean(@Nonnull String path) { + return getWrappedDocument().getBoolean(path); + } + + @Override + default boolean getBoolean(@Nonnull String path, boolean def) { + return getWrappedDocument().getBoolean(path, def); + } + + @Nonnull + @Override + default List getStringList(@Nonnull String path) { + return getWrappedDocument().getStringList(path); + } + + @Nonnull + @Override + default String[] getStringArray(@Nonnull String path) { + return getWrappedDocument().getStringArray(path); + } + + @Nonnull + @Override + default List mapList(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapList(path, mapper); + } + + @Nonnull + @Override + default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnumList(path, classOfEnum); + } + + @Nonnull + @Override + default List getUUIDList(@Nonnull String path) { + return getWrappedDocument().getUUIDList(path); + } + + @Nonnull + @Override + default List getCharacterList(@Nonnull String path) { + return getWrappedDocument().getCharacterList(path); + } + + @Nonnull + @Override + default List getByteList(@Nonnull String path) { + return getWrappedDocument().getByteList(path); + } + + @Nonnull + @Override + default List getShortList(@Nonnull String path) { + return getWrappedDocument().getShortList(path); + } + + @Nonnull + @Override + default List getIntegerList(@Nonnull String path) { + return getWrappedDocument().getIntegerList(path); + } + + @Nonnull + @Override + default List getLongList(@Nonnull String path) { + return getWrappedDocument().getLongList(path); + } + + @Nonnull + @Override + default List getFloatList(@Nonnull String path) { + return getWrappedDocument().getFloatList(path); + } + + @Nonnull + @Override + default List getDoubleList(@Nonnull String path) { + return getWrappedDocument().getDoubleList(path); + } + + @Nullable + @Override + default UUID getUUID(@Nonnull String path) { + return getWrappedDocument().getUUID(path); + } + + @Nonnull + @Override + default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getWrappedDocument().getUUID(path, def); + } + + @Nullable + @Override + default Date getDate(@Nonnull String path) { + return getWrappedDocument().getDate(path); + } + + @Nonnull + @Override + default Date getDate(@Nonnull String path, @Nonnull Date def) { + return getWrappedDocument().getDate(path, def); + } + + @Nullable + @Override + default OffsetDateTime getDateTime(@Nonnull String path) { + return getWrappedDocument().getDateTime(path); + } + + @Nonnull + @Override + default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getWrappedDocument().getDateTime(path, def); + } + + @Nullable + @Override + default Color getColor(@Nonnull String path) { + return getWrappedDocument().getColor(path); + } + + @Nonnull + @Override + default Color getColor(@Nonnull String path, @Nonnull Color def) { + return getWrappedDocument().getColor(path, def); + } + + @Nullable + @Override + default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnum(path, classOfEnum); + } + + @Nonnull + @Override + default > E getEnum(@Nonnull String path, @Nonnull E def) { + return getWrappedDocument().getEnum(path, def); + } + + @Nullable + @Override + default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializable(path, classOfT); + } + + @Nonnull + @Override + default T getSerializable(@Nonnull String path, @Nonnull T def) { + return getWrappedDocument().getSerializable(path, def); + } + + @Nullable + @Override + default Class getClass(@Nonnull String path) { + return getWrappedDocument().getClass(path); + } + + @Nonnull + @Override + default Class getClass(@Nonnull String path, @Nonnull Class def) { + return getWrappedDocument().getClass(path, def); + } + + @Nullable + @Override + default Version getVersion(@Nonnull String path) { + return getWrappedDocument().getVersion(path); + } + + @Nonnull + @Override + default Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getWrappedDocument().getVersion(path, def); + } + + @Nullable + @Override + default byte[] getBinary(@Nonnull String path) { + return getWrappedDocument().getBinary(path); + } + + @Override + default boolean contains(@Nonnull String path) { + return getWrappedDocument().contains(path); + } + + @Override + default boolean hasChildren(@Nonnull String path) { + return getWrappedDocument().hasChildren(path); + } + + @Override + default boolean isObject(@Nonnull String path) { + return getWrappedDocument().isObject(path); + } + + @Override + default boolean isList(@Nonnull String path) { + return getWrappedDocument().isList(path); + } + + @Override + default boolean isDocument(@Nonnull String path) { + return getWrappedDocument().isDocument(path); + } + + @Override + default boolean isEmpty() { + return getWrappedDocument().isEmpty(); + } + + @Override + default int size() { + return getWrappedDocument().size(); + } + + @Nonnull + @Override + default Map values() { + return getWrappedDocument().values(); + } + + @Nonnull + @Override + default Map valuesAsStrings() { + return getWrappedDocument().valuesAsStrings(); + } + + @Nonnull + @Override + default Map children() { + return getWrappedDocument().children(); + } + + @Nonnull + @Override + default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapValues(keyMapper, valueMapper); + } + + @Nonnull + @Override + default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapDocuments(keyMapper, valueMapper); + } + + @Nonnull + @Override + default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocument(path, mapper); + } + + @Nullable + @Override + default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocumentNullable(path, mapper); + } + + @Nonnull + @Override + default Collection keys() { + return getWrappedDocument().keys(); + } + + @Nonnull + @Override + default Set> entrySet() { + return getWrappedDocument().entrySet(); + } + + @Override + default void forEach(@Nonnull BiConsumer action) { + getWrappedDocument().forEach(action); + } + + @Nonnull + @Override + default Document readonly() { + return getWrappedDocument().readonly(); + } + + @Nullable + @Override + default Document getParent() { + return getWrappedDocument().getParent(); + } + + @Nonnull + @Override + default Document getRoot() { + return getWrappedDocument().getRoot(); + } + + @SuppressWarnings("unchecked") + default D self() { + return (D) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java new file mode 100644 index 000000000..7fa62c991 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.common.config.exceptions; + +import javax.annotation.Nonnull; + +public final class ConfigReadOnlyException extends IllegalStateException { + + public ConfigReadOnlyException(@Nonnull String action) { + super("Config." + action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java new file mode 100644 index 000000000..2af90f2c1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.common.debug; + +import net.codingarea.commons.common.collection.NumberFormatter; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class TimingsHelper { + + public static final ILogger LOGGER = ILogger.forThisClass(); + private static final Map timings = new ConcurrentHashMap<>(); + + private TimingsHelper() {} + + public static void start(@Nonnull String id) { + timings.put(id, System.currentTimeMillis()); + } + + public static void stop(@Nonnull String id) { + Long start = timings.remove(id); + if (start == null) { + LOGGER.warn("Stopped timing {} which was not started before", id); + return; + } + + long time = System.currentTimeMillis() - start; + LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); + } + + public static void restart(@Nonnull String id) { + stop(id); + start(id); + } + + public static void start() { + start(ReflectionUtils.getCallerName()); + } + + public static void stop() { + stop(ReflectionUtils.getCallerName()); + } + + public static void restart() { + restart(ReflectionUtils.getCallerName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java new file mode 100644 index 000000000..49eeec955 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -0,0 +1,498 @@ +package net.codingarea.commons.common.discord; + +import net.codingarea.commons.common.config.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.HttpsURLConnection; +import java.awt.*; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +public class DiscordWebhook { + + protected String url; + protected String content; + protected String username; + protected String avatarUrl; + protected boolean tts; + protected List embeds = new ArrayList<>(); + + private DiscordWebhook() { + } + + /** + * Constructs a new DiscordWebhook instance + * + * @param url The webhook URL obtained in Discord + */ + public DiscordWebhook(@Nonnull String url) { + this.url = url; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username) { + this.url = url; + this.username = username; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + this.content = content; + this.embeds = embeds; + this.tts = tts; + } + + @Nonnull + public DiscordWebhook setUrl(@Nonnull String url) { + this.url = url; + return this; + } + + @Nonnull + public DiscordWebhook setContent(@Nullable String content) { + this.content = content; + return this; + } + + @Nonnull + public DiscordWebhook setUsername(@Nullable String username) { + this.username = username; + return this; + } + + @Nonnull + public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { + this.avatarUrl = avatarUrl; + return this; + } + + @Nonnull + public DiscordWebhook setTts(boolean tts) { + this.tts = tts; + return this; + } + + @Nonnull + public DiscordWebhook addEmbed(EmbedObject embed) { + this.embeds.add(embed); + return this; + } + + public void execute() throws IOException { + if (content == null && embeds.isEmpty()) + throw new IllegalArgumentException("Set content or add at least one EmbedObject"); + + Document json = Document.create(); + + json.set("content", content); + json.set("username", username); + json.set("avatar_url", avatarUrl); + json.set("tts", tts); + + if (!embeds.isEmpty()) { + List embedObjects = new ArrayList<>(); + + for (EmbedObject embed : embeds) { + Document jsonEmbed = Document.create(); + + jsonEmbed.set("title", embed.getTitle()); + jsonEmbed.set("description", embed.getDescription()); + jsonEmbed.set("url", embed.getUrl()); + + if (embed.getColor() != null) { + Color color = embed.getColor(); + int rgb = color.getRed(); + rgb = (rgb << 8) + color.getGreen(); + rgb = (rgb << 8) + color.getBlue(); + + jsonEmbed.set("color", rgb); + } + + EmbedObject.Footer footer = embed.getFooter(); + EmbedObject.Image image = embed.getImage(); + EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); + EmbedObject.Author author = embed.getAuthor(); + List fields = embed.getFields(); + + if (footer != null) { + Document jsonFooter =Document.create(); + + jsonFooter.set("text", footer.getText()); + jsonFooter.set("icon_url", footer.getIconUrl()); + jsonEmbed.set("footer", jsonFooter); + } + + if (image != null) { + Document jsonImage = Document.create(); + + jsonImage.set("url", image.getUrl()); + jsonEmbed.set("image", jsonImage); + } + + if (thumbnail != null) { + Document jsonThumbnail = Document.create(); + + jsonThumbnail.set("url", thumbnail.getUrl()); + jsonEmbed.set("thumbnail", jsonThumbnail); + } + + if (author != null) { + Document jsonAuthor = Document.create(); + + jsonAuthor.set("name", author.getName()); + jsonAuthor.set("url", author.getUrl()); + jsonAuthor.set("icon_url", author.getIconUrl()); + jsonEmbed.set("author", jsonAuthor); + } + + List jsonFields = new ArrayList<>(); + for (EmbedObject.Field field : fields) { + Document jsonField = Document.create(); + + jsonField.set("name", field.getName()); + jsonField.set("value", field.getValue()); + jsonField.set("inline", field.isInline()); + + jsonFields.add(jsonField); + } + + jsonEmbed.set("fields", jsonFields.toArray()); + embedObjects.add(jsonEmbed); + } + + json.set("embeds", embedObjects.toArray()); + } + + URL url = new URL(this.url); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setConnectTimeout(2500); + connection.setReadTimeout(1000); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + connection.setRequestProperty("Accept", "*/*"); + connection.setRequestProperty("Content-Type", "application/json"); + + OutputStream output = connection.getOutputStream(); + output.write(json.toString().getBytes(StandardCharsets.UTF_8)); + output.flush(); + output.close(); + + connection.getInputStream().close(); + connection.disconnect(); + } + + @Nonnull + public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { + if (content != null) content = content.replace(trigger, replacement); + if (username != null) username = username.replace(trigger, replacement); + for (EmbedObject embed : embeds) { + if (embed.author.name != null) embed.author.name = embed.author.name.replace(trigger, replacement); + if (embed.description != null) embed.description = embed.description.replace(trigger, replacement); + if (embed.title != null) embed.title = embed.title.replace(trigger, replacement); + if (embed.footer.text != null) embed.footer.text = embed.footer.text.replace(trigger, replacement); + for (EmbedObject.Field field : embed.fields) { + if (field.name != null) field.name = field.name.replace(trigger, replacement); + if (field.value != null) field.value = field.value.replace(trigger, replacement); + } + } + return this; + } + + public static class EmbedObject { + + protected String title; + protected String description; + protected String url; + protected Color color; + + protected Footer footer; + protected Thumbnail thumbnail; + protected Image image; + protected Author author; + protected List fields = new ArrayList<>(); + + public EmbedObject() { + } + + public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, + @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, + @Nonnull List fields) { + this.title = title; + this.description = description; + this.url = url; + this.color = color; + this.footer = footer; + this.thumbnail = thumbnail; + this.image = image; + this.author = author; + this.fields = fields; + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull + public EmbedObject setTitle(String title) { + this.title = title; + return this; + } + + @Nonnull + public EmbedObject setDescription(String description) { + this.description = description; + return this; + } + + @Nonnull + public EmbedObject setUrl(String url) { + this.url = url; + return this; + } + + @Nonnull + public EmbedObject setColor(Color color) { + this.color = color; + return this; + } + + @Nonnull + public EmbedObject setFooter(String text, String icon) { + this.footer = new Footer(text, icon); + return this; + } + + @Nonnull + public EmbedObject setThumbnail(String url) { + this.thumbnail = new Thumbnail(url); + return this; + } + + @Nonnull + public EmbedObject setImage(String url) { + this.image = new Image(url); + return this; + } + + @Nonnull + public EmbedObject setAuthor(String name, String url, String icon) { + this.author = new Author(name, url, icon); + return this; + } + + @Nonnull + public EmbedObject addField(String name, String value, boolean inline) { + this.fields.add(new Field(name, value, inline)); + return this; + } + + @Override + public EmbedObject clone() { + return new EmbedObject( + title, description, url, color, + footer == null ? null : footer.clone(), + thumbnail == null ? null : thumbnail.clone(), + image == null ? null : image.clone(), + author == null ? null : author.clone(), + DiscordWebhook.clone(fields, Field::clone) + ); + } + + public static class Footer { + + protected String text; + protected String iconUrl; + + private Footer() { + } + + public Footer(String text, String iconUrl) { + this.text = text; + this.iconUrl = iconUrl; + } + + private String getText() { + return text; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Footer clone() { + return new Footer(text, iconUrl); + } + } + + public static class Thumbnail { + + private String url; + + private Thumbnail() { + } + + public Thumbnail(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + protected Thumbnail clone() { + return new Thumbnail(url); + } + } + + public static class Image { + + private String url; + + private Image() { + } + + public Image(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + public Image clone() { + return new Image(url); + } + } + + public static class Author { + + private String name; + private String url; + private String iconUrl; + + private Author() { + } + + public Author(String name, String url, String iconUrl) { + this.name = name; + this.url = url; + this.iconUrl = iconUrl; + } + + private String getName() { + return name; + } + + private String getUrl() { + return url; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Author clone() { + return new Author(name, url, iconUrl); + } + } + + public static class Field { + + private String name; + private String value; + private boolean inline; + + private Field() { + } + + private Field(String name, String value, boolean inline) { + this.name = name; + this.value = value; + this.inline = inline; + } + + private String getName() { + return name; + } + + private String getValue() { + return value; + } + + private boolean isInline() { + return inline; + } + + @Override + protected Field clone() { + return new Field(name, value, inline); + } + } + } + + @Override + public DiscordWebhook clone() { + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + } + + @Nonnull + protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { + List list = new ArrayList<>(collection.size()); + for (T current : collection) { + list.add(cloner.apply(current)); + } + return list; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java new file mode 100644 index 000000000..5bca8f733 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiConsumer; + +@FunctionalInterface +public interface ExceptionallyBiConsumer extends BiConsumer { + + @Override + default void accept(T t, U u) { + try { + acceptExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java new file mode 100644 index 000000000..6977e1ea6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiFunction; + +@FunctionalInterface +public interface ExceptionallyBiFunction extends BiFunction { + + @Override + default R apply(T t, U u) { + try { + return applyExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java new file mode 100644 index 000000000..99f90b68d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.Consumer; + +@FunctionalInterface +public interface ExceptionallyConsumer extends Consumer { + + @Override + default void accept(T t) { + try { + acceptExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java new file mode 100644 index 000000000..007c6d3e7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.DoubleFunction; + +@FunctionalInterface +public interface ExceptionallyDoubleFunction extends DoubleFunction { + + @Override + default R apply(double value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(double value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java new file mode 100644 index 000000000..182afce47 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Function; + +@FunctionalInterface +public interface ExceptionallyFunction extends Function { + + @Override + default R apply(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t) throws Exception; + + @Nonnull + @CheckReturnValue + static ExceptionallyFunction identity() { + return t -> t; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java new file mode 100644 index 000000000..c15637c63 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.IntFunction; + +@FunctionalInterface +public interface ExceptionallyIntFunction extends IntFunction { + + @Override + default R apply(int value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(int value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java new file mode 100644 index 000000000..e3cd46a66 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.LongFunction; + +@FunctionalInterface +public interface ExceptionallyLongFunction extends LongFunction { + + @Override + default R apply(long value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(long value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java new file mode 100644 index 000000000..b15ce02c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; + +@FunctionalInterface +public interface ExceptionallyRunnable extends Runnable, Callable { + + @Override + default void run() { + try { + runExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default Void call() throws Exception { + runExceptionally(); + return null; + } + + void runExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java new file mode 100644 index 000000000..5aab4b750 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +@FunctionalInterface +public interface ExceptionallySupplier extends Supplier, Callable { + + @Override + default T get() { + try { + return getExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default T call() throws Exception { + return getExceptionally(); + } + + T getExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java new file mode 100644 index 000000000..759fd6f38 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToDoubleFunction; + +@FunctionalInterface +public interface ExceptionallyToDoubleFunction extends ToDoubleFunction { + + @Override + default double applyAsDouble(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + double applyExceptionally(T T) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java new file mode 100644 index 000000000..98e5520e9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToIntFunction; + +@FunctionalInterface +public interface ExceptionallyToIntFunction extends ToIntFunction { + + @Override + default int applyAsInt(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + int applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java new file mode 100644 index 000000000..6ace6ef31 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToLongFunction; + +@FunctionalInterface +public interface ExceptionallyToLongFunction extends ToLongFunction { + + @Override + default long applyAsLong(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + long applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java new file mode 100644 index 000000000..02ec550a7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -0,0 +1,282 @@ +package net.codingarea.commons.common.logging; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.internal.FallbackLogger; +import net.codingarea.commons.common.logging.internal.JavaLoggerWrapper; +import net.codingarea.commons.common.logging.internal.SimpleLogger; +import net.codingarea.commons.common.logging.internal.Slf4jLoggerWrapper; +import net.codingarea.commons.common.logging.internal.factory.ConstantLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.DefaultLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.Slf4jLoggerFactory; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.slf4j.LoggerFactory; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ServiceLoader; + +public interface ILogger { + + final class Holder { + + private static ILoggerFactory factory; + private static Data data; + + private static class Data { + private boolean slf4j, slf4jApi; + } + + @Nonnull + private static Data getData() { + if (data == null) + createData(); + + return data; + } + + private static synchronized void createData() { + boolean slf4j = false; + boolean slf4jApi = true; + + try { + Class.forName("org.slf4j.impl.StaticLoggerBinder"); + slf4j = true; + } catch (ClassNotFoundException eStatic) { // there was no static logger binder (SLF4J pre-1.8.x) + try { + Class serviceProviderInterface = Class.forName("org.slf4j.spi.SLF4JServiceProvider"); + // check if there is a service implementation for the service, indicating a provider for SLF4J 1.8.x+ is installed + slf4j = ServiceLoader.load(serviceProviderInterface).iterator().hasNext(); + } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) + try { + // prints warning of missing implementation + LoggerFactory.getLogger(ILogger.class); + } catch (NoClassDefFoundError eApi) { + slf4jApi = false; + } + } + } + + data = new Data(); + data.slf4j = slf4j; + data.slf4jApi = slf4jApi; + } + + @Nonnull + public static ILoggerFactory getFactory() { + if (factory == null) + factory = getFallbackFactory(); + + return factory; + } + + @Nonnull + private static ILoggerFactory getFallbackFactory() { + return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : + isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : + new DefaultLoggerFactory(FallbackLogger::new); + } + + private Holder() {} + + } + + static boolean isSlf4jImplAvailable() { + return Holder.getData().slf4j; + } + + static boolean isSlf4jApiAvailable() { + return Holder.getData().slf4jApi; + } + + @Nonnull + @CheckReturnValue + static ILogger forName(@Nullable String name) { + return getFactory().forName(name); + } + + @Nonnull + @CheckReturnValue + static ILogger forClass(@Nullable Class clazz) { + return forName(clazz == null ? null : clazz.getSimpleName()); + } + + @Nonnull + @CheckReturnValue + static ILogger forClassOf(@Nonnull Object object) { + return forClass(object.getClass()); + } + + @Nonnull + @CheckReturnValue + static ILogger forThisClass() { + return forClass(ReflectionUtils.getCaller()); + } + + @Nonnull + @CheckReturnValue + static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { + return new JavaLoggerWrapper(logger); + } + + @Nonnull + @CheckReturnValue + static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { + return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); + } + + static void setFactory(@Nonnull ILoggerFactory factory) { + Preconditions.checkNotNull(factory); + Holder.factory = factory; + } + + static void setConstantFactory(@Nonnull ILogger logger) { + setFactory(new ConstantLoggerFactory(logger)); + } + + @Nonnull + static ILoggerFactory getFactory() { + return Holder.getFactory(); + } + + void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); + + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + default void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void extended(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void trace(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return level.isShownAtLoggerLevel(getMinLevel()); + } + + default boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + default boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + default boolean isExtendedEnabled() { + return isLevelEnabled(LogLevel.EXTENDED); + } + + default boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + default boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + default boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Nonnull + LogLevel getMinLevel(); + + @Nonnull + ILogger setMinLevel(@Nonnull LogLevel level); + + @Nonnull + @CheckReturnValue + default Slf4jILogger slf4j() { + if (this instanceof Slf4jILogger) + return (Slf4jILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); + } + + @Nonnull + @CheckReturnValue + default JavaILogger java() { + if (this instanceof JavaILogger) + return (JavaILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); + } + + @Nonnull + @CheckReturnValue + default PrintStream asPrintStream(@Nonnull LogLevel level) { + try { + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { + StringBuilder message = new StringBuilder(String.valueOf(messageObject)); + for (Object arg : args) { + if (arg instanceof Throwable) continue; + int index = message.indexOf("{}"); + if (index == -1) break; + message.replace(index, index+2, String.valueOf(arg)); + } + return message.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java new file mode 100644 index 000000000..fed7742e6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java @@ -0,0 +1,15 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface ILoggerFactory { + + @Nonnull + @CheckReturnValue + ILogger forName(@Nullable String name); + + void setDefaultLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java new file mode 100644 index 000000000..ddf6d01c8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.util.logging.Level; + +public enum LogLevel { + + TRACE (0, "TRACE", "trace", Level.FINEST, false), + DEBUG (2, "DEBUG", "debug", Level.FINER, false), + EXTENDED(5, "EXTENDED", "extended", Level.FINE, false), + STATUS (7, "STATUS", "status", Level.CONFIG, false), + INFO (10, "INFO", "info", Level.INFO, false), + WARN (15, "WARN", "warn", Level.WARNING, true), + ERROR (25, "ERROR", "error", Level.SEVERE, true); + + private final String uppercaseName, lowercaseName; + private final Level javaLevel; + private final int value; + private final boolean highlighted; + + LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { + this.uppercaseName = uppercaseName; + this.lowercaseName = lowercaseName; + this.javaLevel = javaLevel; + this.value = value; + this.highlighted = highlighted; + } + + @Nonnull + public Level getJavaUtilLevel() { + return javaLevel; + } + + public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { + return this.getValue() >= loggerLevel.getValue(); + } + + public int getValue() { + return value; + } + + @Nonnull + public String getLowerCaseName() { + return lowercaseName; + } + + @Nonnull + public String getUpperCaseName() { + return uppercaseName; + } + + public boolean isHighlighted() { + return highlighted; + } + + @Nonnull + public static LogLevel fromJavaLevel(@Nonnull Level level) { + for (LogLevel logLevel : values()) { + if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) + return logLevel; + } + return INFO; + } + + @Nonnull + public static LogLevel fromValue(int value) { + for (LogLevel level : values()) { + if (level.getValue() == value) + return level; + } + return INFO; + } + + @Nonnull + public static LogLevel fromName(@Nonnull String name) { + for (LogLevel level : values()) { + if (level.getUpperCaseName().equalsIgnoreCase(name)) + return level; + } + return INFO; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java new file mode 100644 index 000000000..7095492ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public class LogOutputStream extends ByteArrayOutputStream { + + private final ILogger logger; + private final LogLevel level; + + public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { + this.logger = logger; + this.level = level; + } + + @Override + public void flush() throws IOException { + String input = this.toString(StandardCharsets.UTF_8.name()); + this.reset(); + + if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { + logger.log(level, input); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java new file mode 100644 index 000000000..06deb942a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface LoggingApiUser { + + @Nonnull + ILogger getTargetLogger(); + + default void error(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().error(message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().warn(message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().info(message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().status(message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().extended(message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().debug(message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().trace(message, args); + } + + default boolean isTraceEnabled() { + return getTargetLogger().isTraceEnabled(); + } + + default boolean isDebugEnabled() { + return getTargetLogger().isDebugEnabled(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java new file mode 100644 index 000000000..c4731eead --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java @@ -0,0 +1,159 @@ +package net.codingarea.commons.common.logging; + +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; + +public interface WrappedILogger extends ILogger { + + @Nonnull + ILogger getWrappedLogger(); + + @Override + default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void error(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void error(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void warn(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void warn(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void info(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void info(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void status(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void status(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void extended(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void extended(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void debug(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void debug(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void trace(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default void trace(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return getWrappedLogger().isLevelEnabled(level); + } + + @Override + default boolean isTraceEnabled() { + return getWrappedLogger().isTraceEnabled(); + } + + @Override + default boolean isDebugEnabled() { + return getWrappedLogger().isDebugEnabled(); + } + + @Override + default boolean isExtendedEnabled() { + return getWrappedLogger().isExtendedEnabled(); + } + + @Override + default boolean isInfoEnabled() { + return getWrappedLogger().isInfoEnabled(); + } + + @Override + default boolean isWarnEnabled() { + return getWrappedLogger().isWarnEnabled(); + } + + @Override + default boolean isErrorEnabled() { + return getWrappedLogger().isErrorEnabled(); + } + + @Nonnull + @Override + default LogLevel getMinLevel() { + return getWrappedLogger().getMinLevel(); + } + + @Nonnull + @Override + default ILogger setMinLevel(@Nonnull LogLevel level) { + return getWrappedLogger().setMinLevel(level); + } + + @Nonnull + @Override + default Slf4jILogger slf4j() { + return getWrappedLogger().slf4j(); + } + + @Nonnull + @Override + default JavaILogger java() { + return getWrappedLogger().java(); + } + + @Nonnull + @Override + default PrintStream asPrintStream(@Nonnull LogLevel level) { + return getWrappedLogger().asPrintStream(level); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java new file mode 100644 index 000000000..e19b07015 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java @@ -0,0 +1,23 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public class HandledAsyncLogger extends HandledLogger { + + protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); + + public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + executor.execute(() -> logNow(entry)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java new file mode 100644 index 000000000..cde16aac4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CopyOnWriteArrayList; + +public abstract class HandledLogger implements ILogger { + + protected final Collection handlers = new CopyOnWriteArrayList<>(); + protected LogLevel level; + + public HandledLogger(@Nonnull LogLevel initialLevel) { + this.level = initialLevel; + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!level.isShownAtLoggerLevel(this.level)) return; + Throwable exception = null; + for (Object arg : args) { + if (arg instanceof Throwable) + exception = (Throwable) arg; + } + log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); + } + + public void log(@Nonnull LogEntry entry) { + if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; + log0(entry); + } + + protected abstract void log0(@Nonnull LogEntry entry); + + protected void logNow(@Nonnull LogEntry entry) { + for (LogHandler handler : handlers) { + try { + handler.handle(entry); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @Nonnull + public HandledLogger addHandler(@Nonnull LogHandler... handler) { + handlers.addAll(Arrays.asList(handler)); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java new file mode 100644 index 000000000..0a62ac68b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; + +public class HandledSyncLogger extends HandledLogger { + + public HandledSyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + logNow(entry); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java new file mode 100644 index 000000000..5068d301b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; + +public class LogEntry { + + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; + + public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { + this.timestamp = timestamp; + this.threadName = threadName; + this.message = message; + this.level = level; + this.exception = exception; + } + + @Nonnull + public Instant getTimestamp() { + return timestamp; + } + + @Nonnull + public String getThreadName() { + return threadName; + } + + @Nonnull + public String getMessage() { + return message; + } + + @Nonnull + public LogLevel getLevel() { + return level; + } + + @Nullable + public Throwable getException() { + return exception; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java new file mode 100644 index 000000000..36141fed5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.logging.handler; + +import javax.annotation.Nonnull; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +public interface LogHandler { + + DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); + + void handle(@Nonnull LogEntry entry) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java new file mode 100644 index 000000000..711a8ab54 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal; + +import javax.annotation.Nonnull; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Because you can't change the level of a plugin logger properly, we create a wrapper for the plugin logger + * and map all levels below {@link Level#INFO} to {@link Level#INFO}, if they are loggable. + */ +public class BukkitLoggerWrapper extends JavaLoggerWrapper { + + public BukkitLoggerWrapper(@Nonnull Logger logger) { + super(logger); + } + + @Nonnull + @Override + protected Level mapLevel(@Nonnull Level level) { + if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) + return Level.INFO; + return level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java new file mode 100644 index 000000000..4a5e83e9c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +public class FallbackLogger implements ILogger { + + protected final PrintStream stream = System.err; + protected final String name; + + protected LogLevel level = LogLevel.INFO; + + public FallbackLogger(@Nullable String name) { + this.name = name; + } + + public FallbackLogger() { + this(null); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!isLevelEnabled(level)) return; + stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); + for (Object arg : args) { + if (!(arg instanceof Throwable)) continue; + ((Throwable)arg).printStackTrace(stream); + } + } + + @Nonnull + @Override + public FallbackLogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @CheckReturnValue + public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { + Thread thread = Thread.currentThread(); + String threadName = thread.getName(); + String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + return name == null ? + String.format("[%s: %s/%s]: %s", time, threadName, level.getUpperCaseName(), message) : + String.format("[%s: %s/%s] %s: %s", time, threadName, level.getUpperCaseName(), name, message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java new file mode 100644 index 000000000..f0c64bf8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -0,0 +1,666 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.JavaILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ResourceBundle; +import java.util.function.Supplier; +import java.util.logging.*; + +public class JavaLoggerWrapper extends JavaILogger { + + protected final Logger logger; + + public JavaLoggerWrapper(@Nonnull Logger logger) { + super(null, null); + this.logger = logger; + } + + @Override + public boolean getUseParentHandlers() { + return logger.getUseParentHandlers(); + } + + @Override + public Filter getFilter() { + return logger.getFilter(); + } + + @Override + public Handler[] getHandlers() { + return logger.getHandlers(); + } + + @Override + public Level getLevel() { + return logger.getLevel(); + } + + @Override + public Logger getParent() { + return logger.getParent(); + } + + @Override + public ResourceBundle getResourceBundle() { + return logger.getResourceBundle(); + } + + @Override + public String getResourceBundleName() { + return logger.getResourceBundleName(); + } + + @Override + public void log(LogRecord record) { + mapLevel(record); + logger.log(record); + } + + @Override + public void log(Level level, String msg, Object[] params) { + logger.log(mapLevel(level), msg, params); + } + + @Override + public void log(Level level, String msg, Object param1) { + logger.log(mapLevel(level), msg, param1); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + logger.log(mapLevel(level), msgSupplier); + } + + @Override + public void log(Level level, String msg) { + logger.log(mapLevel(level), msg); + } + + @Override + public void log(Level level, String msg, Throwable thrown) { + logger.log(mapLevel(level), msg, thrown); + } + + @Override + public void log(Level level, Throwable thrown, Supplier msgSupplier) { + logger.log(mapLevel(level), thrown, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, param1); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, params); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, thrown); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, thrown, msgSupplier); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Object... params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, thrown); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, param1); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, thrown); + } + + @Override + public boolean isLoggable(Level level) { + return logger.isLoggable(level); + } + + @Override + public void setLevel(Level newLevel) throws SecurityException { + logger.setLevel(newLevel); + } + + @Override + public void setFilter(Filter newFilter) throws SecurityException { + logger.setFilter(newFilter); + } + + @Override + public void setParent(Logger parent) { + logger.setParent(parent); + } + + @Override + public void setResourceBundle(ResourceBundle bundle) { + logger.setResourceBundle(bundle); + } + + @Override + public void setUseParentHandlers(boolean useParentHandlers) { + logger.setUseParentHandlers(useParentHandlers); + } + + @Override + public void severe(String msg) { + logger.severe(msg); + } + + @Override + public void severe(Supplier msgSupplier) { + logger.severe(msgSupplier); + } + + @Override + public void entering(String sourceClass, String sourceMethod) { + logger.entering(sourceClass, sourceMethod); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object param1) { + logger.entering(sourceClass, sourceMethod, param1); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object[] params) { + logger.entering(sourceClass, sourceMethod, params); + } + + @Override + public void exiting(String sourceClass, String sourceMethod) { + logger.exiting(sourceClass, sourceMethod); + } + + @Override + public void exiting(String sourceClass, String sourceMethod, Object result) { + logger.exiting(sourceClass, sourceMethod, result); + } + + @Override + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { + logger.throwing(sourceClass, sourceMethod, thrown); + } + + @Override + public void warning(String msg) { + logger.warning(msg); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void config(String msg) { + logger.config(msg); + } + + @Override + public void fine(String msg) { + logger.fine(msg); + } + + @Override + public void finer(String msg) { + logger.finer(msg); + } + + @Override + public void finest(String msg) { + logger.finest(msg); + } + + @Override + public void warning(Supplier msgSupplier) { + logger.warning(msgSupplier); + } + + @Override + public void info(Supplier msgSupplier) { + logger.info(msgSupplier); + } + + @Override + public void config(Supplier msgSupplier) { + logger.config(msgSupplier); + } + + @Override + public void fine(Supplier msgSupplier) { + logger.fine(msgSupplier); + } + + @Override + public void finer(Supplier msgSupplier) { + logger.finer(msgSupplier); + } + + @Override + public void finest(Supplier msgSupplier) { + logger.finest(msgSupplier); + } + + @Override + public void addHandler(Handler handler) throws SecurityException { + logger.addHandler(handler); + } + + @Override + public void removeHandler(Handler handler) throws SecurityException { + logger.removeHandler(handler); + } + + @Override + public int hashCode() { + return logger.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return logger.equals(obj); + } + + @Override + public String toString() { + return logger.toString(); + } + + protected void mapLevel(@Nonnull LogRecord record) { + record.setLevel(mapLevel(record.getLevel())); + } + + @Nonnull + protected Level mapLevel(@Nonnull Level level) { + return level; + } + + @Nonnull + @Override + public JavaILogger setMinLevel(@Nonnull LogLevel level) { + setLevel(level.getJavaUtilLevel()); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return LogLevel.fromJavaLevel(logger.getLevel()); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + Throwable thrown = null; + for (Object arg : args) { + if (arg instanceof Throwable) + thrown = (Throwable) arg; + } + log(level.getJavaUtilLevel(), ILogger.formatMessage(message, args), thrown); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + +// @Override +// public void trace(String msg) { +// trace(msg, new Object[0]); +// } +// +// @Override +// public void trace(String format, Object arg) { +// trace(format, new Object[] { arg }); +// } +// +// @Override +// public void trace(String format, Object arg1, Object arg2) { +// trace(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void trace(String msg, Throwable t) { +// trace(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isTraceEnabled(Marker marker) { +// return isTraceEnabled(); +// } +// +// @Override +// public void trace(Marker marker, String msg) { +// trace(msg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg) { +// trace(format, arg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg1, Object arg2) { +// trace(format, arg1, arg2); +// } +// +// @Override +// public void trace(Marker marker, String format, Object... argArray) { +// trace(format, argArray); +// } +// +// @Override +// public void trace(Marker marker, String msg, Throwable t) { +// trace(msg, t); +// } +// +// @Override +// public boolean isDebugEnabled() { +// return isLevelEnabled(LogLevel.DEBUG); +// } +// +// @Override +// public void debug(String msg) { +// debug(msg, new Object[0]); +// } +// +// @Override +// public void debug(String format, Object arg) { +// debug(format, new Object[] { arg }); +// } +// +// @Override +// public void debug(String format, Object arg1, Object arg2) { +// debug(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void debug(String msg, Throwable t) { +// debug(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isDebugEnabled(Marker marker) { +// return isDebugEnabled(); +// } +// +// @Override +// public void debug(Marker marker, String msg) { +// debug(msg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg) { +// debug(format, arg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg1, Object arg2) { +// debug(format, arg1, arg2); +// } +// +// @Override +// public void debug(Marker marker, String format, Object... arguments) { +// debug(format, arguments); +// } +// +// @Override +// public void debug(Marker marker, String msg, Throwable t) { +// debug(msg, t); +// } +// +// @Override +// public boolean isInfoEnabled() { +// return isLevelEnabled(LogLevel.INFO); +// } +// +// @Override +// public void info(String format, Object arg) { +// info(format, new Object[] { arg }); +// } +// +// @Override +// public void info(String format, Object arg1, Object arg2) { +// info(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void info(String msg, Throwable t) { +// info(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isInfoEnabled(Marker marker) { +// return isInfoEnabled(); +// } +// +// @Override +// public void info(Marker marker, String msg) { +// info(msg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg) { +// info(format, arg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg1, Object arg2) { +// info(format, arg1, arg2); +// } +// +// @Override +// public void info(Marker marker, String format, Object... arguments) { +// info(format, arguments); +// } +// +// @Override +// public void info(Marker marker, String msg, Throwable t) { +// info(msg, t); +// } +// +// @Override +// public boolean isWarnEnabled() { +// return isLevelEnabled(LogLevel.WARN); +// } +// +// @Override +// public void warn(String msg) { +// warn(msg, new Object[0]); +// } +// +// @Override +// public void warn(String format, Object arg) { +// warn(format, new Object[] { arg }); +// } +// +// @Override +// public void warn(String format, Object arg1, Object arg2) { +// warn(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void warn(String msg, Throwable t) { +// warn(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isWarnEnabled(Marker marker) { +// return isWarnEnabled(); +// } +// +// @Override +// public void warn(Marker marker, String msg) { +// warn(marker); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg) { +// warn(format, arg); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg1, Object arg2) { +// warn(format, arg1, arg2); +// } +// +// @Override +// public void warn(Marker marker, String format, Object... arguments) { +// warn(format, arguments); +// } +// +// @Override +// public void warn(Marker marker, String msg, Throwable t) { +// warn(msg, t); +// } +// +// @Override +// public boolean isErrorEnabled() { +// return isLevelEnabled(LogLevel.ERROR); +// } +// +// @Override +// public void error(String msg) { +// error(msg, new Object[0]); +// } +// +// @Override +// public void error(String format, Object arg) { +// error(format, new Object[] { arg }); +// } +// +// @Override +// public void error(String format, Object arg1, Object arg2) { +// error(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void error(String msg, Throwable t) { +// error(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isErrorEnabled(Marker marker) { +// return isErrorEnabled(); +// } +// +// @Override +// public void error(Marker marker, String msg) { +// error(msg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg) { +// error(format, arg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg1, Object arg2) { +// error(format, arg1, arg2); +// } +// +// @Override +// public void error(Marker marker, String format, Object... arguments) { +// error(format, arguments); +// } +// +// @Override +// public void error(Marker marker, String msg, Throwable t) { +// error(msg, t); +// } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java new file mode 100644 index 000000000..d99ca1fa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java @@ -0,0 +1,365 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class SimpleLogger extends FallbackLogger implements Slf4jILogger { + + public SimpleLogger(@Nullable String name) { + super(name); + } + + public SimpleLogger() { + super(); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + super.log(level, message, args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void trace(@Nullable String message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public void trace(@Nullable Object message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + @Override + public void trace(String msg) { + trace(msg, new Object[0]); + } + + @Override + public void trace(String format, Object arg) { + trace(format, new Object[] { arg }); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + trace(format, new Object[] { arg1, arg2 }); + } + + @Override + public void trace(String msg, Throwable t) { + trace(msg, new Object[] { t }); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + @Override + public void debug(String msg) { + debug(msg, new Object[0]); + } + + @Override + public void debug(String format, Object arg) { + debug(format, new Object[] { arg }); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + debug(format, new Object[] { arg1, arg2 }); + } + + @Override + public void debug(String msg, Throwable t) { + debug(msg, new Object[] { t }); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + @Override + public void info(String msg) { + info(msg, new Object[0]); + } + + @Override + public void info(String format, Object arg) { + info(format, new Object[] { arg }); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + info(format, new Object[] { arg1, arg2 }); + } + + @Override + public void info(String msg, Throwable t) { + info(msg, new Object[] { t }); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } + + @Override + public boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + @Override + public void warn(String msg) { + warn(msg, new Object[0]); + } + + @Override + public void warn(String format, Object arg) { + warn(format, new Object[] { arg }); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + warn(format, new Object[] { arg1, arg2 }); + } + + @Override + public void warn(String msg, Throwable t) { + warn(msg, new Object[] { t }); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } + + @Override + public void warn(Marker marker, String msg) { + warn(marker); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } + + @Override + public boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Override + public void error(String msg) { + error(msg, new Object[0]); + } + + @Override + public void error(String format, Object arg) { + error(format, new Object[] { arg }); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + error(format, new Object[] { arg1, arg2 }); + } + + @Override + public void error(String msg, Throwable t) { + error(msg, new Object[] { t }); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + error(msg, t); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java new file mode 100644 index 000000000..cc1b66a52 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java @@ -0,0 +1,173 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.WrappedILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.helpers.MarkerIgnoringBase; + +import javax.annotation.Nonnull; + +public class Slf4jILoggerWrapper extends MarkerIgnoringBase implements WrappedILogger, Slf4jILogger { + + private final ILogger logger; + + public Slf4jILoggerWrapper(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger getWrappedLogger() { + return logger; + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String message) { + logger.trace(message); + } + + @Override + public void trace(String message, Object arg) { + logger.trace(message, arg); + } + + @Override + public void trace(String message, Object arg1, Object arg2) { + logger.trace(message, arg1, arg2); + } + + @Override + public void trace(String message, Object... args) { + logger.trace(message, args); + } + + @Override + public void trace(String message, Throwable ex) { + logger.trace(message, ex); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String message) { + logger.debug(message); + } + + @Override + public void debug(String message, Object arg) { + logger.debug(message, arg); + } + + @Override + public void debug(String message, Object arg1, Object arg2) { + logger.debug(message, arg1, arg2); + } + + @Override + public void debug(String message, Object... args) { + logger.debug(message, args); + } + + @Override + public void debug(String message, Throwable ex) { + logger.debug(message, ex); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String message) { + logger.info(message); + } + + @Override + public void info(String message, Object arg) { + logger.info(message, arg); + } + + @Override + public void info(String message, Object arg1, Object arg2) { + logger.info(message, arg1, arg2); + } + + @Override + public void info(String message, Object... args) { + logger.info(message, args); + } + + @Override + public void info(String message, Throwable ex) { + logger.info(message, ex); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String message) { + logger.warn(message); + } + + @Override + public void warn(String message, Object arg) { + logger.warn(message, arg); + } + + @Override + public void warn(String message, Object... args) { + logger.warn(message, args); + } + + @Override + public void warn(String message, Object arg1, Object arg2) { + logger.warn(message, arg1, arg2); + } + + @Override + public void warn(String message, Throwable ex) { + logger.warn(message, ex); + } + + @Override + public boolean isErrorEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void error(String message) { + logger.error(message); + } + + @Override + public void error(String message, Object arg) { + logger.error(message, arg); + } + + @Override + public void error(String message, Object arg1, Object arg2) { + logger.error(message, arg1, arg2); + } + + @Override + public void error(String message, Object... args) { + logger.error(message, args); + } + + @Override + public void error(String message, Throwable ex) { + logger.error(message, ex); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java new file mode 100644 index 000000000..079877479 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java @@ -0,0 +1,369 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Logger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerWrapper implements Slf4jILogger { + + protected final Logger logger; + + public Slf4jLoggerWrapper(@Nonnull Logger logger) { + this.logger = logger; + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.trace(msg); + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + } + + @Override + public void trace(String msg, Throwable t) { + logger.trace(msg, t); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + @Override + public void trace(Marker marker, String msg) { + logger.trace(marker, msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + logger.trace(marker, format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + logger.trace(marker, format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + logger.trace(marker, format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + logger.trace(marker, msg, t); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.debug(msg); + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + } + + @Override + public void debug(String msg, Throwable t) { + logger.debug(msg, t); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + @Override + public void debug(Marker marker, String msg) { + logger.debug(marker, msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + logger.debug(marker, format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + logger.debug(marker, format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + logger.debug(marker, format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + logger.debug(marker, msg, t); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + } + + @Override + public void info(String msg, Throwable t) { + logger.info(msg, t); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + @Override + public void info(Marker marker, String msg) { + logger.info(marker, msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + logger.info(marker, format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + logger.info(marker, format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + logger.info(marker, format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + logger.info(marker, msg, t); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.warn(msg); + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + } + + @Override + public void warn(String msg, Throwable t) { + logger.warn(msg, t); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + @Override + public void warn(Marker marker, String msg) { + logger.warn(marker, msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + logger.warn(marker, format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + logger.warn(marker, format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + logger.warn(marker, format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + logger.warn(marker, msg, t); + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.error(msg); + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + switch (level) { + case TRACE: + trace(message, args); + return; + case DEBUG: + case EXTENDED: + debug(message, args); + return; + case STATUS: + case INFO: + info(message, args); + return; + case WARN: + warn(message, args); + return; + case ERROR: + error(message, args); + } + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + } + + @Override + public void error(String msg, Throwable t) { + logger.error(msg, t); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + @Override + public void error(Marker marker, String msg) { + logger.error(marker, msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + logger.error(marker, format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + logger.error(marker, format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + logger.error(marker, format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + logger.error(marker, msg, t); + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + if (logger.isTraceEnabled()) { + return LogLevel.TRACE; + } else if (logger.isDebugEnabled()) { + return LogLevel.DEBUG; + } else if (logger.isInfoEnabled()) { + return LogLevel.INFO; + } else if (logger.isWarnEnabled()) { + return LogLevel.WARN; + } else { + return LogLevel.ERROR; + } + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java new file mode 100644 index 000000000..2f4a6067d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class ConstantLoggerFactory implements ILoggerFactory { + + protected final ILogger logger; + + public ConstantLoggerFactory(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return logger; + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + logger.setMinLevel(level); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java new file mode 100644 index 000000000..7825389f4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +public class DefaultLoggerFactory implements ILoggerFactory { + + protected final Map loggers = new ConcurrentHashMap<>(); + protected final Function creator; + protected LogLevel level = LogLevel.DEBUG; + + public DefaultLoggerFactory(@Nonnull Function creator) { + this.creator = creator; + } + + @Nonnull + @Override + @CheckReturnValue + public synchronized ILogger forName(@Nullable String name) { + return loggers.computeIfAbsent(name == null ? "anonymous" : name, unused -> creator.apply(name).setMinLevel(level)); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + this.level = level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java new file mode 100644 index 000000000..e3948466a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerFactory implements ILoggerFactory { + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return ILogger.forSlf4jLogger( + LoggerFactory.getLogger(name == null ? "Logger" : name) + ); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java new file mode 100644 index 000000000..fde8ffb8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.logging.Logger; + +public abstract class JavaILogger extends Logger implements ILogger { + + protected JavaILogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } + + @Nonnull + @Override + public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java new file mode 100644 index 000000000..05afb6c81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import org.slf4j.Logger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface Slf4jILogger extends ILogger, Logger { + + @Override + boolean isTraceEnabled(); + + @Override + boolean isDebugEnabled(); + + @Override + boolean isInfoEnabled(); + + @Override + boolean isWarnEnabled(); + + @Override + boolean isErrorEnabled(); + + @Override + void trace(@Nullable String message, @Nonnull Object... args); + + @Override + void debug(@Nullable String message, @Nonnull Object... args); + + @Override + void info(@Nullable String message, @Nonnull Object... args); + + @Override + void warn(@Nullable String message, @Nonnull Object... args); + + @Override + void error(@Nullable String message, @Nonnull Object... args); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java new file mode 100644 index 000000000..fc9a86c16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -0,0 +1,101 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Map; + +public final class BukkitReflectionSerializationUtils { + + private BukkitReflectionSerializationUtils() {} + + protected static final ILogger logger = ILogger.forThisClass(); + + public static boolean isSerializable(@Nonnull Class clazz) { + try { + clazz.getMethod("serialize"); + return true; + } catch (Throwable ex) { + return false; + } + } + + @Nullable + public static Map serializeObject(@Nonnull Object object) { + Class classOfObject = object.getClass(); + try { + + Method method = classOfObject.getMethod("serialize"); + method.setAccessible(true); + Object serialized = method.invoke(object); + + if (!(serialized instanceof Map)) throw new IllegalArgumentException(method + " does not return a Map"); + + @SuppressWarnings("unchecked") + Map map = (Map) serialized; + return map; + + } catch (Throwable ex) { + logger.error("Could not serialize object of type {}", classOfObject, ex); + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { + try { + + Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); + Method method = configurationSerializationClass.getMethod("deserializeObject", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + return (T) object; + + } catch (Throwable ex) { + } + + if (classOfT == null) + return null; + + try { + + Method method = classOfT.getMethod("deserialize", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + if (!classOfT.isInstance(object)) throw new IllegalStateException("Deserialization of " + classOfT.getName() + " failed: returned " + (object == null ? null : object.getClass().getName())); + return classOfT.cast(object); + + } catch (Throwable ex) { + logger.error("Could not deserialize object of type {}", classOfT, ex); + return null; + } + } + + @Nonnull + public static String getSerializationName(@Nonnull Class clazz) { + for (Annotation annotation : clazz.getAnnotations()) { + Class annotationType = annotation.annotationType(); + Object value = ReflectionUtils.getAnnotationValue(annotation); + switch (annotationType.getSimpleName()) { + case "DelegateDeserialization": + case "DelegateSerialization": + case "SerializableAs": + if (value instanceof Class) { + return getSerializationName((Class) value); + } else if (value instanceof String) { + return (String) value; + } + break; + } + } + + return clazz.getName(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java new file mode 100644 index 000000000..b8733488f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -0,0 +1,565 @@ +package net.codingarea.commons.common.misc; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyConsumer; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.nio.file.FileSystem; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +public final class FileUtils { + + public static final InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]); + private static final Map ZIP_FILE_SYSTEM_PROPERTIES = ImmutableMap + .of("create", "false", "encoding", "UTF-8"); + private static Path tempDirectory; + + private FileUtils() {} + + @Nullable + public static Path getTempDirectory() { + return tempDirectory; + } + + public static void setTempDirectory(@Nullable Path tempDirectory) { + FileUtils.tempDirectory = tempDirectory; + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { + return newBufferedWriter(file.toPath()); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { + return newBufferedReader(file.toPath()); + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { + return Files.newBufferedWriter(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { + return Files.newBufferedReader(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static String getFileExtension(@Nonnull File file) { + return getFileExtension(file.getName()); + } + + @Nonnull + public static String getFileExtension(@Nonnull Path file) { + return getFileExtension(file.toString()); + } + + @Nonnull + public static String getFileExtension(@Nonnull String filename) { + return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); + } + + @Nonnull + public static String getFileName(@Nonnull File file) { + return getFileName(file.getName()); + } + + @Nonnull + public static String getFileName(@Nonnull Path file) { + return getFileName(file.toString()); + } + + @Nonnull + public static String getFileName(@Nonnull String filename) { + filename = stripFolders(filename); + int index = filename.lastIndexOf('.'); + if (index == -1) return filename; + return filename.substring(0, index); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull File file) { + return getRealFileName(file.getName()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull Path file) { + return getRealFileName(file.toString()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull String filename) { + return stripFolders(filename); + } + + @Nonnull + @CheckReturnValue + private static String stripFolders(@Nonnull String filename) { + int index = filename.lastIndexOf(File.pathSeparator); + if (index == -1) return filename; + return filename.substring(index + 1); + } + + public static void createFilesIfNecessary(@Nonnull File file) throws IOException { + if (file.exists()) return; + + if (file.isDirectory()) { + file.mkdirs(); + } else if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + + file.createNewFile(); + } + + public static void deleteWorldFolder(@Nonnull File path) { + if (path.exists()) { + File[] files = path.listFiles(); + if (files == null) return; + for (File currentFile : files) { + if (currentFile.isDirectory()) { + // Don't delete directories or we'Ll minecraft won't create them again + deleteWorldFolder(currentFile); + } else { + if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions + currentFile.delete(); + } + } + } + } + + public static byte[] toByteArray(@Nullable InputStream inputStream) { + return toByteArray(inputStream, new byte[8192]); + } + + public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffer) { + if (inputStream == null) { + return null; + } + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + copy(inputStream, byteArrayOutputStream, buffer); + return byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return null; + } + + public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { + try (FileSystem fileSystem = FileSystems + .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { + consumer.accept(fileSystem); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + + public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { + copy(inputStream, outputStream, new byte[8192]); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { + copy(inputStream, outputStream, buffer, null); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer, + Consumer lengthInputListener) throws IOException { + int len; + while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { + if (lengthInputListener != null) { + lengthInputListener.accept(len); + } + + outputStream.write(buffer, 0, len); + outputStream.flush(); + } + } + + public static void copy(Path from, Path to) throws IOException { + copy(from, to, new byte[8192]); + } + + public static void copy(Path from, Path to, byte[] buffer) throws IOException { + if (from == null || to == null || !Files.exists(from)) { + return; + } + + if (Files.notExists(to)) { + createDirectory(to.getParent()); + } + + try (InputStream stream = Files.newInputStream(from); OutputStream target = Files.newOutputStream(to)) { + copy(stream, target, buffer); + } + } + + public static void copyFilesToDirectory(Path from, Path to) { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }); + } + + public static void copyFilesToDirectory(Path from, Path to, DirectoryStream.Filter filter) { + if (filter == null) { + copyFilesToDirectory(from, to); + } else { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }, true, filter); + } + } + + public static void delete(Path file) { + if (file == null || Files.notExists(file)) { + return; + } + + if (Files.isDirectory(file)) { + walkFileTree(file, (root, current) -> FileUtils.deleteFile(current)); + } + + FileUtils.deleteFile(file); + } + + public static long size(@Nonnull Path path) { + try { + return Files.size(path); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + /** + * Converts a bunch of directories to a byte array + * + * @param directories The directories which should get converted + * @return A byte array of a zip file created from the provided directories + * @deprecated May cause a heap space (over)load + */ + @Deprecated + public static byte[] convert(Path... directories) { + if (directories == null) { + return emptyZipByteArray(); + } + + try (ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteBuffer, StandardCharsets.UTF_8)) { + for (Path directory : directories) { + zipDir(zipOutputStream, directory, null); + } + } + + return byteBuffer.toByteArray(); + + } catch (IOException ex) { + ex.printStackTrace(); + } + + return emptyZipByteArray(); + } + + @Nonnull + public static Path createTempFile() { + if (tempDirectory != null) + return createTempFile(UUID.randomUUID()); + + try { + File file = File.createTempFile(UUID.randomUUID().toString(), null); + file.deleteOnExit(); + return file.toPath(); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + public static Path createTempFile(@Nonnull UUID uuid) { + Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); + Path file = tempDirectory.resolve(uuid.toString()); + createFile(file); + return file; + } + + public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { + try { + Files.setAttribute(path, attribute, value, options); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { + setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory) throws IOException { + return zipToStream(directory, null); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { + Path target = createTempFile(); + zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); + return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); + } + + @Nullable + public static Path zipToFile(Path directory, Path target) { + return zipToFile(directory, target, null); + } + + @Nullable + public static Path zipToFile(Path directory, Path target, Predicate fileFilter) { + if (directory == null || !Files.exists(directory)) { + return null; + } + + delete(target); + try (OutputStream outputStream = Files.newOutputStream(target, StandardOpenOption.CREATE)) { + zipStream(directory, outputStream, fileFilter); + return target; + } catch (IOException ex) { + ex.printStackTrace(); + } + + return null; + } + + private static void zipStream(Path source, OutputStream buffer, Predicate fileFilter) throws IOException { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) { + if (Files.exists(source)) { + zipDir(zipOutputStream, source, fileFilter); + } + } + } + + private static void zipDir(ZipOutputStream zipOutputStream, Path directory, Predicate fileFilter) throws IOException { + Files.walkFileTree( + directory, + new SimpleFileVisitor() { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (fileFilter != null && !fileFilter.test(file)) { + return FileVisitResult.CONTINUE; + } + + try { + zipOutputStream.putNextEntry(new ZipEntry(directory.relativize(file).toString().replace("\\", "/"))); + Files.copy(file, zipOutputStream); + zipOutputStream.closeEntry(); + } catch (IOException ex) { + zipOutputStream.closeEntry(); + throw ex; + } + return FileVisitResult.CONTINUE; + } + } + ); + } + + public static Path extract(Path zipPath, Path targetDirectory) throws IOException { + if (zipPath == null || targetDirectory == null || !Files.exists(zipPath)) { + return targetDirectory; + } + + try (InputStream input = Files.newInputStream(zipPath)) { + return extract(input, targetDirectory); + } + } + + public static Path extract(InputStream input, Path targetDirectory) throws IOException { + if (input == null || targetDirectory == null) { + return targetDirectory; + } + + extract0(new ZipInputStream(input, StandardCharsets.UTF_8), targetDirectory); + + return targetDirectory; + } + + public static Path extract(byte[] zipData, Path targetDirectory) throws IOException { + if (zipData == null || zipData.length == 0 || targetDirectory == null) { + return targetDirectory; + } + + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(zipData)) { + extract0(new ZipInputStream(byteArrayInputStream, StandardCharsets.UTF_8), targetDirectory); + } + + return targetDirectory; + } + + public static void extract0(ZipInputStream zipInputStream, Path targetDirectory) throws IOException { + ZipEntry zipEntry; + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + extractEntry(zipInputStream, zipEntry, targetDirectory); + zipInputStream.closeEntry(); + } + } + + public static byte[] emptyZipByteArray() { + byte[] bytes = null; + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8); + zipOutputStream.close(); + + bytes = byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return bytes; + } + + private static void extractEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, Path targetDirectory) + throws IOException { + Path file = targetDirectory.resolve(zipEntry.getName()); + ensureChild(targetDirectory, file); + + if (zipEntry.isDirectory()) { + if (!Files.exists(file)) { + Files.createDirectories(file); + } + } else { + Path parent = file.getParent(); + if (!Files.exists(parent)) { + Files.createDirectories(parent); + } + + if (Files.exists(file)) { + Files.delete(file); + } + + Files.createFile(file); + try (OutputStream outputStream = Files.newOutputStream(file)) { + copy(zipInputStream, outputStream); + } + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer) { + walkFileTree(rootDirectoryPath, consumer, true); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories) { + walkFileTree(rootDirectoryPath, consumer, visitDirectories, "*"); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + String glob) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, glob)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, glob); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + DirectoryStream.Filter filter) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, filter)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, filter); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void createDirectory(@Nullable Path directoryPath) { + if (directoryPath != null && Files.notExists(directoryPath)) { + try { + Files.createDirectories(directoryPath); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + public static void createFile(@Nullable Path filePath) { + if (filePath != null && Files.notExists(filePath)) { + try { + if (filePath.getParent() != null) + Files.createDirectories(filePath.getParent()); + Files.createFile(filePath); + } catch (IOException ex) { + } + } + } + + public static void deleteFile(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private static void ensureChild(Path root, Path child) { + Path rootNormal = root.normalize().toAbsolutePath(); + Path childNormal = child.normalize().toAbsolutePath(); + + if (childNormal.getNameCount() <= rootNormal.getNameCount() || !childNormal.startsWith(rootNormal)) { + throw new IllegalStateException("Child " + childNormal + " is not in root path " + rootNormal); + } + } + + @Nonnull + public static Stream list(@Nonnull Path directory) { + try { + return Files.list(directory); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java new file mode 100644 index 000000000..ce3988f94 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -0,0 +1,127 @@ +package net.codingarea.commons.common.misc; + +import com.google.gson.*; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +@SuppressWarnings("unchecked") +public final class GsonUtils { + + private GsonUtils() {} + + @Nullable + public static Object unpackJsonElement(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonObject()) + return convertJsonObjectToMap(element.getAsJsonObject()); + if (element.isJsonArray()) + return convertJsonArrayToStringList(element.getAsJsonArray()); + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isNumber()) return primitive.getAsNumber(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isBoolean()) return primitive.getAsBoolean(); + } + return element; + } + + @Nullable + public static String convertJsonElementToString(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isNumber()) return primitive.getAsNumber() + ""; + if (primitive.isBoolean()) return primitive.getAsBoolean() + ""; + } + return element.toString(); + } + + @Nonnull + public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { + Map map = new LinkedHashMap<>(); + convertJsonObjectToMap(object, map); + return map; + } + + public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { + for (Entry entry : object.entrySet()) { + map.put(entry.getKey(), unpackJsonElement(entry.getValue())); + } + } + + + @Nonnull + public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + list.add(convertJsonElementToString(element)); + } + return list; + } + + @Nonnull + public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { + String[] list = new String[array.size()]; + for (int i = 0; i < array.size(); i++) { + list[i] = convertJsonElementToString(array.get(i)); + } + return list; + } + + @Nonnull + public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { + JsonArray array = new JsonArray(); + iterable.forEach(object -> array.add(gson.toJsonTree(object))); + return array; + } + + @Nonnull + public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { + JsonArray jsonArray = new JsonArray(); + ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); + return jsonArray; + } + + public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + + if (value == null) { + object.add(entry.getKey(), null); + } else if (value instanceof JsonElement) { + object.add(entry.getKey(), (JsonElement) value); + } else if (value instanceof Iterable) { + Iterable iterable = (Iterable) value; + object.add(entry.getKey(), convertIterableToJsonArray(gson, iterable)); + } else if (value.getClass().isArray()) { + object.add(entry.getKey(), convertArrayToJsonArray(gson, value)); + } else if (value instanceof Map) { + Map map = (Map) value; + JsonObject newObject = new JsonObject(); + object.add(entry.getKey(), newObject); + setDocumentProperties(gson, newObject, map); + } else { + object.add(entry.getKey(), gson.toJsonTree(value)); + } + } + } + + public static int getSize(@Nonnull JsonObject object) { + try { + return object.size(); + } catch (NoSuchMethodError ex) { + } + + return object.entrySet().size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java new file mode 100644 index 000000000..6be9f8af1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -0,0 +1,109 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.IOUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.font.TextLayout; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLConnection; + +public final class ImageUtils { + + private ImageUtils() {} + + /** + * @param height The y-position of the text + * @return The width of the text added in pixels + */ + public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); + return lineWidth; + + } + + /** + * @return The ending position of the text + */ + public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { + TextLayout layout = getTextLayout(graphics, text); + graphics.drawString(text, x, height); + return (int) (x + layout.getBounds().getWidth()); + } + + /** + * @return Returns where the text has started + */ + public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { + TextLayout layout = getTextLayout(graphics, text); + int position = (int) (endX - layout.getBounds().getWidth()); + graphics.drawString(text, position, height); + return position; + } + + /** + * @param height The y-position of the text + */ + public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); + } + + /** + * Reads a image from url using {@link ImageIO#read(InputStream)} and returns it + * + * @param url The URL the image is stored to + * + * @throws IOException + * When something goes wrong while connecting or reading the image + */ + public static BufferedImage loadUrl(@Nonnull String url) throws IOException { + URLConnection connection = IOUtils.createConnection(url); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage loadResource(@Nonnull String path) throws IOException { + InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); + return ImageIO.read(stream); + } + + public static BufferedImage loadFile(@Nonnull File file) throws IOException { + return ImageIO.read(file); + } + + @Nonnull + public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { + return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); + } + + public static void darkenImage(@Nonnull BufferedImage image) { + for (int i = 0; i < image.getWidth(); i++) { + for (int j = 0; j < image.getHeight(); j++) { + image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); + } + } + } + + @Nonnull + @CheckReturnValue + public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { + if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); + BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = created.createGraphics(); + graphics.setColor(replacementColor); + graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); + graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); + graphics.dispose(); + return created; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java new file mode 100644 index 000000000..1663748b7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.misc; + +public final class MathHelper { + + private MathHelper() {} + + public static double percentage(double total, double proportion) { + if (proportion == 0) return 0; + return (proportion * 100) / total; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java new file mode 100644 index 000000000..8b84e8f64 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.common.misc; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +public final class PropertiesUtils { + + private PropertiesUtils() {} + + public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java new file mode 100644 index 000000000..2c4566199 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -0,0 +1,258 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.ArrayWalker; +import net.codingarea.commons.common.collection.ClassWalker; +import net.codingarea.commons.common.collection.PublicSecurityManager; +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; + +public final class ReflectionUtils { + + private ReflectionUtils() {} + + @Nonnull + public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Method method : clazz.getMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + return annotatedMethods; + } + + @Nonnull + public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Class currentClass : ClassWalker.walk(clazz)) { + for (Method method : currentClass.getDeclaredMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + } + return annotatedMethods; + } + + @Nonnull + public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredMethod(name, parameterTypes); + } catch (Throwable ex) { + } + } + + throw new NoSuchMethodException(name); + } + + @Nonnull + public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredField(name); + } catch (Throwable ex) { + } + } + + throw new NoSuchFieldException(name); + } + + /** + * @param classOfEnum The class containing the enum constants + * @return The first enum found by the given names + */ + @Nonnull + public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { + for (String name : names) { + try { + return Enum.valueOf(classOfEnum, name); + } catch (IllegalArgumentException | NoSuchFieldError ex) { } + } + throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); + } + + /** + * Iterates through an array which may contain primitive data types or non primitive data types and performs the given action on each element. + * Because we can't just cast such an array to {@code Object[]}, we have to use some reflections. + * + * @param array The target array, as {@link Object}; Can't use an array type here. + * @param The type of data we will cast the content to. Use {@link Object} if the it's unknown. + * + * @throws IllegalArgumentException + * If the {@code array} is not an actual array + * + * @see Array + * @see Array#getLength(Object) + * @see Array#get(Object, int) + */ + public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { + ReflectionUtils.iterableArray(array).forEach(action); + } + + @Nonnull + @CheckReturnValue + public static Iterable iterableArray(@Nonnull Object array) { + return ArrayWalker.walk(array); + } + + @CheckReturnValue + public static Class getCaller(int index) { + try { + return new PublicSecurityManager().getPublicClassContext()[index + 2]; + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @CheckReturnValue + public static Class getCaller() { + return getCaller(2); + } + + @Nonnull + public static String getCallerName() { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + StackTraceElement element = trace[3]; + + String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); + return className + "." + element.getMethodName(); + } + + /** + * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} + * + * @see Class#getField(String) + */ + @Nonnull + public static Field getEnumAsField(@Nonnull Enum enun) { + Class classOfEnum = enun.getClass(); + + try { + return classOfEnum.getField(enun.name()); + } catch (NoSuchFieldException ex) { + throw new WrappedException(ex); + } + } + + /** + * @see Field#getAnnotations() + */ + @Nonnull + public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { + Field field = getEnumAsField(enun); + return field.getAnnotations(); + } + + /** + * @return Returns {@code null} if no annotation of this class is present + * + * @see Field#getAnnotation(Class) + */ + public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { + Field field = getEnumAsField(enun); + return field.getAnnotation(classOfAnnotation); + } + + @Nullable + public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { + try { + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name) { + try { + if (name == null) return null; + return (Class) Class.forName(name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { + try { + if (name == null) return null; + return (Class) Class.forName(name, initialize, classLoader); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { + try { + if (!method.isAccessible()) method.setAccessible(true); + return (T) method.invoke(instance); + } catch (Throwable ex) { + return null; + } + } + + @Nullable + public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { + try { + return invokeMethodOrNull(null, clazz.getMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { + try { + return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T getAnnotationValue(@Nonnull Annotation annotation) { + return invokeMethodOrNull(annotation, "value"); + } + + @Nullable + public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { + E[] values = invokeStaticMethodOrNull(classOfE, "values"); + String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; + for (E value : values) { + for (String method : methodNames) { + if (check(input, invokeMethodOrNull(value, method))) + return value; + } + } + + return null; + } + + private static boolean check(@Nonnull String input, @Nullable Object value) { + if (value == null) return false; + if (value.getClass().isArray()) { + for (Object key : iterableArray(value)) { + if (input.equalsIgnoreCase(String.valueOf(key))) + return true; + } + } + return input.equalsIgnoreCase(String.valueOf(value)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java new file mode 100644 index 000000000..66faae82d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -0,0 +1,143 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; + +public final class SimpleCollectionUtils { + + @Deprecated + public static final String REGEX_1 = ",", + REGEX_2 = "="; + private static final ILogger logger = ILogger.forThisClass(); + private static boolean logMappingError = true; + + private SimpleCollectionUtils() {} + + public static void disableErrorLogging() { + logMappingError = false; + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { + StringBuilder builder = new StringBuilder(); + for (Entry entry : map.entrySet()) { + if (builder.length() != 0) builder.append(REGEX_1); + builder.append(key.apply(entry.getKey())); + builder.append(REGEX_2); + builder.append(value.apply(entry.getValue())); + } + return builder.toString(); + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { + + Map map = new HashMap<>(); + if (string == null) return map; + + String[] args = string.split(REGEX_1); + for (String arg : args) { + try { + + String[] elements = arg.split(REGEX_2); + K keyElement = key.apply(elements[0]); + V valueElement = value.apply(elements[1]); + + if (keyElement == null || valueElement == null) + throw new NullPointerException(); + + map.put(keyElement, valueElement); + + } catch (Exception ex) { + if (logMappingError) + logger.error("Cannot generate key/value: " + ex.getClass().getName() + ": " + ex.getMessage()); + } + } + + return map; + + } + + @Nonnull + @CheckReturnValue + public static Map convertMap(@Nonnull Map map, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + map.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable to map '{}'='{}'", key, value, ex); + } + }); + return result; + } + + @Nonnull + @CheckReturnValue + public static List convert(@Nonnull Collection collection, + @Nonnull Function mapper) { + List result = new ArrayList<>(collection.size()); + collection.forEach(value -> { + try { + result.add(mapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable map '{}'", value, ex); + } + }); + return result; + } + + public static V getMostFrequentValue(@Nonnull Map map) { + Collection values = map.values(); + List list = new ArrayList<>(values); + Set set = new HashSet<>(values); + + V valueMax = null; + int max = 0; + for (V value : set) { + int frequency = Collections.frequency(list, value); + if (frequency > max) { + max = frequency; + valueMax = value; + } + } + + return valueMax; + } + + @SafeVarargs + public static Set setOf(@Nonnull Collection... collections) { + Set set = new HashSet<>(); + for (Collection collection : collections) { + set.addAll(collection); + } + return set; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java new file mode 100644 index 000000000..fdae424a0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -0,0 +1,181 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Supplier; + +public final class StringUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private StringUtils() {} + + @Nonnull + public static String getEnumName(@Nonnull Enum enun) { + return getEnumName(enun.name()); + } + + @Nonnull + public static String getEnumName(@Nonnull String name) { + StringBuilder builder = new StringBuilder(); + boolean nextUpperCase = true; + for (char letter : name.toCharArray()) { + // Replace _ with space + if (letter == '_') { + builder.append(' '); + nextUpperCase = true; + continue; + } + builder.append(nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter)); + nextUpperCase = false; + } + return builder.toString(); + } + + @Nonnull + public static String format(@Nonnull String sequence, @Nonnull Object... args) { + char start = '{', end = '}'; + boolean inArgument = false; + StringBuilder argument = new StringBuilder(); + StringBuilder builder = new StringBuilder(); + for (char c : sequence.toCharArray()) { + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + Object replacement = + current instanceof Supplier ? ((Supplier)current).get() : + current instanceof Callable ? ((Callable)current).call() : + current; + builder.append(replacement); + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + logger.warn("Invalid argument index '{}'", argument); + builder.append(start).append(argument).append(end); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + builder.append(c); + } + if (argument.length() > 0) builder.append(start).append(argument); + return builder.toString(); + } + + @Nonnull + public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { + return Optional.of(input) + .filter(name -> name.contains(separator)) + .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) + .orElse(""); + } + + @Nonnull + public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = format(array[i], args); + } + return result; + } + + @Nonnull + public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { + StringBuilder builder = new StringBuilder(); + for (String string : array) { + if (builder.length() != 0) builder.append(separator); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String[] getStringAsArray(@Nonnull String string) { + return string.split("\n"); + } + + @Nonnull + public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { + StringBuilder builder = new StringBuilder(); + for (T t : iterable) { + if (builder.length() > 0) builder.append(separator); + String string = mapper.apply(t); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String repeat(@Nullable Object sequence, int amount) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < amount; i++) builder.append(sequence); + return builder.toString(); + } + + private static int getMultiplier(char c) { + switch (Character.toLowerCase(c)) { + default: return 1; + case 'm': return 60; + case 'h': return 60*60; + case 'd': return 24*60*60; + case 'w': return 7*24*60*60; + case 'y': return 365*24*60*60; + } + } + + public static long parseSeconds(@Nonnull String input) { + if (input.toLowerCase().startsWith("perm")) return -1; + long current = 0; + long seconds = 0; + for (char c : input.toCharArray()) { + try { + long i = Long.parseUnsignedLong(String.valueOf(c)); + current *= 10; + current += i; + } catch (Exception ignored) { + int multiplier = getMultiplier(c); + seconds += current * multiplier; + current = 0; + } + } + seconds += current; + return seconds; + } + + public static boolean isNumber(@Nonnull String sequence) { + try { + Double.parseDouble(sequence); + return true; + } catch (Exception ex) { + return false; + } + } + + private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { + int lastIndex = 0; + for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { + int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); + if (index == -1) return -1; + lastIndex = index + 1; + } + + return lastIndex; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java new file mode 100644 index 000000000..d9e31fedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.annotations.Since; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public interface Version { + + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = getRevision(); + return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) + : String.format("%s.%s", getMajor(), getMinor()); + } + + default int intValue() { + int major = getMajor(); + int minor = getMinor(); + int revision = getRevision(); + + if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); + if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); + if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); + + return revision + + minor * 100 + + major * 10000; + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); + return parse(object.getClass().getAnnotation(Since.class).value()); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + for (V version : versions) { + if (version.isNewerThan(target)) continue; + return version; + } + throw new IllegalArgumentException("No version found for '" + target + "'"); + } + + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java new file mode 100644 index 000000000..14a6a89c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.version; + +import javax.annotation.Nonnull; +import java.util.Comparator; + +public class VersionComparator implements Comparator { + + @Override + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java new file mode 100644 index 000000000..29dbac10b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -0,0 +1,80 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nullable; +import java.util.Objects; + +public class VersionInfo implements Version { + + protected static final ILogger logger = ILogger.forThisClass(); + + private final int major, minor, revision; + + public VersionInfo() { + this(1, 0, 0); + } + + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Version)) return false; + return this.equals((Version) other); + } + + @Override + public int hashCode() { + return Objects.hash(major, minor, revision); + } + + @Override + public String toString() { + return this.format(); + } + + /** + * @throws IllegalArgumentException + * If the version could not be parsed + */ + public static Version parseExceptionally(@Nullable String input) { + if (input == null) throw new IllegalArgumentException("Version cannot be null"); + String[] array = input.split("\\."); + if (array.length == 0) throw new IllegalArgumentException("Version cannot be empty"); + try { + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); + } catch (Exception ex) { + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", ex.getMessage()); + return def; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Database.java b/plugin/src/main/java/net/codingarea/commons/database/Database.java new file mode 100644 index 000000000..9092f3c1f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Database.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public interface Database { + + ILogger LOGGER = ILogger.forThisClass(); + + @Nonnull + @CheckReturnValue + static Database empty() { + return new EmptyDatabase(true); + } + + @Nonnull + @CheckReturnValue + static Database unsupported() { + return new EmptyDatabase(false); + } + + boolean isConnected(); + + /** + * Creates the connection to the database synchronously. + * + * @throws DatabaseException + * If the connection could not be established + * @throws DatabaseAlreadyConnectedException + * If this database is already {@link #isConnected() connected} + */ + void connect() throws DatabaseException; + + /** + * Creates the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was established successfully + */ + boolean connectSafely(); + + /** + * Closes the connection to the database synchronously. + * + * @throws DatabaseException + * If something went wrong while closing the connection to the database + * @throws DatabaseConnectionClosedException + * If this database is not {@link #isConnected() connected} + */ + void disconnect() throws DatabaseException; + + /** + * Closes the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was closed without errors + */ + boolean disconnectSafely(); + + void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; + void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); + + @Nonnull + default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { + return Task.asyncRunExceptionally(() -> createTable(name, columns)); + } + + @Nonnull + @CheckReturnValue + DatabaseListTables listTables(); + + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseQuery query(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseUpdate update(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(@Nonnull String table); + + @Nonnull + @CheckReturnValue + SpecificDatabase getSpecificDatabase(@Nonnull String name); + + @Nonnull + DatabaseConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java new file mode 100644 index 000000000..8c67b2b87 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.config.Propertyable; + +import javax.annotation.Nonnull; + +public final class DatabaseConfig { + + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; + private final boolean portIsSet; + + public DatabaseConfig(String host, String database, String password, String user, int port) { + this(host, database, null, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String password, String user) { + this(host, database, null, password, user, 0, false, null); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port) { + this(host, database, authDatabase, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String authDatabase, String password, String user) { + this(host, database, authDatabase, password, user, 0, false, null); + } + + public DatabaseConfig(String database, String file) { + this(null, database, null, null, null, 0, false, file); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port, boolean portIsSet, String file) { + this.host = host; + this.database = database; + this.authDatabase = authDatabase; + this.password = password; + this.user = user; + this.port = port; + this.portIsSet = portIsSet; + this.file = file; + } + + public DatabaseConfig(@Nonnull Propertyable config) { + this( + config.getString("host"), + config.getString("database"), + config.getString("auth-database"), + config.getString("password"), + config.getString("user"), + config.getInt("port"), + config.contains("port"), + config.getString("file") + ); + } + + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { + return portIsSet; + } + + public String getFile() { + return file; + } + + @Override + public String toString() { + return "DatabaseConfig{" + + "host='" + host + '\'' + + ", database='" + database + '\'' + + ", authDatabase='" + authDatabase + '\'' + + ", user='" + user + '\'' + + ", file='" + file + '\'' + + ", port=" + port + + ", portIsSet=" + portIsSet + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java new file mode 100644 index 000000000..0770c8b67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -0,0 +1,288 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.abstraction.DefaultSpecificDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; + +public class EmptyDatabase implements Database { + + private final boolean silent; + + public EmptyDatabase(boolean silent) { + this.silent = silent; + } + + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { + throw new UnsupportedOperationException(message); + } + + @Override + public boolean isConnected() { + return false; + } + + @Override + public void connect() throws DatabaseException { + if (!silent) + exception("Cannot connect with a NOP Database"); + } + + @Override + public boolean connectSafely() { + return false; + } + + @Override + public void disconnect() throws DatabaseException { + if (!silent) + exception("Cannot disconnect from a NOP Database"); + } + + @Override + public boolean disconnectSafely() { + return false; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + if (!silent) + exception("Cannot create tables from a NOP Database"); + } + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + if (!silent) + exception("Cannot list tables of a NOP Database"); + + return new EmptyListTables(); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + if (!silent) + exception("Cannot count entries of a NOP Database"); + + return new EmptyCountEntries(); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + if (!silent) + exception("Cannot query in a NOP Database"); + + return new EmptyDatabaseQuery(); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + if (!silent) + exception("Cannot update in a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + if (!silent) + exception("Cannot insert into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + if (!silent) + exception("Cannot inset or update into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + if (!silent) + exception("Cannot delete from a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "EmptyDatabase[silent=" + silent + "]"; + } + + public static class EmptyDatabaseQuery implements DatabaseQuery { + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + return new DefaultExecutedQuery(Collections.emptyList()); + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.syncCall(this::execute); + } + + } + + public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Override + public Void execute() throws DatabaseException { + return null; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completedVoid(); + } + + } + + public static class EmptyCountEntries implements DatabaseCountEntries { + + @Nonnull + @Override + public Long execute() throws DatabaseException { + return 0L; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completed(0L); + } + + } + + public static class EmptyListTables implements DatabaseListTables { + + @Nonnull + @Override + public List execute() throws DatabaseException { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Task> executeAsync() { + return Task.completed(Collections.emptyList()); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Order.java b/plugin/src/main/java/net/codingarea/commons/database/Order.java new file mode 100644 index 000000000..8165ecb8e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Order.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.hierarchy.OrderedAction; + +/** + * @see OrderedAction#orderBy(String, Order) + */ +public enum Order { + + HIGHEST, + LOWEST + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java new file mode 100644 index 000000000..f58d9d0aa --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public final class SQLColumn { + + public enum Type { + /** A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 */ + CHAR, + /** A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 */ + VARCHAR, + /** Equal to {@link #CHAR}, but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 */ + BINARY, + /** Equal to {@link #VARCHAR}, but stores binary byte strings. The size parameter specifies the maximum column length in bytes. */ + VARBINARY, + /** For BLOBs (Binary Large OBjects). Max length: 255 bytes */ + TINYBLOB, + /** Holds a string with a maximum length of 255 characters */ + TINYTEXT, + /** Holds a string with a maximum length of 65,535 bytes */ + TEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + BLOB, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + MEDIUMTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data */ + MEDIUMBLOB, + /** Holds a string with a maximum length of 4,294,967,295 characters */ + LONGTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data */ + LONGBLOB, + /** A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them */ + ENUM, + /** A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list */ + SET, + /** A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1. */ + BIT, + /** A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255) */ + TINYINT, + /** Zero is considered as false, nonzero values are considered as true. */ + BOOLEAN, + /** A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255) */ + SMALLINT, + /** A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255) */ + MEDIUMINT, + /** A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255) */ + INT, + /** A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255) */ + BIGINT, + /** A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE() */ + FLOAT, + /** A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter */ + DOUBLE, + /** An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.*/ + DECIMAL + } + + private final String name; + private final String type; + private final String param; + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { + if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); + if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); + + this.name = name; + this.type = type; + this.param = param; + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { + this(name, type, String.valueOf(size)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { + this(name, type, String.valueOf(size), String.valueOf(d)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { + this(name, type, StringUtils.getArrayAsString(params, ", ")); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { + this(name, type.name(), param); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { + this(name, type.name(), size); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { + this(name, type.name(), size, d); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { + this(name, type.name(), params); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { + this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getType() { + return type; + } + + @Nullable + public Type findType() { + return ReflectionUtils.getEnumOrNull(type.toUpperCase(), Type.class); + } + + @Nullable + public String getParam() { + return param; + } + + @Override + public String toString() { + return name + " " + type + (param == null ? "" : "(" + param + ")"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java new file mode 100644 index 000000000..56ae16184 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +public final class SimpleDatabaseTypeResolver { + + private SimpleDatabaseTypeResolver() {} + + private static final Map registry = new HashMap<>(); + static { + registerType("mongodb", "net.codingarea.commons.database.mongodb.MongoDBDatabase"); + registerType("mysql", "net.codingarea.commons.database.sql.mysql.MySQLDatabase"); + registerType("sqlite", "net.codingarea.commons.database.sql.sqlite.SQLiteDatabase"); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name) { + return ReflectionUtils.getClassOrNull(registry.get(name)); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { + return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); + } + + public static void registerType(@Nonnull String name, @Nonnull String className) { + registry.put(name, className); + } + + public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { + registerType(name, databaseClass.getName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java new file mode 100644 index 000000000..3ef75df74 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.*; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +/** + * Represents a table/collection of a database + * + * @see Database + * @see Database#getSpecificDatabase(String) + */ +public interface SpecificDatabase { + + boolean isConnected(); + + @Nonnull + String getName(); + + /** + * @see Database#countEntries(String) + */ + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(); + + /** + * @see Database#query(String) + */ + @Nonnull + @CheckReturnValue + DatabaseQuery query(); + + /** + * @see Database#update(String) + */ + @Nonnull + @CheckReturnValue + DatabaseUpdate update(); + + /** + * @see Database#insert(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(); + + /** + * @see Database#insertOrUpdate(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(); + + /** + * @see Database#delete(String) + */ + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(); + + @Nonnull + Database getParent(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java new file mode 100644 index 000000000..755ddeedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -0,0 +1,100 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; + +public abstract class AbstractDatabase implements Database { + + protected final DatabaseConfig config; + + public AbstractDatabase(@Nonnull DatabaseConfig config) { + this.config = config; + } + + @Override + public boolean disconnectSafely() { + try { + disconnect(); + LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not disconnect from database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void disconnect() throws DatabaseException { + checkConnection(); + try { + disconnect0(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + protected abstract void disconnect0() throws Exception; + + @Override + public boolean connectSafely() { + try { + connect(); + LOGGER.status("Successfully created connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not connect to database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void connect() throws DatabaseException { + if (isConnected()) throw new DatabaseAlreadyConnectedException(); + try { + connect0(); + } catch (Exception ex) { + if (ex instanceof DatabaseException) throw (DatabaseException) ex; + throw new DatabaseException(ex); + } + } + + protected abstract void connect0() throws Exception; + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + try { + createTable(name, columns); + } catch (DatabaseException ex) { + LOGGER.error("Could not create table (" + this.getClass().getSimpleName() + ")", ex); + } + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + return config; + } + + protected final void checkConnection() throws DatabaseConnectionClosedException { + if (!isConnected()) + throw new DatabaseConnectionClosedException(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "[connected=" + isConnected() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java new file mode 100644 index 000000000..dd437cfb5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java @@ -0,0 +1,124 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.action.ExecutedQuery; + +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +public class DefaultExecutedQuery implements ExecutedQuery { + + protected final List results; + + public DefaultExecutedQuery(@Nonnull List results) { + this.results = results; + } + + @Nonnull + @Override + public Optional first() { + if (results.isEmpty()) return Optional.empty(); + return Optional.ofNullable(results.get(0)); + } + + @Nonnull + @Override + public Optional get(int index) { + if (index >= results.size()) return Optional.empty(); + return Optional.ofNullable(results.get(index)); + } + + @Nonnull + @Override + public Stream all() { + return results.stream(); + } + + @Nonnull + @Override + public > C toCollection(@Nonnull C collection) { + collection.addAll(results); + return collection; + } + + @Nonnull + @Override + public Document[] toArray(@Nonnull IntFunction arraySupplier) { + Document[] array = arraySupplier.apply(size()); + for (int i = 0; i < size(); i++) { + array[i] = results.get(i); + } + return array; + } + + @Override + public int index(@Nonnull Predicate filter) { + int index = 0; + for (Document result : results) { + if (filter.test(result)) + return index; + index++; + } + return -1; + } + + @Override + public boolean isEmpty() { + return results.isEmpty(); + } + + @Override + public boolean isSet() { + return !results.isEmpty(); + } + + @Override + public int size() { + return results.size(); + } + + @Override + public void print(@Nonnull PrintStream out) { + if (results.isEmpty()) { + out.println(""); + return; + } + + int index = 0; + for (Document result : results) { + out.print(index + " | "); + result.forEach((key, value) -> { + out.print(key + " = '" + value + "' "); + }); + out.println(); + index++; + } + } + + @Override + public Iterator iterator() { + return Collections.unmodifiableCollection(results).iterator(); + } + + @Override + public String toString() { + return "ExecutedQuery[size=" + size() + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultExecutedQuery documents = (DefaultExecutedQuery) o; + return Objects.equals(results, documents.results); + } + + @Override + public int hashCode() { + return Objects.hash(results); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java new file mode 100644 index 000000000..52496f6c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java @@ -0,0 +1,90 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.*; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class DefaultSpecificDatabase implements SpecificDatabase { + + protected final Database parent; + protected final String name; + + public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { + this.parent = parent; + this.name = name; + } + + @Override + public boolean isConnected() { + return parent.isConnected(); + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries() { + return parent.countEntries(name); + } + + @Nonnull + @Override + public DatabaseQuery query() { + return parent.query(name); + } + + @Nonnull + @Override + public DatabaseUpdate update() { + return parent.update(name); + } + + @Nonnull + @Override + public DatabaseInsertion insert() { + return parent.insert(name); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate() { + return parent.insertOrUpdate(name); + } + + @Nonnull + @Override + public DatabaseDeletion delete() { + return parent.delete(name); + } + + @Nonnull + @Override + public Database getParent() { + return parent; + } + + @Override + public String toString() { + return "SpecificDatabase[" + name + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultSpecificDatabase that = (DefaultSpecificDatabase) o; + return Objects.equals(parent, that.parent) && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(parent, name); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java new file mode 100644 index 000000000..118141f4e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; + +public class CachedDatabaseAccess extends DirectDatabaseAccess { + + protected final Map cache = new ConcurrentHashMap<>(); + + public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + super(database, config, mapper); + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key, def); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + V cached = cache.get(key); + if (cached != null) return Optional.of(cached); + + return super.getValueOptional(key); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + cache.put(key, value); + super.setValue(key, value); + } + + @Nonnull + public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getString); + } + + @Nonnull + public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); + } + + @Nonnull + public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); + } + + @Nonnull + public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); + } + + @Nonnull + public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Document::getDocument); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java new file mode 100644 index 000000000..9215c50cd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; + +public interface DatabaseAccess { + + @Nullable + V getValue(@Nonnull String key) throws DatabaseException; + + @Nonnull + V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; + + @Nonnull + Optional getValueOptional(@Nonnull String key) throws DatabaseException; + + void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; + + default boolean hasValue(@Nonnull String key) throws DatabaseException { + return getValueOptional(key).isPresent(); + } + + @Nonnull + Database getDatabase(); + + @Nonnull + DatabaseAccessConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java new file mode 100644 index 000000000..824b8bbdd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.database.access; + +import javax.annotation.Nonnull; + +public final class DatabaseAccessConfig { + + private final String table; + private final String keyField; + private final String valueField; + + public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { + this.table = table; + this.keyField = keyField; + this.valueField = valueField; + } + + @Nonnull + public String getTable() { + return table; + } + + @Nonnull + public String getKeyField() { + return keyField; + } + + @Nonnull + public String getValueField() { + return valueField; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java new file mode 100644 index 000000000..e2213d1bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.function.BiFunction; + +public class DirectDatabaseAccess implements DatabaseAccess { + + protected final Database database; + protected final DatabaseAccessConfig config; + protected final BiFunction mapper; + + public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + this.database = database; + this.config = config; + this.mapper = mapper; + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + return getValue0(key).orElse(null); + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + return getValue0(key).orElse(def); + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + return getValue0(key); + } + + @Nonnull + protected Optional getValue0(@Nonnull String key) throws DatabaseException { + return database.query(config.getTable()) + .where(config.getKeyField(), key) + .execute().first() + .map(document -> mapper.apply(document, config.getValueField())); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + database.insertOrUpdate(config.getTable()) + .set(config.getValueField(), value) + .where(config.getKeyField(), key) + .execute(); + } + + @Nonnull + @Override + public Database getDatabase() { + return database; + } + + @Nonnull + @Override + public DatabaseAccessConfig getConfig() { + return config; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java new file mode 100644 index 000000000..da7a8ee61 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.exceptions.UnsignedDatabaseException; + +import javax.annotation.Nonnull; + +/** + * Some action which will be executed on a database. + * + * This action is only prepared. + * + * It will be executed synchronously by calling {@link #execute()}, + * a {@link DatabaseException} will be thrown when something goes from or + * a {@link DatabaseConnectionClosedException} will be thrown + * when the connection to the database is already closed. + * + * It will also be executed synchronously by calling {@link #executeUnsigned()} but this method has no signed exceptions ({@code throws} declaration), + * so when an exception occurs it will be rethrown as a {@link UnsignedDatabaseException}. + * + * Calling {@link #executeAsync()} will return a new {@link Task} which will complete when the action is done or fail if something went wrong (a {@link DatabaseException} was thrown). + * + * @param The type of the result this action will return + * + * @see WhereAction + * @see SetAction + * @see OrderedAction + * + * @see DatabaseListTables + * @see DatabaseCountEntries + * @see DatabaseDeletion + * @see DatabaseUpdate + * @see DatabaseInsertion + * @see DatabaseInsertionOrUpdate + * @see DatabaseQuery + */ +public interface DatabaseAction { + + /** + * Executes this action synchronously + * + * @return the result of type {@link R} returned by the database + * + * @throws DatabaseException + * If a database error occurs + * @throws DatabaseConnectionClosedException + * If the database is no longer connected + */ + R execute() throws DatabaseException; + + /** + * Executes this action synchronously without any signed exceptions + * + * @return the result of type {@link R} returned by the database + * + * @throws UnsignedDatabaseException + * If a database error occurs + */ + default R executeUnsigned() { + try { + return execute(); + } catch (DatabaseException ex) { + throw new UnsignedDatabaseException(ex); + } + } + + /** + * Executes this action asynchronous + * + * @return a new {@link Task} which will be completed when the action was executed + */ + @Nonnull + default Task executeAsync() { + return Task.asyncCall(this::execute); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java new file mode 100644 index 000000000..70bedb389 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Database#countEntries(String) + * @see SpecificDatabase#countEntries() + */ +public interface DatabaseCountEntries extends DatabaseAction { + + @Nonnull + @Override + @Nonnegative + Long execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java new file mode 100644 index 000000000..3c3b20fe1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#delete(String) + * @see SpecificDatabase#delete() + */ +public interface DatabaseDeletion extends DatabaseAction, WhereAction { + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java new file mode 100644 index 000000000..ef0d7b8ca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insert(String) + * @see SpecificDatabase#insert() + */ +public interface DatabaseInsertion extends DatabaseAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseInsertion set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java new file mode 100644 index 000000000..000f76a09 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java @@ -0,0 +1,45 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insertOrUpdate(String) + * @see SpecificDatabase#insertOrUpdate() + */ +public interface DatabaseInsertionOrUpdate extends DatabaseUpdate, DatabaseInsertion { + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java new file mode 100644 index 000000000..be7173659 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import java.util.List; + +/** + * @see Database#listTables() + */ +public interface DatabaseListTables extends DatabaseAction> { + + @Nonnull + @Override + List execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java new file mode 100644 index 000000000..770b8b542 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#query(String) + * @see SpecificDatabase#query() + */ +public interface DatabaseQuery extends DatabaseAction, WhereAction, OrderedAction { + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Object object); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseQuery select(@Nonnull String... selection); + + @Nonnull + @CheckReturnValue + DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); + + @Nonnull + @Override + @CheckReturnValue + ExecutedQuery execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java new file mode 100644 index 000000000..83073b113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#update(String) + * @see SpecificDatabase#update() + */ +public interface DatabaseUpdate extends DatabaseAction, WhereAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java new file mode 100644 index 000000000..37cf98630 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java @@ -0,0 +1,86 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * @see DatabaseQuery#execute() + */ +public interface ExecutedQuery extends Iterable { + + @Nonnull + @CheckReturnValue + Optional first(); + + @Nonnull + @CheckReturnValue + default Document firstOrEmpty() { + return first().orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Optional get(int index); + + @Nonnull + @CheckReturnValue + default Document getOrEmpty(int index) { + return get(index).orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Stream all(); + + @Nonnull + @CheckReturnValue + default List toList() { + return toCollection((IntFunction>) ArrayList::new); + } + + @Nonnull + @CheckReturnValue + default Set toSet() { + return toCollection((IntFunction>) HashSet::new); + } + + @Nonnull + > C toCollection(@Nonnull C collection); + + @Nonnull + @CheckReturnValue + default > C toCollection(@Nonnull IntFunction collectionSupplier) { + return toCollection(collectionSupplier.apply(size())); + } + + @Nonnull + Document[] toArray(@Nonnull IntFunction arraySupplier); + + int index(@Nonnull Predicate filter); + + boolean isEmpty(); + + boolean isSet(); + + int size(); + + void print(@Nonnull PrintStream out); + + default void print(@Nonnull ILogger logger) { + print(logger.asPrintStream(LogLevel.INFO)); + } + + default void print() { + print(System.out); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java new file mode 100644 index 000000000..edfdc29b1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.action.hierarchy; + +import net.codingarea.commons.database.Order; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface OrderedAction { + + @Nullable + OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java new file mode 100644 index 000000000..cb395773b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface SetAction { + + @Nonnull + SetAction set(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java new file mode 100644 index 000000000..5e5d69c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface WhereAction { + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + WhereAction whereNot(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java new file mode 100644 index 000000000..192f891f6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception in thrown, when a database tries to connect but is already connected. + */ +public class DatabaseAlreadyConnectedException extends DatabaseException { + + public DatabaseAlreadyConnectedException() { + super("Database already connected"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java new file mode 100644 index 000000000..f3563f241 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception is thrown, when a database operation is tried which requires a active connection, but the database is not connected. + */ +public class DatabaseConnectionClosedException extends DatabaseException { + + public DatabaseConnectionClosedException() { + super("Database connection closed"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java new file mode 100644 index 000000000..d42805661 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseAlreadyConnectedException + * @see DatabaseConnectionClosedException + * @see DatabaseUnsupportedFeatureException + * + * @see DatabaseAction#execute() + */ +public class DatabaseException extends Exception { + + protected DatabaseException() { + super(); + } + + public DatabaseException(@Nonnull String message) { + super(message); + } + + public DatabaseException(@Nonnull Throwable cause) { + super(cause); + } + + public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { + super(message, cause); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java new file mode 100644 index 000000000..0f57f6827 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.database.exceptions; + +import javax.annotation.Nonnull; + +public class DatabaseUnsupportedFeatureException extends DatabaseException { + + public DatabaseUnsupportedFeatureException() { + } + + public DatabaseUnsupportedFeatureException(@Nonnull String message) { + super(message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java new file mode 100644 index 000000000..a5f96d5f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java @@ -0,0 +1,24 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseException + * + * @see DatabaseAction#executeUnsigned() + */ +public class UnsignedDatabaseException extends WrappedException { + + public UnsignedDatabaseException(@Nonnull DatabaseException cause) { + super(cause); + } + + @Nonnull + @Override + public DatabaseException getCause() { + return (DatabaseException) super.getCause(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java new file mode 100644 index 000000000..10887b6c3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.sql.abstraction.count.SQLCountEntries; +import net.codingarea.commons.database.sql.abstraction.deletion.SQLDeletion; +import net.codingarea.commons.database.sql.abstraction.insertion.SQLInsertion; +import net.codingarea.commons.database.sql.abstraction.insertorupdate.SQLInsertionOrUpdate; +import net.codingarea.commons.database.sql.abstraction.query.SQLQuery; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public abstract class AbstractSQLDatabase extends AbstractDatabase { + + protected Connection connection; + + public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void disconnect0() throws Exception { + connection.close(); + connection = null; + } + + @Override + public void connect0() throws Exception { + connection = DriverManager.getConnection(createUrl(), config.getUser(), config.getPassword()); + } + + protected abstract String createUrl(); + + @Override + public boolean isConnected() { + try { + if (connection == null) return false; + connection.isClosed(); + return true; + } catch (SQLException ex) { + LOGGER.error("Could not check connection state: " + ex.getMessage()); + return false; + } + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + try { + StringBuilder command = new StringBuilder(); + command.append("CREATE TABLE IF NOT EXISTS `"); + command.append(name); + command.append("` ("); + { + int index = 0; + for (SQLColumn column : columns) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(")"); + + PreparedStatement statement = prepare(command.toString()); + statement.execute(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new SQLCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new SQLQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new SQLQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new SQLUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new SQLInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new SQLInsertion(this, table, values); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new SQLInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new SQLDeletion(this, table); + } + + @Nonnull + public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { + checkConnection(); + PreparedStatement statement = connection.prepareStatement(command.toString()); + SQLHelper.fillParams(statement, args); + return statement; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java new file mode 100644 index 000000000..9fdf86b6c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public final class SQLHelper { + + private SQLHelper() {} + + public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + Object param = serializeObject(params[i]); + statement.setObject(i + 1 /* in sql we count from 1 */, param); + } + } + + @Nullable + public static Object serializeObject(@Nullable Object object) { + if (object == null) return null; + if (object instanceof Number) return object; + if (object instanceof Boolean) return object; + if (object instanceof Enum) return ((Enum)object).name(); + if (object instanceof Json) return ((Json)object).toJson(); + if (object instanceof Map) return new GsonDocument((Map) object).toJson(); + if (object instanceof Iterable) return GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, (Iterable) object).toString(); + if (object.getClass().isArray()) return GsonUtils.convertArrayToJsonArray(GsonDocument.GSON, object).toString(); + return object.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java new file mode 100644 index 000000000..dbf6aa821 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java @@ -0,0 +1,54 @@ +package net.codingarea.commons.database.sql.abstraction.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Objects; + +public class SQLCountEntries implements DatabaseCountEntries { + + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT COUNT(*) FROM `" + table + "`"); + ResultSet result = statement.executeQuery(); + + if (!result.next()) { + result.close(); + return 0L; + } + + long count = result.getLong(1); + result.close(); + return count; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLCountEntries that = (SQLCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java new file mode 100644 index 000000000..d1dfeaf9b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database.sql.abstraction.deletion; + +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLDeletion implements DatabaseDeletion { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where = new HashMap<>(); + + public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("DELETE FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(),args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLDeletion that = (SQLDeletion) o; + return database.equals(that.database) && table.equals(that.table) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java new file mode 100644 index 000000000..6af25eaa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java @@ -0,0 +1,95 @@ +package net.codingarea.commons.database.sql.abstraction.insertion; + +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; + +public class SQLInsertion implements DatabaseInsertion { + + protected final Map values; + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.values = new HashMap<>(); + } + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { + this.database = database; + this.table = table; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(values.size()); + + command.append("INSERT INTO "); + command.append(table); + command.append(" ("); + { + int index = 0; + for (String column : values.keySet()) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(") VALUES ("); + { + int index = 0; + for (Object value : values.values()) { + if (index > 0) command.append(", "); + command.append("?"); + args.add(value); + index++; + } + } + command.append(")"); + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLInsertion that = (SQLInsertion) o; + return values.equals(that.values) && database.equals(that.database) && table.equals(that.table); + } + + @Override + public int hashCode() { + return Objects.hash(values, database, table); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java new file mode 100644 index 000000000..f89cbc135 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.sql.abstraction.insertorupdate; + +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class SQLInsertionOrUpdate extends SQLUpdate implements DatabaseInsertionOrUpdate { + + public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + super(database, table); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { + super.whereNot(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { + super.set(column, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(table, where).execute().isSet()) { + return super.execute(); + } else { + Map insert = new HashMap<>(values); + for (Entry entry : where.entrySet()) { + Object[] args = entry.getValue().getArgs(); + if (args.length == 0) continue; + insert.put(entry.getKey(), args[0]); + } + + database.insert(table, insert).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java new file mode 100644 index 000000000..75536fe81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -0,0 +1,176 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLQuery implements DatabaseQuery { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected String[] selection = { "*" }; + protected String orderBy; + protected Order order; + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + } + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { + this.database = database; + this.table = table; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); + this.selection = selection; + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new LinkedList<>(); + + command.append("SELECT "); + for (int i = 0; i < selection.length; i++) { + if (i > 0) command.append(", "); + command.append(selection[i]); + } + command.append(" FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + if (orderBy != null) { + command.append(" ORDER BY "); + command.append(orderBy); + if (order != null) + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" "); + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + ResultSet result = statement.executeQuery(); + return createExecutedQuery(result); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { + List results = new ArrayList<>(); + ResultSetMetaData data = result.getMetaData(); + while (result.next()) { + Map map = new HashMap<>(); + for (int i = 1; i <= data.getColumnCount(); i++) { + Object value = result.getObject(i); + map.put(data.getColumnLabel(i), value); + } + Document row = new SQLResult(map); + results.add(row); + } + result.close(); + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLQuery sqlQuery = (SQLQuery) o; + return database.equals(sqlQuery.database) && table.equals(sqlQuery.table) && where.equals(sqlQuery.where) && Arrays.equals(selection, sqlQuery.selection) && Objects.equals(orderBy, sqlQuery.orderBy) && order == sqlQuery.order; + } + + @Override + public int hashCode() { + int result = Objects.hash(database, table, where, orderBy, order); + result = 31 * result + Arrays.hashCode(selection); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java new file mode 100644 index 000000000..2d6536855 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.MapDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; + +public final class SQLResult extends MapDocument { + + public SQLResult(@Nonnull Map values) { + super(values); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + try { + return new GsonDocument(getString(path), this, this).readonly(); + } catch (Exception ex) { + return new EmptyDocument(this, null); + } + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java new file mode 100644 index 000000000..d3b4cd844 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -0,0 +1,140 @@ +package net.codingarea.commons.database.sql.abstraction.update; + +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLUpdate implements DatabaseUpdate { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected final Map values; + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.table = table; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { + values.put(column, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("UPDATE "); + command.append(table); + command.append(" SET "); + + { + int index = 0; + for (Entry entry : values.entrySet()) { + if (index > 0) command.append(", "); + command.append("`" + entry.getKey() + "` = ?"); + args.add(entry.getValue()); + index++; + } + } + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.executeUpdate(); + return null; + } catch (SQLException ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLUpdate sqlUpdate = (SQLUpdate) o; + return database.equals(sqlUpdate.database) && table.equals(sqlUpdate.table) && where.equals(sqlUpdate.where) && values.equals(sqlUpdate.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where, values); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java new file mode 100644 index 000000000..f398190fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class ObjectWhere implements SQLWhere { + + protected final String column; + protected final Object value; + protected final String comparator; + + public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { + this.column = column; + this.value = value; + this.comparator = comparator; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("`%s` %s ?", column, comparator); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return column.equals(that.column) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java new file mode 100644 index 000000000..a16075f93 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; + +public interface SQLWhere { + + @Nonnull + Object[] getArgs(); + + @Nonnull + String getAsSQLString(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..7a3fe07b6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements SQLWhere { + + protected final String column; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { + this.column = column; + this.value = value; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("LOWER(%s) = LOWER(?)", column); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return column.equals(that.column) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java new file mode 100644 index 000000000..627b39e20 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.database.sql.mysql; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.list.MySQLListTables; + +import javax.annotation.Nonnull; + +public class MySQLDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load mysql driver"); + } + } + + public MySQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Nonnull + @Override + protected String createUrl() { + return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MySQLListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java new file mode 100644 index 000000000..2d60ee58b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.mysql.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class MySQLListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public MySQLListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SHOW TABLES"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java new file mode 100644 index 000000000..70fbe6953 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.sql.sqlite; + +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.sqlite.list.SQLiteListTables; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.IOException; + +public class SQLiteDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load sqlite driver"); + } + } + + protected final File file; + + public SQLiteDatabase(@Nonnull DatabaseConfig config) { + super(config); + file = new File(config.getFile()); + } + + @Override + public void connect() throws DatabaseException { + try { + FileUtils.createFilesIfNecessary(file); + } catch (IOException ex) { + throw new DatabaseException(ex); + } + + super.connect(); + } + + @Override + protected String createUrl() { + return "jdbc:sqlite:" + file; + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new SQLiteListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java new file mode 100644 index 000000000..f7a4c48d6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.sqlite.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class SQLiteListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/pom.xml b/pom.xml index 43f00b0da..810fb27fb 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,6 @@ - 1.3.15 1.21.4-R0.1-SNAPSHOT From f0c4d9d76b5290be7bb26ed61d499640da57649f Mon Sep 17 00:00:00 2001 From: qodana-bot Date: Sat, 19 Apr 2025 10:33:22 +0000 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=A4=96=20Apply=20quick-fixes=20by=20Q?= =?UTF-8?q?odana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/config/document/BsonDocument.java | 16 +- .../commons/common/misc/BsonUtils.java | 2 +- .../commons/common/misc/MongoUtils.java | 2 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../inventory/PermanentItemChallenge.java | 3 +- .../miscellaneous/EnderGamesChallenge.java | 2 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 3 +- .../challenge/world/SnakeChallenge.java | 2 +- .../type/abstraction/CollectionGoal.java | 2 +- .../menu/generator/MenuGenerator.java | 3 +- .../menu/info/ChallengeMenuClickInfo.java | 10 - .../plugin/management/team/TeamProvider.java | 1 - .../plugin/spigot/listener/CheatListener.java | 3 +- .../utils/bukkit/misc/BukkitStringUtils.java | 2 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 1 - .../plugin/utils/item/ItemBuilder.java | 3 +- .../plugin/utils/misc/ImageUtils.java | 4 +- .../commons/bukkit/core/BukkitModule.java | 18 +- .../bukkit/core/RequirementsChecker.java | 3 +- .../utils/animation/AnimationFrame.java | 6 +- .../bukkit/utils/animation/SoundSample.java | 15 +- .../utils/bstats/JsonObjectBuilder.java | 17 +- .../bukkit/utils/item/ItemBuilder.java | 10 +- .../bukkit/utils/menu/MenuClickInfo.java | 26 +- .../utils/misc/BukkitReflectionUtils.java | 2 +- .../bukkit/utils/wrapper/ActionListener.java | 8 +- .../common/collection/ClassWalker.java | 2 +- .../common/collection/NumberFormatter.java | 2 +- .../collection/SeededRandomWrapper.java | 9 +- .../common/collection/pair/Quadro.java | 21 +- .../common/collection/pair/Triple.java | 17 +- .../commons/common/collection/pair/Tuple.java | 13 +- .../concurrent/task/CompletableTask.java | 2 +- .../config/document/AbstractConfig.java | 4 +- .../common/config/document/MapDocument.java | 14 +- .../config/document/PropertiesDocument.java | 16 +- .../common/config/document/YamlDocument.java | 12 +- ...kkitReflectionSerializableTypeAdapter.java | 2 +- .../common/discord/DiscordWebhook.java | 71 ++--- .../commons/common/logging/ILogger.java | 2 +- .../commons/common/logging/LogLevel.java | 20 +- .../common/logging/LogOutputStream.java | 2 +- .../common/logging/handler/LogEntry.java | 10 +- .../logging/internal/JavaLoggerWrapper.java | 270 ------------------ .../BukkitReflectionSerializationUtils.java | 4 +- .../commons/common/misc/FileUtils.java | 2 +- .../commons/common/misc/GsonUtils.java | 2 +- .../commons/common/misc/ImageUtils.java | 3 +- .../commons/common/misc/ReflectionUtils.java | 9 +- .../common/misc/SimpleCollectionUtils.java | 2 +- .../commons/common/version/VersionInfo.java | 16 +- .../commons/database/DatabaseConfig.java | 54 ++-- .../commons/database/EmptyDatabase.java | 8 +- .../sql/abstraction/query/SQLQuery.java | 2 +- .../sql/abstraction/query/SQLResult.java | 3 +- .../sql/abstraction/update/SQLUpdate.java | 2 +- 57 files changed, 191 insertions(+), 573 deletions(-) diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java index f801ab556..e44ad0bd5 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -80,7 +80,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -89,7 +89,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -98,7 +98,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -107,7 +107,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -116,7 +116,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -125,7 +125,7 @@ public double getDouble(@Nonnull String path, double def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -137,7 +137,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { Object value = bsonDocument.get(path); if (value instanceof Boolean) return (Boolean) value; if (value instanceof String) return Boolean.parseBoolean((String) value); - } catch (Exception ex) { + } catch (Exception ignored) { } return def; } @@ -161,7 +161,7 @@ public UUID getUUID(@Nonnull String path) { Object value = bsonDocument.get(path); if (value instanceof UUID) return (UUID) value; if (value instanceof String) return UUID.fromString((String) value); - } catch (Exception ex) { + } catch (Exception ignored) { } return null; } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java index 05611a0b0..6df6ce127 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -16,7 +16,7 @@ public final class BsonUtils { - protected static final ILogger logger = ILogger.forThisClass(); + private static final ILogger logger = ILogger.forThisClass(); private BsonUtils() { } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java index d0c2c4a37..32e03109f 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -57,7 +57,7 @@ public static Object packObject(@Nullable Object value) { BsonUtils.setDocumentProperties(bson, values); return bson; } else if (value instanceof UUID) { - return ((UUID) value).toString(); + return value.toString(); } else { return value; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 5b15d051e..2cd31b223 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -65,7 +65,7 @@ public RandomPotionEffectChallenge() { @Nullable public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).toList(); ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); possibleEffects.removeAll(activeEffects); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 6b86b70af..99d8ccdb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -17,6 +17,7 @@ import org.bukkit.inventory.Inventory; import javax.annotation.Nonnull; +import java.util.Objects; @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -40,7 +41,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 899c446cc..8a11d2c29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -64,7 +64,7 @@ private void teleportRandom(@Nonnull Player player) { List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() .filter(entity -> !(entity instanceof Player)) .filter(entity -> entity instanceof LivingEntity) - .collect(Collectors.toList()); + .toList(); Entity targetEntity = list.get(globalRandom.nextInt(list.size())); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 90b44a7e9..aa48d502b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -423,7 +423,7 @@ class DocumentCountStatistic extends DocumentStatistic { } } - List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + List newAnswers = answers.stream().map(StringUtils::getEnumName).toList(); answers.clear(); answers.addAll(newAnswers); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 32c31c8f6..2b621dc6f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -29,6 +29,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.Objects; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { @@ -117,7 +118,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 28ae22550..26f25a80c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -56,7 +56,7 @@ public void writeGameState(@Nonnull Document document) { public void loadGameState(@Nonnull Document document) { super.loadGameState(document); - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).toList()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 2ad3bacf4..c9f19f248 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -70,7 +70,7 @@ protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Ru } protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); + List targetStringList = Arrays.stream(target).map(Object::toString).toList(); return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index 5fadbe3f4..bf7090a65 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -14,6 +14,7 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.List; +import java.util.Objects; @Getter @Setter @@ -31,7 +32,7 @@ public abstract class MenuGenerator { public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); return menuPosition instanceof GeneratorMenuPosition - && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING + && Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType() != InventoryType.CRAFTING && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 53b285c9d..9df0dc49b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -30,14 +30,4 @@ public boolean isLowerItemClick() { return !upperItem; } - @Nonnull - public Player getPlayer() { - return player; - } - - @Nonnull - public Inventory getInventory() { - return inventory; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a633ec0d7..f3f6db16f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -2,7 +2,6 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 00de88ed9..2251cdd1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -33,8 +33,7 @@ public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { @EventHandler(priority = EventPriority.MONITOR) public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) { - } + event.isSneaking(); //// Structure structure = entry.getValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index c5f73691e..37e6f5fbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -149,7 +149,7 @@ public static List format(@Nonnull String sequence, @Nonnull Obje if (!currentText.getText().isEmpty()) { results.add(currentText); } - if (argument.length() > 0) { + if (!argument.isEmpty()) { results.add(new TextComponent(String.valueOf(start))); results.add(new TextComponent(String.valueOf(argument))); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 4b941e688..32bb95dfa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -19,7 +19,6 @@ public class NMSProvider { /** * -- GETTER -- * - * @return A border packet factory */ @Getter private static final BorderPacketFactory borderPacketFactory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index b457a897e..42523ce79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -214,7 +214,8 @@ public ItemDescription getBuiltByItemDescription() { @Override public ItemBuilder clone() { - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder itemBuilder = (ItemBuilder) super.clone(); + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); builder.builtByItemDescription = builtByItemDescription; return builder; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index f81f27ba2..e94c8cf0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; +import net.codingarea.commons.common.collection.IOUtils; import org.bukkit.entity.Player; import javax.annotation.Nonnull; @@ -20,8 +21,7 @@ private ImageUtils() { @Nullable public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + HttpURLConnection connection = IOUtils.createConnection(url); return ImageIO.read(connection.getInputStream()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index c90eea42b..31f3e41cb 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,6 +1,7 @@ package net.codingarea.commons.bukkit.core; import com.google.common.base.Charsets; +import lombok.Getter; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -54,7 +55,8 @@ public abstract class BukkitModule extends JavaPlugin { private ExecutorService executorService; private Document config, pluginConfig; private Version version; - private boolean devMode; + @Getter + private boolean devMode; private boolean firstInstall; private boolean isReloaded; private boolean isLoaded; @@ -75,10 +77,10 @@ public final void onLoad() { ILogger.setConstantFactory(this.getILogger()); trySaveDefaultConfig(); if (wasShutdown) isReloaded = true; - if (firstInstall = !getDataFolder().exists()) { + if (firstInstall == !getDataFolder().exists()) { getILogger().info("Detected first install!"); } - if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + if (devMode == getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { getILogger().setLevel(Level.ALL); getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); } else { @@ -142,11 +144,7 @@ protected void handleLoad() throws Exception {} protected void handleEnable() throws Exception {} protected void handleDisable() throws Exception {} - public boolean isDevMode() { - return devMode; - } - - public final boolean isFirstInstall() { + public final boolean isFirstInstall() { return firstInstall; } @@ -185,7 +183,7 @@ public void reloadConfig() { @Nonnull public Document getPluginDocument() { return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("plugin.yml")), Charsets.UTF_8)))); } @Nonnull @@ -344,7 +342,7 @@ private void injectInstance() { Field instanceField = this.getClass().getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, this); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 87cae1721..8b380040c 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -6,6 +6,7 @@ import org.bukkit.Bukkit; import javax.annotation.Nonnull; +import java.util.Objects; public final class RequirementsChecker { @@ -18,7 +19,7 @@ public RequirementsChecker(@Nonnull BukkitModule module) { public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { if (requirements.getBoolean("spigot")) requireSpigot(); if (requirements.getBoolean("paper")) requirePaper(); - if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + if (requirements.contains("version")) requireVersion(Objects.requireNonNull(requirements.getVersion("version"))); } public boolean checkBoolean(@Nonnull Document requirements) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index 130785522..b91add45e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -7,6 +7,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; +import java.util.Objects; public class AnimationFrame implements Cloneable { @@ -59,7 +60,7 @@ public ItemStack getItem(int slot) { @Nullable public Material getItemType(int slot) { - return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + return getItem(slot) == null ? Material.AIR : Objects.requireNonNull(getItem(slot)).getType(); } @Nonnull @@ -78,7 +79,8 @@ public int getSize() { @Nonnull @Override public AnimationFrame clone() { - return new AnimationFrame(content); + AnimationFrame animationFrame = (AnimationFrame) super.clone(); + return new AnimationFrame(content); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 8991960e0..47441780a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.animation; +import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; @@ -35,7 +36,9 @@ public static void playStatusSound(@Nonnull Player player, boolean enabled) { private static final class SoundFrame { - private final float pitch, volume; + @Getter + @Getter + private final float pitch, volume; private final Sound sound; public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { @@ -52,15 +55,7 @@ public void play(@Nonnull Player player, @Nonnull Location location) { player.playSound(location, sound, volume, pitch); } - public float getPitch() { - return pitch; - } - - public float getVolume() { - return volume; - } - - @Nonnull + @Nonnull public Sound getSound() { return sound; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java index 172e2e4ff..e156c6284 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -160,14 +160,15 @@ public JsonObject build() { } /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ + * Escapes the given string like stated in .... + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as " + " and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ private static String escape(String value) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 339bbaba2..868ad8110 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -14,10 +14,7 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.util.*; public class ItemBuilder { @@ -67,7 +64,7 @@ public ItemMeta getMeta() { @Nonnull @SuppressWarnings("unchecked") public final M getCastedMeta() { - return (M) (meta == null ? meta = item.getItemMeta() : meta); + return (M) (meta == null ? Objects.requireNonNull(meta = item.getItemMeta()) : meta); } @Nonnull @@ -254,7 +251,8 @@ public ItemStack toItem() { @Override public ItemBuilder clone() { - return new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder itemBuilder = (ItemBuilder) super.clone(); + return new ItemBuilder(item.clone(), getMeta().clone()); } public static class BannerBuilder extends ItemBuilder { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 5753ad174..0d2e9236d 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.menu; +import lombok.Getter; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -13,9 +14,12 @@ public class MenuClickInfo { protected final Player player; protected final Inventory inventory; - protected final boolean shiftClick; - protected final boolean rightClick; - protected final int slot; + @Getter + protected final boolean shiftClick; + @Getter + protected final boolean rightClick; + @Getter + protected final int slot; public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { this.player = player; @@ -35,23 +39,11 @@ public Inventory getInventory() { return inventory; } - public boolean isRightClick() { - return rightClick; - } - - public boolean isLeftClick() { + public boolean isLeftClick() { return !rightClick; } - public boolean isShiftClick() { - return shiftClick; - } - - public int getSlot() { - return slot; - } - - @Nullable + @Nullable public ItemStack getClickedItem() { return inventory.getItem(slot); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 36284f5e3..46b72210b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -136,7 +136,7 @@ public static NamespacedKey fromString(@Nonnull String key) { */ @Nullable public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { - Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + Preconditions.checkArgument(!string.isEmpty(), "Input string must not be empty or null"); String[] components = string.split(":", 3); if (components.length > 2) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index 8faa0993b..c53353706 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.wrapper; +import lombok.Getter; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -13,7 +14,8 @@ public final class ActionListener implements Listener { private final Class classOfEvent; private final Consumer listener; private final EventPriority priority; - private final boolean ignoreCancelled; + @Getter + private final boolean ignoreCancelled; public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { this.classOfEvent = classOfEvent; @@ -50,8 +52,4 @@ public Class getClassOfEvent() { return classOfEvent; } - public boolean isIgnoreCancelled() { - return ignoreCancelled; - } - } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index d71f0df71..49018ec35 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -4,7 +4,7 @@ import java.util.*; /** - * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java + * @author JDA | ... */ public class ClassWalker implements Iterable> { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 4a734b55b..013c092c1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -48,7 +48,7 @@ default String format(@Nonnull Number number) { return format(number.doubleValue()); } - public static final NumberFormatter + NumberFormatter DEFAULT = fromPattern("0.##", null, false), INTEGER = value -> (int) value + "", SPACE_SPLIT = fromPattern("###,##0.###############", null, false, diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java index a9fcb48f2..0c0f90e5e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -1,11 +1,14 @@ package net.codingarea.commons.common.collection; +import lombok.Getter; + import java.util.Random; /** * Since there is no way of getting the seed of a {@link Random} we create a wrapper * which will save seed. This allows us to save randomization and reload it. */ +@Getter public class SeededRandomWrapper extends Random implements IRandom { protected long seed; @@ -24,11 +27,7 @@ public void setSeed(long seed) { this.seed = seed; } - public long getSeed() { - return seed; - } - - @Override + @Override public String toString() { return "Random[seed=" + seed + "]"; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index df07b890d..734f5cf16 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -12,6 +14,7 @@ * @param The type of the third value * @param The type of the fourth value */ +@Getter public class Quadro implements Pair { protected F first; @@ -40,23 +43,7 @@ public final Object[] values() { return new Object[] { first, second, third, first }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public FF getFourth() { - return fourth; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index 48c8dfcde..b62f55777 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -11,6 +13,7 @@ * @param The type of the second value * @param The type of the third value */ +@Getter public class Triple implements Pair { protected F first; @@ -37,19 +40,7 @@ public final Object[] values() { return new Object[] { first, second, third }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index 9d320ba6e..ce1901dbf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -10,6 +12,7 @@ * @param The type of the first value * @param The type of the second value */ +@Getter public class Tuple implements Pair { protected F first; @@ -34,15 +37,7 @@ public final Object[] values() { return new Object[] { first, second }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 37b71703f..08ab891a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -64,7 +64,7 @@ public Task addListener(@Nonnull TaskListener listener) { } else if (failure != null) { listener.onFailure(this, failure); } else { - listener.onComplete(this, value); + listener.onComplete(this, null); } return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index cce0be2e8..2f9fec69b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -46,7 +46,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return getString(path).charAt(0); + return Objects.requireNonNull(getString(path)).charAt(0); } catch (NullPointerException | IndexOutOfBoundsException ex) { return def; } @@ -175,7 +175,7 @@ public > List getEnumList(@Nonnull String path, @Nonnull Cl @Nonnull @Override public List getCharacterList(@Nonnull String path) { - return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + return mapList(path, string -> string == null || string.isEmpty() ? (char) 0 : string.charAt(0)); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index b0b194d05..eabc2e1a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -129,7 +129,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -138,7 +138,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -147,7 +147,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -156,7 +156,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -165,7 +165,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -174,7 +174,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -184,7 +184,7 @@ public double getDouble(@Nonnull String path, double def) { public boolean getBoolean(@Nonnull String path, boolean def) { try { if (!contains(path)) return def; - switch (getString(path).toLowerCase()) { + switch (Objects.requireNonNull(getString(path)).toLowerCase()) { case "true": case "1": return true; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 58fa7b100..7f5213806 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -78,7 +78,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -87,7 +87,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -96,7 +96,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -105,7 +105,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -114,7 +114,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -123,7 +123,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -139,7 +139,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(getString(path)); + return UUID.fromString(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -155,7 +155,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(getString(path)); + return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index 03bdf14d3..faf4fe162 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -54,7 +54,7 @@ public String getString(@Nonnull String path) { @Override public String getString(@Nonnull String path, @Nonnull String def) { String string = config.getString(path, def); - return string == null ? def : string; + return string; } @Nullable @@ -67,7 +67,7 @@ public Object getObject(@Nonnull String path) { @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { Object value = config.get(path, def); - return value == null ? def : value; + return value; } @Override @@ -147,7 +147,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return getString(path).charAt(0); + return Objects.requireNonNull(getString(path)).charAt(0); } catch (NullPointerException | StringIndexOutOfBoundsException ex) { return def; } @@ -193,7 +193,7 @@ public List getStringList(@Nonnull String path) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(getString(path)); + return UUID.fromString(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -213,7 +213,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(getString(path)); + return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -223,7 +223,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Override public Color getColor(@Nonnull String path) { try { - return Color.decode(getString(path)); + return Color.decode(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index ed36fd787..71f9f7744 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -43,7 +43,7 @@ public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOExce Class clazz = null; try { clazz = Class.forName(classOfType); - } catch (ClassNotFoundException | NullPointerException ex) { + } catch (ClassNotFoundException | NullPointerException ignored) { } Map map = GsonUtils.convertJsonObjectToMap(json); diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index 49eeec955..b75f88549 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -1,5 +1,6 @@ package net.codingarea.commons.common.discord; +import lombok.Getter; import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; @@ -214,7 +215,8 @@ public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String return this; } - public static class EmbedObject { + @Getter + public static class EmbedObject { protected String title; protected String description; @@ -244,43 +246,7 @@ public EmbedObject(@Nullable String title, @Nullable String description, @Nullab this.fields = fields; } - public String getTitle() { - return title; - } - - public String getDescription() { - return description; - } - - public String getUrl() { - return url; - } - - public Color getColor() { - return color; - } - - public Footer getFooter() { - return footer; - } - - public Thumbnail getThumbnail() { - return thumbnail; - } - - public Image getImage() { - return image; - } - - public Author getAuthor() { - return author; - } - - public List getFields() { - return fields; - } - - @Nonnull + @Nonnull public EmbedObject setTitle(String title) { this.title = title; return this; @@ -336,7 +302,8 @@ public EmbedObject addField(String name, String value, boolean inline) { @Override public EmbedObject clone() { - return new EmbedObject( + EmbedObject embedObject = (EmbedObject) super.clone(); + return new EmbedObject( title, description, url, color, footer == null ? null : footer.clone(), thumbnail == null ? null : thumbnail.clone(), @@ -368,8 +335,9 @@ private String getIconUrl() { } @Override - protected Footer clone() { - return new Footer(text, iconUrl); + protected Footer clone() throws CloneNotSupportedException { + Footer footer1 = (Footer) super.clone(); + return new Footer(text, iconUrl); } } @@ -389,8 +357,9 @@ private String getUrl() { } @Override - protected Thumbnail clone() { - return new Thumbnail(url); + protected Thumbnail clone() throws CloneNotSupportedException { + Thumbnail thumbnail1 = (Thumbnail) super.clone(); + return new Thumbnail(url); } } @@ -411,7 +380,8 @@ private String getUrl() { @Override public Image clone() { - return new Image(url); + Image image1 = (Image) super.clone(); + return new Image(url); } } @@ -443,8 +413,9 @@ private String getIconUrl() { } @Override - protected Author clone() { - return new Author(name, url, iconUrl); + protected Author clone() throws CloneNotSupportedException { + Author author1 = (Author) super.clone(); + return new Author(name, url, iconUrl); } } @@ -476,15 +447,17 @@ private boolean isInline() { } @Override - protected Field clone() { - return new Field(name, value, inline); + protected Field clone() throws CloneNotSupportedException { + Field field = (Field) super.clone(); + return new Field(name, value, inline); } } } @Override public DiscordWebhook clone() { - return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + DiscordWebhook discordWebhook = (DiscordWebhook) super.clone(); + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index 02ec550a7..eb337e206 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -260,7 +260,7 @@ default JavaILogger java() { @CheckReturnValue default PrintStream asPrintStream(@Nonnull LogLevel level) { try { - return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8); } catch (Exception ex) { throw new WrappedException(ex); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index ddf6d01c8..58d6c7262 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.logging; +import lombok.Getter; + import javax.annotation.Nonnull; import java.util.logging.Level; @@ -15,8 +17,10 @@ public enum LogLevel { private final String uppercaseName, lowercaseName; private final Level javaLevel; - private final int value; - private final boolean highlighted; + @Getter + private final int value; + @Getter + private final boolean highlighted; LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { this.uppercaseName = uppercaseName; @@ -35,11 +39,7 @@ public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { return this.getValue() >= loggerLevel.getValue(); } - public int getValue() { - return value; - } - - @Nonnull + @Nonnull public String getLowerCaseName() { return lowercaseName; } @@ -49,11 +49,7 @@ public String getUpperCaseName() { return uppercaseName; } - public boolean isHighlighted() { - return highlighted; - } - - @Nonnull + @Nonnull public static LogLevel fromJavaLevel(@Nonnull Level level) { for (LogLevel logLevel : values()) { if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index 7095492ed..c747fbf1a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -17,7 +17,7 @@ public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { @Override public void flush() throws IOException { - String input = this.toString(StandardCharsets.UTF_8.name()); + String input = this.toString(StandardCharsets.UTF_8); this.reset(); if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 5068d301b..3212680b9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -8,11 +8,11 @@ public class LogEntry { - private Instant timestamp; - private String threadName; - private String message; - private LogLevel level; - private Throwable exception; + private final Instant timestamp; + private final String threadName; + private final String message; + private final LogLevel level; + private final Throwable exception; public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { this.timestamp = timestamp; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index f0c64bf8d..b9c95d540 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -393,274 +393,4 @@ public void debug(@Nullable Object message, @Nonnull Object... args) { } - @Override - public boolean isTraceEnabled() { - return isLevelEnabled(LogLevel.TRACE); - } - -// @Override -// public void trace(String msg) { -// trace(msg, new Object[0]); -// } -// -// @Override -// public void trace(String format, Object arg) { -// trace(format, new Object[] { arg }); -// } -// -// @Override -// public void trace(String format, Object arg1, Object arg2) { -// trace(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void trace(String msg, Throwable t) { -// trace(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isTraceEnabled(Marker marker) { -// return isTraceEnabled(); -// } -// -// @Override -// public void trace(Marker marker, String msg) { -// trace(msg); -// } -// -// @Override -// public void trace(Marker marker, String format, Object arg) { -// trace(format, arg); -// } -// -// @Override -// public void trace(Marker marker, String format, Object arg1, Object arg2) { -// trace(format, arg1, arg2); -// } -// -// @Override -// public void trace(Marker marker, String format, Object... argArray) { -// trace(format, argArray); -// } -// -// @Override -// public void trace(Marker marker, String msg, Throwable t) { -// trace(msg, t); -// } -// -// @Override -// public boolean isDebugEnabled() { -// return isLevelEnabled(LogLevel.DEBUG); -// } -// -// @Override -// public void debug(String msg) { -// debug(msg, new Object[0]); -// } -// -// @Override -// public void debug(String format, Object arg) { -// debug(format, new Object[] { arg }); -// } -// -// @Override -// public void debug(String format, Object arg1, Object arg2) { -// debug(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void debug(String msg, Throwable t) { -// debug(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isDebugEnabled(Marker marker) { -// return isDebugEnabled(); -// } -// -// @Override -// public void debug(Marker marker, String msg) { -// debug(msg); -// } -// -// @Override -// public void debug(Marker marker, String format, Object arg) { -// debug(format, arg); -// } -// -// @Override -// public void debug(Marker marker, String format, Object arg1, Object arg2) { -// debug(format, arg1, arg2); -// } -// -// @Override -// public void debug(Marker marker, String format, Object... arguments) { -// debug(format, arguments); -// } -// -// @Override -// public void debug(Marker marker, String msg, Throwable t) { -// debug(msg, t); -// } -// -// @Override -// public boolean isInfoEnabled() { -// return isLevelEnabled(LogLevel.INFO); -// } -// -// @Override -// public void info(String format, Object arg) { -// info(format, new Object[] { arg }); -// } -// -// @Override -// public void info(String format, Object arg1, Object arg2) { -// info(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void info(String msg, Throwable t) { -// info(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isInfoEnabled(Marker marker) { -// return isInfoEnabled(); -// } -// -// @Override -// public void info(Marker marker, String msg) { -// info(msg); -// } -// -// @Override -// public void info(Marker marker, String format, Object arg) { -// info(format, arg); -// } -// -// @Override -// public void info(Marker marker, String format, Object arg1, Object arg2) { -// info(format, arg1, arg2); -// } -// -// @Override -// public void info(Marker marker, String format, Object... arguments) { -// info(format, arguments); -// } -// -// @Override -// public void info(Marker marker, String msg, Throwable t) { -// info(msg, t); -// } -// -// @Override -// public boolean isWarnEnabled() { -// return isLevelEnabled(LogLevel.WARN); -// } -// -// @Override -// public void warn(String msg) { -// warn(msg, new Object[0]); -// } -// -// @Override -// public void warn(String format, Object arg) { -// warn(format, new Object[] { arg }); -// } -// -// @Override -// public void warn(String format, Object arg1, Object arg2) { -// warn(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void warn(String msg, Throwable t) { -// warn(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isWarnEnabled(Marker marker) { -// return isWarnEnabled(); -// } -// -// @Override -// public void warn(Marker marker, String msg) { -// warn(marker); -// } -// -// @Override -// public void warn(Marker marker, String format, Object arg) { -// warn(format, arg); -// } -// -// @Override -// public void warn(Marker marker, String format, Object arg1, Object arg2) { -// warn(format, arg1, arg2); -// } -// -// @Override -// public void warn(Marker marker, String format, Object... arguments) { -// warn(format, arguments); -// } -// -// @Override -// public void warn(Marker marker, String msg, Throwable t) { -// warn(msg, t); -// } -// -// @Override -// public boolean isErrorEnabled() { -// return isLevelEnabled(LogLevel.ERROR); -// } -// -// @Override -// public void error(String msg) { -// error(msg, new Object[0]); -// } -// -// @Override -// public void error(String format, Object arg) { -// error(format, new Object[] { arg }); -// } -// -// @Override -// public void error(String format, Object arg1, Object arg2) { -// error(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void error(String msg, Throwable t) { -// error(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isErrorEnabled(Marker marker) { -// return isErrorEnabled(); -// } -// -// @Override -// public void error(Marker marker, String msg) { -// error(msg); -// } -// -// @Override -// public void error(Marker marker, String format, Object arg) { -// error(format, arg); -// } -// -// @Override -// public void error(Marker marker, String format, Object arg1, Object arg2) { -// error(format, arg1, arg2); -// } -// -// @Override -// public void error(Marker marker, String format, Object... arguments) { -// error(format, arguments); -// } -// -// @Override -// public void error(Marker marker, String msg, Throwable t) { -// error(msg, t); -// } - } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index fc9a86c16..b01426a87 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -12,7 +12,7 @@ public final class BukkitReflectionSerializationUtils { private BukkitReflectionSerializationUtils() {} - protected static final ILogger logger = ILogger.forThisClass(); + private static final ILogger logger = ILogger.forThisClass(); public static boolean isSerializable(@Nonnull Class clazz) { try { @@ -56,7 +56,7 @@ public static T deserializeObject(@Nonnull Map map, @Nullabl return (T) object; - } catch (Throwable ex) { + } catch (Throwable ignored) { } if (classOfT == null) diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index b8733488f..e3438e1fe 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -531,7 +531,7 @@ public static void createFile(@Nullable Path filePath) { if (filePath.getParent() != null) Files.createDirectories(filePath.getParent()); Files.createFile(filePath); - } catch (IOException ex) { + } catch (IOException ignored) { } } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index ce3988f94..4f7d07eee 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -118,7 +118,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject public static int getSize(@Nonnull JsonObject object) { try { return object.size(); - } catch (NoSuchMethodError ex) { + } catch (NoSuchMethodError ignored) { } return object.entrySet().size(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index 6be9f8af1..a19e89e89 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -73,7 +73,8 @@ public static BufferedImage loadUrl(@Nonnull String url) throws IOException { public static BufferedImage loadResource(@Nonnull String path) throws IOException { InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); - return ImageIO.read(stream); + assert stream != null; + return ImageIO.read(stream); } public static BufferedImage loadFile(@Nonnull File file) throws IOException { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 2c4566199..4fb6cb7a4 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -49,7 +49,7 @@ public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredMethod(name, parameterTypes); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } @@ -61,7 +61,7 @@ public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull S for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredField(name); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@Nonnull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ex) { } + } catch (IllegalArgumentException | NoSuchFieldError ignored) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); } @@ -234,7 +234,8 @@ public static T getAnnotationValue(@Nonnull Annotation annotation) { public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { E[] values = invokeStaticMethodOrNull(classOfE, "values"); String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; - for (E value : values) { + assert values != null; + for (E value : values) { for (String method : methodNames) { if (check(input, invokeMethodOrNull(value, method))) return value; diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index 66faae82d..e92d8938e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -35,7 +35,7 @@ public static void disableErrorLogging() { public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { StringBuilder builder = new StringBuilder(); for (Entry entry : map.entrySet()) { - if (builder.length() != 0) builder.append(REGEX_1); + if (!builder.isEmpty()) builder.append(REGEX_1); builder.append(key.apply(entry.getKey())); builder.append(REGEX_2); builder.append(value.apply(entry.getValue())); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index 29dbac10b..b24f8cd0b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,10 +1,12 @@ package net.codingarea.commons.common.version; +import lombok.Getter; import net.codingarea.commons.common.logging.ILogger; import javax.annotation.Nullable; import java.util.Objects; +@Getter public class VersionInfo implements Version { protected static final ILogger logger = ILogger.forThisClass(); @@ -21,19 +23,7 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getRevision() { - return revision; - } - - @Override + @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Version)) return false; diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 8c67b2b87..2c169866d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -1,18 +1,26 @@ package net.codingarea.commons.database; +import lombok.Getter; import net.codingarea.commons.common.config.Propertyable; import javax.annotation.Nonnull; public final class DatabaseConfig { - private final String host; - private final String database; - private final String authDatabase; - private final String password; - private final String user; - private final String file; - private final int port; + @Getter + private final String host; + @Getter + private final String database; + @Getter + private final String authDatabase; + @Getter + private final String password; + @Getter + private final String user; + @Getter + private final String file; + @Getter + private final int port; private final boolean portIsSet; public DatabaseConfig(String host, String database, String password, String user, int port) { @@ -57,39 +65,11 @@ public DatabaseConfig(@Nonnull Propertyable config) { ); } - public int getPort() { - return port; - } - - public String getAuthDatabase() { - return authDatabase; - } - - public String getDatabase() { - return database; - } - - public String getHost() { - return host; - } - - public String getPassword() { - return password; - } - - public String getUser() { - return user; - } - - public boolean isPortSet() { + public boolean isPortSet() { return portIsSet; } - public String getFile() { - return file; - } - - @Override + @Override public String toString() { return "DatabaseConfig{" + "host='" + host + '\'' + diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index 0770c8b67..ea78c59a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -1,5 +1,6 @@ package net.codingarea.commons.database; +import lombok.Getter; import net.codingarea.commons.common.concurrent.task.Task; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; @@ -11,6 +12,7 @@ import java.util.Collections; import java.util.List; +@Getter public class EmptyDatabase implements Database { private final boolean silent; @@ -19,11 +21,7 @@ public EmptyDatabase(boolean silent) { this.silent = silent; } - public boolean isSilent() { - return silent; - } - - protected void exception(@Nonnull String message) { + protected void exception(@Nonnull String message) { throw new UnsupportedOperationException(message); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 75536fe81..66f00bfbb 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -121,7 +121,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { command.append(" ORDER BY "); command.append(orderBy); if (order != null) - command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" ").append(order == Order.HIGHEST ? "DESC" : "ASC"); command.append(" "); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index 2d6536855..b0cb9da9c 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -8,6 +8,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; +import java.util.Objects; public final class SQLResult extends MapDocument { @@ -19,7 +20,7 @@ public SQLResult(@Nonnull Map values) { @Override public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { try { - return new GsonDocument(getString(path), this, this).readonly(); + return new GsonDocument(Objects.requireNonNull(getString(path)), this, this).readonly(); } catch (Exception ex) { return new EmptyDocument(this, null); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index d3b4cd844..47dae0851 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -92,7 +92,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { int index = 0; for (Entry entry : values.entrySet()) { if (index > 0) command.append(", "); - command.append("`" + entry.getKey() + "` = ?"); + command.append("`").append(entry.getKey()).append("` = ?"); args.add(entry.getValue()); index++; } From 09b9655510c793ada4d4d6858701cd84706bf501 Mon Sep 17 00:00:00 2001 From: qodana-bot Date: Sat, 19 Apr 2025 10:37:39 +0000 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=A4=96=20Apply=20quick-fixes=20by=20Q?= =?UTF-8?q?odana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../challenge/effect/RandomPotionEffectChallenge.java | 1 - .../challenge/miscellaneous/EnderGamesChallenge.java | 1 - .../challenges/plugin/utils/misc/ImageUtils.java | 1 - .../commons/common/collection/NumberFormatter.java | 11 +++++------ .../commons/common/config/document/YamlDocument.java | 6 ++---- 5 files changed, 7 insertions(+), 13 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 2cd31b223..728e12152 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -22,7 +22,6 @@ import java.util.Arrays; import java.util.List; import java.util.Random; -import java.util.stream.Collectors; @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 8a11d2c29..5ada48f48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -18,7 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; -import java.util.stream.Collectors; @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index e94c8cf0d..a8cce7289 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -10,7 +10,6 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.net.HttpURLConnection; -import java.net.URL; public final class ImageUtils { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 013c092c1..f9ed17251 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -138,8 +138,7 @@ default String format(@Nonnull Number number) { long seconds = (long) (value); long minutes = seconds / 60; long hours = minutes / 60; - seconds %= 60; - minutes %= 60; + minutes %= 60; return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); }, @@ -330,13 +329,13 @@ default String format(@Nonnull Number number) { @Nonnull @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { return fromPattern(pattern, ending, positive, null); } @Nonnull @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { DecimalFormat format = new DecimalFormat(pattern); if (init != null) init.accept(format); return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); @@ -344,13 +343,13 @@ public static NumberFormatter fromPattern(@Nonnull String pattern, String ending @Nonnull @CheckReturnValue - public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { action.accept(symbols); return symbols; } @CheckReturnValue - public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index faf4fe162..4bb41d219 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -53,8 +53,7 @@ public String getString(@Nonnull String path) { @Nonnull @Override public String getString(@Nonnull String path, @Nonnull String def) { - String string = config.getString(path, def); - return string; + return config.getString(path, def); } @Nullable @@ -66,8 +65,7 @@ public Object getObject(@Nonnull String path) { @Nonnull @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { - Object value = config.get(path, def); - return value; + return config.get(path, def); } @Override From b8f93ebdebd8bfca82583110dc328da637c4a12e Mon Sep 17 00:00:00 2001 From: Dominik Date: Mon, 21 Apr 2025 22:13:41 +0200 Subject: [PATCH 4/5] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-fixe?= =?UTF-8?q?s=20by=20Qodana"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 09b9655510c793ada4d4d6858701cd84706bf501. --- .../challenge/effect/RandomPotionEffectChallenge.java | 1 + .../challenge/miscellaneous/EnderGamesChallenge.java | 1 + .../challenges/plugin/utils/misc/ImageUtils.java | 1 + .../commons/common/collection/NumberFormatter.java | 11 ++++++----- .../commons/common/config/document/YamlDocument.java | 6 ++++-- 5 files changed, 13 insertions(+), 7 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 728e12152..2cd31b223 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.stream.Collectors; @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 5ada48f48..8a11d2c29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -18,6 +18,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; +import java.util.stream.Collectors; @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index a8cce7289..e94c8cf0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -10,6 +10,7 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.URL; public final class ImageUtils { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index f9ed17251..013c092c1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -138,7 +138,8 @@ default String format(@Nonnull Number number) { long seconds = (long) (value); long minutes = seconds / 60; long hours = minutes / 60; - minutes %= 60; + seconds %= 60; + minutes %= 60; return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); }, @@ -329,13 +330,13 @@ default String format(@Nonnull Number number) { @Nonnull @CheckReturnValue - static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { return fromPattern(pattern, ending, positive, null); } @Nonnull @CheckReturnValue - static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { DecimalFormat format = new DecimalFormat(pattern); if (init != null) init.accept(format); return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); @@ -343,13 +344,13 @@ static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boole @Nonnull @CheckReturnValue - static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { action.accept(symbols); return symbols; } @CheckReturnValue - static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index 4bb41d219..faf4fe162 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -53,7 +53,8 @@ public String getString(@Nonnull String path) { @Nonnull @Override public String getString(@Nonnull String path, @Nonnull String def) { - return config.getString(path, def); + String string = config.getString(path, def); + return string; } @Nullable @@ -65,7 +66,8 @@ public Object getObject(@Nonnull String path) { @Nonnull @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { - return config.get(path, def); + Object value = config.get(path, def); + return value; } @Override From b9d4bfb2ad06dd0266490244393eacfadedf50c1 Mon Sep 17 00:00:00 2001 From: Dominik Date: Mon, 21 Apr 2025 22:13:44 +0200 Subject: [PATCH 5/5] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-fixe?= =?UTF-8?q?s=20by=20Qodana"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit f0c4d9d76b5290be7bb26ed61d499640da57649f. --- .../common/config/document/BsonDocument.java | 16 +- .../commons/common/misc/BsonUtils.java | 2 +- .../commons/common/misc/MongoUtils.java | 2 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../inventory/PermanentItemChallenge.java | 3 +- .../miscellaneous/EnderGamesChallenge.java | 2 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 3 +- .../challenge/world/SnakeChallenge.java | 2 +- .../type/abstraction/CollectionGoal.java | 2 +- .../menu/generator/MenuGenerator.java | 3 +- .../menu/info/ChallengeMenuClickInfo.java | 10 + .../plugin/management/team/TeamProvider.java | 1 + .../plugin/spigot/listener/CheatListener.java | 3 +- .../utils/bukkit/misc/BukkitStringUtils.java | 2 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 1 + .../plugin/utils/item/ItemBuilder.java | 3 +- .../plugin/utils/misc/ImageUtils.java | 4 +- .../commons/bukkit/core/BukkitModule.java | 18 +- .../bukkit/core/RequirementsChecker.java | 3 +- .../utils/animation/AnimationFrame.java | 6 +- .../bukkit/utils/animation/SoundSample.java | 15 +- .../utils/bstats/JsonObjectBuilder.java | 17 +- .../bukkit/utils/item/ItemBuilder.java | 10 +- .../bukkit/utils/menu/MenuClickInfo.java | 26 +- .../utils/misc/BukkitReflectionUtils.java | 2 +- .../bukkit/utils/wrapper/ActionListener.java | 8 +- .../common/collection/ClassWalker.java | 2 +- .../common/collection/NumberFormatter.java | 2 +- .../collection/SeededRandomWrapper.java | 9 +- .../common/collection/pair/Quadro.java | 21 +- .../common/collection/pair/Triple.java | 17 +- .../commons/common/collection/pair/Tuple.java | 13 +- .../concurrent/task/CompletableTask.java | 2 +- .../config/document/AbstractConfig.java | 4 +- .../common/config/document/MapDocument.java | 14 +- .../config/document/PropertiesDocument.java | 16 +- .../common/config/document/YamlDocument.java | 12 +- ...kkitReflectionSerializableTypeAdapter.java | 2 +- .../common/discord/DiscordWebhook.java | 71 +++-- .../commons/common/logging/ILogger.java | 2 +- .../commons/common/logging/LogLevel.java | 20 +- .../common/logging/LogOutputStream.java | 2 +- .../common/logging/handler/LogEntry.java | 10 +- .../logging/internal/JavaLoggerWrapper.java | 270 ++++++++++++++++++ .../BukkitReflectionSerializationUtils.java | 4 +- .../commons/common/misc/FileUtils.java | 2 +- .../commons/common/misc/GsonUtils.java | 2 +- .../commons/common/misc/ImageUtils.java | 3 +- .../commons/common/misc/ReflectionUtils.java | 9 +- .../common/misc/SimpleCollectionUtils.java | 2 +- .../commons/common/version/VersionInfo.java | 16 +- .../commons/database/DatabaseConfig.java | 54 ++-- .../commons/database/EmptyDatabase.java | 8 +- .../sql/abstraction/query/SQLQuery.java | 2 +- .../sql/abstraction/query/SQLResult.java | 3 +- .../sql/abstraction/update/SQLUpdate.java | 2 +- 57 files changed, 573 insertions(+), 191 deletions(-) diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java index e44ad0bd5..f801ab556 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -80,7 +80,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -89,7 +89,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -98,7 +98,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -107,7 +107,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -116,7 +116,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -125,7 +125,7 @@ public double getDouble(@Nonnull String path, double def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -137,7 +137,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { Object value = bsonDocument.get(path); if (value instanceof Boolean) return (Boolean) value; if (value instanceof String) return Boolean.parseBoolean((String) value); - } catch (Exception ignored) { + } catch (Exception ex) { } return def; } @@ -161,7 +161,7 @@ public UUID getUUID(@Nonnull String path) { Object value = bsonDocument.get(path); if (value instanceof UUID) return (UUID) value; if (value instanceof String) return UUID.fromString((String) value); - } catch (Exception ignored) { + } catch (Exception ex) { } return null; } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java index 6df6ce127..05611a0b0 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -16,7 +16,7 @@ public final class BsonUtils { - private static final ILogger logger = ILogger.forThisClass(); + protected static final ILogger logger = ILogger.forThisClass(); private BsonUtils() { } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java index 32e03109f..d0c2c4a37 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -57,7 +57,7 @@ public static Object packObject(@Nullable Object value) { BsonUtils.setDocumentProperties(bson, values); return bson; } else if (value instanceof UUID) { - return value.toString(); + return ((UUID) value).toString(); } else { return value; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 2cd31b223..5b15d051e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -65,7 +65,7 @@ public RandomPotionEffectChallenge() { @Nullable public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).toList(); + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); possibleEffects.removeAll(activeEffects); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 99d8ccdb6..6b86b70af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -17,7 +17,6 @@ import org.bukkit.inventory.Inventory; import javax.annotation.Nonnull; -import java.util.Objects; @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -41,7 +40,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 8a11d2c29..899c446cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -64,7 +64,7 @@ private void teleportRandom(@Nonnull Player player) { List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() .filter(entity -> !(entity instanceof Player)) .filter(entity -> entity instanceof LivingEntity) - .toList(); + .collect(Collectors.toList()); Entity targetEntity = list.get(globalRandom.nextInt(list.size())); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index aa48d502b..90b44a7e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -423,7 +423,7 @@ class DocumentCountStatistic extends DocumentStatistic { } } - List newAnswers = answers.stream().map(StringUtils::getEnumName).toList(); + List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); answers.clear(); answers.addAll(newAnswers); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 2b621dc6f..32c31c8f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -29,7 +29,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Objects; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { @@ -118,7 +117,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 26f25a80c..28ae22550 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -56,7 +56,7 @@ public void writeGameState(@Nonnull Document document) { public void loadGameState(@Nonnull Document document) { super.loadGameState(document); - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).toList()); + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index c9f19f248..2ad3bacf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -70,7 +70,7 @@ protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Ru } protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).toList(); + List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index bf7090a65..5fadbe3f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -14,7 +14,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.List; -import java.util.Objects; @Getter @Setter @@ -32,7 +31,7 @@ public abstract class MenuGenerator { public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); return menuPosition instanceof GeneratorMenuPosition - && Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType() != InventoryType.CRAFTING + && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 9df0dc49b..53b285c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -30,4 +30,14 @@ public boolean isLowerItemClick() { return !upperItem; } + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index f3f6db16f..a633ec0d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -2,6 +2,7 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 2251cdd1b..00de88ed9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -33,7 +33,8 @@ public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { @EventHandler(priority = EventPriority.MONITOR) public void onSneak(PlayerToggleSneakEvent event) { - event.isSneaking(); + if (!event.isSneaking()) { + } //// Structure structure = entry.getValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index 37e6f5fbc..c5f73691e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -149,7 +149,7 @@ public static List format(@Nonnull String sequence, @Nonnull Obje if (!currentText.getText().isEmpty()) { results.add(currentText); } - if (!argument.isEmpty()) { + if (argument.length() > 0) { results.add(new TextComponent(String.valueOf(start))); results.add(new TextComponent(String.valueOf(argument))); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 32bb95dfa..4b941e688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -19,6 +19,7 @@ public class NMSProvider { /** * -- GETTER -- * + * @return A border packet factory */ @Getter private static final BorderPacketFactory borderPacketFactory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 42523ce79..b457a897e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -214,8 +214,7 @@ public ItemDescription getBuiltByItemDescription() { @Override public ItemBuilder clone() { - ItemBuilder itemBuilder = (ItemBuilder) super.clone(); - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); builder.builtByItemDescription = builtByItemDescription; return builder; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index e94c8cf0d..f81f27ba2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.common.collection.IOUtils; import org.bukkit.entity.Player; import javax.annotation.Nonnull; @@ -21,7 +20,8 @@ private ImageUtils() { @Nullable public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = IOUtils.createConnection(url); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); return ImageIO.read(connection.getInputStream()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index 31f3e41cb..c90eea42b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,7 +1,6 @@ package net.codingarea.commons.bukkit.core; import com.google.common.base.Charsets; -import lombok.Getter; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -55,8 +54,7 @@ public abstract class BukkitModule extends JavaPlugin { private ExecutorService executorService; private Document config, pluginConfig; private Version version; - @Getter - private boolean devMode; + private boolean devMode; private boolean firstInstall; private boolean isReloaded; private boolean isLoaded; @@ -77,10 +75,10 @@ public final void onLoad() { ILogger.setConstantFactory(this.getILogger()); trySaveDefaultConfig(); if (wasShutdown) isReloaded = true; - if (firstInstall == !getDataFolder().exists()) { + if (firstInstall = !getDataFolder().exists()) { getILogger().info("Detected first install!"); } - if (devMode == getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { getILogger().setLevel(Level.ALL); getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); } else { @@ -144,7 +142,11 @@ protected void handleLoad() throws Exception {} protected void handleEnable() throws Exception {} protected void handleDisable() throws Exception {} - public final boolean isFirstInstall() { + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { return firstInstall; } @@ -183,7 +185,7 @@ public void reloadConfig() { @Nonnull public Document getPluginDocument() { return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("plugin.yml")), Charsets.UTF_8)))); + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); } @Nonnull @@ -342,7 +344,7 @@ private void injectInstance() { Field instanceField = this.getClass().getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, this); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 8b380040c..87cae1721 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -6,7 +6,6 @@ import org.bukkit.Bukkit; import javax.annotation.Nonnull; -import java.util.Objects; public final class RequirementsChecker { @@ -19,7 +18,7 @@ public RequirementsChecker(@Nonnull BukkitModule module) { public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { if (requirements.getBoolean("spigot")) requireSpigot(); if (requirements.getBoolean("paper")) requirePaper(); - if (requirements.contains("version")) requireVersion(Objects.requireNonNull(requirements.getVersion("version"))); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); } public boolean checkBoolean(@Nonnull Document requirements) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index b91add45e..130785522 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -7,7 +7,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; -import java.util.Objects; public class AnimationFrame implements Cloneable { @@ -60,7 +59,7 @@ public ItemStack getItem(int slot) { @Nullable public Material getItemType(int slot) { - return getItem(slot) == null ? Material.AIR : Objects.requireNonNull(getItem(slot)).getType(); + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); } @Nonnull @@ -79,8 +78,7 @@ public int getSize() { @Nonnull @Override public AnimationFrame clone() { - AnimationFrame animationFrame = (AnimationFrame) super.clone(); - return new AnimationFrame(content); + return new AnimationFrame(content); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 47441780a..8991960e0 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.animation; -import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; @@ -36,9 +35,7 @@ public static void playStatusSound(@Nonnull Player player, boolean enabled) { private static final class SoundFrame { - @Getter - @Getter - private final float pitch, volume; + private final float pitch, volume; private final Sound sound; public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { @@ -55,7 +52,15 @@ public void play(@Nonnull Player player, @Nonnull Location location) { player.playSound(location, sound, volume, pitch); } - @Nonnull + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull public Sound getSound() { return sound; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java index e156c6284..172e2e4ff 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -160,15 +160,14 @@ public JsonObject build() { } /** - * Escapes the given string like stated in .... - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as " - " and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ private static String escape(String value) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 868ad8110..339bbaba2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -14,7 +14,10 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; public class ItemBuilder { @@ -64,7 +67,7 @@ public ItemMeta getMeta() { @Nonnull @SuppressWarnings("unchecked") public final M getCastedMeta() { - return (M) (meta == null ? Objects.requireNonNull(meta = item.getItemMeta()) : meta); + return (M) (meta == null ? meta = item.getItemMeta() : meta); } @Nonnull @@ -251,8 +254,7 @@ public ItemStack toItem() { @Override public ItemBuilder clone() { - ItemBuilder itemBuilder = (ItemBuilder) super.clone(); - return new ItemBuilder(item.clone(), getMeta().clone()); + return new ItemBuilder(item.clone(), getMeta().clone()); } public static class BannerBuilder extends ItemBuilder { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 0d2e9236d..5753ad174 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.menu; -import lombok.Getter; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -14,12 +13,9 @@ public class MenuClickInfo { protected final Player player; protected final Inventory inventory; - @Getter - protected final boolean shiftClick; - @Getter - protected final boolean rightClick; - @Getter - protected final int slot; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { this.player = player; @@ -39,11 +35,23 @@ public Inventory getInventory() { return inventory; } - public boolean isLeftClick() { + public boolean isRightClick() { + return rightClick; + } + + public boolean isLeftClick() { return !rightClick; } - @Nullable + public boolean isShiftClick() { + return shiftClick; + } + + public int getSlot() { + return slot; + } + + @Nullable public ItemStack getClickedItem() { return inventory.getItem(slot); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 46b72210b..36284f5e3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -136,7 +136,7 @@ public static NamespacedKey fromString(@Nonnull String key) { */ @Nullable public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { - Preconditions.checkArgument(!string.isEmpty(), "Input string must not be empty or null"); + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); String[] components = string.split(":", 3); if (components.length > 2) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index c53353706..8faa0993b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.wrapper; -import lombok.Getter; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -14,8 +13,7 @@ public final class ActionListener implements Listener { private final Class classOfEvent; private final Consumer listener; private final EventPriority priority; - @Getter - private final boolean ignoreCancelled; + private final boolean ignoreCancelled; public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { this.classOfEvent = classOfEvent; @@ -52,4 +50,8 @@ public Class getClassOfEvent() { return classOfEvent; } + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } + } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index 49018ec35..d71f0df71 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -4,7 +4,7 @@ import java.util.*; /** - * @author JDA | ... + * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java */ public class ClassWalker implements Iterable> { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 013c092c1..4a734b55b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -48,7 +48,7 @@ default String format(@Nonnull Number number) { return format(number.doubleValue()); } - NumberFormatter + public static final NumberFormatter DEFAULT = fromPattern("0.##", null, false), INTEGER = value -> (int) value + "", SPACE_SPLIT = fromPattern("###,##0.###############", null, false, diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java index 0c0f90e5e..a9fcb48f2 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -1,14 +1,11 @@ package net.codingarea.commons.common.collection; -import lombok.Getter; - import java.util.Random; /** * Since there is no way of getting the seed of a {@link Random} we create a wrapper * which will save seed. This allows us to save randomization and reload it. */ -@Getter public class SeededRandomWrapper extends Random implements IRandom { protected long seed; @@ -27,7 +24,11 @@ public void setSeed(long seed) { this.seed = seed; } - @Override + public long getSeed() { + return seed; + } + + @Override public String toString() { return "Random[seed=" + seed + "]"; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index 734f5cf16..df07b890d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -14,7 +12,6 @@ * @param The type of the third value * @param The type of the fourth value */ -@Getter public class Quadro implements Pair { protected F first; @@ -43,7 +40,23 @@ public final Object[] values() { return new Object[] { first, second, third, first }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index b62f55777..48c8dfcde 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -13,7 +11,6 @@ * @param The type of the second value * @param The type of the third value */ -@Getter public class Triple implements Pair { protected F first; @@ -40,7 +37,19 @@ public final Object[] values() { return new Object[] { first, second, third }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index ce1901dbf..9d320ba6e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -12,7 +10,6 @@ * @param The type of the first value * @param The type of the second value */ -@Getter public class Tuple implements Pair { protected F first; @@ -37,7 +34,15 @@ public final Object[] values() { return new Object[] { first, second }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 08ab891a7..37b71703f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -64,7 +64,7 @@ public Task addListener(@Nonnull TaskListener listener) { } else if (failure != null) { listener.onFailure(this, failure); } else { - listener.onComplete(this, null); + listener.onComplete(this, value); } return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index 2f9fec69b..cce0be2e8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -46,7 +46,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return Objects.requireNonNull(getString(path)).charAt(0); + return getString(path).charAt(0); } catch (NullPointerException | IndexOutOfBoundsException ex) { return def; } @@ -175,7 +175,7 @@ public > List getEnumList(@Nonnull String path, @Nonnull Cl @Nonnull @Override public List getCharacterList(@Nonnull String path) { - return mapList(path, string -> string == null || string.isEmpty() ? (char) 0 : string.charAt(0)); + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index eabc2e1a7..b0b194d05 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -129,7 +129,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -138,7 +138,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -147,7 +147,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -156,7 +156,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -165,7 +165,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -174,7 +174,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -184,7 +184,7 @@ public double getDouble(@Nonnull String path, double def) { public boolean getBoolean(@Nonnull String path, boolean def) { try { if (!contains(path)) return def; - switch (Objects.requireNonNull(getString(path)).toLowerCase()) { + switch (getString(path).toLowerCase()) { case "true": case "1": return true; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 7f5213806..58fa7b100 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -78,7 +78,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -87,7 +87,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -96,7 +96,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -105,7 +105,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -114,7 +114,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -123,7 +123,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -139,7 +139,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(Objects.requireNonNull(getString(path))); + return UUID.fromString(getString(path)); } catch (Exception ex) { return null; } @@ -155,7 +155,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); + return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index faf4fe162..03bdf14d3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -54,7 +54,7 @@ public String getString(@Nonnull String path) { @Override public String getString(@Nonnull String path, @Nonnull String def) { String string = config.getString(path, def); - return string; + return string == null ? def : string; } @Nullable @@ -67,7 +67,7 @@ public Object getObject(@Nonnull String path) { @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { Object value = config.get(path, def); - return value; + return value == null ? def : value; } @Override @@ -147,7 +147,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return Objects.requireNonNull(getString(path)).charAt(0); + return getString(path).charAt(0); } catch (NullPointerException | StringIndexOutOfBoundsException ex) { return def; } @@ -193,7 +193,7 @@ public List getStringList(@Nonnull String path) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(Objects.requireNonNull(getString(path))); + return UUID.fromString(getString(path)); } catch (Exception ex) { return null; } @@ -213,7 +213,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); + return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { return null; } @@ -223,7 +223,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Override public Color getColor(@Nonnull String path) { try { - return Color.decode(Objects.requireNonNull(getString(path))); + return Color.decode(getString(path)); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index 71f9f7744..ed36fd787 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -43,7 +43,7 @@ public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOExce Class clazz = null; try { clazz = Class.forName(classOfType); - } catch (ClassNotFoundException | NullPointerException ignored) { + } catch (ClassNotFoundException | NullPointerException ex) { } Map map = GsonUtils.convertJsonObjectToMap(json); diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index b75f88549..49eeec955 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -1,6 +1,5 @@ package net.codingarea.commons.common.discord; -import lombok.Getter; import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; @@ -215,8 +214,7 @@ public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String return this; } - @Getter - public static class EmbedObject { + public static class EmbedObject { protected String title; protected String description; @@ -246,7 +244,43 @@ public EmbedObject(@Nullable String title, @Nullable String description, @Nullab this.fields = fields; } - @Nonnull + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull public EmbedObject setTitle(String title) { this.title = title; return this; @@ -302,8 +336,7 @@ public EmbedObject addField(String name, String value, boolean inline) { @Override public EmbedObject clone() { - EmbedObject embedObject = (EmbedObject) super.clone(); - return new EmbedObject( + return new EmbedObject( title, description, url, color, footer == null ? null : footer.clone(), thumbnail == null ? null : thumbnail.clone(), @@ -335,9 +368,8 @@ private String getIconUrl() { } @Override - protected Footer clone() throws CloneNotSupportedException { - Footer footer1 = (Footer) super.clone(); - return new Footer(text, iconUrl); + protected Footer clone() { + return new Footer(text, iconUrl); } } @@ -357,9 +389,8 @@ private String getUrl() { } @Override - protected Thumbnail clone() throws CloneNotSupportedException { - Thumbnail thumbnail1 = (Thumbnail) super.clone(); - return new Thumbnail(url); + protected Thumbnail clone() { + return new Thumbnail(url); } } @@ -380,8 +411,7 @@ private String getUrl() { @Override public Image clone() { - Image image1 = (Image) super.clone(); - return new Image(url); + return new Image(url); } } @@ -413,9 +443,8 @@ private String getIconUrl() { } @Override - protected Author clone() throws CloneNotSupportedException { - Author author1 = (Author) super.clone(); - return new Author(name, url, iconUrl); + protected Author clone() { + return new Author(name, url, iconUrl); } } @@ -447,17 +476,15 @@ private boolean isInline() { } @Override - protected Field clone() throws CloneNotSupportedException { - Field field = (Field) super.clone(); - return new Field(name, value, inline); + protected Field clone() { + return new Field(name, value, inline); } } } @Override public DiscordWebhook clone() { - DiscordWebhook discordWebhook = (DiscordWebhook) super.clone(); - return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index eb337e206..02ec550a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -260,7 +260,7 @@ default JavaILogger java() { @CheckReturnValue default PrintStream asPrintStream(@Nonnull LogLevel level) { try { - return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8); + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); } catch (Exception ex) { throw new WrappedException(ex); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index 58d6c7262..ddf6d01c8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.logging; -import lombok.Getter; - import javax.annotation.Nonnull; import java.util.logging.Level; @@ -17,10 +15,8 @@ public enum LogLevel { private final String uppercaseName, lowercaseName; private final Level javaLevel; - @Getter - private final int value; - @Getter - private final boolean highlighted; + private final int value; + private final boolean highlighted; LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { this.uppercaseName = uppercaseName; @@ -39,7 +35,11 @@ public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { return this.getValue() >= loggerLevel.getValue(); } - @Nonnull + public int getValue() { + return value; + } + + @Nonnull public String getLowerCaseName() { return lowercaseName; } @@ -49,7 +49,11 @@ public String getUpperCaseName() { return uppercaseName; } - @Nonnull + public boolean isHighlighted() { + return highlighted; + } + + @Nonnull public static LogLevel fromJavaLevel(@Nonnull Level level) { for (LogLevel logLevel : values()) { if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index c747fbf1a..7095492ed 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -17,7 +17,7 @@ public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { @Override public void flush() throws IOException { - String input = this.toString(StandardCharsets.UTF_8); + String input = this.toString(StandardCharsets.UTF_8.name()); this.reset(); if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 3212680b9..5068d301b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -8,11 +8,11 @@ public class LogEntry { - private final Instant timestamp; - private final String threadName; - private final String message; - private final LogLevel level; - private final Throwable exception; + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { this.timestamp = timestamp; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index b9c95d540..f0c64bf8d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -393,4 +393,274 @@ public void debug(@Nullable Object message, @Nonnull Object... args) { } + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + +// @Override +// public void trace(String msg) { +// trace(msg, new Object[0]); +// } +// +// @Override +// public void trace(String format, Object arg) { +// trace(format, new Object[] { arg }); +// } +// +// @Override +// public void trace(String format, Object arg1, Object arg2) { +// trace(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void trace(String msg, Throwable t) { +// trace(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isTraceEnabled(Marker marker) { +// return isTraceEnabled(); +// } +// +// @Override +// public void trace(Marker marker, String msg) { +// trace(msg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg) { +// trace(format, arg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg1, Object arg2) { +// trace(format, arg1, arg2); +// } +// +// @Override +// public void trace(Marker marker, String format, Object... argArray) { +// trace(format, argArray); +// } +// +// @Override +// public void trace(Marker marker, String msg, Throwable t) { +// trace(msg, t); +// } +// +// @Override +// public boolean isDebugEnabled() { +// return isLevelEnabled(LogLevel.DEBUG); +// } +// +// @Override +// public void debug(String msg) { +// debug(msg, new Object[0]); +// } +// +// @Override +// public void debug(String format, Object arg) { +// debug(format, new Object[] { arg }); +// } +// +// @Override +// public void debug(String format, Object arg1, Object arg2) { +// debug(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void debug(String msg, Throwable t) { +// debug(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isDebugEnabled(Marker marker) { +// return isDebugEnabled(); +// } +// +// @Override +// public void debug(Marker marker, String msg) { +// debug(msg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg) { +// debug(format, arg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg1, Object arg2) { +// debug(format, arg1, arg2); +// } +// +// @Override +// public void debug(Marker marker, String format, Object... arguments) { +// debug(format, arguments); +// } +// +// @Override +// public void debug(Marker marker, String msg, Throwable t) { +// debug(msg, t); +// } +// +// @Override +// public boolean isInfoEnabled() { +// return isLevelEnabled(LogLevel.INFO); +// } +// +// @Override +// public void info(String format, Object arg) { +// info(format, new Object[] { arg }); +// } +// +// @Override +// public void info(String format, Object arg1, Object arg2) { +// info(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void info(String msg, Throwable t) { +// info(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isInfoEnabled(Marker marker) { +// return isInfoEnabled(); +// } +// +// @Override +// public void info(Marker marker, String msg) { +// info(msg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg) { +// info(format, arg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg1, Object arg2) { +// info(format, arg1, arg2); +// } +// +// @Override +// public void info(Marker marker, String format, Object... arguments) { +// info(format, arguments); +// } +// +// @Override +// public void info(Marker marker, String msg, Throwable t) { +// info(msg, t); +// } +// +// @Override +// public boolean isWarnEnabled() { +// return isLevelEnabled(LogLevel.WARN); +// } +// +// @Override +// public void warn(String msg) { +// warn(msg, new Object[0]); +// } +// +// @Override +// public void warn(String format, Object arg) { +// warn(format, new Object[] { arg }); +// } +// +// @Override +// public void warn(String format, Object arg1, Object arg2) { +// warn(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void warn(String msg, Throwable t) { +// warn(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isWarnEnabled(Marker marker) { +// return isWarnEnabled(); +// } +// +// @Override +// public void warn(Marker marker, String msg) { +// warn(marker); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg) { +// warn(format, arg); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg1, Object arg2) { +// warn(format, arg1, arg2); +// } +// +// @Override +// public void warn(Marker marker, String format, Object... arguments) { +// warn(format, arguments); +// } +// +// @Override +// public void warn(Marker marker, String msg, Throwable t) { +// warn(msg, t); +// } +// +// @Override +// public boolean isErrorEnabled() { +// return isLevelEnabled(LogLevel.ERROR); +// } +// +// @Override +// public void error(String msg) { +// error(msg, new Object[0]); +// } +// +// @Override +// public void error(String format, Object arg) { +// error(format, new Object[] { arg }); +// } +// +// @Override +// public void error(String format, Object arg1, Object arg2) { +// error(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void error(String msg, Throwable t) { +// error(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isErrorEnabled(Marker marker) { +// return isErrorEnabled(); +// } +// +// @Override +// public void error(Marker marker, String msg) { +// error(msg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg) { +// error(format, arg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg1, Object arg2) { +// error(format, arg1, arg2); +// } +// +// @Override +// public void error(Marker marker, String format, Object... arguments) { +// error(format, arguments); +// } +// +// @Override +// public void error(Marker marker, String msg, Throwable t) { +// error(msg, t); +// } + } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index b01426a87..fc9a86c16 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -12,7 +12,7 @@ public final class BukkitReflectionSerializationUtils { private BukkitReflectionSerializationUtils() {} - private static final ILogger logger = ILogger.forThisClass(); + protected static final ILogger logger = ILogger.forThisClass(); public static boolean isSerializable(@Nonnull Class clazz) { try { @@ -56,7 +56,7 @@ public static T deserializeObject(@Nonnull Map map, @Nullabl return (T) object; - } catch (Throwable ignored) { + } catch (Throwable ex) { } if (classOfT == null) diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index e3438e1fe..b8733488f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -531,7 +531,7 @@ public static void createFile(@Nullable Path filePath) { if (filePath.getParent() != null) Files.createDirectories(filePath.getParent()); Files.createFile(filePath); - } catch (IOException ignored) { + } catch (IOException ex) { } } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index 4f7d07eee..ce3988f94 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -118,7 +118,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject public static int getSize(@Nonnull JsonObject object) { try { return object.size(); - } catch (NoSuchMethodError ignored) { + } catch (NoSuchMethodError ex) { } return object.entrySet().size(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index a19e89e89..6be9f8af1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -73,8 +73,7 @@ public static BufferedImage loadUrl(@Nonnull String url) throws IOException { public static BufferedImage loadResource(@Nonnull String path) throws IOException { InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); - assert stream != null; - return ImageIO.read(stream); + return ImageIO.read(stream); } public static BufferedImage loadFile(@Nonnull File file) throws IOException { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 4fb6cb7a4..2c4566199 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -49,7 +49,7 @@ public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredMethod(name, parameterTypes); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } @@ -61,7 +61,7 @@ public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull S for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredField(name); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@Nonnull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ignored) { } + } catch (IllegalArgumentException | NoSuchFieldError ex) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); } @@ -234,8 +234,7 @@ public static T getAnnotationValue(@Nonnull Annotation annotation) { public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { E[] values = invokeStaticMethodOrNull(classOfE, "values"); String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; - assert values != null; - for (E value : values) { + for (E value : values) { for (String method : methodNames) { if (check(input, invokeMethodOrNull(value, method))) return value; diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index e92d8938e..66faae82d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -35,7 +35,7 @@ public static void disableErrorLogging() { public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { StringBuilder builder = new StringBuilder(); for (Entry entry : map.entrySet()) { - if (!builder.isEmpty()) builder.append(REGEX_1); + if (builder.length() != 0) builder.append(REGEX_1); builder.append(key.apply(entry.getKey())); builder.append(REGEX_2); builder.append(value.apply(entry.getValue())); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index b24f8cd0b..29dbac10b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,12 +1,10 @@ package net.codingarea.commons.common.version; -import lombok.Getter; import net.codingarea.commons.common.logging.ILogger; import javax.annotation.Nullable; import java.util.Objects; -@Getter public class VersionInfo implements Version { protected static final ILogger logger = ILogger.forThisClass(); @@ -23,7 +21,19 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - @Override + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Version)) return false; diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 2c169866d..8c67b2b87 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -1,26 +1,18 @@ package net.codingarea.commons.database; -import lombok.Getter; import net.codingarea.commons.common.config.Propertyable; import javax.annotation.Nonnull; public final class DatabaseConfig { - @Getter - private final String host; - @Getter - private final String database; - @Getter - private final String authDatabase; - @Getter - private final String password; - @Getter - private final String user; - @Getter - private final String file; - @Getter - private final int port; + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; private final boolean portIsSet; public DatabaseConfig(String host, String database, String password, String user, int port) { @@ -65,11 +57,39 @@ public DatabaseConfig(@Nonnull Propertyable config) { ); } - public boolean isPortSet() { + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { return portIsSet; } - @Override + public String getFile() { + return file; + } + + @Override public String toString() { return "DatabaseConfig{" + "host='" + host + '\'' + diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index ea78c59a7..0770c8b67 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -1,6 +1,5 @@ package net.codingarea.commons.database; -import lombok.Getter; import net.codingarea.commons.common.concurrent.task.Task; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; @@ -12,7 +11,6 @@ import java.util.Collections; import java.util.List; -@Getter public class EmptyDatabase implements Database { private final boolean silent; @@ -21,7 +19,11 @@ public EmptyDatabase(boolean silent) { this.silent = silent; } - protected void exception(@Nonnull String message) { + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { throw new UnsupportedOperationException(message); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 66f00bfbb..75536fe81 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -121,7 +121,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { command.append(" ORDER BY "); command.append(orderBy); if (order != null) - command.append(" ").append(order == Order.HIGHEST ? "DESC" : "ASC"); + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); command.append(" "); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index b0cb9da9c..2d6536855 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -8,7 +8,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; -import java.util.Objects; public final class SQLResult extends MapDocument { @@ -20,7 +19,7 @@ public SQLResult(@Nonnull Map values) { @Override public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { try { - return new GsonDocument(Objects.requireNonNull(getString(path)), this, this).readonly(); + return new GsonDocument(getString(path), this, this).readonly(); } catch (Exception ex) { return new EmptyDocument(this, null); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index 47dae0851..d3b4cd844 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -92,7 +92,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { int index = 0; for (Entry entry : values.entrySet()) { if (index > 0) command.append(", "); - command.append("`").append(entry.getKey()).append("` = ?"); + command.append("`" + entry.getKey() + "` = ?"); args.add(entry.getValue()); index++; }