Repository: Realizedd/Duels Branch: master Commit: 2fc934867ee3 Files: 256 Total size: 704.3 KB Directory structure: gitextract_mv1mshjz/ ├── .gitignore ├── LICENSE.md ├── README.md ├── build.gradle ├── duels-api/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── me/ │ └── realized/ │ └── duels/ │ └── api/ │ ├── Duels.java │ ├── arena/ │ │ ├── Arena.java │ │ └── ArenaManager.java │ ├── command/ │ │ └── SubCommand.java │ ├── event/ │ │ ├── SourcedEvent.java │ │ ├── arena/ │ │ │ ├── ArenaCreateEvent.java │ │ │ ├── ArenaEvent.java │ │ │ ├── ArenaRemoveEvent.java │ │ │ ├── ArenaSetPositionEvent.java │ │ │ └── ArenaStateChangeEvent.java │ │ ├── kit/ │ │ │ ├── KitCreateEvent.java │ │ │ ├── KitEquipEvent.java │ │ │ ├── KitEvent.java │ │ │ └── KitRemoveEvent.java │ │ ├── match/ │ │ │ ├── MatchEndEvent.java │ │ │ ├── MatchEvent.java │ │ │ └── MatchStartEvent.java │ │ ├── queue/ │ │ │ ├── QueueCreateEvent.java │ │ │ ├── QueueEvent.java │ │ │ ├── QueueJoinEvent.java │ │ │ ├── QueueLeaveEvent.java │ │ │ ├── QueueRemoveEvent.java │ │ │ └── sign/ │ │ │ ├── QueueSignCreateEvent.java │ │ │ ├── QueueSignEvent.java │ │ │ └── QueueSignRemoveEvent.java │ │ ├── request/ │ │ │ ├── RequestAcceptEvent.java │ │ │ ├── RequestDenyEvent.java │ │ │ ├── RequestEvent.java │ │ │ └── RequestSendEvent.java │ │ ├── spectate/ │ │ │ ├── SpectateEndEvent.java │ │ │ ├── SpectateEvent.java │ │ │ └── SpectateStartEvent.java │ │ └── user/ │ │ └── UserCreateEvent.java │ ├── extension/ │ │ └── DuelsExtension.java │ ├── kit/ │ │ ├── Kit.java │ │ └── KitManager.java │ ├── match/ │ │ └── Match.java │ ├── queue/ │ │ ├── DQueue.java │ │ ├── DQueueManager.java │ │ └── sign/ │ │ ├── QueueSign.java │ │ └── QueueSignManager.java │ ├── request/ │ │ └── Request.java │ ├── spectate/ │ │ ├── SpectateManager.java │ │ └── Spectator.java │ └── user/ │ ├── MatchInfo.java │ ├── User.java │ └── UserManager.java ├── duels-plugin/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── java/ │ │ └── me/ │ │ └── realized/ │ │ └── duels/ │ │ ├── DuelsPlugin.java │ │ ├── Permissions.java │ │ ├── api/ │ │ │ └── DuelsAPI.java │ │ ├── arena/ │ │ │ ├── ArenaImpl.java │ │ │ ├── ArenaManagerImpl.java │ │ │ ├── Countdown.java │ │ │ └── MatchImpl.java │ │ ├── betting/ │ │ │ └── BettingManager.java │ │ ├── command/ │ │ │ ├── BaseCommand.java │ │ │ └── commands/ │ │ │ ├── SpectateCommand.java │ │ │ ├── duel/ │ │ │ │ ├── DuelCommand.java │ │ │ │ └── subcommands/ │ │ │ │ ├── AcceptCommand.java │ │ │ │ ├── DenyCommand.java │ │ │ │ ├── InventoryCommand.java │ │ │ │ ├── StatsCommand.java │ │ │ │ ├── ToggleCommand.java │ │ │ │ ├── TopCommand.java │ │ │ │ └── VersionCommand.java │ │ │ ├── duels/ │ │ │ │ ├── DuelsCommand.java │ │ │ │ └── subcommands/ │ │ │ │ ├── AddsignCommand.java │ │ │ │ ├── BindCommand.java │ │ │ │ ├── CreateCommand.java │ │ │ │ ├── CreatequeueCommand.java │ │ │ │ ├── DeleteCommand.java │ │ │ │ ├── DeletekitCommand.java │ │ │ │ ├── DeletequeueCommand.java │ │ │ │ ├── DeletesignCommand.java │ │ │ │ ├── EditCommand.java │ │ │ │ ├── HelpCommand.java │ │ │ │ ├── InfoCommand.java │ │ │ │ ├── ListCommand.java │ │ │ │ ├── LoadkitCommand.java │ │ │ │ ├── LobbyCommand.java │ │ │ │ ├── OptionsCommand.java │ │ │ │ ├── PlaysoundCommand.java │ │ │ │ ├── ReloadCommand.java │ │ │ │ ├── ResetCommand.java │ │ │ │ ├── ResetratingCommand.java │ │ │ │ ├── SavekitCommand.java │ │ │ │ ├── SetCommand.java │ │ │ │ ├── SetitemCommand.java │ │ │ │ ├── SetlobbyCommand.java │ │ │ │ ├── SetratingCommand.java │ │ │ │ ├── TeleportCommand.java │ │ │ │ └── ToggleCommand.java │ │ │ └── queue/ │ │ │ ├── QueueCommand.java │ │ │ └── subcommands/ │ │ │ ├── JoinCommand.java │ │ │ └── LeaveCommand.java │ │ ├── config/ │ │ │ ├── Config.java │ │ │ ├── Lang.java │ │ │ └── converters/ │ │ │ └── ConfigConverter9_10.java │ │ ├── data/ │ │ │ ├── ArenaData.java │ │ │ ├── ItemData.java │ │ │ ├── KitData.java │ │ │ ├── LocationData.java │ │ │ ├── MatchData.java │ │ │ ├── PlayerData.java │ │ │ ├── PotionEffectData.java │ │ │ ├── QueueData.java │ │ │ ├── QueueSignData.java │ │ │ ├── UserData.java │ │ │ └── UserManagerImpl.java │ │ ├── duel/ │ │ │ └── DuelManager.java │ │ ├── extension/ │ │ │ ├── ExtensionClassLoader.java │ │ │ ├── ExtensionInfo.java │ │ │ └── ExtensionManager.java │ │ ├── gui/ │ │ │ ├── BaseButton.java │ │ │ ├── betting/ │ │ │ │ ├── BettingGui.java │ │ │ │ └── buttons/ │ │ │ │ ├── CancelButton.java │ │ │ │ ├── DetailsButton.java │ │ │ │ ├── HeadButton.java │ │ │ │ └── StateButton.java │ │ │ ├── bind/ │ │ │ │ ├── BindGui.java │ │ │ │ └── buttons/ │ │ │ │ └── BindButton.java │ │ │ ├── inventory/ │ │ │ │ ├── InventoryGui.java │ │ │ │ └── buttons/ │ │ │ │ ├── EffectsButton.java │ │ │ │ ├── HeadButton.java │ │ │ │ ├── HealthButton.java │ │ │ │ ├── HungerButton.java │ │ │ │ └── PotionCounterButton.java │ │ │ ├── options/ │ │ │ │ ├── OptionsGui.java │ │ │ │ └── buttons/ │ │ │ │ └── OptionButton.java │ │ │ └── settings/ │ │ │ ├── SettingsGui.java │ │ │ └── buttons/ │ │ │ ├── ArenaSelectButton.java │ │ │ ├── CancelButton.java │ │ │ ├── ItemBettingButton.java │ │ │ ├── KitSelectButton.java │ │ │ ├── OwnInventoryButton.java │ │ │ ├── RequestDetailsButton.java │ │ │ └── RequestSendButton.java │ │ ├── hook/ │ │ │ ├── HookManager.java │ │ │ └── hooks/ │ │ │ ├── BountyHuntersHook.java │ │ │ ├── CombatLogXHook.java │ │ │ ├── CombatTagPlusHook.java │ │ │ ├── EssentialsHook.java │ │ │ ├── FactionsHook.java │ │ │ ├── LeaderHeadsHook.java │ │ │ ├── MVdWPlaceholderHook.java │ │ │ ├── McMMOHook.java │ │ │ ├── MyPetHook.java │ │ │ ├── PlaceholderHook.java │ │ │ ├── PvPManagerHook.java │ │ │ ├── SimpleClansHook.java │ │ │ ├── VaultHook.java │ │ │ └── worldguard/ │ │ │ └── WorldGuardHook.java │ │ ├── inventories/ │ │ │ └── InventoryManager.java │ │ ├── kit/ │ │ │ ├── KitImpl.java │ │ │ └── KitManagerImpl.java │ │ ├── listeners/ │ │ │ ├── DamageListener.java │ │ │ ├── EnderpearlListener.java │ │ │ ├── KitItemListener.java │ │ │ ├── KitOptionsListener.java │ │ │ ├── LingerPotionListener.java │ │ │ ├── PotionListener.java │ │ │ ├── ProjectileHitListener.java │ │ │ └── TeleportListener.java │ │ ├── logging/ │ │ │ └── LogManager.java │ │ ├── player/ │ │ │ ├── PlayerInfo.java │ │ │ └── PlayerInfoManager.java │ │ ├── queue/ │ │ │ ├── Queue.java │ │ │ ├── QueueEntry.java │ │ │ ├── QueueManager.java │ │ │ └── sign/ │ │ │ ├── QueueSignImpl.java │ │ │ └── QueueSignManagerImpl.java │ │ ├── request/ │ │ │ ├── RequestImpl.java │ │ │ └── RequestManager.java │ │ ├── setting/ │ │ │ ├── CachedInfo.java │ │ │ ├── Settings.java │ │ │ └── SettingsManager.java │ │ ├── shaded/ │ │ │ └── bstats/ │ │ │ └── Metrics.java │ │ ├── spectate/ │ │ │ ├── SpectateManagerImpl.java │ │ │ └── SpectatorImpl.java │ │ ├── teleport/ │ │ │ └── Teleport.java │ │ └── util/ │ │ ├── BlockUtil.java │ │ ├── DateUtil.java │ │ ├── EnumUtil.java │ │ ├── EventUtil.java │ │ ├── Loadable.java │ │ ├── Log.java │ │ ├── NumberUtil.java │ │ ├── PlayerUtil.java │ │ ├── Reloadable.java │ │ ├── StringUtil.java │ │ ├── TextBuilder.java │ │ ├── UUIDUtil.java │ │ ├── UpdateChecker.java │ │ ├── collection/ │ │ │ └── StreamUtil.java │ │ ├── command/ │ │ │ └── AbstractCommand.java │ │ ├── compat/ │ │ │ ├── CompatUtil.java │ │ │ ├── Identifiers.java │ │ │ ├── Inventories.java │ │ │ ├── Items.java │ │ │ ├── Panes.java │ │ │ ├── Skulls.java │ │ │ ├── Titles.java │ │ │ └── nbt/ │ │ │ └── NBT.java │ │ ├── config/ │ │ │ ├── AbstractConfiguration.java │ │ │ └── convert/ │ │ │ └── Converter.java │ │ ├── function/ │ │ │ ├── Pair.java │ │ │ └── TriFunction.java │ │ ├── gui/ │ │ │ ├── AbstractGui.java │ │ │ ├── Button.java │ │ │ ├── GuiListener.java │ │ │ ├── MultiPageGui.java │ │ │ └── SinglePageGui.java │ │ ├── hook/ │ │ │ ├── AbstractHookManager.java │ │ │ └── PluginHook.java │ │ ├── inventory/ │ │ │ ├── InventoryBuilder.java │ │ │ ├── InventoryUtil.java │ │ │ ├── ItemBuilder.java │ │ │ ├── ItemUtil.java │ │ │ └── Slots.java │ │ ├── io/ │ │ │ └── FileUtil.java │ │ ├── json/ │ │ │ ├── DefaultBasedDeserializer.java │ │ │ └── JsonUtil.java │ │ ├── metadata/ │ │ │ └── MetadataUtil.java │ │ ├── reflect/ │ │ │ └── ReflectionUtil.java │ │ └── yaml/ │ │ └── YamlUtil.java │ └── resources/ │ ├── config.yml │ ├── lang.yml │ └── plugin.yml ├── duels-worldguard/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── me/ │ └── realized/ │ └── duels/ │ └── hook/ │ └── hooks/ │ └── worldguard/ │ └── WorldGuardHandler.java ├── duels-worldguard-v6/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── me/ │ └── realized/ │ └── duels/ │ └── hook/ │ └── hooks/ │ └── worldguard/ │ └── WorldGuard6Handler.java ├── duels-worldguard-v7/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── me/ │ └── realized/ │ └── duels/ │ └── hook/ │ └── hooks/ │ └── worldguard/ │ └── WorldGuard7Handler.java ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── libs/ │ ├── BountyHunters-2.2.6.jar │ ├── CombatTagPlus.jar │ ├── Factions-1.6.9.5-U0.1.14.jar │ ├── Factions.jar │ ├── LeaderHeadsAPI.jar │ ├── MVdWPlaceholderAPI-3.1.1.jar │ ├── MassiveCore.jar │ ├── MyPet-2.3.4.jar │ ├── PvPManager-3.7.16.jar │ ├── SimpleClans-2.14.4.1.jar │ └── Vault-1.6.7.jar └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store .gradle/ .idea/ build/ out/ ================================================ FILE: LICENSE.md ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Duels

[![](https://jitpack.io/v/Realizedd/Duels.svg)](https://jitpack.io/#Realizedd/Duels) A duel plugin for spigot. Spigot Project Page --- * **[Wiki](https://github.com/Realizedd/Duels/wiki)** * **[Commands](https://github.com/Realizedd/Duels/wiki/commands)** * **[Permissions](https://github.com/Realizedd/Duels/wiki/permissions)** * **[Placeholders](https://github.com/Realizedd/Duels/wiki/placeholders)** * **[Extensions](https://github.com/Realizedd/Duels/wiki/extensions)** * **[config.yml](https://github.com/Realizedd/Duels/blob/master/duels-plugin/src/main/resources/config.yml)** * **[lang.yml](https://github.com/Realizedd/Duels/blob/master/duels-plugin/src/main/resources/lang.yml)** * **[Support Discord](https://discord.gg/RNy45sg)** ### Getting the dependency #### Repository Gradle: ```groovy maven { name 'jitpack-repo' url 'https://jitpack.io' } ``` Maven: ```xml jitpack-repo https://jitpack.io ``` #### Dependency Gradle: ```groovy compile group: 'com.github.Realizedd.Duels', name: 'duels-api', version: '3.5.1' ``` Maven: ```xml com.github.Realizedd.Duels duels-api 3.5.1 provided ``` ### plugin.yml Add Duels as a soft-depend to ensure Duels is fully loaded before your plugin. ```yaml soft-depend: [Duels] ``` ### Getting the API instance ```java @Override public void onEnable() { Duels api = (Duels) Bukkit.getServer().getPluginManager().getPlugin("Duels"); } ``` ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() gradlePluginPortal() } dependencies { classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.4' } } allprojects { group 'me.realized' version '3.5.3' } subprojects { apply plugin: 'java' apply plugin: 'java-library' apply plugin: 'com.github.johnrengelman.shadow' apply plugin: 'maven-publish' sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() maven { name 'spigot-repo' url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } maven { name 'bungeecord-repo' url 'https://oss.sonatype.org/content/repositories/snapshots/' } maven { name 'mojang-repo' url 'https://libraries.minecraft.net/' } maven { name 'clip-repo' url 'https://repo.extendedclip.com/content/repositories/placeholderapi/' } maven { name 'enginehub-repo' url 'https://maven.enginehub.org/repo/' } maven { name 'codemc-repo' url 'https://repo.codemc.io/repository/maven-public/' } maven { name 'essentialsx-repo' url 'https://repo.essentialsx.net/releases/' } flatDir { dirs "$rootDir/libs/" } } } ================================================ FILE: duels-api/build.gradle ================================================ dependencies { compileOnly 'org.jetbrains:annotations-java5:22.0.0' implementation 'org.spigotmc:spigot-api:1.14.4-R0.1-SNAPSHOT' } publishing { publications { maven(MavenPublication) { groupId = project.group.toString() artifactId = project.name.toLowerCase() version = project.version from components.java } } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/Duels.java ================================================ package me.realized.duels.api; import me.realized.duels.api.arena.ArenaManager; import me.realized.duels.api.command.SubCommand; import me.realized.duels.api.kit.KitManager; import me.realized.duels.api.queue.DQueueManager; import me.realized.duels.api.queue.sign.QueueSignManager; import me.realized.duels.api.spectate.SpectateManager; import me.realized.duels.api.user.UserManager; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; public interface Duels extends Plugin { /** * Gets the UserManager singleton used by Duels. * * @return UserManager singleton */ @NotNull UserManager getUserManager(); /** * Gets the ArenaManager singleton used by Duels. * * @return ArenaManager singleton */ @NotNull ArenaManager getArenaManager(); /** * Gets the KitManager singleton used by Duels. * * @return KitManager singleton */ @NotNull KitManager getKitManager(); /** * Gets the SpectateManager singleton used by Duels. * * @return SpectateManager singleton * @since 3.4.1 */ @NotNull SpectateManager getSpectateManager(); /** * Gets the DQueueManager singleton used by Duels. * * @return DQueueManager singleton */ @NotNull DQueueManager getQueueManager(); /** * Gets the QueueSignManager singleton used by Duels. * * @return QueueSignManager singleton */ @NotNull QueueSignManager getQueueSignManager(); /** * Registers a {@link SubCommand} to a Command registered by Duels. * * @param command Name of the parent command to register the {@link SubCommand}. * @param subCommand {@link SubCommand} to register. * @return True if sub command was successfully registered. False otherwise. */ boolean registerSubCommand(@NotNull final String command, @NotNull final SubCommand subCommand); /** * Registers a {@link Listener} that will be automatically unregistered on unload of Duels. * * @param listener {@link Listener} to register. * @since 3.1.2 */ void registerListener(@NotNull final Listener listener); /** * Reloads the plugin. * * @return True if reload was successful. False otherwise. */ boolean reload(); /** * Runs the task on server thread. * * @param task Task to run. * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doSync(@NotNull final Runnable task); /** * Runs the task after delay on server thread. * * @param task Task to run. * @param delay time to delay. 20L = 1s * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doSyncAfter(@NotNull final Runnable task, long delay); /** * Runs the task after delay on server thread repeatedly. * * @param task Task to run. * @param delay time to delay the start of repeat. 20L = 1s * @param interval interval of this task. 20L = 1s * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doSyncRepeat(@NotNull final Runnable task, long delay, long interval); /** * Runs the task asynchronously. * * @param task Task to run asynchronously. * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doAsync(@NotNull final Runnable task); /** * Runs the task after delay asynchronously. * * @param task Task to run asynchronously. * @param delay time to delay. 20L = 1s * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doAsyncAfter(@NotNull final Runnable task, long delay); /** * Runs the task after delay asynchronously repeatedly. * * @param task Task to run asynchronously. * @param delay time to delay the start of repeat. 20L = 1s * @param interval interval of this task. 20L = 1s * @return BukkitTask executed. * @since 3.1.0 */ BukkitTask doAsyncRepeat(@NotNull final Runnable task, long delay, long interval); /** * Cancels the task if not already cancelled. * * @param task Task to cancel if not already cancelled. * @since 3.2.0 */ void cancelTask(@NotNull final BukkitTask task); /** * Cancels a task with id if found and running. * * @param id Id of the task to cancel. * @since 3.2.0 */ void cancelTask(final int id); /** * Logs a message with {@link java.util.logging.Level#INFO}. * * @param message message to log. * @since 3.1.0 */ void info(@NotNull final String message); /** * Logs a message with {@link java.util.logging.Level#WARNING}. * * @param message message to log. * @since 3.1.0 */ void warn(@NotNull final String message); /** * Logs a message with {@link java.util.logging.Level#SEVERE}. * * @param message message to log. * @since 3.1.0 */ void error(@NotNull final String message); /** * Logs a message and the {@link Throwable} provided with {@link java.util.logging.Level#SEVERE}. * * @param message message to log. * @param thrown {@link Throwable} to log. * @since 3.1.0 */ void error(@NotNull final String message, @NotNull Throwable thrown); /** * Current plugin version. * * @return version of the plugin. * @since 3.1.0 */ String getVersion(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/arena/Arena.java ================================================ package me.realized.duels.api.arena; import me.realized.duels.api.event.arena.ArenaRemoveEvent; import me.realized.duels.api.event.arena.ArenaSetPositionEvent; import me.realized.duels.api.event.arena.ArenaStateChangeEvent; import me.realized.duels.api.match.Match; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an Arena loaded on the server. */ public interface Arena { /** * The name of this arena. Will not contain a dash character ("-"). * * @return Never-null {@link String} that is the name of this arena. */ @NotNull String getName(); /** * Whether or not this arena is currently disabled. * * @return True if this arena is disabled. False otherwise. * @see #setDisabled(CommandSender, boolean) */ boolean isDisabled(); /** * Disables this arena which prevents it from being used in duels. * Note: Calls {@link ArenaStateChangeEvent}. * * @param source {@link CommandSender} that will be the source of the {@link ArenaStateChangeEvent} called. May be null! * @param disabled True to disable the arena, False to enable. * @return True if arena was disabled successfully. False if called {@link ArenaStateChangeEvent} was cancelled by a plugin. */ boolean setDisabled(@Nullable final CommandSender source, final boolean disabled); /** * Calls {@link #setDisabled(CommandSender, boolean)} with the source being null. * * @return True if arena was disabled successfully. False if called {@link ArenaStateChangeEvent} was cancelled by a plugin. * @see #setDisabled(CommandSender, boolean) */ boolean setDisabled(final boolean disabled); /** * The spawnpoint set for the position number. * * @param pos Position number associated with the spawnpoint * @return {@link Location} associated with the position number or null if position is unset. */ @Nullable Location getPosition(final int pos); /** * Sets a spawnpoint with the given position and location. * Note: Calls {@link ArenaSetPositionEvent}. * * @param source {@link Player} that will be the source of the {@link ArenaSetPositionEvent} called. May be null! * @param pos Position number for the spawnpoint. * @param location Location to be the spawnpoint. Should not be null! * @return True if the spawnpoint was set successfully. False if called {@link ArenaSetPositionEvent} was cancelled by a plugin. */ boolean setPosition(@Nullable final Player source, final int pos, @NotNull final Location location); /** * Calls {@link #setPosition(Player, int, Location)} with the source being null. * * @return True if the spawnpoint was set successfully. False if called {@link ArenaSetPositionEvent} was cancelled by a plugin. * @see #setPosition(Player, int, Location) */ boolean setPosition(final int pos, @NotNull final Location location); /** * Whether or not a duel is currently being played in this arena. If returned true, {@link #getMatch()} is guaranteed to return a {@link Match} instance. * * @return True if this arena is in use. False otherwise. */ boolean isUsed(); /** * The {@link Match} being played in this arena. May be null if no match is being played. * * @return {@link Match} instance if a duel is currently being played in this arena. null otherwise. */ @Nullable Match getMatch(); /** * Whether or not the player is playing in this arena. * * @param player {@link Player} to check if in this arena. Should not be null! * @return True if the player is in this arena. False otherwise. */ boolean has(@NotNull final Player player); /** * Whether or not this {@link Arena} has been removed. * * @return True if this {@link Arena} has been removed. False otherwise. * @see ArenaRemoveEvent * @since 3.2.0 */ boolean isRemoved(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/arena/ArenaManager.java ================================================ package me.realized.duels.api.arena; import java.util.List; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the ArenaManager singleton used by Duels. */ public interface ArenaManager { /** * Attempts to find an {@link Arena} instance associated with the given name. * * @param name Name to search through the loaded arenas. Should not be null! * @return {@link Arena} instance that has a name matching with the given name or null if not exists. */ @Nullable Arena get(@NotNull final String name); /** * Attempts to find an {@link Arena} instance that contains the player. * * @param player Player to search through the loaded arenas. Should not be null! * @return {@link Arena} instance that contains the player or null if not exists. */ @Nullable Arena get(@NotNull final Player player); /** * Whether or not the given player is in a match. If returned true, {@link #get(Player)} is guaranteed to return a {@link Arena} instance. * * @param player Player to check if in match. Should not be null! * @return True if player was in a match. False otherwise. */ boolean isInMatch(@NotNull final Player player); /** * An UnmodifiableList of {@link Arena}s that are currently loaded. * * @return Never-null UnmodifiableList of {@link Arena}s that are currently loaded. * @since 3.4.0 */ @NotNull List getArenas(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/command/SubCommand.java ================================================ package me.realized.duels.api.command; import java.util.Objects; import me.realized.duels.api.Duels; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * An abstract SubCommand class that hooks into commands registered by Duels. * * @see Duels#registerSubCommand(String, SubCommand) */ public abstract class SubCommand { private final String name, usage, description, permission; private final boolean playerOnly; private final int length; private final String[] aliases; /** * The constructor for a subcommand. * * @param name Name of this subcommand. Should not be null! * @param usage Usage of this subcommand. May be null. * @param description Description of this subcommand. May be null. * @param permission Permission of this subcommand. May be null. * @param playerOnly Whether or not this subcommand should be player only. * @param length Length of this subcommand. Must be greater than or equal to 1. * @param aliases Aliases of this subcommand. */ public SubCommand(@NotNull final String name, @Nullable final String usage, @Nullable final String description, @Nullable final String permission, final boolean playerOnly, final int length, final String... aliases) { Objects.requireNonNull(name, "name"); this.name = name; this.usage = usage; this.description = description; this.permission = permission; this.playerOnly = playerOnly; this.length = Math.max(length, 1); this.aliases = aliases; } /** * The name of this subcommand. * * @return Never-null {@link String} that is the name of this subcommand. */ public String getName() { return name; } /** * The usage of this subcommand. * * @return Usage of this subcommand or null if unspecified. */ public String getUsage() { return usage; } /** * The description of this subcommand. * * @return Description of this subcommand or null if unspecified. */ public String getDescription() { return description; } /** * The permission of this subcommand. If set to null, it will inherit its parent's permission. * * @return Permission of this subcommand or null if unspecified. */ public String getPermission() { return permission; } /** * Whether or not this subcommand can only be used by a player. If the parent of this subcommand is player only, this value will not be considered. * * @return True if this subcommand is player only. False otherwise. */ public boolean isPlayerOnly() { return playerOnly; } /** * The length of this subcommand. * * @return Length of this subcommand. */ public int getLength() { return length; } /** * The aliases of this subcommand. * * @return Aliases of this subcommand. */ public String[] getAliases() { return aliases; } public abstract void execute(final CommandSender sender, final String label, final String[] args); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/SourcedEvent.java ================================================ package me.realized.duels.api.event; import org.bukkit.command.CommandSender; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; /** * Represents an event that may have a source. */ public abstract class SourcedEvent extends Event { private final CommandSender source; protected SourcedEvent(@Nullable final CommandSender source) { this.source = source; } /** * Source of this event. May be null! * * @return {@link CommandSender} that is the source of this event or null. */ @Nullable public CommandSender getSource() { return source; } /** * Whether or not this event has a source specified. * * @return True if there was a source specified. False otherwise. */ public boolean hasSource() { return getSource() != null; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/arena/ArenaCreateEvent.java ================================================ package me.realized.duels.api.event.arena; import me.realized.duels.api.arena.Arena; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a new {@link Arena} is created. */ public class ArenaCreateEvent extends ArenaEvent { private static final HandlerList handlers = new HandlerList(); public ArenaCreateEvent(@Nullable final CommandSender source, @NotNull final Arena arena) { super(source, arena); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/arena/ArenaEvent.java ================================================ package me.realized.duels.api.event.arena; import java.util.Objects; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.event.SourcedEvent; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an event caused by a {@link Arena}. */ public abstract class ArenaEvent extends SourcedEvent { private final Arena arena; ArenaEvent(@Nullable final CommandSender source, @NotNull final Arena arena) { super(source); Objects.requireNonNull(arena, "arena"); this.arena = arena; } /** * {@link Arena} instance associated with this event. * * @return Never-null {@link Arena} instance associated with this event. */ @NotNull public Arena getArena() { return arena; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/arena/ArenaRemoveEvent.java ================================================ package me.realized.duels.api.event.arena; import me.realized.duels.api.arena.Arena; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when an {@link Arena} is removed. * * @see Arena#isRemoved() */ public class ArenaRemoveEvent extends ArenaEvent { private static final HandlerList handlers = new HandlerList(); public ArenaRemoveEvent(@Nullable final CommandSender source, @NotNull final Arena arena) { super(source, arena); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/arena/ArenaSetPositionEvent.java ================================================ package me.realized.duels.api.event.arena; import java.util.Objects; import me.realized.duels.api.arena.Arena; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a new spawnpoint is set for an {@link Arena}. * * @see Arena#setPosition(Player, int, Location) */ public class ArenaSetPositionEvent extends ArenaEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private int pos; private Location location; private boolean cancelled; public ArenaSetPositionEvent(@Nullable final CommandSender source, @NotNull final Arena arena, final int pos, @NotNull final Location location) { super(source, arena); Objects.requireNonNull(location, "location"); this.pos = pos; this.location = location; } /** * The position number of the spawnpoint set. * * @return position number of the spawnpoint set. */ public int getPos() { return pos; } /** * Sets a new position number for the spawnpoint. * * @param pos New position number for the spawnpoint set. */ public void setPos(final int pos) { this.pos = pos; } /** * The location of the spawnpoint set. * * @return location of the spawnpoint set. */ public Location getLocation() { return location; } /** * Sets a new location for the spawnpoint. * * @param location New location for the spawnpoint set. */ public void setLocation(final Location location) { this.location = location; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/arena/ArenaStateChangeEvent.java ================================================ package me.realized.duels.api.event.arena; import me.realized.duels.api.arena.Arena; import org.bukkit.command.CommandSender; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when an {@link Arena} is enabled or disabled. * * @see Arena#setDisabled(CommandSender, boolean) */ public class ArenaStateChangeEvent extends ArenaEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean disabled; private boolean cancelled; public ArenaStateChangeEvent(@Nullable final CommandSender source, @NotNull final Arena arena, final boolean disabled) { super(source, arena); this.disabled = disabled; } /** * Whether or not the {@link Arena} is disabling. * * @return True if the {@link Arena} will be disabled. False otherwise. */ public boolean isDisabled() { return disabled; } /** * Sets a new state for the {@link Arena}. * * @param disabled True to disable the {@link Arena}. False to enable. */ public void setDisabled(final boolean disabled) { this.disabled = disabled; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/kit/KitCreateEvent.java ================================================ package me.realized.duels.api.event.kit; import java.util.Objects; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.kit.KitManager; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Kit} is created. * * @see KitManager#create(Player, String) */ public class KitCreateEvent extends KitEvent { private static final HandlerList handlers = new HandlerList(); private final Player source; public KitCreateEvent(@NotNull final Player source, @NotNull final Kit kit) { super(source, kit); Objects.requireNonNull(source, "source"); this.source = source; } @NotNull @Override public Player getSource() { return source; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/kit/KitEquipEvent.java ================================================ package me.realized.duels.api.event.kit; import java.util.Objects; import me.realized.duels.api.kit.Kit; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Player} equips a {@link Kit}. * * @see Kit#equip(Player) */ public class KitEquipEvent extends KitEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Player source; private boolean cancelled; public KitEquipEvent(@NotNull final Player source, @NotNull final Kit kit) { super(source, kit); Objects.requireNonNull(source, "source"); this.source = source; } /** * {@link Player} who is equipping the {@link Kit}. * * @return Never-null {@link Player} who is equipping the {@link Kit}. */ @NotNull @Override public Player getSource() { return source; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/kit/KitEvent.java ================================================ package me.realized.duels.api.event.kit; import java.util.Objects; import me.realized.duels.api.event.SourcedEvent; import me.realized.duels.api.kit.Kit; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an event caused by a {@link Kit}. */ public abstract class KitEvent extends SourcedEvent { private final Kit kit; KitEvent(@Nullable final CommandSender source, @NotNull final Kit kit) { super(source); Objects.requireNonNull(kit, "kit"); this.kit = kit; } /** * {@link Kit} instance associated with this event. * * @return Never-null {@link Kit} instance associated with this event. */ @NotNull public Kit getKit() { return kit; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/kit/KitRemoveEvent.java ================================================ package me.realized.duels.api.event.kit; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.kit.KitManager; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a {@link Kit} is removed. * * @see KitManager#remove(CommandSender, String) * @see Kit#isRemoved() */ public class KitRemoveEvent extends KitEvent { private static final HandlerList handlers = new HandlerList(); public KitRemoveEvent(@Nullable final CommandSender source, @NotNull final Kit kit) { super(source, kit); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/match/MatchEndEvent.java ================================================ package me.realized.duels.api.event.match; import java.util.Objects; import java.util.UUID; import me.realized.duels.api.match.Match; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a {@link Match} is ending. * * Note: {@link Match#isFinished()} will return true only after this event is called. */ public class MatchEndEvent extends MatchEvent { private static final HandlerList handlers = new HandlerList(); private final UUID winner, loser; private final Reason reason; public MatchEndEvent(@NotNull final Match match, @Nullable final UUID winner, @Nullable final UUID loser, @NotNull final Reason reason) { super(match); Objects.requireNonNull(reason, "reason"); this.winner = winner; this.loser = loser; this.reason = reason; } /** * Winner of the {@link Match}. May be null if there was a no winner! * * @return {@link UUID} of the winner of the {@link Match}. May be null if there was a no winner! */ @Nullable public UUID getWinner() { return winner; } /** * Loser of the {@link Match}. May be null if there was a no loser! * * @return {@link UUID} of the loser of the {@link Match}. May be null if there was a no loser! */ @Nullable public UUID getLoser() { return loser; } /** * End reason of the {@link Match}. If reason is {@link Reason#OPPONENT_DEFEAT}, {@link #getWinner()} and {@link #getLoser()} is guaranteed to not return null. * * @return {@link Reason} that is the end reason of the {@link Match}. */ @NotNull public Reason getReason() { return reason; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } public enum Reason { OPPONENT_DEFEAT, TIE, MAX_TIME_REACHED, PLUGIN_DISABLE, OTHER } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/match/MatchEvent.java ================================================ package me.realized.duels.api.event.match; import java.util.Objects; import me.realized.duels.api.match.Match; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; /** * Represents an event caused by a {@link Match}. */ public abstract class MatchEvent extends Event { private final Match match; MatchEvent(@NotNull final Match match) { Objects.requireNonNull(match, "match"); this.match = match; } /** * {@link Match} instance associated with this event. * * @return Never-null {@link Match} instance associated with this event. */ public Match getMatch() { return match; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/match/MatchStartEvent.java ================================================ package me.realized.duels.api.event.match; import java.util.Objects; import me.realized.duels.api.match.Match; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Match} has started. */ public class MatchStartEvent extends MatchEvent { private static final HandlerList handlers = new HandlerList(); private final Player[] players; public MatchStartEvent(@NotNull final Match match, @NotNull final Player... players) { super(match); Objects.requireNonNull(players, "players"); this.players = players; } /** * The starters of the {@link Match}. * * @return Never-null {@link Player} array representing the starters of the {@link Match}. */ @NotNull public Player[] getPlayers() { return players; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/QueueCreateEvent.java ================================================ package me.realized.duels.api.event.queue; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.queue.DQueue; import me.realized.duels.api.queue.DQueueManager; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a {@link DQueue} is created. * * @see DQueueManager#create(CommandSender, Kit, int) */ public class QueueCreateEvent extends QueueEvent { private static final HandlerList handlers = new HandlerList(); public QueueCreateEvent(@Nullable final CommandSender source, @NotNull final DQueue queue) { super(source, queue); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/QueueEvent.java ================================================ package me.realized.duels.api.event.queue; import java.util.Objects; import me.realized.duels.api.event.SourcedEvent; import me.realized.duels.api.queue.DQueue; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an event caused by a {@link DQueue}. * * @since 3.2.0 */ public abstract class QueueEvent extends SourcedEvent { private final DQueue queue; QueueEvent(@Nullable final CommandSender source, @NotNull final DQueue queue) { super(source); Objects.requireNonNull(queue, "queue"); this.queue = queue; } /** * {@link DQueue} instance associated with this event. * * @return Never-null {@link DQueue} instance associated with this event. */ @NotNull public DQueue getQueue() { return queue; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/QueueJoinEvent.java ================================================ package me.realized.duels.api.event.queue; import java.util.Objects; import me.realized.duels.api.queue.DQueue; import me.realized.duels.api.queue.DQueueManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a player is joining a {@link DQueue}. * * @see DQueueManager#addToQueue(Player, DQueue) * @since 3.2.0 */ public class QueueJoinEvent extends QueueEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Player source; private boolean cancelled; public QueueJoinEvent(@NotNull final Player source, @NotNull final DQueue queue) { super(source, queue); Objects.requireNonNull(source, "source"); this.source = source; } /** * {@link Player} who is joining the {@link DQueue}. * * @return Never-null {@link Player} who is joining the {@link DQueue}. */ @NotNull @Override public Player getSource() { return source; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/QueueLeaveEvent.java ================================================ package me.realized.duels.api.event.queue; import java.util.Objects; import me.realized.duels.api.queue.DQueue; import me.realized.duels.api.queue.DQueueManager; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a player is leaving a {@link DQueue}. * * @see DQueueManager#removeFromQueue(Player) * @since 3.2.0 */ public class QueueLeaveEvent extends QueueEvent { private static final HandlerList handlers = new HandlerList(); private final Player source; public QueueLeaveEvent(@NotNull final Player source, @NotNull final DQueue queue) { super(source, queue); Objects.requireNonNull(source, "source"); this.source = source; } /** * {@link Player} who is leaving the {@link DQueue}. * * @return Never-null {@link Player} who is leaving the {@link DQueue}. */ @NotNull @Override public Player getSource() { return source; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/QueueRemoveEvent.java ================================================ package me.realized.duels.api.event.queue; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.queue.DQueue; import me.realized.duels.api.queue.DQueueManager; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a {@link DQueue} is removed. * * @see DQueueManager#remove(CommandSender, Kit, int) * @see DQueue#isRemoved() * @since 3.2.0 */ public class QueueRemoveEvent extends QueueEvent { private static final HandlerList handlers = new HandlerList(); public QueueRemoveEvent(@Nullable final CommandSender source, @NotNull final DQueue queue) { super(source, queue); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/sign/QueueSignCreateEvent.java ================================================ package me.realized.duels.api.event.queue.sign; import me.realized.duels.api.queue.sign.QueueSign; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link QueueSign} is created. * * @since 3.2.0 */ public class QueueSignCreateEvent extends QueueSignEvent { private static final HandlerList handlers = new HandlerList(); public QueueSignCreateEvent(@NotNull final Player source, @NotNull final QueueSign queueSign) { super(source, queueSign); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/sign/QueueSignEvent.java ================================================ package me.realized.duels.api.event.queue.sign; import java.util.Objects; import me.realized.duels.api.event.SourcedEvent; import me.realized.duels.api.queue.sign.QueueSign; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; /** * Represents an event caused by a {@link QueueSign}. * * @since 3.2.0 */ public abstract class QueueSignEvent extends SourcedEvent { private final Player source; private final QueueSign queueSign; QueueSignEvent(@NotNull final Player source, @NotNull final QueueSign queueSign) { super(source); Objects.requireNonNull(source, "source"); Objects.requireNonNull(queueSign, "queueSign"); this.source = source; this.queueSign = queueSign; } /** * {@link Player} who is the source of this event. * * @return Never-null {@link Player} who is the source of this event. */ @NotNull @Override public Player getSource() { return source; } /** * {@link QueueSign} instance associated with this event. * * @return Never-null {@link QueueSign} instance associated with this event. */ @NotNull public QueueSign getQueueSign() { return queueSign; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/queue/sign/QueueSignRemoveEvent.java ================================================ package me.realized.duels.api.event.queue.sign; import me.realized.duels.api.queue.sign.QueueSign; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link QueueSign} is removed. * * @see QueueSign#isRemoved() * @since 3.2.0 */ public class QueueSignRemoveEvent extends QueueSignEvent { private static final HandlerList handlers = new HandlerList(); public QueueSignRemoveEvent(@NotNull final Player source, @NotNull final QueueSign queueSign) { super(source, queueSign); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/request/RequestAcceptEvent.java ================================================ package me.realized.duels.api.event.request; import me.realized.duels.api.request.Request; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Player} accepts a {@link Request} from a {@link Player}. * * @since 3.2.1 */ public class RequestAcceptEvent extends RequestEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; /** * @param source {@link Player} who is accepting this {@link Request}. * @param target {@link Player} who sent this {@link Request}. * @param request {@link Request} that is being handled. */ public RequestAcceptEvent(@NotNull final Player source, @NotNull final Player target, @NotNull final Request request) { super(source, target, request); } /** * Whether or not this event has been cancelled. * * @return True if this event has been cancelled. False otherwise. */ @Override public boolean isCancelled() { return cancelled; } /** * Whether or not to cancel this event. * When cancelled, the request will not be removed and remain as unhandled. * * @param cancelled True to cancel this event. */ @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/request/RequestDenyEvent.java ================================================ package me.realized.duels.api.event.request; import me.realized.duels.api.request.Request; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Player} denies a {@link Request} from a {@link Player}. * * @since 3.2.1 */ public class RequestDenyEvent extends RequestEvent { private static final HandlerList handlers = new HandlerList(); /** * @param source {@link Player} who is denying this {@link Request}. * @param target {@link Player} who sent this {@link Request}. * @param request {@link Request} that is being handled. */ public RequestDenyEvent(@NotNull final Player source, @NotNull final Player target, @NotNull final Request request) { super(source, target, request); } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/request/RequestEvent.java ================================================ package me.realized.duels.api.event.request; import java.util.Objects; import me.realized.duels.api.event.SourcedEvent; import me.realized.duels.api.request.Request; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; /** * Represents an event caused by a {@link Request}. * * @since 3.2.1 */ public abstract class RequestEvent extends SourcedEvent { private final Player source, target; private final Request request; RequestEvent(@NotNull final Player source, @NotNull final Player target, @NotNull final Request request) { super(source); Objects.requireNonNull(source, "source"); Objects.requireNonNull(target, "target"); Objects.requireNonNull(request, "request"); this.source = source; this.target = target; this.request = request; } /** * {@link Player} who is the source of this event. * * @return Never-null {@link Player} who is the source of this event. */ @NotNull @Override public Player getSource() { return source; } /** * {@link Player} who is the target of this event. * * @return Never-null {@link Player} who is the target of this event. */ @NotNull public Player getTarget() { return target; } /** * {@link Request} instance associated with this event. * * @return Never-null {@link Request} instance associated with this event. */ @NotNull public Request getRequest() { return request; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/request/RequestSendEvent.java ================================================ package me.realized.duels.api.event.request; import me.realized.duels.api.request.Request; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a {@link Player} sends a {@link Request} to a {@link Player}. */ public class RequestSendEvent extends RequestEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; public RequestSendEvent(@NotNull final Player source, @NotNull final Player target, @NotNull final Request request) { super(source, target, request); } /** * Whether or not this event has been cancelled. * * @return True if this event has been cancelled. False otherwise. */ @Override public boolean isCancelled() { return cancelled; } /** * Whether or not to cancel this event. * * @param cancelled True to cancel this event. */ @Override public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/spectate/SpectateEndEvent.java ================================================ package me.realized.duels.api.event.spectate; import me.realized.duels.api.spectate.Spectator; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called before a player stops spectating. */ public class SpectateEndEvent extends SpectateEvent { private static final HandlerList handlers = new HandlerList(); public SpectateEndEvent(@NotNull final Player source, @NotNull final Spectator spectator) { super(source, spectator); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/spectate/SpectateEvent.java ================================================ package me.realized.duels.api.event.spectate; import java.util.Objects; import me.realized.duels.api.event.SourcedEvent; import me.realized.duels.api.spectate.Spectator; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; /** * Represents an event caused by a {@link Spectator}. */ public abstract class SpectateEvent extends SourcedEvent { private final Player source; private final Spectator spectator; SpectateEvent(@NotNull final Player source, @NotNull Spectator spectator) { super(source); Objects.requireNonNull(source, "source"); Objects.requireNonNull(spectator, "spectator"); this.source = source; this.spectator = spectator; } @NotNull @Override public Player getSource() { return source; } /** * {@link Spectator} instance associated with this event. * * @return Never-null {@link Spectator} instance associated with this event. */ @NotNull public Spectator getSpectator() { return spectator; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/spectate/SpectateStartEvent.java ================================================ package me.realized.duels.api.event.spectate; import me.realized.duels.api.spectate.Spectator; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called before a player starts spectating. */ public class SpectateStartEvent extends SpectateEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; public SpectateStartEvent(@NotNull final Player source, @NotNull final Spectator spectator) { super(source, spectator); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(final boolean cancel) { this.cancelled = cancel; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/event/user/UserCreateEvent.java ================================================ package me.realized.duels.api.event.user; import java.util.Objects; import me.realized.duels.api.user.User; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; /** * Called when a new {@link User} is created. */ public class UserCreateEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final User user; public UserCreateEvent(@NotNull final User user) { Objects.requireNonNull(user, "user"); this.user = user; } /** * The {@link User} that was created. * * @return Never-null {@link User} that was created. */ @NotNull public User getUser() { return user; } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/extension/DuelsExtension.java ================================================ package me.realized.duels.api.extension; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Objects; import me.realized.duels.api.Duels; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class DuelsExtension { protected Duels api; private String name; private File folder; private File file; private File dataFolder; private boolean enabled; private File configFile; private FileConfiguration config; final void init(final Duels api, final String name, final File folder, final File file) { this.api = api; this.name = name; this.folder = folder; this.file = file; this.dataFolder = new File(folder, name); this.configFile = new File(dataFolder, "config.yml"); } @NotNull public Duels getApi() { return api; } @NotNull public final String getName() { return name; } @NotNull public File getFolder() { return folder; } @NotNull public File getFile() { return file; } @NotNull public File getDataFolder() { return dataFolder; } public boolean isEnabled() { return enabled; } public final void setEnabled(final boolean enabled) { if (this.enabled == enabled) { return; } if (enabled) { onEnable(); } else { onDisable(); } this.enabled = enabled; } public void saveResource(@NotNull String resourcePath) { Objects.requireNonNull(resourcePath, "resourcePath"); resourcePath = resourcePath.replace('\\', '/'); try (InputStream in = getResource(resourcePath)) { if (in == null) { throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + file); } if (!dataFolder.exists()) { dataFolder.mkdir(); } final File outFile = new File(dataFolder, resourcePath); int lastIndex = resourcePath.lastIndexOf('/'); File outDir = new File(dataFolder, resourcePath.substring(0, Math.max(lastIndex, 0))); if (!outDir.exists()) { outDir.mkdirs(); } try (OutputStream out = new FileOutputStream(outFile)) { final byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } catch (IOException ex) { api.error("Could not save resource '" + resourcePath + "'", ex); } } @Nullable public InputStream getResource(@NotNull final String filename) { Objects.requireNonNull(filename, "filename"); try { final URL url = getClass().getClassLoader().getResource(filename); if (url == null) { return null; } final URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException ex) { api.error("Could not find resource with filename '" + filename + "'", ex); return null; } } public FileConfiguration getConfig() { if (config == null) { reloadConfig(); } return config; } public void reloadConfig() { if (!configFile.exists()) { saveResource("config.yml"); } config = YamlConfiguration.loadConfiguration(configFile); } public void saveConfig() { try { getConfig().save(configFile); } catch (IOException ex) { api.error("Failed to save config", ex); } } public void onEnable() {} public void onDisable() {} /** * @return The version of Duels that this extension requires in order to enable. * * @deprecated As of v3.2.0. Specify 'api-version' in extension.yml instead. */ @Deprecated @Nullable public String getRequiredVersion() { return null; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/kit/Kit.java ================================================ package me.realized.duels.api.kit; import me.realized.duels.api.event.kit.KitEquipEvent; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; /** * Represents an Kit loaded on the server. */ public interface Kit { /** * The name of this kit. Will not contain a dash character ("-"). * * @return Never-null {@link String} that is the name of this kit. */ @NotNull String getName(); /** * The item displayed in the kit selector gui. * * @return item displayed in the kit selector gui. */ @NotNull ItemStack getDisplayed(); /** * Whether or not this kit requires a permission. * If usePermission is enabled, players must have the permission 'duels.kit.[name] (space in name replaced to dash)' to use the kit. * * @return True if usePermission is enabled for this kit. False otherwise. */ boolean isUsePermission(); /** * Enables or disables usePermission for this kit. * * @param usePermission True to enable usePermission. False otherwise. */ void setUsePermission(final boolean usePermission); /** * Whether or not this kit has arenaSpecific enabled. * If arenaSpecific is enabled, only arenas with their name starting with this kit's name appended with an underscore will be available when playing with this kit. * * @return True if arenaSpecific is enabled. False otherwise. */ boolean isArenaSpecific(); /** * Enables or disables arenaSpecific for this kit. * * @param arenaSpecific True to enable arenaSpecific. False otherwise. */ void setArenaSpecific(final boolean arenaSpecific); /** * Equips the {@link Player} with the contents of this kit. * Note: Calls {@link KitEquipEvent}. * * @param player {@link Player} to equip this kit. * @return True if {@link Player} has successfully equipped this kit. False otherwise. */ boolean equip(@NotNull final Player player); /** * Whether or not this {@link Kit} has been removed. * * @return True if this {@link Kit} has been removed. False otherwise. * @see KitManager#remove(CommandSender, String) * @since 3.2.0 */ boolean isRemoved(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/kit/KitManager.java ================================================ package me.realized.duels.api.kit; import java.util.List; import me.realized.duels.api.event.kit.KitCreateEvent; import me.realized.duels.api.event.kit.KitRemoveEvent; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the KitManager singleton used by Duels. */ public interface KitManager { /** * Attempts to find an {@link Kit} instance associated with the given name. * * @param name Name to search through the loaded kits. Should not be null! * @return {@link Kit} instance that has a name matching with the given name or null if not exists. */ @Nullable Kit get(@NotNull final String name); /** * Creates a kit with given name and {@link Player}'s inventory contents. * Note: Calls {@link KitCreateEvent} on successful creation. * * @param creator {@link Player} who is the creator of this kit. * @param name Name of the newly created {@link Kit}. Requires to be alphanumeric (underscore is allowed). * @return The newly created {@link Kit} or null if a kit with given name already exists. */ @Nullable Kit create(@NotNull final Player creator, @NotNull final String name); /** * Removes a kit with given name. * Note: Calls {@link KitRemoveEvent} on successful removal. * * @param source {@link CommandSender} who is the source of this call. * @param name Name of the kit to remove. * @return The removed {@link Kit} or null if no {@link Kit} was found with the given name. */ @Nullable Kit remove(@Nullable CommandSender source, @NotNull final String name); /** * Calls {@link #remove(CommandSender, String)} with source being null. * * @see #remove(CommandSender, String) */ @Nullable Kit remove(@NotNull final String name); /** * An UnmodifiableList of {@link Kit}s that are currently loaded. * * @return Never-null UnmodifiableList of {@link Kit}s that are currently loaded. * @since 3.1.0 */ @NotNull List getKits(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/match/Match.java ================================================ package me.realized.duels.api.match; import java.util.List; import java.util.Set; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.kit.Kit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an ongoing Match. */ public interface Match { /** * The {@link Arena} this {@link Match} is taking place in. * * @return {@link Arena} this {@link Match} is taking place in. */ @NotNull Arena getArena(); /** * The start of this match {@link Match} milliseconds. * Note: {@link System#currentTimeMillis()} subtracted by the result of this method will give the duration of the current {@link Match} in milliseconds. * * @return start of this match in milliseconds. */ long getStart(); /** * The {@link Kit} used in this {@link Match}. * * @return {@link Kit} used in this {@link Match} or null if players are using their own inventories. */ @Nullable Kit getKit(); /** * UnmodifiableList of ItemStacks the player has bet for this {@link Match}. * * @param player {@link Player} to get the list of bet items. * @return Never-null UnmodifiableList of ItemStacks the player has bet for this {@link Match}. */ @NotNull List getItems(@NotNull final Player player); /** * The bet amount for this {@link Match}. * * @return bet Bet amount for this {@link Match} or 0 if no bet was specified. */ int getBet(); /** * Whether or not this {@link Match} is finished. * * @return true if this {@link Match} has finished or false otherwise. * @since 3.4.1 */ boolean isFinished(); /** * UnmodifiableSet of alive players in this {@link Match}. * * @return Never-null UnmodifiableSet of alive players in this {@link Match}. * @since 3.1.0 */ @NotNull Set getPlayers(); /** * UnmodifiableSet of players who started this {@link Match}. * Note: This set includes players who are offline. If you keep a reference * to this match, all the player objects of those who started this match will * not be garbage-collected. * * @return Never-null UnmodifiableSet of players who started this {@link Match}. * @since 3.4.1 */ @NotNull Set getStartingPlayers(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/queue/DQueue.java ================================================ package me.realized.duels.api.queue; import java.util.List; import me.realized.duels.api.kit.Kit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents a Queue loaded on the server. */ public interface DQueue { /** * The {@link Kit} set for this {@link DQueue}. * * @return {@link Kit} set for this {@link DQueue} or null if no kit was set. */ @Nullable Kit getKit(); /** * The bet amount for this {@link DQueue}. * * @return Bet amount for this {@link DQueue} or 0 if no bet was specified. */ int getBet(); /** * Whether or not the given {@link Player} is in this {@link DQueue}. * * @param player Player to check if in this {@link DQueue}. Must not be null! * @return True if player is in this {@link DQueue}. False otherwise. */ boolean isInQueue(@NotNull final Player player); /** * An UnmodifiableList of {@link Player}s in this queue. * * @return Never-null UnmodifiableList of {@link Player}s in this queue. */ @NotNull List getQueuedPlayers(); /** * Whether or not this {@link DQueue} has been removed. * * @return True if this {@link DQueue} has been removed. False otherwise. * @see DQueueManager#remove(Kit, int) */ boolean isRemoved(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/queue/DQueueManager.java ================================================ package me.realized.duels.api.queue; import java.util.List; import me.realized.duels.api.event.queue.QueueCreateEvent; import me.realized.duels.api.event.queue.QueueJoinEvent; import me.realized.duels.api.event.queue.QueueLeaveEvent; import me.realized.duels.api.event.queue.QueueRemoveEvent; import me.realized.duels.api.kit.Kit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the QueueManager singleton used by Duels. * * @since 3.2.0 */ public interface DQueueManager { /** * Gets a {@link DQueue} with the given kit and bet. * * @param kit Kit to check for match in the queues. * @param bet Bet to check for match in the queues. * @return DQueue with the given kit and bet if found, otherwise null. */ @Nullable DQueue get(@Nullable final Kit kit, final int bet); /** * Gets a {@link DQueue} with the given {@link Player}. * * @param player Player to check if in queue * @return The queue player is in or null if not in queue */ @Nullable DQueue get(@NotNull final Player player); /** * Creates a new {@link DQueue}. * Note: Calls {@link QueueCreateEvent} on successful creation. * * @param kit Kit of the DQueue to create * @param bet Bet of the DQueue to create * @return The newly created DQueue or null if a queue with given kit and bet already exists */ @Nullable DQueue create(@Nullable final CommandSender source, @Nullable final Kit kit, final int bet); /** * Calls {@link #create(CommandSender, Kit, int)} with source being null. * * @see #create(CommandSender, Kit, int) */ @Nullable DQueue create(@Nullable final Kit kit, final int bet); /** * Removes a new {@link DQueue}. * Note: Calls {@link QueueRemoveEvent} on successful removal. * * @param kit Kit to check for match in the queues * @param bet Bet to check for match in the queues * @return The removed DQueue if found, otherwise null * @see DQueue#isRemoved() */ @Nullable DQueue remove(@Nullable final CommandSender source, @Nullable final Kit kit, final int bet); /** * Calls {@link #remove(CommandSender, Kit, int)} with source being null. * * @see #remove(CommandSender, Kit, int) */ @Nullable DQueue remove(@Nullable final Kit kit, final int bet); /** * Whether or not the {@link Player} is in a queue. * * @param player {@link Player} to check if in queue. * @return True if {@link Player} is in a queue. False otherwise. */ boolean isInQueue(@NotNull final Player player); /** * Adds the {@link Player} to the given {@link DQueue}. * Note: Calls {@link QueueJoinEvent}. * * @param player {@link Player} to add to {@link DQueue}. * @param queue {@link DQueue} to add the {@link Player}. * @return True if {@link Player} was successfully queued. False otherwise. */ boolean addToQueue(@NotNull final Player player, @NotNull final DQueue queue); /** * Removes the {@link Player} from the queue. * Note: Calls {@link QueueLeaveEvent} if {@link Player} was in a {@link DQueue}. * * @param player {@link Player} to remove from queue. * @return The {@link DQueue} that {@link Player} was in or null if {@link Player} was not in a queue. */ @Nullable DQueue removeFromQueue(@NotNull final Player player); /** * An UnmodifiableList of {@link DQueue}s that are currently loaded. * * @return Never-null UnmodifiableList of {@link DQueue}s that are currently loaded. */ @NotNull List getQueues(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/queue/sign/QueueSign.java ================================================ package me.realized.duels.api.queue.sign; import me.realized.duels.api.event.queue.sign.QueueSignRemoveEvent; import me.realized.duels.api.queue.DQueue; import org.bukkit.Location; import org.jetbrains.annotations.NotNull; /** * Represents a QueueSign loaded on the server. */ public interface QueueSign { /** * The {@link Location} of this {@link QueueSign}. * * @return Never-null {@link Location} of this {@link QueueSign}. */ @NotNull Location getLocation(); /** * The {@link DQueue} that is linked with this {@link QueueSign}. * * @return Never-null {@link DQueue} that is linked with this {@link QueueSign}. */ @NotNull DQueue getQueue(); /** * Whether or not this {@link QueueSign} has been removed. * * @return True if this {@link QueueSign} has been removed. False otherwise. * @see QueueSignRemoveEvent */ boolean isRemoved(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/queue/sign/QueueSignManager.java ================================================ package me.realized.duels.api.queue.sign; import java.util.List; import org.bukkit.block.Sign; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the QueueSignManager singleton used by Duels. * * @since 3.2.0 */ public interface QueueSignManager { /** * Gets a {@link QueueSign} that is associated with the given {@link Sign}. * * @param sign {@link Sign} to match in the loaded queue signs. * @return {@link QueueSign} associated with the {@link Sign} or null if not found. */ @Nullable QueueSign get(@NotNull final Sign sign); /** * An UnmodifiableList of {@link QueueSign}s that are currently loaded. * * @return Never-null UnmodifiableList of {@link QueueSign}s that are currently loaded. */ @NotNull List getQueueSigns(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/request/Request.java ================================================ package me.realized.duels.api.request; import java.util.UUID; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.kit.Kit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents a Request sent. */ public interface Request { /** * The {@link UUID} of sender of this {@link Request}. * * @return Never-null {@link UUID} of the sender of this {@link Request}. */ @NotNull UUID getSender(); /** * The {@link UUID} of the receiver of this {@link Request}. * * @return Never-null {@link UUID} of the receiver of this {@link Request}. */ @NotNull UUID getTarget(); /** * The {@link Kit} for this {@link Request} or null if no {@link Kit} was selected. * * @return {@link Kit} for this {@link Request} or null if no {@link Kit} was selected. */ @Nullable Kit getKit(); /** * The {@link Arena} for this {@link Request} or null if no {@link Arena} was selected. * * @return {@link Arena} for this {@link Request} or null if no {@link Arena} was selected. */ @Nullable Arena getArena(); /** * Whether or not item betting is enabled for this {@link Request}. * * @return True if item betting is enabled for this {@link Request}. False otherwise. */ boolean canBetItems(); /** * The bet for this {@link Request}. * * @return Bet amount for this {@link Request} or 0 if not specified. */ int getBet(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/spectate/SpectateManager.java ================================================ package me.realized.duels.api.spectate; import java.util.List; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.event.spectate.SpectateEndEvent; import me.realized.duels.api.event.spectate.SpectateStartEvent; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the SpectateManager singleton used by Duels. * * @since 3.4.1 */ public interface SpectateManager { /** * Attempts to find a {@link Spectator} instance associated to the player given. * * @param player Player to search through the spectator cache. Should not be null! * @return {@link Spectator} instance associated to player if exists or null otherwise. */ @Nullable Spectator get(@NotNull final Player player); /** * Checks if a player is spectating a match. * * @param player Player to check if spectating. Should not be null! * @return true if player is spectating or false otherwise. */ boolean isSpectating(@NotNull final Player player); /** * Attempts to put the player in spectator mode and teleports player to target player in match. * * The method will return a result other than Result.SUCCESS if: * - Player is already in spectator mode * - Player is in a queue * - Player is in a match * - Target is not in a match * - {@link SpectateStartEvent} is cancelled * * Note: Calls {@link SpectateStartEvent} before player is turned into spectator mode. * * @param player Player to put in spectator mode. Should not be null! * @param target Target player to teleport to. Should not be null! * @return Never-null {@link Result} instance indicating the outcome of this call. */ @NotNull Result startSpectating(@NotNull final Player player, @NotNull final Player target); /** * Puts a player out of spectator mode. * * Note: Calls {@link SpectateEndEvent} after player stops spectating. * * @param player Player to stop spectating. Should not be null! */ void stopSpectating(@NotNull final Player player); /** * An UnmodifiableList of {@link Spectator}s that are currently spectating the given {@link Arena}. * * @param arena {@link Arena} to get spectators * @return Never-null UnmodifiableList of {@link Spectator}s spectating given {@link Arena} */ @NotNull List getSpectators(@NotNull final Arena arena); enum Result { ALREADY_SPECTATING, IN_QUEUE, IN_MATCH, TARGET_NOT_IN_MATCH, EVENT_CANCELLED, SUCCESS; } } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/spectate/Spectator.java ================================================ package me.realized.duels.api.spectate; import java.util.UUID; import me.realized.duels.api.arena.Arena; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents a Spectator spectating a match. * * @since 3.4.1 */ public interface Spectator { /** * The {@link UUID} of this spectator. * * @return {@link UUID} of this spectator. */ @NotNull UUID getUuid(); /** * The {@link Player} instance of this spectator. * * @return The {@link Player} instance of this spectator or null if player is not online. * @since 3.5.1 */ @Nullable Player getPlayer(); /** * The {@link UUID} of the player this spectator is spectating. * * @return {@link UUID} of the player this spectator is spectating. * @since 3.5.1 */ @NotNull UUID getTargetUuid(); /** * The {@link Player} instance of the player this spectator is spectating. * * @return The {@link Player} instance of player this spectator is spectating or null if player is not online. * @since 3.5.1 */ @Nullable Player getTarget(); /** * The {@link Arena} this spectator is spectating. * * @return {@link Arena} this spectator is spectating. */ @NotNull Arena getArena(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/user/MatchInfo.java ================================================ package me.realized.duels.api.user; import java.util.GregorianCalendar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the data of a match that had occured in the past. */ public interface MatchInfo { /** * The name of the winner of this match. * * @return Never-null name of the winner of this match. */ @NotNull String getWinner(); /** * The name of the loser of this match. * * @return Never-null name of the loser of this match. */ @NotNull String getLoser(); /** * The name of the kit used in this match or null if no kit was used. * * @return Name of the kit used in this match or null if no kit was used. */ @Nullable String getKit(); /** * The created timestamp of this match info in milliseconds. * Note: Uses {@link GregorianCalendar#getTimeInMillis()}. * * @return created timestamp of this match info in milliseconds. */ long getCreation(); /** * The duration of this match in milliseconds. * * @return Duration of this match in milliseconds. */ long getDuration(); /** * The winner's finishing health. * * @return Winner's finishing health. */ double getHealth(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/user/User.java ================================================ package me.realized.duels.api.user; import java.util.List; import java.util.UUID; import me.realized.duels.api.kit.Kit; import org.jetbrains.annotations.NotNull; /** * Represents a User loaded on the server. */ public interface User { /** * The {@link UUID} of this user. thread-safe! * * @return {@link UUID} of this user. */ @NotNull UUID getUuid(); /** * The Name of this user. thread-safe! * * @return Name of this user. */ @NotNull String getName(); /** * Total wins of this user. thread-safe! * * @return total wins of this user. */ int getWins(); /** * Sets new total wins for this user * * @param wins New total wins. */ void setWins(final int wins); /** * Total losses of this user. thread-safe! * * @return total losses of this user. */ int getLosses(); /** * Sets new total wins for this user. * * @param losses New total losses. */ void setLosses(final int losses); /** * Whether or not this user is receiving duel requests. * * @return True if this user has requests enabled. False otherwise. */ boolean canRequest(); /** * Enables or disables duel requests for this user. * * @param requests True to allow sending duel requests to this user. False otherwise. */ void setRequests(final boolean requests); /** * UnmodifiableList of recent matches for this user. * * @return Never-null UnmodifiableList of recent matches for this user. */ @NotNull List getMatches(); /** * Gets the no kit rating. thread-safe! * * @return no kit rating. * @since 3.3.0 */ int getRating(); /** * Gets the rating of the given {@link Kit}. thread-safe! * * @param kit {@link Kit} to check for rating. * @return Rating for this {@link Kit}. */ int getRating(@NotNull final Kit kit); /** * Resets the rating to default for the no kit rating. thread-safe! * * @since 3.3.0 */ void resetRating(); /** * Resets the rating to default for the given {@link Kit}. thread-safe! * * @param kit {@link Kit} to reset the rating to default. */ void resetRating(@NotNull final Kit kit); /** * Resets user's wins, losses, recent matches, and all rating. */ void reset(); } ================================================ FILE: duels-api/src/main/java/me/realized/duels/api/user/UserManager.java ================================================ package me.realized.duels.api.user; import java.util.List; import java.util.Objects; import java.util.UUID; import me.realized.duels.api.kit.Kit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents the UserManager singleton used by Duels. */ public interface UserManager { /** * Whether or not had all users completed loading to the memory. * * @return True if all users have completed loading to the memory. False otherwise. */ boolean isLoaded(); /** * Gets a {@link User} with the given name. * Note: If {@link #isLoaded()} returns false, this may return null even if userdata file exists. * * @param name Name of the user to get. * @return {@link User} with the given name or null if not exists. */ @Nullable User get(@NotNull final String name); /** * Gets a {@link User} with the given {@link UUID}. * Note: If {@link #isLoaded()} returns false, this may return null even if userdata file exists. * * @param uuid {@link UUID} of the user to get. * @return {@link User} with the given {@link UUID} or null if not exists. */ @Nullable User get(@NotNull final UUID uuid); /** * Calls {@link #get(UUID)} with {@link Player#getUniqueId()}. * * @see #get(UUID) */ @Nullable User get(@NotNull final Player player); /** * Gets the top wins. thread-safe! * * @return {@link TopEntry} containing name and wins of the top 10 Wins or null if the leaderboard has not loaded yet. */ @Nullable TopEntry getTopWins(); /** * Gets the top losses. thread-safe! * * @return {@link TopEntry} containing name and losses of the top 10 Losses or null if the leaderboard has not loaded yet. */ @Nullable TopEntry getTopLosses(); /** * Gets the top rating for no kit. thread-safe! * * @return {@link TopEntry} containing name and rating of the top 10 Rating for no kit or null if the leaderboard has not loaded yet. * @since 3.3.0 */ @Nullable TopEntry getTopRatings(); /** * Gets the top rating for the given {@link Kit}. thread-safe! * * @param kit {@link Kit} to get {@link TopEntry}. * @return {@link TopEntry} containing name and rating of the top 10 Rating for kit or null if the leaderboard has not loaded yet. */ @Nullable TopEntry getTopRatings(@NotNull final Kit kit); class TopEntry { private final long creation; private final String type, identifier; private final List data; public TopEntry(@NotNull final String type, @NotNull final String identifier, @NotNull final List data) { Objects.requireNonNull(type, "type"); Objects.requireNonNull(identifier, "identifier"); Objects.requireNonNull(data, "data"); this.creation = System.currentTimeMillis(); this.type = type; this.identifier = identifier; this.data = data; } public long getCreation() { return creation; } public String getType() { return type; } public String getIdentifier() { return identifier; } public List getData() { return data; } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final TopEntry topEntry = (TopEntry) other; return Objects.equals(type, topEntry.type) && Objects.equals(identifier, topEntry.identifier) && Objects.equals(data, topEntry.data); } @Override public int hashCode() { return Objects.hash(type, identifier, data); } } class TopData implements Comparable { private final UUID uuid; private final String name; private final int value; public TopData(@NotNull final UUID uuid, @NotNull final String name, final int value) { Objects.requireNonNull(uuid, "uuid"); Objects.requireNonNull(name, "name"); this.uuid = uuid; this.name = name; this.value = value; } public UUID getUuid() { return uuid; } public String getName() { return name; } public int getValue() { return value; } @Override public int compareTo(@NotNull final TopData data) { Objects.requireNonNull(data, "data"); return Integer.compare(value, data.value); } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final TopData topData = (TopData) other; return value == topData.value && Objects.equals(uuid, topData.uuid) && Objects.equals(name, topData.name); } @Override public int hashCode() { return Objects.hash(uuid, name, value); } } } ================================================ FILE: duels-plugin/build.gradle ================================================ import org.apache.tools.ant.filters.ReplaceTokens clean.doFirst { delete "$rootDir/out/" } processResources { duplicatesStrategy = DuplicatesStrategy.INCLUDE from(sourceSets.main.resources.srcDirs) { include '**/*.yml' filter(ReplaceTokens, tokens: [VERSION: project.version]) } } dependencies { compileOnly 'org.jetbrains:annotations-java5:22.0.0' compileOnly 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22' implementation 'org.spigotmc:spigot-api:1.14.4-R0.1-SNAPSHOT' implementation 'com.mojang:authlib:1.5.21' implementation 'me.clip:placeholderapi:2.11.1' implementation 'com.SirBlobman.combatlogx:CombatLogX-API:10.0.0.0-SNAPSHOT' implementation ('net.essentialsx:EssentialsX:2.19.2') { transitive = false } implementation (name: 'MVdWPlaceholderAPI-3.1.1') { transitive = false } implementation name: 'Vault-1.6.7' implementation name: 'CombatTagPlus' implementation name: 'PvPManager-3.7.16' implementation name: 'Factions-1.6.9.5-U0.1.14' implementation name: 'MassiveCore' implementation name: 'Factions' implementation name: 'MyPet-2.3.4' implementation name: 'BountyHunters-2.2.6' implementation name: 'SimpleClans-2.14.4.1' implementation name: 'LeaderHeadsAPI' implementation project(':duels-api') implementation project(':duels-worldguard') implementation project(':duels-worldguard-v6') implementation project(':duels-worldguard-v7') implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.1' } shadowJar { getDestinationDirectory().set(file("$rootDir/out/")) final String archiveName = parent.name + '-' + project.version + '.jar' getArchiveFileName().set(archiveName) dependencies { include(project(':duels-api')) include(project(':duels-worldguard')) include(project(':duels-worldguard-v6')) include(project(':duels-worldguard-v7')) include(dependency('com.fasterxml.jackson.core:.*')) } final String group = project.group.toString() + "." + parent.name.toLowerCase() + ".shaded." relocate 'com.fasterxml.jackson.core', group + 'jackson-core' } // To build Duels plugin jar, run './gradlew clean build'. build { dependsOn(shadowJar) } publishing { publications { maven(MavenPublication) { groupId = project.group.toString() artifactId = project.name.toLowerCase() version = project.version from components.java } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/DuelsPlugin.java ================================================ package me.realized.duels; import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.stream.Collectors; import lombok.Getter; import me.realized.duels.api.Duels; import me.realized.duels.api.command.SubCommand; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.betting.BettingManager; import me.realized.duels.command.commands.SpectateCommand; import me.realized.duels.command.commands.duel.DuelCommand; import me.realized.duels.command.commands.duels.DuelsCommand; import me.realized.duels.command.commands.queue.QueueCommand; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.ItemData; import me.realized.duels.data.ItemData.ItemDataDeserializer; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.duel.DuelManager; import me.realized.duels.extension.ExtensionClassLoader; import me.realized.duels.extension.ExtensionManager; import me.realized.duels.hook.HookManager; import me.realized.duels.inventories.InventoryManager; import me.realized.duels.kit.KitManagerImpl; import me.realized.duels.listeners.DamageListener; import me.realized.duels.listeners.EnderpearlListener; import me.realized.duels.listeners.KitItemListener; import me.realized.duels.listeners.KitOptionsListener; import me.realized.duels.listeners.LingerPotionListener; import me.realized.duels.listeners.PotionListener; import me.realized.duels.listeners.ProjectileHitListener; import me.realized.duels.listeners.TeleportListener; import me.realized.duels.logging.LogManager; import me.realized.duels.player.PlayerInfoManager; import me.realized.duels.queue.QueueManager; import me.realized.duels.queue.sign.QueueSignManagerImpl; import me.realized.duels.request.RequestManager; import me.realized.duels.setting.SettingsManager; import me.realized.duels.shaded.bstats.Metrics; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.teleport.Teleport; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.Log.LogSource; import me.realized.duels.util.Reloadable; import me.realized.duels.util.UpdateChecker; import me.realized.duels.util.command.AbstractCommand; import me.realized.duels.util.gui.GuiListener; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; public class DuelsPlugin extends JavaPlugin implements Duels, LogSource { private static final int BSTATS_ID = 2696; private static final int RESOURCE_ID = 20171; private static final String SPIGOT_INSTALLATION_URL = "https://www.spigotmc.org/wiki/spigot-installation/"; @Getter private static DuelsPlugin instance; private final List loadables = new ArrayList<>(); private int lastLoad; @Getter private LogManager logManager; @Getter private Config configuration; @Getter private Lang lang; @Getter private UserManagerImpl userManager; @Getter private GuiListener guiListener; @Getter private KitManagerImpl kitManager; @Getter private ArenaManagerImpl arenaManager; @Getter private SettingsManager settingManager; @Getter private PlayerInfoManager playerManager; @Getter private SpectateManagerImpl spectateManager; @Getter private BettingManager bettingManager; @Getter private InventoryManager inventoryManager; @Getter private DuelManager duelManager; @Getter private QueueManager queueManager; @Getter private QueueSignManagerImpl queueSignManager; @Getter private RequestManager requestManager; @Getter private HookManager hookManager; @Getter private Teleport teleport; @Getter private ExtensionManager extensionManager; private final Map> commands = new HashMap<>(); private final List registeredListeners = new ArrayList<>(); @Getter private volatile boolean updateAvailable; @Getter private volatile String newVersion; @Override public void onEnable() { instance = this; Log.addSource(this); JsonUtil.registerDeserializer(ItemData.class, ItemDataDeserializer.class); try { logManager = new LogManager(this); } catch (IOException ex) { Log.error("Could not load LogManager. Please contact the developer."); // Manually print the stacktrace since Log#error only prints errors to non-plugin log sources. ex.printStackTrace(); getPluginLoader().disablePlugin(this); return; } Log.addSource(logManager); logManager.debug("onEnable start -> " + System.currentTimeMillis() + "\n"); try { Class.forName("org.spigotmc.SpigotConfig"); } catch (ClassNotFoundException ex) { Log.error("================= *** DUELS LOAD FAILURE *** ================="); Log.error("Duels requires a spigot server to run, but this server was not running on spigot!"); Log.error("To run your server on spigot, follow this guide: " + SPIGOT_INSTALLATION_URL); Log.error("Spigot is compatible with CraftBukkit/Bukkit plugins."); Log.error("================= *** DUELS LOAD FAILURE *** ================="); getPluginLoader().disablePlugin(this); return; } loadables.add(configuration = new Config(this)); loadables.add(lang = new Lang(this)); loadables.add(userManager = new UserManagerImpl(this)); loadables.add(guiListener = new GuiListener<>(this)); loadables.add(kitManager = new KitManagerImpl(this)); loadables.add(arenaManager = new ArenaManagerImpl(this)); loadables.add(settingManager = new SettingsManager(this)); loadables.add(playerManager = new PlayerInfoManager(this)); loadables.add(spectateManager = new SpectateManagerImpl(this)); loadables.add(bettingManager = new BettingManager(this)); loadables.add(inventoryManager = new InventoryManager(this)); loadables.add(duelManager = new DuelManager(this)); loadables.add(queueManager = new QueueManager(this)); loadables.add(queueSignManager = new QueueSignManagerImpl(this)); loadables.add(requestManager = new RequestManager(this)); hookManager = new HookManager(this); loadables.add(teleport = new Teleport(this)); loadables.add(extensionManager = new ExtensionManager(this)); if (!load()) { getPluginLoader().disablePlugin(this); return; } new KitItemListener(this); new DamageListener(this); new PotionListener(this); new TeleportListener(this); new ProjectileHitListener(this); new EnderpearlListener(this); new KitOptionsListener(this); new LingerPotionListener(this); new Metrics(this, BSTATS_ID); if (!configuration.isCheckForUpdates()) { return; } final UpdateChecker updateChecker = new UpdateChecker(this, RESOURCE_ID); updateChecker.check((hasUpdate, newVersion) -> { if (hasUpdate) { DuelsPlugin.this.updateAvailable = true; DuelsPlugin.this.newVersion = newVersion; Log.info("==============================================="); Log.info("An update for " + getName() + " is available!"); Log.info("Download " + getName() + " v" + newVersion + " here:"); Log.info(getDescription().getWebsite()); Log.info("==============================================="); } else { Log.info("No updates were available. You are on the latest version!"); } }); } @Override public void onDisable() { final long start = System.currentTimeMillis(); long last = start; logManager.debug("onDisable start -> " + start + "\n"); unload(); logManager.debug("unload done (took " + Math.abs(last - (last = System.currentTimeMillis())) + "ms)"); Log.clearSources(); logManager.debug("Log#clearSources done (took " + Math.abs(last - System.currentTimeMillis()) + "ms)"); logManager.handleDisable(); instance = null; log(Level.INFO, "Disable process took " + (System.currentTimeMillis() - start) + "ms."); } /** * @return true if load was successful, otherwise false */ private boolean load() { registerCommands( new DuelCommand(this), new QueueCommand(this), new SpectateCommand(this), new DuelsCommand(this) ); for (final Loadable loadable : loadables) { final String name = loadable.getClass().getSimpleName(); try { final long now = System.currentTimeMillis(); logManager.debug("Starting load of " + name + " at " + now); loadable.handleLoad(); logManager.debug(name + " has been loaded. (took " + (System.currentTimeMillis() - now) + "ms)"); lastLoad = loadables.indexOf(loadable); } catch (Exception ex) { // Handles the case of exceptions from LogManager not being logged in file if (loadable instanceof LogSource) { ex.printStackTrace(); } Log.error("There was an error while loading " + name + "! If you believe this is an issue from the plugin, please contact the developer.", ex); return false; } } return true; } /** * @return true if unload was successful, otherwise false */ private boolean unload() { registeredListeners.forEach(HandlerList::unregisterAll); registeredListeners.clear(); // Unregister all extension listeners that isn't using the method Duels#registerListener HandlerList.getRegisteredListeners(this) .stream() .filter(listener -> listener.getListener().getClass().getClassLoader().getClass().isAssignableFrom(ExtensionClassLoader.class)) .forEach(listener -> HandlerList.unregisterAll(listener.getListener())); commands.clear(); for (final Loadable loadable : Lists.reverse(loadables)) { final String name = loadable.getClass().getSimpleName(); try { if (loadables.indexOf(loadable) > lastLoad) { continue; } final long now = System.currentTimeMillis(); logManager.debug("Starting unload of " + name + " at " + now); loadable.handleUnload(); logManager.debug(name + " has been unloaded. (took " + (System.currentTimeMillis() - now) + "ms)"); } catch (Exception ex) { Log.error("There was an error while unloading " + name + "! If you believe this is an issue from the plugin, please contact the developer.", ex); return false; } } return true; } @SafeVarargs private final void registerCommands(final AbstractCommand... commands) { for (final AbstractCommand command : commands) { this.commands.put(command.getName().toLowerCase(), command); command.register(); } } @Override public boolean registerSubCommand(@NotNull final String command, @NotNull final SubCommand subCommand) { Objects.requireNonNull(command, "command"); Objects.requireNonNull(subCommand, "subCommand"); final AbstractCommand result = commands.get(command.toLowerCase()); if (result == null || result.isChild(subCommand.getName().toLowerCase())) { return false; } result.child(new AbstractCommand(this, subCommand) { @Override protected void execute(final CommandSender sender, final String label, final String[] args) { subCommand.execute(sender, label, args); } }); return true; } @Override public void registerListener(@NotNull final Listener listener) { Objects.requireNonNull(listener, "listener"); registeredListeners.add(listener); Bukkit.getPluginManager().registerEvents(listener, this); } @Override public boolean reload() { if (!(unload() && load())) { getPluginLoader().disablePlugin(this); return false; } return true; } @Override public String getVersion() { return getDescription().getVersion(); } public boolean reload(final Loadable loadable) { boolean unloaded = false; try { loadable.handleUnload(); unloaded = true; loadable.handleLoad(); return true; } catch (Exception ex) { Log.error("There was an error while " + (unloaded ? "loading " : "unloading ") + loadable.getClass().getSimpleName() + "! If you believe this is an issue from the plugin, please contact the developer.", ex); return false; } } @Override public BukkitTask doSync(@NotNull final Runnable task) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTask(this, task); } @Override public BukkitTask doSyncAfter(@NotNull final Runnable task, final long delay) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTaskLater(this, task, delay); } @Override public BukkitTask doSyncRepeat(@NotNull final Runnable task, final long delay, final long period) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTaskTimer(this, task, delay, period); } @Override public BukkitTask doAsync(@NotNull final Runnable task) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTaskAsynchronously(this, task); } @Override public BukkitTask doAsyncAfter(@NotNull final Runnable task, final long delay) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTaskLaterAsynchronously(this, task, delay); } @Override public BukkitTask doAsyncRepeat(@NotNull final Runnable task, final long delay, final long period) { Objects.requireNonNull(task, "task"); return Bukkit.getScheduler().runTaskTimerAsynchronously(this, task, delay, period); } @Override public void cancelTask(@NotNull final BukkitTask task) { Objects.requireNonNull(task, "task"); task.cancel(); } @Override public void cancelTask(final int id) { Bukkit.getScheduler().cancelTask(id); } @Override public void info(@NotNull final String message) { Objects.requireNonNull(message, "message"); Log.info(message); } @Override public void warn(@NotNull final String message) { Objects.requireNonNull(message, "message"); Log.warn(message); } @Override public void error(@NotNull final String message) { Objects.requireNonNull(message, "message"); Log.error(message); } @Override public void error(@NotNull final String message, @NotNull final Throwable thrown) { Objects.requireNonNull(message, "message"); Objects.requireNonNull(thrown, "thrown"); Log.error(message, thrown); } public Loadable find(final String name) { return loadables.stream().filter(loadable -> loadable.getClass().getSimpleName().equalsIgnoreCase(name)).findFirst().orElse(null); } public List getReloadables() { return loadables.stream() .filter(loadable -> loadable instanceof Reloadable) .map(loadable -> loadable.getClass().getSimpleName()) .collect(Collectors.toList()); } @Override public void log(final Level level, final String s) { getLogger().log(level, s); } @Override public void log(final Level level, final String s, final Throwable thrown) { getLogger().log(level, s, thrown); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/Permissions.java ================================================ package me.realized.duels; public final class Permissions { public static final String DUEL = "duels.duel"; public static final String STATS = "duels.stats"; public static final String STATS_OTHERS = STATS + ".others"; public static final String TOGGLE = "duels.toggle"; public static final String TOP = "duels.top"; public static final String SPECTATE = "duels.spectate"; public static final String SPEC_ANON = SPECTATE + ".anonymously"; public static final String ADMIN = "duels.admin"; public static final String TP_BYPASS = "duels.teleport.bypass"; public static final String KIT = "duels.kits.%s"; public static final String KIT_ALL = "duels.kits.*"; public static final String KIT_SELECTING = "duels.use.kit-select"; public static final String OWN_INVENTORY = "duels.use.own-inventory"; public static final String ARENA_SELECTING = "duels.use.arena-select"; public static final String ITEM_BETTING = "duels.use.item-betting"; public static final String MONEY_BETTING = "duels.use.money-betting"; public static final String SETTING_ALL = "duels.use.*"; public static final String QUEUE = "duels.queue"; private Permissions() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/api/DuelsAPI.java ================================================ package me.realized.duels.api; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.arena.ArenaManager; import me.realized.duels.api.user.UserManager; import me.realized.duels.data.UserData; import org.bukkit.entity.Player; /** * A static API for Duels. * (This is an old, deprecated API for Duels v2 and below.) * * @deprecated As of v3.0.0, use {@link Duels} instead. */ @Deprecated public class DuelsAPI { /** * @deprecated As of v3.0.0, use {@link UserManager#get(UUID)} instead. */ @Deprecated public static UserData getUser(final UUID uuid, boolean force) { return DuelsPlugin.getInstance().getUserManager().get(uuid); } /** * @deprecated As of v3.0.0, use {@link UserManager#get(Player)} instead. */ @Deprecated public static UserData getUser(final Player player, boolean force) { return DuelsPlugin.getInstance().getUserManager().get(player); } /** * @deprecated As of v3.0.0, use {@link ArenaManager#isInMatch(Player)} instead. */ @Deprecated public static boolean isInMatch(final Player player) { return DuelsPlugin.getInstance().getArenaManager().isInMatch(player); } /** * @deprecated As of v3.0.0, get the version from {@link Duels#getVersion()} instead. */ @Deprecated public static String getVersion() { return DuelsPlugin.getInstance().getVersion(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/arena/ArenaImpl.java ================================================ package me.realized.duels.arena; import com.google.common.collect.Lists; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.event.arena.ArenaSetPositionEvent; import me.realized.duels.api.event.arena.ArenaStateChangeEvent; import me.realized.duels.api.event.match.MatchEndEvent; import me.realized.duels.api.event.match.MatchEndEvent.Reason; import me.realized.duels.gui.BaseButton; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.Items; import me.realized.duels.util.function.Pair; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ArenaImpl extends BaseButton implements Arena { @Getter private final String name; @Getter private boolean disabled; @Getter private final Set kits = new HashSet<>(); @Getter private final Map positions = new HashMap<>(); @Getter private MatchImpl match; @Getter(value = AccessLevel.PACKAGE) @Setter(value = AccessLevel.PACKAGE) private Countdown countdown; @Getter @Setter(value = AccessLevel.PACKAGE) private boolean removed; public ArenaImpl(final DuelsPlugin plugin, final String name, final boolean disabled) { super(plugin, ItemBuilder .of(Items.EMPTY_MAP) .name(plugin.getLang().getMessage("GUI.arena-selector.buttons.arena.name", "name", name)) .lore(plugin.getLang().getMessage("GUI.arena-selector.buttons.arena.lore-unavailable").split("\n")) .build() ); this.name = name; this.disabled = disabled; } public ArenaImpl(final DuelsPlugin plugin, final String name) { this(plugin, name, false); } public void refreshGui(final boolean available) { setLore(lang.getMessage("GUI.arena-selector.buttons.arena.lore-" + (available ? "available" : "unavailable")).split("\n")); arenaManager.getGui().calculatePages(); } @Nullable @Override public Location getPosition(final int pos) { return positions.get(pos); } @Override public boolean setPosition(@Nullable final Player source, final int pos, @NotNull final Location location) { Objects.requireNonNull(location, "location"); if (pos <= 0 || pos > 2) { return false; } final ArenaSetPositionEvent event = new ArenaSetPositionEvent(source, this, pos, location); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } positions.put(pos, location); arenaManager.saveArenas(); refreshGui(isAvailable()); return true; } @Override public boolean setPosition(final int pos, @NotNull final Location location) { return setPosition(null, pos, location); } @Override public boolean setDisabled(@Nullable final CommandSender source, final boolean disabled) { final ArenaStateChangeEvent event = new ArenaStateChangeEvent(source, this, disabled); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } this.disabled = event.isDisabled(); arenaManager.saveArenas(); refreshGui(isAvailable()); return true; } @Override public boolean setDisabled(final boolean disabled) { return setDisabled(null, disabled); } public boolean isBoundless() { return kits.isEmpty(); } public boolean isBound(@Nullable final KitImpl kit) { return kit != null && kits.contains(kit); } public void bind(final KitImpl kit) { if (isBound(kit)) { kits.remove(kit); } else { kits.add(kit); } arenaManager.saveArenas(); } @Override public boolean isUsed() { return match != null; } public boolean isAvailable() { return !isDisabled() && !isUsed() && getPosition(1) != null && getPosition(2) != null; } public MatchImpl startMatch(final KitImpl kit, final Map> items, final int bet, final Queue source) { this.match = new MatchImpl(this, kit, items, bet, source); refreshGui(false); return match; } public void endMatch(final UUID winner, final UUID loser, final Reason reason) { spectateManager.stopSpectating(this); final MatchEndEvent event = new MatchEndEvent(match, winner, loser, reason); Bukkit.getPluginManager().callEvent(event); final Queue source = match.getSource(); match.setFinished(); match = null; if (source != null) { source.update(); queueManager.getGui().calculatePages(); } refreshGui(true); } public void startCountdown(final String kit, final Map> info) { final List messages = config.getCdMessages(); if (messages.isEmpty()) { return; } this.countdown = new Countdown(plugin, this, kit, info, messages, config.getTitles()); countdown.runTaskTimer(plugin, 0L, 20L); } boolean isCounting() { return countdown != null; } @Override public boolean has(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return isUsed() && !match.getPlayerMap().getOrDefault(player, true); } public void add(final Player player) { if (isUsed()) { match.getPlayerMap().put(player, false); } } public void remove(final Player player) { if (isUsed() && match.getPlayerMap().containsKey(player)) { match.getPlayerMap().put(player, true); } } public boolean isEndGame() { return size() <= 1; } public int size() { return isUsed() ? match.getAlivePlayers().size() : 0; } public Player first() { return isUsed() ? match.getAlivePlayers().iterator().next() : null; } public Player getOpponent(final Player player) { return isUsed() ? match.getAllPlayers().stream().filter(other -> !player.equals(other)).findFirst().orElse(null) : null; } public Set getPlayers() { return isUsed() ? match.getAllPlayers() : Collections.emptySet(); } public void broadcast(final String message) { final List receivers = Lists.newArrayList(getPlayers()); spectateManager.getSpectatorsImpl(this) .stream() .map(spectator -> Bukkit.getPlayer(spectator.getUuid())) .forEach(receivers::add); receivers.forEach(player -> player.sendMessage(message)); } @Override public void onClick(final Player player) { if (!isAvailable()) { return; } final Settings settings = settingManager.getSafely(player); final String kitName = settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.none"); if (!arenaManager.isSelectable(settings.getKit(), this)) { lang.sendMessage(player, "ERROR.setting.arena-not-applicable", "kit", kitName, "arena", name); return; } settings.setArena(this); settings.openGui(player); } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final ArenaImpl arena = (ArenaImpl) other; return Objects.equals(name, arena.name); } @Override public int hashCode() { return Objects.hash(name); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/arena/ArenaManagerImpl.java ================================================ package me.realized.duels.arena; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Charsets; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.arena.ArenaManager; import me.realized.duels.api.event.arena.ArenaCreateEvent; import me.realized.duels.api.event.arena.ArenaRemoveEvent; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.ArenaData; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.MultiPageGui; import me.realized.duels.util.inventory.ItemBuilder; import me.realized.duels.util.io.FileUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ArenaManagerImpl implements Loadable, ArenaManager { private static final String FILE_NAME = "arenas.json"; private static final String ERROR_NOT_ALPHANUMERIC = "Could not load arena %s: Name is not alphanumeric."; private static final String ARENAS_LOADED = "Loaded %s arena(s)."; private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final File file; private final List arenas = new ArrayList<>(); @Getter private MultiPageGui gui; public ArenaManagerImpl(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.file = new File(plugin.getDataFolder(), FILE_NAME); Bukkit.getPluginManager().registerEvents(new ArenaListener(), plugin); } @Override public void handleLoad() throws IOException { gui = new MultiPageGui<>(plugin, lang.getMessage("GUI.arena-selector.title"), config.getArenaSelectorRows(), arenas); gui.setSpaceFiller(Items.from(config.getArenaSelectorFillerType(), config.getArenaSelectorFillerData())); gui.setPrevButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.previous-page.name")).build()); gui.setNextButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.next-page.name")).build()); gui.setEmptyIndicator(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.empty.name")).build()); plugin.getGuiListener().addGui(gui); if (FileUtil.checkNonEmpty(file, true)) { try (final Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)) { final List data = JsonUtil.getObjectMapper().readValue(reader, new TypeReference>() {}); if (data != null) { for (final ArenaData arenaData : data) { if (!StringUtil.isAlphanumeric(arenaData.getName())) { Log.warn(this, String.format(ERROR_NOT_ALPHANUMERIC, arenaData.getName())); continue; } arenas.add(arenaData.toArena(plugin)); } } } } Log.info(this, String.format(ARENAS_LOADED, arenas.size())); gui.calculatePages(); } @Override public void handleUnload() { if (gui != null) { plugin.getGuiListener().removeGui(gui); } arenas.clear(); } void saveArenas() { final List data = new ArrayList<>(); for (final ArenaImpl arena : arenas) { data.add(new ArenaData(arena)); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, data); writer.flush(); } catch (IOException ex) { Log.error(this, ex.getMessage(), ex); } } @Nullable @Override public ArenaImpl get(@NotNull final String name) { Objects.requireNonNull(name, "name"); return arenas.stream().filter(arena -> arena.getName().equals(name)).findFirst().orElse(null); } @Nullable @Override public ArenaImpl get(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return arenas.stream().filter(arena -> arena.has(player)).findFirst().orElse(null); } @Override public boolean isInMatch(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return get(player) != null; } @NotNull @Override public List getArenas() { return Collections.unmodifiableList(arenas); } public boolean create(final CommandSender source, final String name) { if (get(name) != null) { return false; } final ArenaImpl arena = new ArenaImpl(plugin, name); arenas.add(arena); saveArenas(); final ArenaCreateEvent event = new ArenaCreateEvent(source, arena); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return true; } public boolean remove(final CommandSender source, final ArenaImpl arena) { if (arenas.remove(arena)) { arena.setRemoved(true); saveArenas(); final ArenaRemoveEvent event = new ArenaRemoveEvent(source, arena); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return true; } return false; } public List getArenasImpl() { return arenas; } public Set getPlayers() { return arenas.stream().flatMap(arena -> arena.getPlayers().stream()).collect(Collectors.toSet()); } public long getPlayersInMatch(final Queue queue) { return arenas.stream().filter(arena -> arena.isUsed() && arena.getMatch().isFromQueue() && arena.getMatch().getSource().equals(queue)).count() * 2; } public boolean isSelectable(@Nullable final KitImpl kit, @NotNull final ArenaImpl arena) { if (!arena.isAvailable()) { return false; } if (arena.isBoundless()) { if (kit == null) { return true; } else { return !kit.isArenaSpecific(); } } return arena.isBound(kit); } public ArenaImpl randomArena(final KitImpl kit) { final List available = arenas.stream().filter(arena -> isSelectable(kit, arena)).collect(Collectors.toList()); return !available.isEmpty() ? available.get(ThreadLocalRandom.current().nextInt(available.size())) : null; } public List getNames() { return arenas.stream().map(ArenaImpl::getName).collect(Collectors.toList()); } // Called on kit removal public void clearBinds(final KitImpl kit) { arenas.stream().filter(arena -> arena.isBound(kit)).forEach(arena -> arena.bind(kit)); } private class ArenaListener implements Listener { @EventHandler(ignoreCancelled = true) public void on(final PlayerInteractEvent event) { if (!event.hasBlock() || !config.isPreventInteract()) { return; } final ArenaImpl arena = get(event.getPlayer()); if (arena == null || !arena.isCounting()) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final EntityDamageEvent event) { if (!config.isPreventPvp() || !(event.getEntity() instanceof Player)) { return; } final ArenaImpl arena = get((Player) event.getEntity()); if (arena == null || !arena.isCounting()) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final ProjectileLaunchEvent event) { if (!config.isPreventLaunchProjectile()) { return; } final ProjectileSource shooter = event.getEntity().getShooter(); if (!(shooter instanceof Player)) { return; } final ArenaImpl arena = get((Player) shooter); if (arena == null || !arena.isCounting()) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final PlayerMoveEvent event) { if (!config.isPreventMovement()) { return; } final Location from = event.getFrom(); final Location to = event.getTo(); if (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ()) { return; } final ArenaImpl arena = get(event.getPlayer()); if (arena == null || !arena.isCounting()) { return; } event.setTo(event.getFrom()); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/arena/Countdown.java ================================================ package me.realized.duels.arena; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.Titles; import me.realized.duels.util.function.Pair; import org.bukkit.scheduler.BukkitRunnable; class Countdown extends BukkitRunnable { private final Config config; private final ArenaImpl arena; private final String kit; private final Map> info; private final List messages; private final List titles; private boolean finished; Countdown(final DuelsPlugin plugin, final ArenaImpl arena, final String kit, final Map> info, final List messages, final List titles) { this.config = plugin.getConfiguration(); this.arena = arena; this.kit = kit; this.info = info; this.messages = Lists.newArrayList(messages); this.titles = Lists.newArrayList(titles); } @Override public void run() { if (finished) { return; } final String rawMessage = messages.remove(0); final String message = StringUtil.color(rawMessage); final String title = !titles.isEmpty() ? titles.remove(0) : null; arena.getPlayers().forEach(player -> { config.playSound(player, rawMessage); final Pair info = this.info.get(player.getUniqueId()); if (info != null) { player.sendMessage(message .replace("%opponent%", info.getKey()) .replace("%opponent_rating%", String.valueOf(info.getValue())) .replace("%kit%", kit) .replace("%arena%", arena.getName()) ); } else { player.sendMessage(message); } if (title != null) { Titles.send(player, title, null, 0, 20, 50); } }); if (!arena.isUsed() || messages.isEmpty()) { arena.setCountdown(null); cancel(); finished = true; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/arena/MatchImpl.java ================================================ package me.realized.duels.arena; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import lombok.Getter; import me.realized.duels.api.match.Match; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class MatchImpl implements Match { @Getter private final ArenaImpl arena; @Getter private final long start; @Getter private final KitImpl kit; private final Map> items; @Getter private final int bet; @Getter private final Queue source; @Getter private boolean finished; // Default value for players is false, which is set to true if player is killed in the match. private final Map players = new HashMap<>(); MatchImpl(final ArenaImpl arena, final KitImpl kit, final Map> items, final int bet, final Queue source) { this.arena = arena; this.start = System.currentTimeMillis(); this.kit = kit; this.items = items; this.bet = bet; this.source = source; } Map getPlayerMap() { return players; } Set getAlivePlayers() { return players.entrySet().stream().filter(entry -> !entry.getValue()).map(Entry::getKey).collect(Collectors.toSet()); } public Set getAllPlayers() { return players.keySet(); } public boolean isDead(final Player player) { return players.getOrDefault(player, true); } public boolean isFromQueue() { return source != null; } public boolean isOwnInventory() { return kit == null; } public List getItems() { return items != null ? items.values().stream().flatMap(Collection::stream).collect(Collectors.toList()) : Collections.emptyList(); } void setFinished() { finished = true; } public long getDurationInMillis() { return System.currentTimeMillis() - start; } @NotNull @Override public List getItems(@NotNull final Player player) { Objects.requireNonNull(player, "player"); if (this.items == null) { return Collections.emptyList(); } final List items = this.items.get(player.getUniqueId()); return items != null ? items : Collections.emptyList(); } @NotNull @Override public Set getPlayers() { return Collections.unmodifiableSet(getAlivePlayers()); } @NotNull @Override public Set getStartingPlayers() { return Collections.unmodifiableSet(getAllPlayers()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/betting/BettingManager.java ================================================ package me.realized.duels.betting; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.betting.BettingGui; import me.realized.duels.hook.hooks.VaultHook; import me.realized.duels.setting.Settings; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.gui.GuiListener; import org.bukkit.entity.Player; import org.bukkit.event.Listener; public class BettingManager implements Loadable, Listener { private final DuelsPlugin plugin; private final GuiListener guiListener; public BettingManager(final DuelsPlugin plugin) { this.plugin = plugin; this.guiListener = plugin.getGuiListener(); } @Override public void handleLoad() { final VaultHook vaultHook = plugin.getHookManager().getHook(VaultHook.class); if (vaultHook == null) { Log.info(this, "Vault was not found! Money betting feature will be automatically disabled."); } else if (vaultHook.getEconomy() == null) { Log.info(this, "Economy plugin supporting Vault was not found! Money betting feature will be automatically disabled."); } } @Override public void handleUnload() {} public void open(final Settings settings, final Player first, final Player second) { final BettingGui gui = new BettingGui(plugin, settings, first, second); guiListener.addGui(first, gui).open(first); guiListener.addGui(second, gui).open(second); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/BaseCommand.java ================================================ package me.realized.duels.command; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.betting.BettingManager; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.duel.DuelManager; import me.realized.duels.hook.HookManager; import me.realized.duels.inventories.InventoryManager; import me.realized.duels.kit.KitManagerImpl; import me.realized.duels.player.PlayerInfoManager; import me.realized.duels.queue.QueueManager; import me.realized.duels.queue.sign.QueueSignManagerImpl; import me.realized.duels.request.RequestManager; import me.realized.duels.setting.SettingsManager; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.util.command.AbstractCommand; import org.bukkit.command.CommandSender; public abstract class BaseCommand extends AbstractCommand { protected final DuelsPlugin plugin; protected final Config config; protected final Lang lang; protected final UserManagerImpl userManager; protected final KitManagerImpl kitManager; protected final ArenaManagerImpl arenaManager; protected final QueueManager queueManager; protected final QueueSignManagerImpl queueSignManager; protected final SettingsManager settingManager; protected final PlayerInfoManager playerManager; protected final SpectateManagerImpl spectateManager; protected final BettingManager bettingManager; protected final InventoryManager inventoryManager; protected final DuelManager duelManager; protected final RequestManager requestManager; protected final HookManager hookManager; /** * Constructor for a sub command */ protected BaseCommand(final DuelsPlugin plugin, final String name, final String usage, final String description, final String permission, final int length, final boolean playerOnly, final String... aliases) { super(plugin, name, usage, description, permission, length, playerOnly, aliases); this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.userManager = plugin.getUserManager(); this.kitManager = plugin.getKitManager(); this.arenaManager = plugin.getArenaManager(); this.queueManager = plugin.getQueueManager(); this.queueSignManager = plugin.getQueueSignManager(); this.settingManager = plugin.getSettingManager(); this.playerManager = plugin.getPlayerManager(); this.spectateManager = plugin.getSpectateManager(); this.bettingManager = plugin.getBettingManager(); this.inventoryManager = plugin.getInventoryManager(); this.duelManager = plugin.getDuelManager(); this.requestManager = plugin.getRequestManager(); this.hookManager = plugin.getHookManager(); } /** * Constructor for a sub command, inherits parent permission */ protected BaseCommand(final DuelsPlugin plugin, final String name, final String usage, final String description, final int length, final boolean playerOnly, final String... aliases) { this(plugin, name, usage, description, null, length, playerOnly, aliases); } /** * Constructor for a parent command */ protected BaseCommand(final DuelsPlugin plugin, final String name, final String permission, final boolean playerOnly) { this(plugin, name, null, null, permission, -1, playerOnly); } @Override protected void handleMessage(final CommandSender sender, final MessageType type, final String... args) { switch (type) { case PLAYER_ONLY: super.handleMessage(sender, type, args); break; case NO_PERMISSION: lang.sendMessage(sender, "ERROR.no-permission", "permission", args[0]); break; case SUB_COMMAND_INVALID: lang.sendMessage(sender, "ERROR.command.invalid-sub-command", "command", args[0], "argument", args[1]); break; case SUB_COMMAND_USAGE: lang.sendMessage(sender, "COMMAND.sub-command-usage", "command", args[0], "usage", args[1], "description", args[2]); break; } } protected List handleTabCompletion(final String argument, final Collection collection) { return collection.stream() .filter(value -> value.toLowerCase().startsWith(argument.toLowerCase())) .map(value -> value.replace(" ", "-")) .collect(Collectors.toList()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/SpectateCommand.java ================================================ package me.realized.duels.command.commands; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.spectate.SpectateManager.Result; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.arena.MatchImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.spectate.SpectatorImpl; import me.realized.duels.util.inventory.InventoryUtil; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SpectateCommand extends BaseCommand { public SpectateCommand(final DuelsPlugin plugin) { super(plugin, "spectate", Permissions.SPECTATE, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; final SpectatorImpl spectator = spectateManager.get(player); // If player is already spectating, using /spectate will put them out of spectator mode. if (spectator != null) { spectateManager.stopSpectating(player); lang.sendMessage(player, "COMMAND.spectate.stop-spectate", "name", spectator.getTargetName()); return; } if (args.length == 0) { lang.sendMessage(sender, "COMMAND.spectate.usage", "command", label); return; } if (config.isSpecRequiresClearedInventory() && InventoryUtil.hasItem(player)) { lang.sendMessage(sender, "ERROR.duel.inventory-not-empty"); return; } final Player target = Bukkit.getPlayerExact(args[0]); if (target == null) { lang.sendMessage(sender, "ERROR.player.not-found", "name", args[0]); return; } final Result result = spectateManager.startSpectating(player, target); switch (result) { case EVENT_CANCELLED: return; case IN_MATCH: lang.sendMessage(player, "ERROR.spectate.already-spectating.sender"); return; case IN_QUEUE: lang.sendMessage(player, "ERROR.duel.already-in-queue"); return; case ALREADY_SPECTATING: lang.sendMessage(player, "ERROR.duel.already-in-match.sender"); return; case TARGET_NOT_IN_MATCH: lang.sendMessage(player, "ERROR.spectate.not-in-match", "name", target.getName()); return; case SUCCESS: final ArenaImpl arena = arenaManager.get(target); // Meaningless checks to halt IDE warnings as target is guaranteed to be in a match if result is SUCCESS. if (arena == null || arena.getMatch() == null) { return; } final MatchImpl match = arena.getMatch(); final String kit = match.getKit() != null ? match.getKit().getName() : lang.getMessage("GENERAL.none"); lang.sendMessage(player, "COMMAND.spectate.start-spectate", "name", target.getName(), "opponent", arena.getOpponent(target).getName(), "kit", kit, "arena", arena.getName(), "bet_amount", match.getBet() ); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/DuelCommand.java ================================================ package me.realized.duels.command.commands.duel; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.command.commands.duel.subcommands.AcceptCommand; import me.realized.duels.command.commands.duel.subcommands.DenyCommand; import me.realized.duels.command.commands.duel.subcommands.InventoryCommand; import me.realized.duels.command.commands.duel.subcommands.StatsCommand; import me.realized.duels.command.commands.duel.subcommands.ToggleCommand; import me.realized.duels.command.commands.duel.subcommands.TopCommand; import me.realized.duels.command.commands.duel.subcommands.VersionCommand; import me.realized.duels.data.UserData; import me.realized.duels.hook.hooks.CombatLogXHook; import me.realized.duels.hook.hooks.CombatTagPlusHook; import me.realized.duels.hook.hooks.PvPManagerHook; import me.realized.duels.hook.hooks.VaultHook; import me.realized.duels.hook.hooks.worldguard.WorldGuardHook; import me.realized.duels.kit.KitImpl; import me.realized.duels.setting.Settings; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import me.realized.duels.util.inventory.InventoryUtil; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class DuelCommand extends BaseCommand { private final CombatTagPlusHook combatTagPlus; private final PvPManagerHook pvpManager; private final CombatLogXHook combatLogX; private final WorldGuardHook worldGuard; private final VaultHook vault; public DuelCommand(final DuelsPlugin plugin) { super(plugin, "duel", Permissions.DUEL, true); child( new AcceptCommand(plugin), new DenyCommand(plugin), new StatsCommand(plugin), new ToggleCommand(plugin), new TopCommand(plugin), new InventoryCommand(plugin), new VersionCommand(plugin) ); this.combatTagPlus = hookManager.getHook(CombatTagPlusHook.class); this.pvpManager = hookManager.getHook(PvPManagerHook.class); this.combatLogX = hookManager.getHook(CombatLogXHook.class); this.worldGuard = hookManager.getHook(WorldGuardHook.class); this.vault = hookManager.getHook(VaultHook.class); } @Override protected boolean executeFirst(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; if (userManager.get(player) == null) { lang.sendMessage(sender, "ERROR.data.load-failure"); return true; } if (args.length == 0) { lang.sendMessage(sender, "COMMAND.duel.usage", "command", label); return true; } if (isChild(args[0])) { return false; } if (config.isRequiresClearedInventory() && InventoryUtil.hasItem(player)) { lang.sendMessage(sender, "ERROR.duel.inventory-not-empty"); return true; } if (config.isPreventCreativeMode() && player.getGameMode() == GameMode.CREATIVE) { lang.sendMessage(sender, "ERROR.duel.in-creative-mode"); return true; } if (config.getBlacklistedWorlds().contains(player.getWorld().getName())) { lang.sendMessage(sender, "ERROR.duel.in-blacklisted-world"); return true; } if ((combatTagPlus != null && combatTagPlus.isTagged(player)) || (pvpManager != null && pvpManager.isTagged(player)) || (combatLogX != null && combatLogX.isTagged(player))) { lang.sendMessage(sender, "ERROR.duel.is-tagged"); return true; } String duelzone = null; if (worldGuard != null && config.isDuelzoneEnabled() && (duelzone = worldGuard.findDuelZone(player)) == null) { lang.sendMessage(sender, "ERROR.duel.not-in-duelzone", "regions", config.getDuelzones()); return true; } if (arenaManager.isInMatch(player)) { lang.sendMessage(sender, "ERROR.duel.already-in-match.sender"); return true; } if (spectateManager.isSpectating(player)) { lang.sendMessage(sender, "ERROR.spectate.already-spectating.sender"); return true; } final Player target = Bukkit.getPlayerExact(args[0]); if (target == null || !player.canSee(target)) { lang.sendMessage(sender, "ERROR.player.not-found", "name", args[0]); return true; } if (player.equals(target)) { lang.sendMessage(sender, "ERROR.duel.is-self"); return true; } final UserData user = userManager.get(target); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", target.getName()); return true; } if (!sender.hasPermission(Permissions.ADMIN) && !user.canRequest()) { lang.sendMessage(sender, "ERROR.duel.requests-disabled", "name", target.getName()); return true; } if (requestManager.has(player, target)) { lang.sendMessage(sender, "ERROR.duel.already-has-request", "name", target.getName()); return true; } if (arenaManager.isInMatch(target)) { lang.sendMessage(sender, "ERROR.duel.already-in-match.target", "name", target.getName()); return true; } if (spectateManager.isSpectating(target)) { lang.sendMessage(sender, "ERROR.spectate.already-spectating.target", "name", target.getName()); return true; } final Settings settings = settingManager.getSafely(player); // Reset bet to prevent accidents settings.setBet(0); settings.setTarget(target); settings.setBaseLoc(player); settings.setDuelzone(player, duelzone); boolean sendRequest = false; if (args.length > 1) { final int amount = NumberUtil.parseInt(args[1]).orElse(0); if (amount > 0 && config.isMoneyBettingEnabled()) { if (config.isMoneyBettingUsePermission() && !player.hasPermission(Permissions.MONEY_BETTING) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.MONEY_BETTING); return true; } if (vault == null || vault.getEconomy() == null) { lang.sendMessage(sender, "ERROR.setting.disabled-option", "option", lang.getMessage("GENERAL.betting")); return true; } if (!vault.getEconomy().has(player, amount)) { lang.sendMessage(sender, "ERROR.command.not-enough-money"); return true; } settings.setBet(amount); } if (args.length > 2) { if (args[2].equalsIgnoreCase("true")) { if (!config.isItemBettingEnabled()) { lang.sendMessage(player, "ERROR.setting.disabled-option", "option", lang.getMessage("GENERAL.item-betting")); return true; } if (config.isItemBettingUsePermission() && !player.hasPermission(Permissions.ITEM_BETTING) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.ITEM_BETTING); return true; } settings.setItemBetting(true); } if (args.length > 3) { if (args[3].equals("-")) { if (!config.isOwnInventoryEnabled()) { lang.sendMessage(player, "ERROR.setting.disabled-option", "option", lang.getMessage("GENERAL.own-inventory")); return true; } if (config.isOwnInventoryUsePermission() && !player.hasPermission(Permissions.OWN_INVENTORY) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.OWN_INVENTORY); return true; } settings.setOwnInventory(true); } else if (!config.isKitSelectingEnabled()) { lang.sendMessage(player, "ERROR.setting.disabled-option", "option", lang.getMessage("GENERAL.kit-selector")); return true; } else { final String name = StringUtil.join(args, " ", 3, args.length); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return true; } final String permission = String.format(Permissions.KIT, name.replace(" ", "-").toLowerCase()); if (kit.isUsePermission() && !player.hasPermission(Permissions.KIT_ALL) && !player.hasPermission(permission)) { lang.sendMessage(player, "ERROR.no-permission", "permission", permission); return true; } settings.setKit(kit); } sendRequest = true; } } } if (sendRequest) { // If all settings were selected via command, send request without opening settings GUI. requestManager.send(player, target, settings); } else if (config.isOwnInventoryEnabled()) { // If own inventory is enabled, prompt request settings GUI. settings.openGui(player); } else { // Maintain old behavior: If own inventory is disabled, prompt kit selector first instead of request settings GUI. kitManager.getGui().open(player); } return true; } @Override protected void execute(final CommandSender sender, final String label, final String[] args) {} // Disables default TabCompleter @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/AcceptCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.request.RequestAcceptEvent; import me.realized.duels.command.BaseCommand; import me.realized.duels.hook.hooks.CombatLogXHook; import me.realized.duels.hook.hooks.CombatTagPlusHook; import me.realized.duels.hook.hooks.PvPManagerHook; import me.realized.duels.hook.hooks.worldguard.WorldGuardHook; import me.realized.duels.request.RequestImpl; import me.realized.duels.setting.Settings; import me.realized.duels.util.inventory.InventoryUtil; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class AcceptCommand extends BaseCommand { private final CombatTagPlusHook combatTagPlus; private final PvPManagerHook pvpManager; private final CombatLogXHook combatLogX; private final WorldGuardHook worldGuard; public AcceptCommand(final DuelsPlugin plugin) { super(plugin, "accept", "accept [player]", "Accepts a duel request.", 2, true); this.combatTagPlus = hookManager.getHook(CombatTagPlusHook.class); this.pvpManager = hookManager.getHook(PvPManagerHook.class); this.combatLogX = plugin.getHookManager().getHook(CombatLogXHook.class); this.worldGuard = hookManager.getHook(WorldGuardHook.class); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; if (config.isRequiresClearedInventory() && InventoryUtil.hasItem(player)) { lang.sendMessage(sender, "ERROR.duel.inventory-not-empty"); return; } if (config.isPreventCreativeMode() && player.getGameMode() == GameMode.CREATIVE) { lang.sendMessage(sender, "ERROR.duel.in-creative-mode"); return; } if ((combatTagPlus != null && combatTagPlus.isTagged(player)) || (pvpManager != null && pvpManager.isTagged(player)) || (combatLogX != null && combatLogX.isTagged(player))) { lang.sendMessage(sender, "ERROR.duel.is-tagged"); return; } String duelzone = null; if (worldGuard != null && config.isDuelzoneEnabled() && (duelzone = worldGuard.findDuelZone(player)) == null) { lang.sendMessage(sender, "ERROR.duel.not-in-duelzone", "regions", config.getDuelzones()); return; } if (arenaManager.isInMatch(player)) { lang.sendMessage(sender, "ERROR.duel.already-in-match.sender"); return; } if (spectateManager.isSpectating(player)) { lang.sendMessage(sender, "ERROR.spectate.already-spectating.sender"); return; } final Player target = Bukkit.getPlayerExact(args[1]); if (target == null || !player.canSee(target)) { lang.sendMessage(sender, "ERROR.player.not-found", "name", args[1]); return; } final RequestImpl request = requestManager.get(target, player); if (request == null) { lang.sendMessage(sender, "ERROR.duel.no-request", "name", target.getName()); return; } final RequestAcceptEvent event = new RequestAcceptEvent(player, target, request); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } requestManager.remove(target, player); if (arenaManager.isInMatch(target)) { lang.sendMessage(sender, "ERROR.duel.already-in-match.target", "name", target.getName()); return; } if (spectateManager.isSpectating(target)) { lang.sendMessage(sender, "ERROR.spectate.already-spectating.target", "name", target.getName()); return; } final Settings settings = request.getSettings(); final String kit = settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.not-selected"); final String arena = settings.getArena() != null ? settings.getArena().getName() : lang.getMessage("GENERAL.random"); final double bet = settings.getBet(); final String itemBetting = settings.isItemBetting() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"); lang.sendMessage(player, "COMMAND.duel.request.accept.receiver", "name", target.getName(), "kit", kit, "arena", arena, "bet_amount", bet, "item_betting", itemBetting); lang.sendMessage(target, "COMMAND.duel.request.accept.sender", "name", player.getName(), "kit", kit, "arena", arena, "bet_amount", bet, "item_betting", itemBetting); if (settings.isItemBetting()) { settings.setBaseLoc(player); settings.setDuelzone(player, duelzone); bettingManager.open(settings, target, player); } else { duelManager.startMatch(player, target, settings, null, null); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/DenyCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.request.RequestDenyEvent; import me.realized.duels.command.BaseCommand; import me.realized.duels.request.RequestImpl; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class DenyCommand extends BaseCommand { public DenyCommand(final DuelsPlugin plugin) { super(plugin, "deny", "deny [player]", "Declines a duel request.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; final Player target = Bukkit.getPlayerExact(args[1]); if (target == null || !player.canSee(target)) { lang.sendMessage(sender, "ERROR.player.not-found", "name", args[1]); return; } final RequestImpl request; if ((request = requestManager.remove(target, player)) == null) { lang.sendMessage(sender, "ERROR.duel.no-request", "name", target.getName()); return; } final RequestDenyEvent event = new RequestDenyEvent(player, target, request); Bukkit.getPluginManager().callEvent(event); lang.sendMessage(player, "COMMAND.duel.request.deny.receiver", "name", target.getName()); lang.sendMessage(target, "COMMAND.duel.request.deny.sender", "name", player.getName()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/InventoryCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.gui.inventory.InventoryGui; import me.realized.duels.util.UUIDUtil; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class InventoryCommand extends BaseCommand { public InventoryCommand(final DuelsPlugin plugin) { super(plugin, "_", "_ [uuid]", "Displays player's inventories after match.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UUID target = UUIDUtil.parseUUID(args[1]); if (target == null) { lang.sendMessage(sender, "ERROR.inventory-view.not-a-uuid", "input", args[1]); return; } final InventoryGui gui = inventoryManager.get(UUID.fromString(args[1])); if (gui == null) { lang.sendMessage(sender, "ERROR.inventory-view.not-found", "uuid", target); return; } gui.open((Player) sender); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/StatsCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import java.util.Calendar; import java.util.GregorianCalendar; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import me.realized.duels.util.DateUtil; import me.realized.duels.util.TextBuilder; import net.md_5.bungee.api.chat.HoverEvent.Action; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class StatsCommand extends BaseCommand { public StatsCommand(final DuelsPlugin plugin) { super(plugin, "stats", null, null, Permissions.STATS, 1, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; if (args.length > getLength()) { if (!sender.hasPermission(Permissions.STATS_OTHERS)) { lang.sendMessage(sender, "ERROR.no-permission", "permission", Permissions.STATS_OTHERS); return; } displayStats(player, args[1]); return; } displayStats(player, player.getName()); } private void displayStats(final Player sender, final String name) { final UserData user = userManager.get(name); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", name); return; } final String wins = String.valueOf(user.getWins()); final String losses = String.valueOf(user.getLosses()); final String wlRatio = String.valueOf(user.getLosses() > 0 ? Math.round(((double) user.getWins() / (double) user.getLosses()) * 100.0) / 100.0 : user.getWins()); final String requests = String.valueOf(user.canRequest() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled")); final Object[] args = {"name", user.getName(), "wins", wins, "losses", losses, "wl_ratio", wlRatio, "requests_enabled", requests}; lang.sendMessage(sender, "COMMAND.duel.stats.displayed", args); if (config.isDisplayKitRatings() || config.isDisplayNoKitRating()) { lang.sendMessage(sender, "COMMAND.duel.stats.rating.header", args); if (config.isDisplayNoKitRating()) { lang.sendMessage(sender, "COMMAND.duel.stats.rating.format", "type", config.getTopNoKitType(), "kit", config.getTopNoKitType(), "rating", user.getRating()); } if (config.isDisplayKitRatings()) { kitManager.getKits().forEach(kit -> lang.sendMessage(sender, "COMMAND.duel.stats.rating.format", "type", kit.getName(), "kit", kit.getName(), "rating", user.getRating(kit))); } lang.sendMessage(sender, "COMMAND.duel.stats.rating.footer", args); } if (config.isDisplayPastMatches()) { lang.sendMessage(sender, "COMMAND.duel.stats.match.header", args); final Calendar calendar = new GregorianCalendar(); user.getMatches().forEach(match -> { final String kit = match.getKit() != null ? match.getKit() : lang.getMessage("GENERAL.none"); final String duration = DateUtil.formatMilliseconds(match.getDuration()); final String timeSince = DateUtil.formatMilliseconds(calendar.getTimeInMillis() - match.getCreation()); TextBuilder .of(lang.getMessage("COMMAND.duel.stats.match.format", "winner", match.getWinner(), "loser", match.getLoser())) .setHoverEvent(Action.SHOW_TEXT, lang.getMessage("COMMAND.duel.stats.match.hover-text", "kit", kit, "duration", duration, "time", timeSince, "health", match.getHealth())) .send(sender); }); lang.sendMessage(sender, "COMMAND.duel.stats.match.footer", args); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/ToggleCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class ToggleCommand extends BaseCommand { public ToggleCommand(final DuelsPlugin plugin) { super(plugin, "toggle", null, null, Permissions.TOGGLE, 1, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UserData user = userManager.get((Player) sender); if (user == null) { lang.sendMessage(sender, "ERROR.data.load-failure"); return; } user.setRequests(!user.canRequest()); lang.sendMessage(sender, "COMMAND.duel.toggle." + (user.canRequest() ? "enabled" : "disabled")); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/TopCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.user.UserManager.TopData; import me.realized.duels.api.user.UserManager.TopEntry; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.CommandSender; public class TopCommand extends BaseCommand { public TopCommand(final DuelsPlugin plugin) { super(plugin, "top", "top [-:kit:wins:losses]", "Displays top wins, losses, or rating for kit.", Permissions.TOP, 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { if (!userManager.isLoaded()) { lang.sendMessage(sender, "ERROR.data.not-loaded"); return; } final TopEntry topEntry; if (args[1].equals("-")) { topEntry = userManager.getTopRatings(); } else if (args[1].equalsIgnoreCase("wins")) { topEntry = userManager.getWins(); } else if (args[1].equalsIgnoreCase("losses")) { topEntry = userManager.getLosses(); } else { final String name = StringUtil.join(args, " ", 1, args.length); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } topEntry = userManager.getTopRatings(kit); } final List top; if (topEntry == null || (top = topEntry.getData()).isEmpty()) { lang.sendMessage(sender, "ERROR.top.no-data-available"); return; } lang.sendMessage(sender, "COMMAND.duel.top.next-update", "remaining", userManager.getNextUpdate(topEntry.getCreation())); lang.sendMessage(sender, "COMMAND.duel.top.header", "type", topEntry.getType()); for (int i = 0; i < top.size(); i++) { final TopData data = top.get(i); lang.sendMessage(sender, "COMMAND.duel.top.display-format", "rank", i + 1, "name", data.getName(), "score", data.getValue(), "identifier", topEntry.getIdentifier()); } lang.sendMessage(sender, "COMMAND.duel.top.footer", "type", topEntry.getType()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/VersionCommand.java ================================================ package me.realized.duels.command.commands.duel.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import me.realized.duels.util.TextBuilder; import net.md_5.bungee.api.chat.ClickEvent.Action; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; public class VersionCommand extends BaseCommand { public VersionCommand(final DuelsPlugin plugin) { super(plugin, "version", null, null, Permissions.DUEL, 1, true, "v"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final PluginDescriptionFile info = plugin.getDescription(); TextBuilder .of(StringUtil.color("&b" + info.getFullName() + " by " + info.getAuthors().get(0) + " &l[Click]")) .setClickEvent(Action.OPEN_URL, info.getWebsite()) .send((Player) sender); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/DuelsCommand.java ================================================ package me.realized.duels.command.commands.duels; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.command.commands.duels.subcommands.AddsignCommand; import me.realized.duels.command.commands.duels.subcommands.BindCommand; import me.realized.duels.command.commands.duels.subcommands.CreateCommand; import me.realized.duels.command.commands.duels.subcommands.CreatequeueCommand; import me.realized.duels.command.commands.duels.subcommands.DeleteCommand; import me.realized.duels.command.commands.duels.subcommands.DeletekitCommand; import me.realized.duels.command.commands.duels.subcommands.DeletequeueCommand; import me.realized.duels.command.commands.duels.subcommands.DeletesignCommand; import me.realized.duels.command.commands.duels.subcommands.EditCommand; import me.realized.duels.command.commands.duels.subcommands.HelpCommand; import me.realized.duels.command.commands.duels.subcommands.InfoCommand; import me.realized.duels.command.commands.duels.subcommands.ListCommand; import me.realized.duels.command.commands.duels.subcommands.LoadkitCommand; import me.realized.duels.command.commands.duels.subcommands.LobbyCommand; import me.realized.duels.command.commands.duels.subcommands.OptionsCommand; import me.realized.duels.command.commands.duels.subcommands.PlaysoundCommand; import me.realized.duels.command.commands.duels.subcommands.ReloadCommand; import me.realized.duels.command.commands.duels.subcommands.ResetCommand; import me.realized.duels.command.commands.duels.subcommands.ResetratingCommand; import me.realized.duels.command.commands.duels.subcommands.SavekitCommand; import me.realized.duels.command.commands.duels.subcommands.SetCommand; import me.realized.duels.command.commands.duels.subcommands.SetitemCommand; import me.realized.duels.command.commands.duels.subcommands.SetlobbyCommand; import me.realized.duels.command.commands.duels.subcommands.SetratingCommand; import me.realized.duels.command.commands.duels.subcommands.TeleportCommand; import me.realized.duels.command.commands.duels.subcommands.ToggleCommand; import org.bukkit.command.CommandSender; public class DuelsCommand extends BaseCommand { public DuelsCommand(final DuelsPlugin plugin) { super(plugin, "duels", Permissions.ADMIN, false); child( new HelpCommand(plugin), new SavekitCommand(plugin), new DeletekitCommand(plugin), new LoadkitCommand(plugin), new SetitemCommand(plugin), new OptionsCommand(plugin), new BindCommand(plugin), new CreateCommand(plugin), new DeleteCommand(plugin), new SetCommand(plugin), new ToggleCommand(plugin), new TeleportCommand(plugin), new CreatequeueCommand(plugin), new DeletequeueCommand(plugin), new AddsignCommand(plugin), new DeletesignCommand(plugin), new SetlobbyCommand(plugin), new LobbyCommand(plugin), new InfoCommand(plugin), new ListCommand(plugin), new EditCommand(plugin), new SetratingCommand(plugin), new ResetCommand(plugin), new ResetratingCommand(plugin), new PlaysoundCommand(plugin), new ReloadCommand(plugin) ); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { lang.sendMessage(sender, "COMMAND.duels.usage", "command", label); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/AddsignCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import me.realized.duels.util.BlockUtil; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.Location; import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class AddsignCommand extends BaseCommand { public AddsignCommand(final DuelsPlugin plugin) { super(plugin, "addsign", "addsign [bet] [kit:-]", "Creates a queue sign with given bet and kit.", 3, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; final Sign sign = BlockUtil.getTargetBlock(player, Sign.class, 6); if (sign == null) { lang.sendMessage(sender, "ERROR.sign.not-a-sign"); return; } final int bet = NumberUtil.parseInt(args[1]).orElse(0); KitImpl kit = null; if (!args[2].equals("-")) { String name = StringUtil.join(args, " ", 2, args.length).replace("-", " "); kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } } final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); final Queue queue = queueManager.get(kit, bet); if (queue == null) { lang.sendMessage(sender, "ERROR.queue.not-found", "bet_amount", bet, "kit", kitName); return; } if (!queueSignManager.create(player, sign.getLocation(), queue)) { lang.sendMessage(sender, "ERROR.sign.already-exists"); return; } final Location location = sign.getLocation(); lang.sendMessage(sender, "COMMAND.duels.add-sign", "location", StringUtil.parse(location), "kit", kitName, "bet_amount", bet); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } if (args.length > 2) { return handleTabCompletion(args[2], kitManager.getNames(true)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/BindCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.gui.bind.BindGui; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class BindCommand extends BaseCommand { public BindCommand(final DuelsPlugin plugin) { super(plugin, "bind", "bind [kit]", "Opens the arena bind gui for kit.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } final Player player = (Player) sender; plugin.getGuiListener().addGui(player, new BindGui(plugin, kit), true).open(player); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(false)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/CreateCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.CommandSender; public class CreateCommand extends BaseCommand { public CreateCommand(final DuelsPlugin plugin) { super(plugin, "create", "create [name]", "Creates an arena with given name.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length); if (!StringUtil.isAlphanumeric(name)) { lang.sendMessage(sender, "ERROR.command.name-not-alphanumeric", "name", name); return; } if (!arenaManager.create(sender, name)) { lang.sendMessage(sender, "ERROR.arena.already-exists", "name", name); return; } lang.sendMessage(sender, "COMMAND.duels.create", "name", name); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/CreatequeueCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class CreatequeueCommand extends BaseCommand { public CreatequeueCommand(final DuelsPlugin plugin) { super(plugin, "createqueue", "createqueue [bet] [-:kit]", "Creates a queue with given bet and kit.", 3, false, "createq"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final int bet = NumberUtil.parseInt(args[1]).orElse(0); KitImpl kit = null; if (!args[2].equals("-")) { String name = StringUtil.join(args, " ", 2, args.length).replace("-", " "); kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } } final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); if (queueManager.create(sender, kit, bet) == null) { lang.sendMessage(sender, "ERROR.queue.already-exists", "kit", kitName, "bet_amount", bet); return; } lang.sendMessage(sender, "COMMAND.duels.create-queue", "kit", kitName, "bet_amount", bet); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } if (args.length > 2) { return handleTabCompletion(args[2], kitManager.getNames(true)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/DeleteCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class DeleteCommand extends BaseCommand { public DeleteCommand(final DuelsPlugin plugin) { super(plugin, "delete", "delete [name]", "Deletes an arena.", 2, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final ArenaImpl arena = arenaManager.get(name); if (arena == null) { lang.sendMessage(sender, "ERROR.arena.not-found", "name", name); return; } if (arena.isUsed()) { lang.sendMessage(sender, "ERROR.arena.delete-failure", "name", name); return; } arenaManager.remove(sender, arena); lang.sendMessage(sender, "COMMAND.duels.delete", "name", name); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], arenaManager.getNames()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/DeletekitCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class DeletekitCommand extends BaseCommand { public DeletekitCommand(final DuelsPlugin plugin) { super(plugin, "deletekit", "deletekit [name]", "Deletes a kit.", 2, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); if (kitManager.remove(sender, name) == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } lang.sendMessage(sender, "COMMAND.duels.delete-kit", "name", name); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(false)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/DeletequeueCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class DeletequeueCommand extends BaseCommand { public DeletequeueCommand(final DuelsPlugin plugin) { super(plugin, "deletequeue", "deletequeue [bet] [-:kit]", "Deletes a queue.", 3, false, "delqueue", "delq"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final int bet = NumberUtil.parseInt(args[1]).orElse(0); KitImpl kit = null; if (!args[2].equals("-")) { String name = StringUtil.join(args, " ", 2, args.length).replace("-", " "); kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } } final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); if (queueManager.remove(sender, kit, bet) == null) { lang.sendMessage(sender, "ERROR.queue.not-found", "bet_amount", bet, "kit", kitName); return; } lang.sendMessage(sender, "COMMAND.duels.delete-queue", "kit", kitName, "bet_amount", bet); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } if (args.length > 2) { return handleTabCompletion(args[2], kitManager.getNames(true)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/DeletesignCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.kit.Kit; import me.realized.duels.command.BaseCommand; import me.realized.duels.queue.Queue; import me.realized.duels.queue.sign.QueueSignImpl; import me.realized.duels.util.BlockUtil; import me.realized.duels.util.StringUtil; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Sign; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class DeletesignCommand extends BaseCommand { public DeletesignCommand(final DuelsPlugin plugin) { super(plugin, "deletesign", null, null, 1, true, "delsign"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; final Sign sign = BlockUtil.getTargetBlock(player, Sign.class, 6); if (sign == null) { lang.sendMessage(sender, "ERROR.sign.not-a-sign"); return; } final QueueSignImpl queueSign = queueSignManager.remove(player, sign.getLocation()); if (queueSign == null) { lang.sendMessage(sender, "ERROR.sign.not-found"); return; } sign.setType(Material.AIR); sign.update(true); final Location location = sign.getLocation(); final Queue queue = queueSign.getQueue(); final Kit kit = queue.getKit(); final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); lang.sendMessage(sender, "COMMAND.duels.del-sign", "location", StringUtil.parse(location), "kit", kitName, "bet_amount", queue.getBet()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/EditCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.user.User; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.function.TriFunction; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class EditCommand extends BaseCommand { private final Map> getters = new HashMap<>(); private final Map> setters = new HashMap<>(); private final Map> actions = new HashMap<>(); public EditCommand(final DuelsPlugin plugin) { super(plugin, "edit", "edit [name] [add:remove:set] [wins:losses] [amount]", "Edits player's wins or losses.", 5, false); getters.put("wins", User::getWins); getters.put("losses", User::getLosses); setters.put("wins", User::setWins); setters.put("losses", User::setLosses); actions.put("set", (user, type, amount) -> amount); actions.put("add", (user, type, amount) -> getters.get(type).apply(user) + amount); actions.put("remove", (user, type, amount) -> getters.get(type).apply(user) - amount); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UserData user = userManager.get(args[1]); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", args[1]); return; } final String actionName = args[2].toLowerCase(); final TriFunction action = actions.get(actionName); if (action == null) { lang.sendMessage(sender, "ERROR.command.invalid-action", "action", actionName, "available_actions", actions.keySet()); return; } final String option = args[3].toLowerCase(); final BiConsumer setter = setters.get(option); if (setter == null) { lang.sendMessage(sender, "ERROR.command.invalid-option", "option", option, "available_options", getters.keySet()); return; } final int amount = Math.max(NumberUtil.parseInt(args[4]).orElse(0), 0); setter.accept(user, action.apply(user, option, amount)); lang.sendMessage(sender, "COMMAND.duels.edit", "name", user.getName(), "type", option, "action", actionName, "amount", amount); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 3) { return actions.keySet().stream() .filter(type -> type.toLowerCase().startsWith(args[2].toLowerCase())) .collect(Collectors.toList()); } if (args.length == 4) { return setters.keySet().stream() .filter(type -> type.toLowerCase().startsWith(args[3].toLowerCase())) .collect(Collectors.toList()); } if (args.length > 4) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/HelpCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import com.google.common.collect.Lists; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class HelpCommand extends BaseCommand { private final List categories = Lists.newArrayList("arena", "kit", "queue", "sign", "user", "extra"); public HelpCommand(final DuelsPlugin plugin) { super(plugin, "help", null, null, 1, false, "h"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { if (args.length == getLength() || !categories.contains(args[1].toLowerCase())) { lang.sendMessage(sender, "COMMAND.duels.usage", "command", label); return; } lang.sendMessage(sender, "COMMAND.duels.help." + args[1].toLowerCase(), "command", label); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return categories.stream() .filter(category -> category.toLowerCase().startsWith(args[1].toLowerCase())) .collect(Collectors.toList()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/InfoCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class InfoCommand extends BaseCommand { public InfoCommand(final DuelsPlugin plugin) { super(plugin, "info", "info [name]", "Displays information about the selected arena.", 2, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final ArenaImpl arena = arenaManager.get(name); if (arena == null) { lang.sendMessage(sender, "ERROR.arena.not-found", "name", name); return; } final String inUse = arena.isUsed() ? lang.getMessage("GENERAL.true") : lang.getMessage("GENERAL.false"); final String disabled = arena.isDisabled() ? lang.getMessage("GENERAL.true") : lang.getMessage("GENERAL.false"); final String kits = StringUtil.join(arena.getKits().stream().map(KitImpl::getName).collect(Collectors.toList()), ", "); final String positions = StringUtil.join(arena.getPositions().values().stream().map(StringUtil::parse).collect(Collectors.toList()), ", "); final String players = StringUtil.join(arena.getPlayers().stream().map(Player::getName).collect(Collectors.toList()), ", "); lang.sendMessage(sender, "COMMAND.duels.info", "name", name, "in_use", inUse, "disabled", disabled, "kits", !kits.isEmpty() ? kits : lang.getMessage("GENERAL.none"), "positions", !positions.isEmpty() ? positions : lang.getMessage("GENERAL.none"), "players", !players.isEmpty() ? players : lang.getMessage("GENERAL.none")); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], arenaManager.getNames()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/ListCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.queue.DQueue; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.queue.sign.QueueSignImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.CommandSender; public class ListCommand extends BaseCommand { public ListCommand(final DuelsPlugin plugin) { super(plugin, "list", null, null, 1, false, "ls"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final List arenas = new ArrayList<>(); arenaManager.getArenasImpl().forEach(arena -> arenas.add("&" + getColor(arena) + arena.getName())); final String kits = StringUtil.join(kitManager.getKits().stream().map(Kit::getName).collect(Collectors.toList()), ", "); final String queues = StringUtil.join(queueManager.getQueues().stream().map(DQueue::toString).collect(Collectors.toList()), ", "); final String signs = StringUtil.join(queueSignManager.getSigns().stream().map(QueueSignImpl::toString).collect(Collectors.toList()), ", "); lang.sendMessage(sender, "COMMAND.duels.list", "arenas", !arenas.isEmpty() ? StringUtil.join(arenas, "&r, &r") : lang.getMessage("GENERAL.none"), "kits", !kits.isEmpty() ? kits : lang.getMessage("GENERAL.none"), "queues", !queues.isEmpty() ? queues : lang.getMessage("GENERAL.none"), "queue_signs", !signs.isEmpty() ? signs : lang.getMessage("GENERAL.none"), "lobby", StringUtil.parse(playerManager.getLobby())); } private String getColor(final ArenaImpl arena) { return arena.isDisabled() ? "4" : (arena.getPositions().size() < 2 ? "9" : arena.isUsed() ? "c" : "a"); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/LoadkitCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class LoadkitCommand extends BaseCommand { public LoadkitCommand(final DuelsPlugin plugin) { super(plugin, "loadkit", "loadkit [name]", "Loads the selected kit to your inventory.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } final Player player = (Player) sender; player.getInventory().clear(); kit.equip(player); lang.sendMessage(sender, "COMMAND.duels.load-kit", "name", name); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(false)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/LobbyCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class LobbyCommand extends BaseCommand { public LobbyCommand(final DuelsPlugin plugin) { super(plugin, "lobby", null, null, 1, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { ((Player) sender).teleport(playerManager.getLobby()); lang.sendMessage(sender, "COMMAND.duels.lobby"); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/OptionsCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.gui.options.OptionsGui; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class OptionsCommand extends BaseCommand { public OptionsCommand(final DuelsPlugin plugin) { super(plugin, "options", "options [kit]", "Opens the options gui for kit.", 2, true, "useoption"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } final Player player = (Player) sender; plugin.getGuiListener().addGui(player, new OptionsGui(plugin, player, kit), true).open(player); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(false)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/PlaysoundCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.config.Config.MessageSound; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class PlaysoundCommand extends BaseCommand { public PlaysoundCommand(final DuelsPlugin plugin) { super(plugin, "playsound", "playsound [name]", "Plays the selected sound if defined.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final MessageSound sound = config.getSound(args[1]); if (sound == null) { lang.sendMessage(sender, "ERROR.sound.not-found", "name", args[1]); return; } final Player player = (Player) sender; player.playSound(player.getLocation(), sound.getType(), sound.getVolume(), sound.getPitch()); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return config.getSounds().stream() .filter(name -> name.toLowerCase().startsWith(args[1].toLowerCase())) .collect(Collectors.toList()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/ReloadCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.Loadable; import me.realized.duels.util.Reloadable; import me.realized.duels.util.StringUtil; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class ReloadCommand extends BaseCommand { public ReloadCommand(final DuelsPlugin plugin) { super(plugin, "reload", null, null, 1, false, "rl"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { if (args.length > getLength()) { final Loadable target = plugin.find(args[1]); if (!(target instanceof Reloadable)) { sender.sendMessage(ChatColor.RED + "Invalid module. The following modules are available for a reload: " + StringUtil.join(plugin.getReloadables(), ", ")); return; } final String name = target.getClass().getSimpleName(); if (plugin.reload(target)) { sender.sendMessage(ChatColor.GREEN + "[" + plugin.getDescription().getFullName() + "] Successfully reloaded " + name + "."); } else { sender.sendMessage(ChatColor.RED + "An error occured while reloading " + name + "! Please check the console for more information."); } return; } if (plugin.reload()) { sender.sendMessage(ChatColor.GREEN + "[" + plugin.getDescription().getFullName() + "] Reload complete."); } else { sender.sendMessage(ChatColor.RED + "An error occured while reloading the plugin! Please check the console for more information."); } } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return plugin.getReloadables().stream() .filter(name -> name.toLowerCase().startsWith(args[1].toLowerCase())) .collect(Collectors.toList()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/ResetCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import org.bukkit.command.CommandSender; public class ResetCommand extends BaseCommand { public ResetCommand(final DuelsPlugin plugin) { super(plugin, "reset", "reset [name]", "Resets player's stats.", 2, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UserData user = userManager.get(args[1]); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", args[1]); return; } user.reset(); lang.sendMessage(sender, "COMMAND.duels.reset", "name", user.getName()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/ResetratingCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class ResetratingCommand extends BaseCommand { public ResetratingCommand(final DuelsPlugin plugin) { super(plugin, "resetrating", "resetrating [name] [-:kit:all]", "Resets specified kit's rating or all.", 3, false, "resetr"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UserData user = userManager.get(args[1]); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", args[1]); return; } if (args[2].equalsIgnoreCase("all")) { user.resetRating(); kitManager.getKits().forEach(user::resetRating); lang.sendMessage(sender, "COMMAND.duels.reset-rating", "name", user.getName(), "kit", "all"); } else if (args[2].equals("-")) { user.resetRating(); lang.sendMessage(sender, "COMMAND.duels.reset-rating", "name", user.getName(), "kit", lang.getMessage("GENERAL.none")); } else { final String name = StringUtil.join(args, " ", 2, args.length).replace("-", " "); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } user.resetRating(kit); lang.sendMessage(sender, "COMMAND.duels.reset-rating", "name", user.getName(), "kit", name); } } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 3) { return handleTabCompletion(args[2], kitManager.getNames(true)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/SavekitCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SavekitCommand extends BaseCommand { public SavekitCommand(final DuelsPlugin plugin) { super(plugin, "savekit", "savekit [name]", "Saves a kit with given name.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String[] argsNoOptions = Arrays.stream(args).filter(s -> !s.startsWith("-")).toArray(String[]::new); final String name = StringUtil.join(argsNoOptions, " ", 1, argsNoOptions.length); if (!StringUtil.isAlphanumeric(name)) { lang.sendMessage(sender, "ERROR.command.name-not-alphanumeric", "name", name); return; } if (kitManager.create((Player) sender, name, Arrays.asList(args).contains("-o")) == null) { lang.sendMessage(sender, "ERROR.kit.already-exists", "name", name); return; } lang.sendMessage(sender, "COMMAND.duels.save-kit", "name", name); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/SetCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SetCommand extends BaseCommand { public SetCommand(final DuelsPlugin plugin) { super(plugin, "set", "set [name] [1:2]", "Sets the teleport position of an arena.", 3, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length - 1).replace("-", " "); final ArenaImpl arena = arenaManager.get(name); if (arena == null) { lang.sendMessage(sender, "ERROR.arena.not-found", "name", name); return; } final int pos = NumberUtil.parseInt(args[args.length - 1]).orElse(arena.getPositions().size() + 1); if (pos <= 0 || pos > 2) { lang.sendMessage(sender, "ERROR.arena.invalid-position"); return; } final Player player = (Player) sender; final Location location = player.getLocation().clone(); arena.setPosition(player, pos, location); lang.sendMessage(sender, "COMMAND.duels.set", "position", pos, "name", name, "location", StringUtil.parse(location)); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], arenaManager.getNames()); } if (args.length > 2) { return Arrays.asList("1", "2"); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/SetitemCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import me.realized.duels.util.inventory.InventoryUtil; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SetitemCommand extends BaseCommand { public SetitemCommand(final DuelsPlugin plugin) { super(plugin, "setitem", "setitem [name]", "Sets the displayed item for selected kit.", 2, true); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; final ItemStack held = InventoryUtil.getItemInHand(player); if (held == null || held.getType() == Material.AIR) { lang.sendMessage(sender, "ERROR.kit.empty-hand"); return; } final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final KitImpl kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } kit.setDisplayed(held.clone()); kitManager.getGui().calculatePages(); lang.sendMessage(sender, "COMMAND.duels.set-item", "name", name); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(false)); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/SetlobbyCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SetlobbyCommand extends BaseCommand { public SetlobbyCommand(final DuelsPlugin plugin) { super(plugin, "setlobby", null, null, 1, true, "setspawn"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { if (!playerManager.setLobby((Player) sender)) { lang.sendMessage(sender, "ERROR.command.lobby-save-failure"); return; } lang.sendMessage(sender, "COMMAND.duels.set-lobby"); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/SetratingCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.command.BaseCommand; import me.realized.duels.data.UserData; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class SetratingCommand extends BaseCommand { public SetratingCommand(final DuelsPlugin plugin) { super(plugin, "setrating", "setrating [name] [-:kit] [amount]", "Sets player's rating for kit.", 4, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final UserData user = userManager.get(args[1]); if (user == null) { lang.sendMessage(sender, "ERROR.data.not-found", "name", args[1]); return; } KitImpl kit = null; if (!args[2].equals("-")) { final String name = StringUtil.join(args, " ", 2, args.length - 1).replace("-", " "); kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } } final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); final int rating = Math.max(NumberUtil.parseInt(args[args.length - 1]).orElse(config.getDefaultRating()), 0); user.setRating(kit, rating); lang.sendMessage(sender, "COMMAND.duels.set-rating", "name", user.getName(), "kit", kitName, "rating", rating); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 3) { return handleTabCompletion(args[2], kitManager.getNames(true)); } if (args.length > 3) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/TeleportCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class TeleportCommand extends BaseCommand { public TeleportCommand(final DuelsPlugin plugin) { super(plugin, "teleport", "teleport [name] <-2>", "Teleports to an arena.", 2, true, "tp", "goto"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final boolean second = args[args.length - 1].equals("-2"); final String name = StringUtil.join(args, " ", 1, args.length - (second ? 1 : 0)).replace("-", " "); final ArenaImpl arena = arenaManager.get(name); if (arena == null) { lang.sendMessage(sender, "ERROR.arena.not-found", "name", name); return; } if (arena.getPositions().isEmpty()) { lang.sendMessage(sender, "ERROR.arena.no-position-set", "name", name); return; } final int pos = second ? 2 : 1; final Location location = arena.getPosition(pos); if (location == null) { lang.sendMessage(sender, "ERROR.arena.invalid-position"); return; } ((Player) sender).teleport(location); lang.sendMessage(sender, "COMMAND.duels.teleport", "name", name, "position", pos); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], arenaManager.getNames()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/duels/subcommands/ToggleCommand.java ================================================ package me.realized.duels.command.commands.duels.subcommands; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.command.BaseCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class ToggleCommand extends BaseCommand { public ToggleCommand(final DuelsPlugin plugin) { super(plugin, "toggle", "toggle [name]", "Enables or disables an arena.", 2, false); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final String name = StringUtil.join(args, " ", 1, args.length).replace("-", " "); final ArenaImpl arena = arenaManager.get(name); if (arena == null) { lang.sendMessage(sender, "ERROR.arena.not-found", "name", name); return; } arena.setDisabled(sender, !arena.isDisabled()); lang.sendMessage(sender, "COMMAND.duels.toggle", "name", name, "state", arena.isDisabled() ? lang.getMessage("GENERAL.disabled") : lang.getMessage("GENERAL.enabled")); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], arenaManager.getNames()); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/queue/QueueCommand.java ================================================ package me.realized.duels.command.commands.queue; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.command.commands.queue.subcommands.JoinCommand; import me.realized.duels.command.commands.queue.subcommands.LeaveCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class QueueCommand extends BaseCommand { public QueueCommand(final DuelsPlugin plugin) { super(plugin, "queue", Permissions.QUEUE, true); child( new JoinCommand(plugin), new LeaveCommand(plugin) ); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; if (userManager.get(player) == null) { lang.sendMessage(sender, "ERROR.data.load-failure"); return; } queueManager.getGui().open(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/queue/subcommands/JoinCommand.java ================================================ package me.realized.duels.command.commands.queue.subcommands; import java.util.Arrays; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class JoinCommand extends BaseCommand { public JoinCommand(final DuelsPlugin plugin) { super(plugin, "join", "join [-:kit] [bet]", "Joins a queue.", Permissions.QUEUE, 2, true, "j"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { final Player player = (Player) sender; KitImpl kit = null; if (!args[1].startsWith("-")) { String name = StringUtil.join(args, " ", 1, args.length - (args.length > 2 ? 1 : 0)).replace("-", " "); kit = kitManager.get(name); if (kit == null) { lang.sendMessage(sender, "ERROR.kit.not-found", "name", name); return; } } final String kitName = kit != null ? kit.getName() : lang.getMessage("GENERAL.none"); final int bet = args.length > 2 ? NumberUtil.parseInt(args[args.length - 1]).orElse(0) : 0; final Queue queue = args[1].equals("-r") ? queueManager.randomQueue() : queueManager.get(kit, bet); if (queue == null) { lang.sendMessage(sender, "ERROR.queue.not-found", "bet_amount", bet, "kit", kitName); return; } queueManager.queue(player, queue); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 2) { return handleTabCompletion(args[1], kitManager.getNames(true)); } if (args.length > 2) { return Arrays.asList("0", "10", "50", "100", "500", "1000"); } return null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/command/commands/queue/subcommands/LeaveCommand.java ================================================ package me.realized.duels.command.commands.queue.subcommands; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.command.BaseCommand; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class LeaveCommand extends BaseCommand { public LeaveCommand(final DuelsPlugin plugin) { super(plugin, "leave", null, null, Permissions.QUEUE, 1, true, "l"); } @Override protected void execute(final CommandSender sender, final String label, final String[] args) { if (queueManager.remove((Player) sender) == null) { lang.sendMessage(sender, "ERROR.queue.not-in-queue"); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/config/Config.java ================================================ package me.realized.duels.config; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.converters.ConfigConverter9_10; import me.realized.duels.util.EnumUtil; import me.realized.duels.util.config.AbstractConfiguration; import org.bukkit.Sound; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; public class Config extends AbstractConfiguration { @Getter private int version; @Getter private boolean checkForUpdates; @Getter private boolean ctpPreventDuel; @Getter private boolean ctpPreventTag; @Getter private boolean pmPreventDuel; @Getter private boolean pmPreventTag; @Getter private boolean clxPreventDuel; @Getter private boolean clxPreventTag; @Getter private boolean autoUnvanish; @Getter private boolean setBackLocation; @Getter private boolean disableSkills; @Getter private boolean fuNoPowerLoss; @Getter private boolean fNoPowerLoss; @Getter private boolean duelzoneEnabled; @Getter private List duelzones; @Getter private boolean myPetDespawn; @Getter private boolean preventBountyLoss; @Getter private boolean preventKDRChange; @Getter private String lhWinsCmd; @Getter private String lhWinsTitle; @Getter private String lhLossesCmd; @Getter private String lhLossesTitle; @Getter private boolean requiresClearedInventory; @Getter private boolean preventCreativeMode; @Getter private boolean ownInventoryEnabled; @Getter private boolean ownInventoryDropInventoryItems; @Getter private boolean ownInventoryUsePermission; @Getter private boolean kitSelectingEnabled; @Getter private boolean kitSelectingUsePermission; @Getter private boolean arenaSelectingEnabled; @Getter private boolean arenaSelectingUsePermission; @Getter private boolean itemBettingEnabled; @Getter private boolean itemBettingUsePermission; @Getter private boolean moneyBettingEnabled; @Getter private boolean moneyBettingUsePermission; @Getter private int expiration; @Getter private int maxDuration; @Getter private boolean startCommandsEnabled; @Getter private boolean startCommandsQueueOnly; @Getter private List startCommands; @Getter private boolean endCommandsEnabled; @Getter private boolean endCommandsQueueOnly; @Getter private List endCommands; @Getter private boolean projectileHitMessageEnabled; @Getter private List projectileHitMessageTypes; @Getter private boolean preventInventoryOpen; @Getter private boolean protectKitItems; @Getter private boolean removeEmptyBottle; @Getter private boolean preventTpToMatchPlayers; @Getter private boolean forceAllowCombat; @Getter private boolean cancelIfMoved; @Getter private List blacklistedWorlds; @Getter private boolean teleportToLastLocation; @Getter private int teleportDelay; @Getter private boolean spawnFirework; @Getter private boolean arenaOnlyEndMessage; @Getter private boolean displayInventories; @Getter private boolean preventItemDrop; @Getter private boolean preventItemPickup; @Getter private boolean limitTeleportEnabled; @Getter private double distanceAllowed; @Getter private boolean blockAllCommands; @Getter private List whitelistedCommands; @Getter private List blacklistedCommands; @Getter private List queueBlacklistedCommands; @Getter private boolean ratingEnabled; @Getter private int kFactor; @Getter private int defaultRating; @Getter private boolean ratingQueueOnly; @Getter private boolean specRequiresClearedInventory; @Getter private boolean specUseSpectatorGamemode; @Getter private boolean specAddInvisibilityEffect; @Getter private List specWhitelistedCommands; @Getter private boolean cdEnabled; @Getter private List cdMessages; @Getter private List titles; @Getter private boolean preventMovement; @Getter private boolean preventLaunchProjectile; @Getter private boolean preventPvp; @Getter private boolean preventInteract; @Getter private boolean displayKitRatings; @Getter private boolean displayNoKitRating; @Getter private boolean displayPastMatches; @Getter private int matchesToDisplay; @Getter private long topUpdateInterval; @Getter private String topWinsType; @Getter private String topWinsIdentifier; @Getter private String topLossesType; @Getter private String topLossesIdentifier; @Getter private String topKitType; @Getter private String topKitIdentifier; @Getter private String topNoKitType; @Getter private String topNoKitIdentifier; @Getter private int kitSelectorRows; @Getter private String kitSelectorFillerType; @Getter private short kitSelectorFillerData; @Getter private int arenaSelectorRows; @Getter private String arenaSelectorFillerType; @Getter private short arenaSelectorFillerData; @Getter private String settingsFillerType; @Getter private short settingsFillerData; @Getter private int queuesRows; @Getter private String queuesFillerType; @Getter private short queuesFillerData; @Getter private boolean inheritKitItemType; @Getter private double soupHeartsToRegen; @Getter private boolean soupRemoveEmptyBowl; @Getter private boolean soupCancelIfAlreadyFull; private final Map sounds = new HashMap<>(); public Config(final DuelsPlugin plugin) { super(plugin, "config"); } @Override protected void loadValues(FileConfiguration configuration) throws Exception { final int prevVersion = configuration.getInt("config-version", 0); if (prevVersion < 10) { configuration = convert(new ConfigConverter9_10()); } else if (prevVersion < getLatestVersion()) { configuration = convert(null); } version = configuration.getInt("config-version"); checkForUpdates = configuration.getBoolean("check-for-updates", true); ctpPreventDuel = configuration.getBoolean("supported-plugins.CombatTagPlus.prevent-duel-if-tagged", true); ctpPreventTag = configuration.getBoolean("supported-plugins.CombatTagPlus.prevent-tag-in-duel", true); pmPreventDuel = configuration.getBoolean("supported-plugins.PvPManager.prevent-duel-if-tagged", true); pmPreventTag = configuration.getBoolean("supported-plugins.PvPManager.prevent-tag-in-duel", true); clxPreventDuel = configuration.getBoolean("supported-plugins.CombatLogX.prevent-duel-if-tagged", true); clxPreventTag = configuration.getBoolean("supported-plugins.CombatLogX.prevent-tag-in-duel", true); autoUnvanish = configuration.getBoolean("supported-plugins.Essentials.auto-unvanish", true); setBackLocation = configuration.getBoolean("supported-plugins.Essentials.set-back-location", true); disableSkills = configuration.getBoolean("supported-plugins.mcMMO.disable-skills-in-duel", true); fuNoPowerLoss = configuration.getBoolean("supported-plugins.FactionsUUID.no-power-loss-in-duel", true); fNoPowerLoss = configuration.getBoolean("supported-plugins.Factions.no-power-loss-in-duel", true); duelzoneEnabled = configuration.getBoolean("supported-plugins.WorldGuard.duelzone.enabled", false); duelzones = configuration.getStringList("supported-plugins.WorldGuard.duelzone.regions"); myPetDespawn = configuration.getBoolean("supported-plugins.MyPet.despawn-pet-in-duel", false); preventBountyLoss = configuration.getBoolean("supported-plugins.BountyHunters.prevent-bounty-loss-in-duel", true); preventKDRChange = configuration.getBoolean("supported-plugins.SimpleClans.prevent-kdr-change", true); lhWinsCmd = configuration.getString("supported-plugins.LeaderHeads.wins.menu.command", "openwins"); lhWinsTitle = configuration.getString("supported-plugins.LeaderHeads.wins.menu.title", "Duel Wins"); lhLossesCmd = configuration.getString("supported-plugins.LeaderHeads.losses.menu.command", "openlosses"); lhLossesTitle = configuration.getString("supported-plugins.LeaderHeads.losses.menu.title", "Duel Losses"); requiresClearedInventory = configuration.getBoolean("request.requires-cleared-inventory", true); preventCreativeMode = configuration.getBoolean("request.prevent-creative-mode", false); ownInventoryEnabled = configuration.getBoolean("request.use-own-inventory.enabled", true); ownInventoryDropInventoryItems = configuration.getBoolean("request.use-own-inventory.drop-inventory-items", false); ownInventoryUsePermission = configuration.getBoolean("request.use-own-inventory.use-permission", false); kitSelectingEnabled = configuration.getBoolean("request.kit-selecting.enabled", true); kitSelectingUsePermission = configuration.getBoolean("request.kit-selecting.use-permission", false); arenaSelectingEnabled = configuration.getBoolean("request.arena-selecting.enabled", true); arenaSelectingUsePermission = configuration.getBoolean("request.arena-selecting.use-permission", false); itemBettingEnabled = configuration.getBoolean("request.item-betting.enabled", true); itemBettingUsePermission = configuration.getBoolean("request.item-betting.use-permission", false); moneyBettingEnabled = configuration.getBoolean("request.money-betting.enabled", true); moneyBettingUsePermission = configuration.getBoolean("request.money-betting.use-permission", false); expiration = Math.max(configuration.getInt("request.expiration", 30), 0); maxDuration = configuration.getInt("duel.match.max-duration", -1); startCommandsEnabled = configuration.getBoolean("duel.match.start-commands.enabled", false); startCommandsQueueOnly = configuration.getBoolean("duel.match.start-commands.queue-matches-only", false); startCommands = configuration.getStringList("duel.match.start-commands.commands"); endCommandsEnabled = configuration.getBoolean("duel.match.end-commands.enabled", false); endCommandsQueueOnly = configuration.getBoolean("duel.match.end-commands.queue-matches-only", false); endCommands = configuration.getStringList("duel.match.end-commands.commands"); projectileHitMessageEnabled = configuration.getBoolean("duel.projectile-hit-message.enabled", true); projectileHitMessageTypes = configuration.getStringList("duel.projectile-hit-message.types"); preventInventoryOpen = configuration.getBoolean("duel.prevent-inventory-open", true); protectKitItems = configuration.getBoolean("duel.protect-kit-items", true); removeEmptyBottle = configuration.getBoolean("duel.remove-empty-bottle", true); preventTpToMatchPlayers = configuration.getBoolean("duel.prevent-teleport-to-match-players", true); forceAllowCombat = configuration.getBoolean("duel.force-allow-combat", true); cancelIfMoved = configuration.getBoolean("duel.cancel-if-moved", false); blacklistedWorlds = configuration.getStringList("duel.blacklisted-worlds"); teleportToLastLocation = configuration.getBoolean("duel.teleport-to-last-location", false); teleportDelay = configuration.getInt("duel.teleport-delay", 5); spawnFirework = configuration.getBoolean("duel.spawn-firework", true); arenaOnlyEndMessage = configuration.getBoolean("duel.arena-only-end-message", false); displayInventories = configuration.getBoolean("duel.display-inventories", true); preventItemDrop = configuration.getBoolean("duel.prevent-item-drop", false); preventItemPickup = configuration.getBoolean("duel.prevent-item-pickup", true); limitTeleportEnabled = configuration.getBoolean("duel.limit-teleportation.enabled", true); distanceAllowed = configuration.getDouble("duel.limit-teleportation.distance-allowed", 5.0); blockAllCommands = configuration.getBoolean("duel.block-all-commands", false); whitelistedCommands = configuration.getStringList("duel.whitelisted-commands"); blacklistedCommands = configuration.getStringList("duel.blacklisted-commands"); queueBlacklistedCommands = configuration.getStringList("queue.blacklisted-commands"); ratingEnabled = configuration.getBoolean("rating.enabled", true); kFactor = Math.max(configuration.getInt("rating.k-factor", 32), 1); defaultRating = Math.max(configuration.getInt("rating.default-rating", 1400), 0); ratingQueueOnly = configuration.getBoolean("rating.queue-matches-only", true); specRequiresClearedInventory = configuration.getBoolean("spectate.requires-cleared-inventory", false); specUseSpectatorGamemode = configuration.getBoolean("spectate.use-spectator-gamemode", false); specAddInvisibilityEffect = configuration.getBoolean("spectate.add-invisibility-effect", true); specWhitelistedCommands = configuration.getStringList("spectate.whitelisted-commands"); cdEnabled = configuration.getBoolean("countdown.enabled", true); cdMessages = configuration.getStringList("countdown.messages"); titles = configuration.getStringList("countdown.titles"); preventMovement = configuration.getBoolean("countdown.prevent.movement", true); preventLaunchProjectile = configuration.getBoolean("countdown.prevent.launch-projectile", true); preventPvp = configuration.getBoolean("countdown.prevent.pvp", true); preventInteract = configuration.getBoolean("countdown.prevent.interact", true); displayKitRatings = configuration.getBoolean("stats.display-kit-ratings", true); displayNoKitRating = configuration.getBoolean("stats.display-nokit-rating", false); displayPastMatches = configuration.getBoolean("stats.display-past-matches", true); matchesToDisplay = Math.max(configuration.getInt("stats.matches-to-display", 10), 0); topUpdateInterval = Math.max(configuration.getInt("top.update-interval", 5), 1) * 60L * 1000L; topWinsType = configuration.getString("top.displayed-replacers.wins.type", "Wins"); topWinsIdentifier = configuration.getString("top.displayed-replacers.wins.identifier", "wins"); topLossesType = configuration.getString("top.displayed-replacers.losses.type", "Losses"); topLossesIdentifier = configuration.getString("top.displayed-replacers.losses.identifier", "losses"); topKitType = configuration.getString("top.displayed-replacers.kit.type", "%kit%"); topKitIdentifier = configuration.getString("top.displayed-replacers.kit.identifier", "rating"); topNoKitType = configuration.getString("top.displayed-replacers.no-kit.type", "No Kit"); topNoKitIdentifier = configuration.getString("top.displayed-replacers.no-kit.identifier", "rating"); kitSelectorRows = Math.min(Math.max(configuration.getInt("guis.kit-selector.rows", 2), 1), 5); kitSelectorFillerType = configuration.getString("guis.kit-selector.space-filler-item.type", "STAINED_GLASS_PANE"); kitSelectorFillerData = (short) configuration.getInt("guis.kit-selector.space-filler-item.data", 0); arenaSelectorRows = Math.min(Math.max(configuration.getInt("guis.arena-selector.rows", 3), 1), 5); arenaSelectorFillerType = configuration.getString("guis.arena-selector.space-filler-item.type", "STAINED_GLASS_PANE"); arenaSelectorFillerData = (short) configuration.getInt("guis.arena-selector.space-filler-item.data", 0); settingsFillerType = configuration.getString("guis.settings.space-filler-item.type", "STAINED_GLASS_PANE"); settingsFillerData = (short) configuration.getInt("guis.settings.space-filler-item.data", 0); queuesRows = Math.min(Math.max(configuration.getInt("guis.queues.rows", 3), 1), 5); queuesFillerType = configuration.getString("guis.queues.space-filler-item.type", "STAINED_GLASS_PANE"); queuesFillerData = (short) configuration.getInt("guis.queues.space-filler-item.data", 0); inheritKitItemType = configuration.getBoolean("guis.queues.inherit-kit-item-type", true); soupHeartsToRegen = Math.max(configuration.getDouble("soup.hearts-to-regen", 3.5), 0); soupRemoveEmptyBowl = configuration.getBoolean("soup.remove-empty-bowl", true); soupCancelIfAlreadyFull = configuration.getBoolean("soup.cancel-if-already-full", true); final ConfigurationSection sounds = configuration.getConfigurationSection("sounds"); if (sounds != null) { for (final String name : sounds.getKeys(false)) { final ConfigurationSection sound = sounds.getConfigurationSection(name); final Sound type = EnumUtil.getByName(sound.getString("type"), Sound.class); if (type == null) { continue; } this.sounds.put(name, new MessageSound(type, sound.getDouble("pitch"), sound.getDouble("volume"), sound.getStringList("trigger-messages"))); } } } public void playSound(final Player player, final String message) { sounds.values().stream() .filter(sound -> sound.getMessages().contains(message)) .forEach(sound -> player.playSound(player.getLocation(), sound.getType(), sound.getVolume(), sound.getPitch())); } public MessageSound getSound(final String name) { return sounds.get(name); } public Set getSounds() { return sounds.keySet(); } public class MessageSound { @Getter private final Sound type; @Getter private final float pitch, volume; @Getter private final List messages; MessageSound(final Sound type, final double pitch, final double volume, final List messages) { this.type = type; this.pitch = (float) pitch; this.volume = (float) volume; this.messages = messages; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/config/Lang.java ================================================ package me.realized.duels.config; import com.google.common.collect.Sets; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import me.realized.duels.DuelsPlugin; import me.realized.duels.util.Log; import me.realized.duels.util.Reloadable; import me.realized.duels.util.StringUtil; import me.realized.duels.util.config.AbstractConfiguration; import org.bukkit.command.CommandSender; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; public class Lang extends AbstractConfiguration implements Reloadable { private final Config config; private final Map messages = new HashMap<>(); public Lang(final DuelsPlugin plugin) { super(plugin, "lang"); this.config = plugin.getConfiguration(); } @Override protected void loadValues(FileConfiguration configuration) throws Exception { if (configuration.getInt("config-version", 0) < getLatestVersion()) { configuration = convert(null); } final Map strings = new HashMap<>(); for (String key : configuration.getKeys(true)) { if (key.equals("config-version")) { continue; } // Fixes a weird occurrence with FileConfiguration#getKeys that an extra separator char is prepended when called after FileConfiguration#set if (key.startsWith(".")) { key = key.substring(1); } final Object value = configuration.get(key); if (value == null || value instanceof MemorySection) { continue; } final String message = value instanceof List ? StringUtil.fromList((List) value) : value.toString(); if (key.startsWith("STRINGS")) { final String[] args = key.split(Pattern.quote(".")); strings.put(args[args.length - 1], message); } else { messages.put(key, message); } } messages.replaceAll((key, value) -> { for (final Map.Entry entry : strings.entrySet()) { final String placeholder = "{" + entry.getKey() + "}"; if (StringUtil.containsIgnoreCase(value, placeholder)) { value = value.replaceAll("(?i)" + Pattern.quote(placeholder), entry.getValue()); } } return value; }); } @Override protected Set transferredSections() { return Sets.newHashSet("STRINGS"); } @Override public void handleUnload() { messages.clear(); } private String getRawMessage(final String key) { final String message = messages.get(key); if (message == null) { Log.error(this, "Failed to load message: provided key '" + key + "' has no assigned value"); return null; } // Allow disabling any message by setting it to '' return !message.isEmpty() ? message : null; } public String getMessage(final String key) { final String message = getRawMessage(key); return message != null ? StringUtil.color(message) : null; } private String replace(String message, Object... replacers) { // If given an array of replacers as a single parameter, expand the array. if (replacers.length == 1 && replacers[0] instanceof Object[]) { replacers = (Object[]) replacers[0]; } for (int i = 0; i < replacers.length; i += 2) { if (i + 1 >= replacers.length) { break; } message = message.replace("%" + replacers[i].toString() + "%", String.valueOf(replacers[i + 1])); } return message; } public String getMessage(final String key, final Object... replacers) { final String message = getMessage(key); return message != null ? replace(message, replacers) : null; } public void sendMessage(final CommandSender receiver, final String key, final Object... replacers) { final String message = getRawMessage(key); if (message == null) { return; } if (receiver instanceof Player) { config.playSound((Player) receiver, message); } receiver.sendMessage(StringUtil.color(replace(message, replacers))); } public void sendMessage(final Collection players, final String key, final Object... replacers) { players.forEach(player -> sendMessage(player, key, replacers)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/config/converters/ConfigConverter9_10.java ================================================ package me.realized.duels.config.converters; import java.util.HashMap; import java.util.Map; import me.realized.duels.util.config.convert.Converter; public class ConfigConverter9_10 implements Converter { @Override public Map renamedKeys() { final Map keys = new HashMap<>(); keys.put("duel.use-own-inventory.enabled", "request.use-own-inventory.enabled"); return keys; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/ArenaData.java ================================================ package me.realized.duels.data; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; public class ArenaData { @Getter private String name; private boolean disabled; private Set kits = new HashSet<>(); private Map positions = new HashMap<>(); private ArenaData() {} public ArenaData(final ArenaImpl arena) { this.name = arena.getName(); this.disabled = arena.isDisabled(); arena.getKits().forEach(kit -> this.kits.add(kit.getName())); arena.getPositions().entrySet() .stream().filter(entry -> entry.getValue().getWorld() != null).forEach(entry -> positions.put(entry.getKey(), LocationData.fromLocation(entry.getValue()))); } public ArenaImpl toArena(final DuelsPlugin plugin) { final ArenaImpl arena = new ArenaImpl(plugin, name, disabled); // Manually bind kits and add locations to prevent saveArenas being called kits.stream().map(name -> plugin.getKitManager().get(name)).filter(Objects::nonNull).forEach(kit -> arena.getKits().add(kit)); positions.forEach((key, value) -> arena.getPositions().put(key, value.toLocation())); arena.refreshGui(arena.isAvailable()); return arena; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/ItemData.java ================================================ package me.realized.duels.data; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import me.realized.duels.util.EnumUtil; import me.realized.duels.util.collection.StreamUtil; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Identifiers; import me.realized.duels.util.inventory.ItemBuilder; import me.realized.duels.util.inventory.ItemUtil; import me.realized.duels.util.json.DefaultBasedDeserializer; import me.realized.duels.util.yaml.YamlUtil; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; public class ItemData { public static ItemData fromItemStack(final ItemStack item) { return new ItemData(item); } @SuppressWarnings("unchecked") private static void patchItemFlags(final Map item) { final Object meta = item.get("meta"); if (meta instanceof Map) { final Map metaAsMap = (Map) meta; final Object itemFlags = metaAsMap.get("ItemFlags"); if (itemFlags instanceof Iterable) { metaAsMap.put("ItemFlags", StreamUtil.asStream((Iterable) itemFlags).map(Object::toString).collect(Collectors.toSet())); } } } private Map item; private ItemData() {} private ItemData(ItemStack item) { item = Identifiers.removeIdentifier(item); final String dumped = YamlUtil.bukkitYamlDump(item); this.item = YamlUtil.yamlLoad(dumped); } public ItemStack toItemStack(final boolean kitItem) { if (item == null || item.isEmpty()) { return null; } if (CompatUtil.isPre1_12()) { patchItemFlags(item); } final String dumped = YamlUtil.yamlDump(item); ItemStack item = YamlUtil.bukkitYamlLoadAs(dumped, ItemStack.class); return kitItem ? Identifiers.addIdentifier(item) : item; } public ItemStack toItemStack() { return toItemStack(true); } public static class ItemDataDeserializer extends DefaultBasedDeserializer { private static boolean checkOldJson = true; public ItemDataDeserializer(final JsonDeserializer defaultDeserializer) { super(ItemData.class, defaultDeserializer); } @Override public ItemData deserialize(final JsonParser parser, final DeserializationContext context) throws IOException { JsonNode node = null; JsonParser actual = parser; // Create a copy of current json as node tree in case old json version is detected. if (checkOldJson) { node = parser.readValueAsTree(); actual = parser.getCodec().treeAsTokens(node); actual.nextToken(); } ItemData data = (ItemData) defaultDeserializer.deserialize(actual, context); if (data.item != null) { // If an item was successfully parsed to new json, disable old json check (assume kit file is in new json format) to reduce overhead. checkOldJson = false; } else if (node != null) { if (!node.isObject()) { return null; } if (node.has("serializedItem")) { return new ItemData(ItemUtil.itemFrom64(node.get("serializedItem").textValue())); } final String material = node.get("material").textValue(); final int amount = node.has("amount") ? node.get("amount").intValue() : 1; final short damage = node.has("data") ? node.get("data").shortValue() : 0; final Material type = Material.getMaterial(material); if (type == null) { return null; } final ItemBuilder builder = ItemBuilder.of(type, amount, damage); if (node.has("displayName")) { builder.name(node.get("displayName").textValue()); } if (node.has("lore")) { builder.lore(StreamUtil.asStream(node.get("lore")).map(JsonNode::textValue).collect(Collectors.toList())); } if (node.has("enchantments")) { final JsonNode enchantments = node.get("enchantments"); StreamUtil.asStream(enchantments.fieldNames()).forEach(entry -> { final Enchantment enchantment = Enchantment.getByName(entry); if (enchantment == null) { return; } builder.enchant(enchantment, enchantments.get(entry).asInt()); }); } if (node.has("flags") && CompatUtil.hasItemFlag()) { final JsonNode flags = node.get("flags"); StreamUtil.asStream(flags).forEach(flagNode -> { final ItemFlag flag = EnumUtil.getByName(flagNode.textValue(), ItemFlag.class); if (flag == null) { return; } builder.editMeta(meta -> meta.addItemFlags(flag)); }); } if (node.has("unbreakable") && node.get("unbreakable").booleanValue()) { builder.unbreakable(); } if (node.has("owner")) { builder.head(node.get("owner").textValue()); } if (node.has("color")) { builder.leatherArmorColor(node.get("color").textValue()); } if (node.has("effects")) { final JsonNode effects = node.get("effects"); builder.editMeta(meta -> { final PotionMeta potionMeta = (PotionMeta) meta; StreamUtil.asStream(effects.fieldNames()).forEach(entry -> { final String[] split = effects.get(entry).textValue().split("-"); final int duration = Integer.parseInt(split[0]); final int amplifier = Integer.parseInt(split[1]); final PotionEffectType effectType = PotionEffectType.getByName(entry); if (effectType == null) { return; } potionMeta.addCustomEffect(new PotionEffect(effectType, duration, amplifier), true); }); }); } if (node.has("itemData") && !CompatUtil.isPre1_9()) { final List args = Arrays.asList(node.get("itemData").textValue().split("-")); final PotionType potionType = EnumUtil.getByName(args.get(0), PotionType.class); if (potionType != null) { builder.potion(potionType, args.contains("extended"), args.contains("strong")); } } if (node.has("attributeModifiers") && CompatUtil.hasAttributes()) { final JsonNode attributes = node.get("attributeModifiers"); StreamUtil.asStream(attributes).forEach(attributeNode -> builder.attribute( attributeNode.get("name").textValue(), attributeNode.get("operation").intValue(), attributeNode.get("amount").doubleValue(), attributeNode.has("slot") ? attributeNode.get("slot").textValue() : null )); } return new ItemData(builder.build()); } return data; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/KitData.java ================================================ package me.realized.duels.data; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import me.realized.duels.DuelsPlugin; import me.realized.duels.kit.KitImpl; import me.realized.duels.kit.KitImpl.Characteristic; import me.realized.duels.util.Log; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; public class KitData { private static transient final String SLOT_LOAD_FAILURE = "Could not load slot %s for kit %s!"; private static transient final String ITEM_LOAD_FAILURE = "Could not load item %s for kit %s!"; public static KitData fromKit(final KitImpl kit) { return new KitData(kit); } private String name; private ItemData displayed; private boolean usePermission; private boolean arenaSpecific; private Set characteristics = new HashSet<>(); private Map> items = new HashMap<>(); // for Gson deserializer private KitData() {} private KitData(final KitImpl kit) { this.name = kit.getName(); this.displayed = ItemData.fromItemStack(kit.getDisplayed()); this.usePermission = kit.isUsePermission(); this.arenaSpecific = kit.isArenaSpecific(); this.characteristics.addAll(kit.getCharacteristics()); for (final Map.Entry> entry : kit.getItems().entrySet()) { final Map data = new HashMap<>(); entry.getValue().entrySet() .stream() .filter(value -> Objects.nonNull(value.getValue())) .forEach(value -> data.put(value.getKey(), ItemData.fromItemStack(value.getValue()))); items.put(entry.getKey(), data); } } public KitImpl toKit(final DuelsPlugin plugin) { ItemStack displayed; if (this.displayed == null || (displayed = this.displayed.toItemStack()) == null) { displayed = ItemBuilder.of(Material.BARRIER).name("&cCould not load displayed item for " + name + "!").build(); } final KitImpl kit = new KitImpl(plugin, name, displayed, usePermission, arenaSpecific, characteristics); for (final Map.Entry> entry : items.entrySet()) { final Map data = new HashMap<>(); entry.getValue().forEach(((slot, itemData) -> { if (itemData == null) { Log.warn(String.format(SLOT_LOAD_FAILURE, slot, kit.getName())); return; } final ItemStack item = itemData.toItemStack(); if (item == null) { Log.warn(String.format(ITEM_LOAD_FAILURE, itemData, kit.getName())); return; } data.put(slot, item); })); kit.getItems().put(entry.getKey(), data); } return kit; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/LocationData.java ================================================ package me.realized.duels.data; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; public class LocationData { public static LocationData fromLocation(final Location location) { return new LocationData(location); } private String world; private double x; private double y; private double z; private float pitch; private float yaw; private LocationData() {} private LocationData(final World world, final double x, final double y, final double z, final float pitch, final float yaw) { this.x = x; this.y = y; this.z = z; this.world = world.getName(); this.pitch = pitch; this.yaw = yaw; } private LocationData(final Location location) { this(location.getWorld(), location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); } public World getWorld() { return Bukkit.getWorld(world); } public Location toLocation() { return new Location(getWorld(), x, y, z, yaw, pitch); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/MatchData.java ================================================ package me.realized.duels.data; import lombok.Getter; import me.realized.duels.api.user.MatchInfo; public class MatchData implements MatchInfo { @Getter private String winner; @Getter private String loser; @Getter private String kit; @Getter private long time; @Getter private long duration; @Getter private double health; private MatchData() {} public MatchData(final String winner, final String loser, final String kit, final long time, final long duration, final double health) { this.winner = winner; this.loser = loser; this.kit = kit; this.time = time; this.duration = duration; this.health = health; } @Override public long getCreation() { return time; } @Override public String toString() { return "MatchData{" + "winner='" + winner + '\'' + ", loser='" + loser + '\'' + ", time=" + time + ", duration=" + duration + ", health=" + health + '}'; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/PlayerData.java ================================================ package me.realized.duels.data; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import me.realized.duels.player.PlayerInfo; import me.realized.duels.util.Log; import org.bukkit.inventory.ItemStack; public class PlayerData { private static transient final String ITEM_LOAD_FAILURE = "Could not load item %s!"; public static PlayerData fromPlayerInfo(final PlayerInfo info) { return new PlayerData(info); } private Map> items = new HashMap<>(); private Collection effects = new ArrayList<>(); private double health; private int hunger; private LocationData location; private List extra = new ArrayList<>(); private PlayerData() {} private PlayerData(final PlayerInfo info) { this.health = info.getHealth(); this.hunger = info.getHunger(); this.location = LocationData.fromLocation(info.getLocation()); for (final Map.Entry> entry : info.getItems().entrySet()) { final Map data = new HashMap<>(); entry.getValue().entrySet() .stream() .filter(value -> Objects.nonNull(value.getValue())) .forEach(value -> data.put(value.getKey(), ItemData.fromItemStack(value.getValue()))); items.put(entry.getKey(), data); } info.getExtra().forEach(item -> extra.add(ItemData.fromItemStack(item))); } public PlayerInfo toPlayerInfo() { final PlayerInfo info = new PlayerInfo( effects.stream().map(PotionEffectData::toPotionEffect).filter(Objects::nonNull).collect(Collectors.toList()), health, hunger, location.toLocation() ); for (final Map.Entry> entry : items.entrySet()) { final Map data = new HashMap<>(); entry.getValue().forEach(((slot, itemData) -> { final ItemStack item = itemData.toItemStack(false); if (item == null) { Log.warn(String.format(ITEM_LOAD_FAILURE, itemData.toString())); return; } data.put(slot, item); })); info.getItems().put(entry.getKey(), data); } info.getExtra().addAll(extra.stream().map(data -> data.toItemStack(false)).filter(Objects::nonNull).collect(Collectors.toList())); return info; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/PotionEffectData.java ================================================ package me.realized.duels.data; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class PotionEffectData { public static PotionEffectData fromPotionEffect(final PotionEffect effect) { return new PotionEffectData(effect); } private String type; private int duration; private int amplifier; private PotionEffectData() {} private PotionEffectData(final PotionEffect effect) { this.type = effect.getType().getName(); this.duration = effect.getDuration(); this.amplifier = effect.getAmplifier(); } public PotionEffect toPotionEffect() { final PotionEffectType effectType = PotionEffectType.getByName(type); if (effectType == null) { return null; } return new PotionEffect(effectType, duration, amplifier); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/QueueData.java ================================================ package me.realized.duels.data; import me.realized.duels.DuelsPlugin; import me.realized.duels.queue.Queue; public class QueueData { private String kit; private int bet; private QueueData() {} public QueueData(final Queue queue) { this.kit = queue.getKit() != null ? queue.getKit().getName() : null; this.bet = queue.getBet(); } public Queue toQueue(final DuelsPlugin plugin) { return new Queue(plugin, kit != null ? plugin.getKitManager().get(kit) : null, bet); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/QueueSignData.java ================================================ package me.realized.duels.data; import me.realized.duels.DuelsPlugin; import me.realized.duels.kit.KitImpl; import me.realized.duels.queue.Queue; import me.realized.duels.queue.sign.QueueSignImpl; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.Sign; public class QueueSignData { private LocationData location; private String kit; private int bet; private QueueSignData() {} public QueueSignData(final QueueSignImpl sign) { this.location = LocationData.fromLocation(sign.getLocation()); final Queue queue = sign.getQueue(); this.kit = queue.getKit() != null ? queue.getKit().getName() : null; this.bet = queue.getBet(); } public QueueSignImpl toQueueSign(final DuelsPlugin plugin) { final Location location = this.location.toLocation(); if (location.getWorld() == null) { return null; } final Block block = location.getBlock(); if (!(block.getState() instanceof Sign)) { return null; } final KitImpl kit = this.kit != null ? plugin.getKitManager().get(this.kit) : null; Queue queue = plugin.getQueueManager().get(kit, bet); if (queue == null) { plugin.getQueueManager().create(kit, bet); queue = plugin.getQueueManager().get(kit, bet); } return new QueueSignImpl(location, plugin.getLang().getMessage("SIGN.format", "kit", this.kit != null ? this.kit : plugin.getLang().getMessage("GENERAL.none"), "bet_amount", bet), queue); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/UserData.java ================================================ package me.realized.duels.data; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; import lombok.Setter; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.user.MatchInfo; import me.realized.duels.api.user.User; import me.realized.duels.util.Log; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class UserData implements User { private static transient final String ERROR_USER_SAVE = "An error occured while saving userdata of %s!"; @Getter private UUID uuid; @Getter @Setter private String name; @Getter private volatile int wins; @Getter private volatile int losses; private boolean requests = true; private ConcurrentHashMap rating; private List matches = new ArrayList<>(); transient File folder; transient int defaultRating; transient int matchesToDisplay; private UserData() {} public UserData(final File folder, final int defaultRating, final int matchesToDisplay, final Player player) { this.folder = folder; this.defaultRating = defaultRating; this.matchesToDisplay = matchesToDisplay; this.uuid = player.getUniqueId(); this.name = player.getName(); } @Override public void setWins(final int wins) { this.wins = wins; if (!isOnline()) { trySave(); } } @Override public void setLosses(final int losses) { this.losses = losses; if (!isOnline()) { trySave(); } } @Override public boolean canRequest() { return requests; } @Override public void setRequests(final boolean requests) { this.requests = requests; if (!isOnline()) { trySave(); } } @NotNull @Override public List getMatches() { return Collections.unmodifiableList(matches); } @Override public int getRating() { return getRatingUnsafe(null); } @Override public int getRating(@NotNull final Kit kit) { return getRatingUnsafe(kit); } @Override public void resetRating() { setRating(null, defaultRating); } @Override public void resetRating(@NotNull final Kit kit) { setRating(kit, defaultRating); } @Override public void reset() { wins = 0; losses = 0; matches.clear(); rating.clear(); if (!isOnline()) { trySave(); } } private int getRatingUnsafe(final Kit kit) { return this.rating != null ? this.rating.getOrDefault(kit == null ? "-" : kit.getName(), defaultRating) : defaultRating; } public void setRating(final Kit kit, final int rating) { if (this.rating == null) { this.rating = new ConcurrentHashMap<>(); } this.rating.put(kit == null ? "-" : kit.getName(), rating); if (!isOnline()) { trySave(); } } private boolean isOnline() { return Bukkit.getPlayer(uuid) != null; } public void addWin() { final int wins = this.wins; this.wins = wins + 1; } public void addLoss() { final int losses = this.losses; this.losses = losses + 1; } public void addMatch(final MatchData matchData) { if (!matches.isEmpty() && matches.size() >= matchesToDisplay) { matches.remove(0); } matches.add(matchData); } void refreshMatches() { if (matches.size() < matchesToDisplay) { return; } final List division = Lists.newArrayList(matches.subList(matches.size() - matchesToDisplay, matches.size())); matches.clear(); matches.addAll(division); } public void trySave() { final File file = new File(folder, uuid + ".json"); try { if (!file.exists()) { file.createNewFile(); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, this); writer.flush(); } } catch (IOException ex) { Log.error(String.format(ERROR_USER_SAVE, name), ex); } } @Override public String toString() { return "UserData{" + "uuid=" + uuid + ", name='" + name + '\'' + ", wins=" + wins + ", losses=" + losses + ", requests=" + requests + ", matches=" + matches + ", rating=" + rating + '}'; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/data/UserManagerImpl.java ================================================ package me.realized.duels.data; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.event.user.UserCreateEvent; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.user.User; import me.realized.duels.api.user.UserManager; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.util.DateUtil; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.StringUtil; import me.realized.duels.util.UUIDUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class UserManagerImpl implements Loadable, Listener, UserManager { private static final String ADMIN_UPDATE_MESSAGE = "&9[Duels] &bDuels &fv%s &7is now available for download! Download at: &c%s"; private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final File folder; private final Map users = new ConcurrentHashMap<>(); private final Map names = new ConcurrentHashMap<>(); private volatile int defaultRating; private volatile int matchesToDisplay; @Getter private volatile boolean loaded; @Getter private volatile TopEntry wins; @Getter private volatile TopEntry losses; @Getter private volatile TopEntry noKit; private final Map topRatings = new ConcurrentHashMap<>(); private int topTask; public UserManagerImpl(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.folder = new File(plugin.getDataFolder(), "users"); if (!folder.exists()) { folder.mkdir(); } Bukkit.getPluginManager().registerEvents(this, plugin); } @Override public void handleLoad() { this.defaultRating = config.getDefaultRating(); this.matchesToDisplay = config.getMatchesToDisplay(); if (matchesToDisplay < 0) { matchesToDisplay = 0; } plugin.doAsync(() -> { final File[] files = folder.listFiles(); if (files != null && files.length > 0) { for (final File file : files) { final String fileName = file.getName(); if (!fileName.endsWith(".json")) { continue; } final String name = fileName.substring(0, fileName.length() - 5); final UUID uuid = UUIDUtil.parseUUID(name); if (uuid == null || users.containsKey(uuid)) { continue; } try (Reader reader = new InputStreamReader(new FileInputStream(file))) { final UserData user = JsonUtil.getObjectMapper().readValue(reader, UserData.class); if (user == null) { Log.warn(this, "Could not load userdata from file: " + fileName); continue; } user.folder = folder; user.defaultRating = defaultRating; user.matchesToDisplay = matchesToDisplay; user.refreshMatches(); // Player might have logged in while reading the file names.putIfAbsent(user.getName().toLowerCase(), uuid); users.putIfAbsent(uuid, user); } catch (IOException ex) { Log.error(this, "Could not load userdata from file: " + fileName, ex); } } } loaded = true; }); this.topTask = plugin.doSyncRepeat(() -> { final Collection kits = plugin.getKitManager().getKits(); plugin.doAsync(() -> { if (!loaded) { return; } TopEntry top; if ((top = get(config.getTopUpdateInterval(), wins, User::getWins, config.getTopWinsType(), config.getTopWinsIdentifier())) != null) { wins = top; } if ((top = get(config.getTopUpdateInterval(), losses, User::getLosses, config.getTopLossesType(), config.getTopLossesIdentifier())) != null) { losses = top; } if ((top = get(config.getTopUpdateInterval(), noKit, User::getRating, config.getTopNoKitType(), config.getTopNoKitIdentifier())) != null) { noKit = top; } topRatings.keySet().removeIf(kit -> !kits.contains(kit)); for (final Kit kit : kits) { final TopEntry entry = topRatings.get(kit); if ((top = get(config.getTopUpdateInterval(), entry, user -> user.getRating(kit), config.getTopKitType().replace("%kit%", kit.getName()), config.getTopKitIdentifier())) != null) { topRatings.put(kit, top); } } }); }, 20L * 5, 20L).getTaskId(); } @Override public void handleUnload() { plugin.cancelTask(topTask); loaded = false; saveUsers(Bukkit.getOnlinePlayers()); users.clear(); names.clear(); topRatings.clear(); } @Nullable @Override public UserData get(@NotNull final String name) { Objects.requireNonNull(name, "name"); final UUID uuid = names.get(name.toLowerCase()); return uuid != null ? get(uuid) : null; } @Nullable @Override public UserData get(@NotNull final UUID uuid) { Objects.requireNonNull(uuid, "uuid"); return users.get(uuid); } @Nullable @Override public UserData get(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return get(player.getUniqueId()); } @Nullable @Override public TopEntry getTopWins() { return wins; } @Nullable @Override public TopEntry getTopLosses() { return losses; } @Nullable @Override public TopEntry getTopRatings() { return noKit; } @Nullable @Override public TopEntry getTopRatings(@NotNull final Kit kit) { Objects.requireNonNull(kit, "kit"); return topRatings.get(kit); } public String getNextUpdate(final long creation) { return DateUtil.format((creation + config.getTopUpdateInterval() - System.currentTimeMillis()) / 1000L); } private TopEntry get(final long interval, final TopEntry previous, final Function function, final String type, final String identifier) { if (previous == null || System.currentTimeMillis() - previous.getCreation() >= interval) { return new TopEntry(type, identifier, subList(sorted(function))); } return null; } private List subList(final List list) { return Collections.unmodifiableList(Lists.newArrayList(list.size() > 10 ? list.subList(0, 10) : list)); } private List sorted(final Function function) { return users.values().stream() .map(data -> new TopData(data.getUuid(), data.getName(), function.apply(data))) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); } private UserData tryLoad(final Player player) { final File file = new File(folder, player.getUniqueId() + ".json"); if (!file.exists()) { final UserData user = new UserData(folder, defaultRating, matchesToDisplay, player); plugin.doSync(() -> Bukkit.getPluginManager().callEvent(new UserCreateEvent(user))); return user; } try (Reader reader = new InputStreamReader(new FileInputStream(file))) { final UserData user = JsonUtil.getObjectMapper().readValue(reader, UserData.class); if (user == null) { return null; } user.folder = folder; user.defaultRating = defaultRating; user.matchesToDisplay = matchesToDisplay; user.refreshMatches(); if (!player.getName().equals(user.getName())) { user.setName(player.getName()); } return user; } catch (IOException ex) { Log.error(this, "An error occured while loading userdata of " + player.getName() + "!", ex); return null; } } private void saveUsers(final Collection players) { for (final Player player : players) { final UserData user = users.remove(player.getUniqueId()); if (user != null) { user.trySave(); } } } @EventHandler public void on(final PlayerJoinEvent event) { final Player player = event.getPlayer(); plugin.doSyncAfter(() -> { if (plugin.isUpdateAvailable() && (player.isOp() || player.hasPermission(Permissions.ADMIN))) { player.sendMessage(StringUtil.color(String.format(ADMIN_UPDATE_MESSAGE, plugin.getNewVersion(), plugin.getDescription().getWebsite()))); } }, 5L); final UserData user = users.get(player.getUniqueId()); if (user != null) { if (!player.getName().equals(user.getName())) { user.setName(player.getName()); names.put(player.getName().toLowerCase(), player.getUniqueId()); } return; } plugin.doAsync(() -> { final UserData data = tryLoad(player); if (data == null) { lang.sendMessage(player, "ERROR.data.load-failure"); return; } names.put(player.getName().toLowerCase(), player.getUniqueId()); users.put(player.getUniqueId(), data); }); } @EventHandler public void on(final PlayerQuitEvent event) { final UUID uuid = event.getPlayer().getUniqueId(); final UserData user = users.remove(uuid); if (user != null) { plugin.doAsync(() -> { user.trySave(); // Put data back after saving to prevent concurrency issues users.put(uuid, user); }); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/duel/DuelManager.java ================================================ package me.realized.duels.duel; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.match.MatchEndEvent.Reason; import me.realized.duels.api.event.match.MatchStartEvent; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.arena.MatchImpl; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.MatchData; import me.realized.duels.data.UserData; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.hook.hooks.CombatLogXHook; import me.realized.duels.hook.hooks.CombatTagPlusHook; import me.realized.duels.hook.hooks.EssentialsHook; import me.realized.duels.hook.hooks.McMMOHook; import me.realized.duels.hook.hooks.MyPetHook; import me.realized.duels.hook.hooks.PvPManagerHook; import me.realized.duels.hook.hooks.VaultHook; import me.realized.duels.hook.hooks.worldguard.WorldGuardHook; import me.realized.duels.inventories.InventoryManager; import me.realized.duels.kit.KitImpl; import me.realized.duels.player.PlayerInfo; import me.realized.duels.player.PlayerInfoManager; import me.realized.duels.queue.Queue; import me.realized.duels.queue.QueueManager; import me.realized.duels.setting.Settings; import me.realized.duels.teleport.Teleport; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.PlayerUtil; import me.realized.duels.util.StringUtil; import me.realized.duels.util.TextBuilder; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Titles; import me.realized.duels.util.function.Pair; import me.realized.duels.util.inventory.InventoryUtil; import net.md_5.bungee.api.chat.ClickEvent.Action; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Firework; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; public class DuelManager implements Loadable { private static final Calendar GREGORIAN_CALENDAR = new GregorianCalendar(); private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final UserManagerImpl userDataManager; private final ArenaManagerImpl arenaManager; private final PlayerInfoManager playerManager; private final InventoryManager inventoryManager; private QueueManager queueManager; private Teleport teleport; private CombatTagPlusHook combatTagPlus; private PvPManagerHook pvpManager; private CombatLogXHook combatLogX; private VaultHook vault; private EssentialsHook essentials; private McMMOHook mcMMO; private WorldGuardHook worldGuard; private MyPetHook myPet; private int durationCheckTask; public DuelManager(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.userDataManager = plugin.getUserManager(); this.arenaManager = plugin.getArenaManager(); this.playerManager = plugin.getPlayerManager(); this.inventoryManager = plugin.getInventoryManager(); plugin.doSyncAfter(() -> Bukkit.getPluginManager().registerEvents(new DuelListener(), plugin), 1L); } @Override public void handleLoad() { this.queueManager = plugin.getQueueManager(); this.teleport = plugin.getTeleport(); this.combatTagPlus = plugin.getHookManager().getHook(CombatTagPlusHook.class); this.pvpManager = plugin.getHookManager().getHook(PvPManagerHook.class); this.combatLogX = plugin.getHookManager().getHook(CombatLogXHook.class); this.vault = plugin.getHookManager().getHook(VaultHook.class); this.essentials = plugin.getHookManager().getHook(EssentialsHook.class); this.mcMMO = plugin.getHookManager().getHook(McMMOHook.class); this.worldGuard = plugin.getHookManager().getHook(WorldGuardHook.class); this.myPet = plugin.getHookManager().getHook(MyPetHook.class); if (config.getMaxDuration() > 0) { this.durationCheckTask = plugin.doSyncRepeat(() -> { for (final ArenaImpl arena : arenaManager.getArenasImpl()) { final MatchImpl match = arena.getMatch(); // Only handle undecided matches (size > 1) if (match == null || match.getDurationInMillis() < (config.getMaxDuration() * 60 * 1000L) || arena.size() <= 1) { continue; } for (final Player player : match.getAllPlayers()) { handleTie(player, arena, match, true); lang.sendMessage(player, "DUEL.on-end.tie"); } arena.endMatch(null, null, Reason.MAX_TIME_REACHED); } }, 0L, 20L).getTaskId(); } } @Override public void handleUnload() { plugin.cancelTask(durationCheckTask); /* 3 Cases: 1. size = 2: Match outcome is yet to be decided (INGAME phase) 2. size = 1: Match ended with a winner and is in ENDGAME phase 3. size = 0: Match ended in a tie (or winner killed themselves during ENDGAME phase) and is in ENDGAME phase */ for (final ArenaImpl arena : arenaManager.getArenasImpl()) { final MatchImpl match = arena.getMatch(); if (match == null) { continue; } final int size = arena.size(); final boolean winnerDecided = size == 1; if (winnerDecided) { final Player winner = arena.first(); lang.sendMessage(winner, "DUEL.on-end.plugin-disable"); handleWin(winner, arena.getOpponent(winner), arena, match); } else { final boolean ongoing = size > 1; for (final Player player : match.getAllPlayers()) { lang.sendMessage(player, "DUEL.on-end.plugin-disable"); handleTie(player, arena, match, ongoing); } } arena.endMatch(null, null, Reason.PLUGIN_DISABLE); } } /** * Resets the player's inventory and balance in the case of a tie game. * * @param player Player to reset state * @param arena Arena the match is taking place * @param match Match the player is in * @param alive Whether the player was alive in the match when the method was called. */ private void handleTie(final Player player, final ArenaImpl arena, final MatchImpl match, boolean alive) { arena.remove(player); // Reset player balance if there was a bet placed. if (vault != null && match.getBet() > 0) { vault.add(match.getBet(), player); } if (mcMMO != null) { mcMMO.enableSkills(player); } final PlayerInfo info = playerManager.get(player); final List items = match.getItems(player); if (alive) { PlayerUtil.reset(player); playerManager.remove(player); if (info != null) { teleport.tryTeleport(player, info.getLocation()); info.restore(player); } else { // If somehow PlayerInfo is not found... teleport.tryTeleport(player, playerManager.getLobby()); } // Give back bet items InventoryUtil.addOrDrop(player, items); } else if (info != null) { // If player remained dead during ENDGAME phase, add the items to cached PlayerInfo of the player. info.getExtra().addAll(items); } else { InventoryUtil.addOrDrop(player, items); } } /** * Rewards the duel winner with money and items bet on the match. * * @param player Player determined to be the winner * @param opponent Player that opposed the winner * @param arena Arena the match is taking place * @param match Match the player is in */ private void handleWin(final Player player, final Player opponent, final ArenaImpl arena, final MatchImpl match) { arena.remove(player); final String opponentName = opponent != null ? opponent.getName() : lang.getMessage("GENERAL.none"); if (vault != null && match.getBet() > 0) { final int amount = match.getBet() * 2; vault.add(amount, player); lang.sendMessage(player, "DUEL.reward.money.message", "name", opponentName, "money", amount); final String title = lang.getMessage("DUEL.reward.money.title", "name", opponentName, "money", amount); if (title != null) { Titles.send(player, title, null, 0, 20, 50); } } if (mcMMO != null) { mcMMO.enableSkills(player); } final PlayerInfo info = playerManager.get(player); final List items = match.getItems(); if (!player.isDead()) { playerManager.remove(player); if (!(match.isOwnInventory() && config.isOwnInventoryDropInventoryItems())) { PlayerUtil.reset(player); } if (info != null) { teleport.tryTeleport(player, info.getLocation()); info.restore(player); } if (InventoryUtil.addOrDrop(player, items)) { lang.sendMessage(player, "DUEL.reward.items.message", "name", opponentName); } } else if (info != null) { info.getExtra().addAll(items); } } public void startMatch(final Player first, final Player second, final Settings settings, final Map> items, final Queue source) { final KitImpl kit = settings.getKit(); if (!settings.isOwnInventory() && kit == null) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.mode-unselected"); refundItems(items, first, second); return; } if (first.isDead() || second.isDead()) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.player-is-dead"); refundItems(items, first, second); return; } if (isBlacklistedWorld(first) || isBlacklistedWorld(second)) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.in-blacklisted-world"); refundItems(items, first, second); return; } if (isTagged(first) || isTagged(second)) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.is-tagged"); refundItems(items, first, second); return; } if (config.isCancelIfMoved() && (notInLoc(first, settings.getBaseLoc(first)) || notInLoc(second, settings.getBaseLoc(second)))) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.player-moved"); refundItems(items, first, second); return; } if (config.isDuelzoneEnabled() && worldGuard != null && (notInDz(first, settings.getDuelzone(first)) || notInDz(second, settings.getDuelzone(second)))) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.not-in-duelzone"); refundItems(items, first, second); return; } if (config.isPreventCreativeMode() && (first.getGameMode() == GameMode.CREATIVE || second.getGameMode() == GameMode.CREATIVE)) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.in-creative-mode"); refundItems(items, first, second); return; } final ArenaImpl arena = settings.getArena() != null ? settings.getArena() : arenaManager.randomArena(kit); if (arena == null || !arena.isAvailable()) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure." + (settings.getArena() != null ? "arena-in-use" : "no-arena-available")); refundItems(items, first, second); return; } if (kit != null && !arenaManager.isSelectable(kit, arena)) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.arena-not-applicable", "kit", kit.getName(), "arena", arena.getName()); refundItems(items, first, second); return; } final int bet = settings.getBet(); if (bet > 0 && vault != null && vault.getEconomy() != null) { if (!vault.has(bet, first, second)) { lang.sendMessage(Arrays.asList(first, second), "DUEL.start-failure.not-enough-money", "bet_amount", bet); refundItems(items, first, second); return; } vault.remove(bet, first, second); } final MatchImpl match = arena.startMatch(kit, items, settings.getBet(), source); addPlayers(match, arena, kit, arena.getPositions(), first, second); if (config.isCdEnabled()) { final Map> info = new HashMap<>(); info.put(first.getUniqueId(), new Pair<>(second.getName(), getRating(kit, userDataManager.get(second)))); info.put(second.getUniqueId(), new Pair<>(first.getName(), getRating(kit, userDataManager.get(first)))); arena.startCountdown(kit != null ? kit.getName() : lang.getMessage("GENERAL.none"), info); } final MatchStartEvent event = new MatchStartEvent(match, first, second); Bukkit.getPluginManager().callEvent(event); } private void refundItems(final Map> items, final Player... players) { if (items != null) { Arrays.stream(players).forEach(player -> InventoryUtil.addOrDrop(player, items.getOrDefault(player.getUniqueId(), Collections.emptyList()))); } } private boolean isBlacklistedWorld(final Player player) { return config.getBlacklistedWorlds().contains(player.getWorld().getName()); } private boolean isTagged(final Player player) { return (combatTagPlus != null && combatTagPlus.isTagged(player)) || (pvpManager != null && pvpManager.isTagged(player)) || (combatLogX != null && combatLogX.isTagged(player)); } private boolean notInLoc(final Player player, final Location location) { if (location == null) { return false; } final Location source = player.getLocation(); return !source.getWorld().equals(location.getWorld()) || source.getBlockX() != location.getBlockX() || source.getBlockY() != location.getBlockY() || source.getBlockZ() != location.getBlockZ(); } private boolean notInDz(final Player player, final String duelzone) { return duelzone != null && !duelzone.equals(worldGuard.findDuelZone(player)); } private int getRating(final KitImpl kit, final UserData user) { return user != null ? user.getRating(kit) : config.getDefaultRating(); } private void addPlayers(final MatchImpl match, final ArenaImpl arena, final KitImpl kit, final Map locations, final Player... players) { int position = 0; for (final Player player : players) { if (match.getSource() == null) { queueManager.remove(player); } if (player.getAllowFlight()) { player.setFlying(false); player.setAllowFlight(false); } player.closeInventory(); playerManager.create(player, match.isOwnInventory() && config.isOwnInventoryDropInventoryItems()); teleport.tryTeleport(player, locations.get(++position)); if (kit != null) { PlayerUtil.reset(player); kit.equip(player); } if (config.isStartCommandsEnabled() && !(match.getSource() == null && config.isStartCommandsQueueOnly())) { try { for (final String command : config.getStartCommands()) { Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("%player%", player.getName())); } } catch (Exception ex) { Log.warn(this, "Error while running match start commands: " + ex.getMessage()); } } if (myPet != null) { myPet.removePet(player); } if (essentials != null) { essentials.tryUnvanish(player); } if (mcMMO != null) { mcMMO.disableSkills(player); } arena.add(player); } } private void handleInventories(final MatchImpl match) { if (!config.isDisplayInventories()) { return; } String color = lang.getMessage("DUEL.inventories.name-color"); final TextBuilder builder = TextBuilder.of(lang.getMessage("DUEL.inventories.message")); final Set players = match.getAllPlayers(); final Iterator iterator = players.iterator(); while (iterator.hasNext()) { final Player player = iterator.next(); builder.add(StringUtil.color(color + player.getName()), Action.RUN_COMMAND, "/duel _ " + player.getUniqueId()); if (iterator.hasNext()) { builder.add(StringUtil.color(color + ", ")); } } builder.send(players); } private void handleStats(final MatchImpl match, final UserData winner, final UserData loser, final MatchData matchData) { if (winner != null && loser != null) { winner.addWin(); loser.addLoss(); winner.addMatch(matchData); loser.addMatch(matchData); final KitImpl kit = match.getKit(); int winnerRating = kit == null ? winner.getRating() : winner.getRating(kit); int loserRating = kit == null ? loser.getRating() : loser.getRating(kit); int change = 0; if (config.isRatingEnabled() && !(!match.isFromQueue() && config.isRatingQueueOnly())) { change = NumberUtil.getChange(config.getKFactor(), winnerRating, loserRating); winner.setRating(kit, winnerRating = winnerRating + change); loser.setRating(kit, loserRating = loserRating - change); } final String message = lang.getMessage("DUEL.on-end.opponent-defeat", "winner", winner.getName(), "loser", loser.getName(), "health", matchData.getHealth(), "kit", matchData.getKit(), "arena", match.getArena().getName(), "winner_rating", winnerRating, "loser_rating", loserRating, "change", change ); if (message == null) { return; } if (config.isArenaOnlyEndMessage()) { match.getArena().broadcast(message); } else { Bukkit.getOnlinePlayers().forEach(player -> player.sendMessage(message)); } } } private class DuelListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void on(final PlayerDeathEvent event) { final Player player = event.getEntity(); final ArenaImpl arena = arenaManager.get(player); if (arena == null) { return; } if (mcMMO != null) { mcMMO.enableSkills(player); } final MatchImpl match = arena.getMatch(); if (match == null) { return; } final Inventory top = player.getOpenInventory().getTopInventory(); if (top.getType() == InventoryType.CRAFTING) { top.clear(); } if (!(match.isOwnInventory() && config.isOwnInventoryDropInventoryItems())) { event.getDrops().clear(); event.setKeepLevel(true); event.setDroppedExp(0); event.setKeepInventory(false); } inventoryManager.create(player, true); arena.remove(player); // Call end task only on the first death if (arena.size() <= 0) { return; } plugin.doSyncAfter(() -> { if (arena.size() == 0) { match.getAllPlayers().forEach(matchPlayer -> { handleTie(matchPlayer, arena, match, false); lang.sendMessage(matchPlayer, "DUEL.on-end.tie"); }); plugin.doSyncAfter(() -> handleInventories(match), 1L); arena.endMatch(null, null, Reason.TIE); return; } final Player winner = arena.first(); inventoryManager.create(winner, false); if (config.isSpawnFirework()) { final Firework firework = (Firework) winner.getWorld().spawnEntity(winner.getEyeLocation(), EntityType.FIREWORK); final FireworkMeta meta = firework.getFireworkMeta(); meta.setPower(0); meta.addEffect(FireworkEffect.builder().withColor(Color.RED).with(FireworkEffect.Type.BALL_LARGE).withTrail().build()); firework.setFireworkMeta(meta); } final double health = Math.ceil(winner.getHealth()) * 0.5; final String kitName = match.getKit() != null ? match.getKit().getName() : lang.getMessage("GENERAL.none"); final long duration = System.currentTimeMillis() - match.getStart(); final long time = GREGORIAN_CALENDAR.getTimeInMillis(); final MatchData matchData = new MatchData(winner.getName(), player.getName(), kitName, time, duration, health); handleStats(match, userDataManager.get(winner), userDataManager.get(player), matchData); plugin.doSyncAfter(() -> handleInventories(match), 1L); plugin.doSyncAfter(() -> { handleWin(winner, player, arena, match); if (config.isEndCommandsEnabled() && !(!match.isFromQueue() && config.isEndCommandsQueueOnly())) { try { for (final String command : config.getEndCommands()) { Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command .replace("%winner%", winner.getName()).replace("%loser%", player.getName()) .replace("%kit%", kitName).replace("%arena%", arena.getName()) .replace("%bet_amount%", String.valueOf(match.getBet())) ); } } catch (Exception ex) { Log.warn(DuelManager.this, "Error while running match end commands: " + ex.getMessage()); } } arena.endMatch(winner.getUniqueId(), player.getUniqueId(), Reason.OPPONENT_DEFEAT); }, config.getTeleportDelay() * 20L); }, 1L); } @EventHandler(ignoreCancelled = true) public void on(final EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) { return; } final Player player = (Player) event.getEntity(); final ArenaImpl arena = arenaManager.get(player); if (arena == null || !arena.isEndGame()) { return; } event.setCancelled(true); } @EventHandler public void on(final PlayerQuitEvent event) { final Player player = event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } player.setHealth(0); } @EventHandler(ignoreCancelled = true) public void on(final PlayerDropItemEvent event) { if (!config.isPreventItemDrop() || !arenaManager.isInMatch(event.getPlayer())) { return; } event.setCancelled(true); lang.sendMessage(event.getPlayer(), "DUEL.prevent.item-drop"); } @EventHandler(ignoreCancelled = true) public void on(final PlayerPickupItemEvent event) { // Fix players not being able to use the Loyalty enchantment in a duel if item pickup is disabled in config. if (!CompatUtil.isPre1_13() && event.getItem().getItemStack().getType() == Material.TRIDENT) { return; } if (!config.isPreventItemPickup() || !arenaManager.isInMatch(event.getPlayer())) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final PlayerCommandPreprocessEvent event) { final String command = event.getMessage().substring(1).split(" ")[0].toLowerCase(); if (!arenaManager.isInMatch(event.getPlayer()) || (config.isBlockAllCommands() ? config.getWhitelistedCommands().contains(command) : !config.getBlacklistedCommands().contains(command))) { return; } event.setCancelled(true); lang.sendMessage(event.getPlayer(), "DUEL.prevent.command", "command", event.getMessage()); } @EventHandler(ignoreCancelled = true) public void on(final PlayerTeleportEvent event) { final Player player = event.getPlayer(); final Location to = event.getTo(); if (!config.isLimitTeleportEnabled() || event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.SPECTATE || !arenaManager.isInMatch(player)) { return; } final Location from = event.getFrom(); if (from.getWorld().equals(to.getWorld()) && from.distance(to) <= config.getDistanceAllowed()) { return; } event.setCancelled(true); lang.sendMessage(player, "DUEL.prevent.teleportation"); } @EventHandler(ignoreCancelled = true) public void on(final InventoryOpenEvent event) { if (!config.isPreventInventoryOpen()) { return; } final Player player = (Player) event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } event.setCancelled(true); lang.sendMessage(player, "DUEL.prevent.inventory-open"); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/extension/ExtensionClassLoader.java ================================================ package me.realized.duels.extension; import com.google.common.io.ByteStreams; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSigner; import java.security.CodeSource; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import lombok.Getter; import me.realized.duels.api.extension.DuelsExtension; public class ExtensionClassLoader extends URLClassLoader { private final JarFile jar; private final Manifest manifest; private final URL url; private final Map> classes = new ConcurrentHashMap<>(); @Getter private final DuelsExtension extension; ExtensionClassLoader(final File file, final ExtensionInfo info, final ClassLoader parent) throws Exception { super(new URL[] {file.toURI().toURL()}, parent); this.jar = new JarFile(file); this.manifest = jar.getManifest(); this.url = file.toURI().toURL(); final Class mainClass = Class.forName(info.getMain(), true, this); if (!DuelsExtension.class.isAssignableFrom(mainClass)) { throw new RuntimeException(mainClass.getName() + " does not extend DuelsExtension"); } this.extension = mainClass.asSubclass(DuelsExtension.class).newInstance(); } protected Class findClass(final String name) throws ClassNotFoundException { Class result = this.classes.get(name); if (result == null) { final String path = name.replace('.', '/').concat(".class"); final JarEntry entry = jar.getJarEntry(path); if (entry != null) { final byte[] classBytes; try (InputStream inputStream = jar.getInputStream(entry)) { classBytes = ByteStreams.toByteArray(inputStream); } catch (IOException ex) { throw new ClassNotFoundException(name, ex); } final int dot = name.lastIndexOf('.'); if (dot != -1) { final String pkgName = name.substring(0, dot); if (getPackage(pkgName) == null) { try { if (manifest != null) { definePackage(pkgName, manifest, url); } else { definePackage(pkgName, null, null, null, null, null, null, null); } } catch (IllegalArgumentException ex) { if (getPackage(pkgName) == null) { throw new IllegalStateException("Cannot find package " + pkgName); } } } } final CodeSigner[] signers = entry.getCodeSigners(); final CodeSource source = new CodeSource(url, signers); result = defineClass(name, classBytes, 0, classBytes.length, source); if (result == null) { result = super.findClass(name); } classes.put(name, result); } } return result; } @Override public URL getResource(final String name) { return findResource(name); } @Override public Enumeration getResources(final String name) throws IOException { return findResources(name); } @Override public void close() throws IOException { try { super.close(); } finally { jar.close(); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/extension/ExtensionInfo.java ================================================ package me.realized.duels.extension; import java.io.File; import java.io.InputStreamReader; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import lombok.Getter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; public class ExtensionInfo { @Getter private final String name, version, main, apiVersion, description, website; @Getter private final List depends, authors; ExtensionInfo(final File file) throws Exception { try (JarFile jar = new JarFile(file)) { final JarEntry entry = jar.getJarEntry("extension.yml"); if (entry == null) { throw new RuntimeException("No extension.yml found"); } try (InputStreamReader reader = new InputStreamReader(jar.getInputStream(entry))) { final FileConfiguration config = YamlConfiguration.loadConfiguration(reader); this.name = getOrThrow(config, "name"); this.version = getOrThrow(config, "version"); this.main = getOrThrow(config, "main"); this.apiVersion = config.getString("api-version"); this.description = config.getString("description", "not specified"); this.website = config.getString("description", "not specified"); this.depends = config.getStringList("depends"); this.authors = config.getStringList("authors"); } } } private String getOrThrow(final FileConfiguration config, final String path) { final String result = config.getString(path); if (result == null) { throw new RuntimeException("No " + path + " specified in extension.yml"); } return result; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/extension/ExtensionManager.java ================================================ package me.realized.duels.extension; import java.io.File; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.Duels; import me.realized.duels.api.extension.DuelsExtension; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.NumberUtil; import org.bukkit.Bukkit; public class ExtensionManager implements Loadable { private static Method INIT_EXTENSION; static { try { INIT_EXTENSION = DuelsExtension.class.getDeclaredMethod("init", Duels.class, String.class, File.class, File.class); INIT_EXTENSION.setAccessible(true); } catch (NoSuchMethodException ignored) {} } private final Map extensions = new HashMap<>(); private final Map info = new HashMap<>(); private final DuelsPlugin plugin; private final File folder; public ExtensionManager(final DuelsPlugin plugin) { this.plugin = plugin; this.folder = new File(plugin.getDataFolder(), "extensions"); if (!folder.exists()) { folder.mkdir(); } } @Override public void handleLoad() { final File[] jars = folder.listFiles((dir, name) -> name.endsWith(".jar")); if (jars == null) { return; } for (final File file : jars) { try { final ExtensionInfo info = new ExtensionInfo(file); if (extensions.containsKey(info.getName())) { Log.error(this, "Could not load extension " + file.getName() + ": An extension with the name '" + info.getName() + "' already exists"); continue; } if (!info.getDepends().isEmpty() && info.getDepends().stream().anyMatch(depend -> !Bukkit.getPluginManager().isPluginEnabled(depend))) { Log.error(this, "Could not load extension " + file.getName() + ": This extension require the following plugins to enable - " + info.getDepends()); continue; } if (info.getApiVersion() != null && NumberUtil.isLower(plugin.getVersion(), info.getApiVersion())) { Log.error(this, "Could not load extension " + file.getName() + ": This extension requires Duels v" + info.getApiVersion() + " or higher!"); continue; } final ExtensionClassLoader classLoader = new ExtensionClassLoader(file, info, DuelsExtension.class.getClassLoader()); final DuelsExtension extension = classLoader.getExtension(); if (extension == null) { Log.error(this, "Could not load extension " + file.getName() + ": Failed to initiate main class"); continue; } final String requiredVersion = extension.getRequiredVersion(); if (requiredVersion != null && NumberUtil.isLower(plugin.getVersion(), requiredVersion)) { Log.error(this, "Could not load extension " + file.getName() + ": This extension requires Duels v" + requiredVersion + " or higher!"); continue; } INIT_EXTENSION.invoke(extension, plugin, info.getName(), folder, file); extension.setEnabled(true); Log.info(this, "Extension '" + extension.getName() + " v" + info.getVersion() + "' is now enabled."); extensions.put(extension.getName(), extension); this.info.put(extension, info); } catch (Throwable thrown) { Log.error(this, "Could not enable extension " + file.getName() + "!", thrown); } } } @Override public void handleUnload() { extensions.values().forEach(extension -> { try { extension.setEnabled(false); final ClassLoader classLoader = extension.getClass().getClassLoader(); if (classLoader instanceof ExtensionClassLoader) { ((ExtensionClassLoader) classLoader).close(); } Log.info(this, "Extension '" + extension.getName() + " v" + info.get(extension).getVersion() + "' is now disabled."); } catch (Exception ex) { Log.error(this, "Could not disable extension " + extension.getName() + "!", ex); } }); extensions.clear(); info.clear(); } public DuelsExtension getExtension(final String name) { return extensions.get(name); } public ExtensionInfo getInfo(final DuelsExtension extension) { return info.get(extension); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/BaseButton.java ================================================ package me.realized.duels.gui; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.kit.KitManagerImpl; import me.realized.duels.queue.QueueManager; import me.realized.duels.queue.sign.QueueSignManagerImpl; import me.realized.duels.request.RequestManager; import me.realized.duels.setting.SettingsManager; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.util.gui.Button; import org.bukkit.inventory.ItemStack; public abstract class BaseButton extends Button { protected final Config config; protected final Lang lang; protected final KitManagerImpl kitManager; protected final ArenaManagerImpl arenaManager; protected final SettingsManager settingManager; protected final QueueManager queueManager; protected final QueueSignManagerImpl queueSignManager; protected final SpectateManagerImpl spectateManager; protected final RequestManager requestManager; protected BaseButton(final DuelsPlugin plugin, final ItemStack displayed) { super(plugin, displayed); this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.kitManager = plugin.getKitManager(); this.arenaManager = plugin.getArenaManager(); this.settingManager = plugin.getSettingManager(); this.queueManager = plugin.getQueueManager(); this.queueSignManager = plugin.getQueueSignManager(); this.spectateManager = plugin.getSpectateManager(); this.requestManager = plugin.getRequestManager(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/betting/BettingGui.java ================================================ package me.realized.duels.gui.betting; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.duel.DuelManager; import me.realized.duels.gui.betting.buttons.CancelButton; import me.realized.duels.gui.betting.buttons.DetailsButton; import me.realized.duels.gui.betting.buttons.HeadButton; import me.realized.duels.gui.betting.buttons.StateButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.AbstractGui; import me.realized.duels.util.gui.Button; import me.realized.duels.util.gui.GuiListener; import me.realized.duels.util.inventory.InventoryBuilder; import me.realized.duels.util.inventory.InventoryUtil; import me.realized.duels.util.inventory.Slots; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; public class BettingGui extends AbstractGui { private final Section[] sections = { new Section(9, 13, 4), new Section(14, 18, 4) }; private final GuiListener guiListener; private final DuelManager duelManager; private final Settings settings; private final Inventory inventory; private final UUID first, second; private boolean firstReady, secondReady, waitDone, cancelWait; public BettingGui(final DuelsPlugin plugin, final Settings settings, final Player first, final Player second) { super(plugin); this.guiListener = plugin.getGuiListener(); this.duelManager = plugin.getDuelManager(); this.settings = settings; this.inventory = InventoryBuilder.of(plugin.getLang().getMessage("GUI.item-betting.title"), 54).build(); this.first = first.getUniqueId(); this.second = second.getUniqueId(); set(inventory, 13, 14, 5, new CancelButton(plugin)); Slots.run(0, 3, slot -> inventory.setItem(slot, Items.ORANGE_PANE.clone())); Slots.run(45, 48, slot -> inventory.setItem(slot, Items.ORANGE_PANE.clone())); Slots.run(6, 9, slot -> inventory.setItem(slot, Items.BLUE_PANE.clone())); Slots.run(51, 54, slot -> inventory.setItem(slot, Items.BLUE_PANE.clone())); set(inventory, 3, new StateButton(plugin, this, first)); set(inventory, 4, new DetailsButton(plugin, settings)); set(inventory, 5, new StateButton(plugin, this, second)); set(inventory, 48, new HeadButton(plugin, first)); set(inventory, 50, new HeadButton(plugin, second)); } private boolean isFirst(final Player player) { return player.getUniqueId().equals(first); } private Section getSection(final Player player) { return isFirst(player) ? sections[0] : sections[1]; } public boolean isReady(final Player player) { return isFirst(player) ? firstReady : secondReady; } public void setReady(final Player player) { if (isFirst(player)) { firstReady = true; } else { secondReady = true; } if (firstReady && secondReady) { new WaitTask().runTaskTimer(plugin, 10L, 20L); } } public void update(final Player player, final Button button) { update(player, inventory, button); } @Override public void open(final Player... players) { for (final Player player : players) { update(player); player.openInventory(inventory); } } @Override public boolean isPart(final Inventory inventory) { return inventory.equals(this.inventory); } @Override public void on(final Player player, final Inventory top, final InventoryClickEvent event) { final Inventory clicked = event.getClickedInventory(); if (clicked == null) { return; } final Button button = get(inventory, event.getSlot()); if (firstReady && secondReady && !(button instanceof CancelButton)) { event.setCancelled(true); return; } final int slot = event.getSlot(); if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY || event.getAction() == InventoryAction.COLLECT_TO_CURSOR) { event.setCancelled(true); return; } if (!clicked.equals(top)) { return; } final Section section = getSection(player); if (section == null) { return; } if (!isReady(player) && section.isPart(slot)) { return; } event.setCancelled(true); if (button == null) { return; } button.onClick(player); } @Override public void on(final Player player, final Set rawSlots, final InventoryDragEvent event) { final Section section = getSection(player); if (section == null) { return; } boolean in = false; boolean out = false; boolean outSec = false; for (final int slot : rawSlots) { if (slot > 53) { out = true; } else { if (!section.isPart(slot)) { outSec = true; } in = true; } } if (in && (isReady(player) || out || outSec)) { event.setCancelled(true); } } @Override public void on(final Player player, final Inventory inventory, final InventoryCloseEvent event) { if (waitDone) { return; } cancelWait = true; InventoryUtil.addOrDrop(player, getSection(player).collect()); guiListener.removeGui(player, this); final Player other = Bukkit.getPlayer(first.equals(player.getUniqueId()) ? second : first); if (other != null) { plugin.doSync(() -> { if (inventory.getViewers().contains(other)) { other.closeInventory(); } }); } } @Override public void clear() { final Player first = Bukkit.getPlayer(BettingGui.this.first); final Player second = Bukkit.getPlayer(BettingGui.this.second); if (first != null && second != null) { InventoryUtil.addOrDrop(first, getSection(first).collect()); InventoryUtil.addOrDrop(second, getSection(second).collect()); } super.clear(); } private class Section { private final int start, end, height; Section(final int start, final int end, final int height) { this.start = start; this.end = end; this.height = height; } private boolean isPart(final int slot) { for (int y = 0; y < height; y++) { for (int x = start; x < end; x++) { if (x + y * 9 == slot) { return true; } } } return false; } private List collect() { final List result = new ArrayList<>(); Slots.run(start, end, height, slot -> { final ItemStack item = inventory.getItem(slot); if (item != null && item.getType() != Material.AIR) { result.add(item); inventory.setItem(slot, null); } }); return result; } } private class WaitTask extends BukkitRunnable { private static final int SLOT_START = 13; private int counter; @Override public void run() { if (cancelWait) { cancel(); return; } if (counter < 5) { final int slot = SLOT_START + 9 * counter; ItemStack item = inventory.getItem(slot); if (CompatUtil.isPre1_13()) { item.setDurability((short) 5); } else { final ItemStack greenPane = Items.GREEN_PANE.clone(); greenPane.setItemMeta(item.getItemMeta()); item = greenPane; } inventory.setItem(slot, item); counter++; return; } cancel(); waitDone = true; final Player first = Bukkit.getPlayer(BettingGui.this.first); final Player second = Bukkit.getPlayer(BettingGui.this.second); if (first == null || second == null) { return; } first.closeInventory(); second.closeInventory(); final Map> items = new HashMap<>(); items.put(first.getUniqueId(), getSection(first).collect()); items.put(second.getUniqueId(), getSection(second).collect()); guiListener.removeGui(first, BettingGui.this); guiListener.removeGui(second, BettingGui.this); duelManager.startMatch(first, second, settings, items, null); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/betting/buttons/CancelButton.java ================================================ package me.realized.duels.gui.betting.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class CancelButton extends BaseButton { public CancelButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder .of(Items.RED_PANE.clone()) .name(plugin.getLang().getMessage("GUI.item-betting.buttons.cancel.name")) .lore(plugin.getLang().getMessage("GUI.item-betting.buttons.cancel.lore").split("\n")) .build() ); } @Override public void onClick(final Player player) { player.closeInventory(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/betting/buttons/DetailsButton.java ================================================ package me.realized.duels.gui.betting.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class DetailsButton extends BaseButton { private final Settings settings; public DetailsButton(final DuelsPlugin plugin, final Settings settings) { super(plugin, ItemBuilder .of(Items.SIGN) .name(plugin.getLang().getMessage("GUI.item-betting.buttons.details.name")) .build() ); this.settings = settings; } @Override public void update(final Player player) { final String lore = lang.getMessage("GUI.item-betting.buttons.details.lore", "kit", settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.not-selected"), "arena", settings.getArena() != null ? settings.getArena().getName() : lang.getMessage("GENERAL.random"), "bet_amount", settings.getBet() ); setLore(lore.split("\n")); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/betting/buttons/HeadButton.java ================================================ package me.realized.duels.gui.betting.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class HeadButton extends BaseButton { public HeadButton(final DuelsPlugin plugin, final Player owner) { super(plugin, ItemBuilder .of(Items.HEAD.clone()) .name(plugin.getLang().getMessage("GUI.item-betting.buttons.head.name", "name", owner.getName())) .build() ); setOwner(owner); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/betting/buttons/StateButton.java ================================================ package me.realized.duels.gui.betting.buttons; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.gui.betting.BettingGui; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class StateButton extends BaseButton { private final BettingGui gui; private final UUID owner; public StateButton(final DuelsPlugin plugin, final BettingGui gui, final Player owner) { super(plugin, ItemBuilder .of(Items.OFF.clone()) .name(plugin.getLang().getMessage("GUI.item-betting.buttons.state.name-not-ready")) .build() ); this.gui = gui; this.owner = owner.getUniqueId(); } @Override public void onClick(final Player player) { if (!gui.isReady(player) && player.getUniqueId().equals(owner)) { setDisplayed(Items.ON.clone()); setDisplayName(lang.getMessage("GUI.item-betting.buttons.state.name-ready")); gui.update(player, this); gui.setReady(player); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/bind/BindGui.java ================================================ package me.realized.duels.gui.bind; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.gui.bind.buttons.BindButton; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.MultiPageGui; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; public class BindGui extends MultiPageGui { public BindGui(final DuelsPlugin plugin, final KitImpl kit) { super(plugin, plugin.getLang().getMessage("GUI.bind.title", "kit", kit.getName()), plugin.getConfiguration().getArenaSelectorRows(), plugin.getArenaManager().getArenasImpl().stream().map(arena -> new BindButton(plugin, kit, arena)).collect(Collectors.toList())); final Config config = plugin.getConfiguration(); final Lang lang = plugin.getLang(); setSpaceFiller(Items.from(config.getArenaSelectorFillerType(), config.getArenaSelectorFillerData())); setPrevButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.arena-selector.buttons.previous-page.name")).build()); setNextButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.arena-selector.buttons.next-page.name")).build()); setEmptyIndicator(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.arena-selector.buttons.empty.name")).build()); // Change design to remove this loop in the future getButtons().forEach(button -> ((BindButton) button).setGui(this)); calculatePages(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/bind/buttons/BindButton.java ================================================ package me.realized.duels.gui.bind.buttons; import java.util.stream.Collectors; import lombok.Setter; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.gui.BaseButton; import me.realized.duels.gui.bind.BindGui; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class BindButton extends BaseButton { @Setter private BindGui gui; private final KitImpl kit; private final ArenaImpl arena; public BindButton(final DuelsPlugin plugin, final KitImpl kit, final ArenaImpl arena) { super(plugin, ItemBuilder.of(Items.EMPTY_MAP).build()); this.kit = kit; this.arena = arena; setDisplayName(plugin.getLang().getMessage("GUI.bind.buttons.arena.name", "arena", arena.getName())); update(); } private void update() { final boolean state = arena.isBound(kit); setGlow(state); String kits = StringUtil.join(arena.getKits().stream().map(KitImpl::getName).collect(Collectors.toList()), ", "); kits = kits.isEmpty() ? lang.getMessage("GENERAL.none") : kits; setLore(lang.getMessage("GUI.bind.buttons.arena.lore-" + (state ? "bound" : "not-bound"), "kits", kits).split("\n")); } @Override public void onClick(final Player player) { arena.bind(kit); update(); gui.calculatePages(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/InventoryGui.java ================================================ package me.realized.duels.gui.inventory; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.inventory.buttons.EffectsButton; import me.realized.duels.gui.inventory.buttons.HeadButton; import me.realized.duels.gui.inventory.buttons.HealthButton; import me.realized.duels.gui.inventory.buttons.HungerButton; import me.realized.duels.gui.inventory.buttons.PotionCounterButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.SinglePageGui; import me.realized.duels.util.inventory.Slots; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class InventoryGui extends SinglePageGui { public InventoryGui(final DuelsPlugin plugin, final Player player, final boolean dead) { super(plugin, plugin.getLang().getMessage("GUI.inventory-view.title", "name", player.getName()), 6); final ItemStack spacing = Items.GRAY_PANE.clone(); Slots.run(0, 9, slot -> inventory.setItem(slot, spacing)); set(4, new HeadButton(plugin, player)); int potions = 0; int slot = 9; for (final ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() != Material.AIR) { if (Items.isHealSplash(item)) { potions++; } inventory.setItem(slot, item.clone()); } slot++; } slot = 48; for (final ItemStack item : player.getInventory().getArmorContents()) { if (item != null && item.getType() != Material.AIR) { inventory.setItem(slot, item.clone()); } slot--; } inventory.setItem(49, spacing); set(50, new PotionCounterButton(plugin, potions)); set(51, new EffectsButton(plugin, player)); set(52, new HungerButton(plugin, player)); set(53, new HealthButton(plugin, player, dead)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/buttons/EffectsButton.java ================================================ package me.realized.duels.gui.inventory.buttons; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; public class EffectsButton extends BaseButton { public EffectsButton(final DuelsPlugin plugin, final Player player) { super(plugin, ItemBuilder .of(Items.WATER_BREATHING_POTION.clone()) .name(plugin.getLang().getMessage("GUI.inventory-view.buttons.effects.name")) .lore(player.getActivePotionEffects().stream() .map(effect -> plugin.getLang().getMessage("GUI.inventory-view.buttons.effects.lore-format", "type", StringUtil.capitalize(effect.getType().getName().replace("_", " ").toLowerCase()), "amplifier", StringUtil.toRoman(effect.getAmplifier() + 1), "duration", (effect.getDuration() / 20))).collect(Collectors.toList())) .build()); editMeta(meta -> { if (CompatUtil.hasItemFlag()) { meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } }); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/buttons/HeadButton.java ================================================ package me.realized.duels.gui.inventory.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class HeadButton extends BaseButton { public HeadButton(final DuelsPlugin plugin, final Player owner) { super(plugin, ItemBuilder .of(Items.HEAD.clone()) .name(plugin.getLang().getMessage("GUI.inventory-view.buttons.head.name", "name", owner.getName())) .build() ); setOwner(owner); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/buttons/HealthButton.java ================================================ package me.realized.duels.gui.inventory.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; public class HealthButton extends BaseButton { public HealthButton(final DuelsPlugin plugin, final Player player, final boolean dead) { super(plugin, ItemBuilder .of(dead ? Items.SKELETON_HEAD : Material.GOLDEN_APPLE) .name(plugin.getLang().getMessage("GUI.inventory-view.buttons.health.name", "health", dead ? 0 : Math.ceil(player.getHealth()) * 0.5)) .build()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/buttons/HungerButton.java ================================================ package me.realized.duels.gui.inventory.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; public class HungerButton extends BaseButton { public HungerButton(final DuelsPlugin plugin, final Player player) { super(plugin, ItemBuilder .of(Material.COOKED_BEEF) .name(plugin.getLang().getMessage("GUI.inventory-view.buttons.hunger.name", "hunger", player.getFoodLevel())) .build() ); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/inventory/buttons/PotionCounterButton.java ================================================ package me.realized.duels.gui.inventory.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.inventory.ItemFlag; public class PotionCounterButton extends BaseButton { public PotionCounterButton(final DuelsPlugin plugin, final int count) { super(plugin, ItemBuilder .of(Items.HEAL_SPLASH_POTION.clone()) .name(plugin.getLang().getMessage("GUI.inventory-view.buttons.potion-counter.name", "potions", count)) .build() ); editMeta(meta -> { if (CompatUtil.hasItemFlag()) { meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } }); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/options/OptionsGui.java ================================================ package me.realized.duels.gui.options; import java.util.function.Consumer; import java.util.function.Function; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.options.buttons.OptionButton; import me.realized.duels.kit.KitImpl; import me.realized.duels.kit.KitImpl.Characteristic; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.SinglePageGui; import me.realized.duels.util.inventory.Slots; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class OptionsGui extends SinglePageGui { private final DuelsPlugin plugin; private final Player owner; public OptionsGui(final DuelsPlugin plugin, final Player player, final KitImpl kit) { super(plugin, plugin.getLang().getMessage("GUI.options.title", "kit", kit.getName()), 2); this.plugin = plugin; this.owner = player; int i = 0; for (final Option option : Option.values()) { set(i++, new OptionButton(plugin, this, kit, option)); } final ItemStack spacing = Items.WHITE_PANE.clone(); Slots.run(9, 18, slot -> inventory.setItem(slot, spacing)); } @Override public void on(final Player player, final Inventory inventory, final InventoryCloseEvent event) { plugin.getGuiListener().removeGui(owner, this); } public enum Option { USEPERMISSION(Material.BARRIER, KitImpl::isUsePermission, kit -> kit.setUsePermission(!kit.isUsePermission()), "When enabled, players must", "have the permission duels.kits.%kit%", "to select this kit for duel."), ARENASPECIFIC(Items.EMPTY_MAP, KitImpl::isArenaSpecific, kit -> kit.setArenaSpecific(!kit.isArenaSpecific()), "When enabled, kit %kit%", "can only be used in", "arenas it is bound to."), SOUP(Items.MUSHROOM_SOUP, Characteristic.SOUP, "When enabled, players will", "receive the amount of health", "defined in config when", "right-clicking a soup."), SUMO(Material.SLIME_BALL, Characteristic.SUMO, "When enabled, players will ", "lose health only when", "interacting with water or lava."), UHC(Material.GOLDEN_APPLE, Characteristic.UHC, "When enabled, player's health", "will not naturally regenerate."), COMBO(Material.IRON_SWORD, Characteristic.COMBO, "When enabled, players will", "have no delay between hits."); @Getter private final Material displayed; @Getter private final String[] description; private final Function getter; private final Consumer setter; Option(final Material displayed, final Function getter, final Consumer setter, final String... description) { this.displayed = displayed; this.description = description; this.getter = getter; this.setter = setter; } Option(final Material displayed, final Characteristic characteristic, final String... description) { this.displayed = displayed; this.description = description; this.getter = kit -> kit.hasCharacteristic(characteristic); this.setter = kit -> kit.toggleCharacteristic(characteristic); } public boolean get(final KitImpl kit) { return getter.apply(kit); } public void set(final KitImpl kit) { setter.accept(kit); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/options/buttons/OptionButton.java ================================================ package me.realized.duels.gui.options.buttons; import java.util.ArrayList; import java.util.Collections; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.gui.options.OptionsGui; import me.realized.duels.gui.options.OptionsGui.Option; import me.realized.duels.kit.KitImpl; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class OptionButton extends BaseButton { private final OptionsGui gui; private final KitImpl kit; private final Option option; public OptionButton(final DuelsPlugin plugin, final OptionsGui gui, final KitImpl kit, final Option option) { super(plugin, ItemBuilder.of(option.getDisplayed()).build()); this.gui = gui; this.kit = kit; this.option = option; setDisplayName(plugin.getLang().getMessage("GUI.options.buttons.option.name", "name", option.name().toLowerCase())); update(); } private void update() { final boolean state = option.get(kit); setGlow(state); final List lore = new ArrayList<>(); for (final String line : option.getDescription()) { lore.add("&f" + line.replace("%kit%", kit.getName())); } Collections.addAll(lore, lang.getMessage("GUI.options.buttons.option.lore", "state", state ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled")).split("\n")); setLore(lore); } @Override public void onClick(final Player player) { option.set(kit); update(); gui.update(player, this); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/SettingsGui.java ================================================ package me.realized.duels.gui.settings; import java.util.ArrayList; import java.util.List; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.gui.BaseButton; import me.realized.duels.gui.settings.buttons.ArenaSelectButton; import me.realized.duels.gui.settings.buttons.CancelButton; import me.realized.duels.gui.settings.buttons.ItemBettingButton; import me.realized.duels.gui.settings.buttons.KitSelectButton; import me.realized.duels.gui.settings.buttons.OwnInventoryButton; import me.realized.duels.gui.settings.buttons.RequestDetailsButton; import me.realized.duels.gui.settings.buttons.RequestSendButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.SinglePageGui; import me.realized.duels.util.inventory.Slots; import org.bukkit.inventory.ItemStack; public class SettingsGui extends SinglePageGui { private static final int[][] PATTERNS = { {13}, {12, 14}, {12, 13, 14}, {12, 13, 14, 22} }; public SettingsGui(final DuelsPlugin plugin) { super(plugin, plugin.getLang().getMessage("GUI.settings.title"), 3); final Config config = plugin.getConfiguration(); final ItemStack spacing = Items.from(config.getSettingsFillerType(), config.getSettingsFillerData()); Slots.run(2, 7, slot -> inventory.setItem(slot, spacing)); Slots.run(11, 16, slot -> inventory.setItem(slot, spacing)); Slots.run(20, 25, slot -> inventory.setItem(slot, spacing)); set(4, new RequestDetailsButton(plugin)); final List buttons = new ArrayList<>(); if (config.isKitSelectingEnabled()) { buttons.add(new KitSelectButton(plugin)); } if (config.isOwnInventoryEnabled()) { buttons.add(new OwnInventoryButton(plugin)); } if (config.isArenaSelectingEnabled()) { buttons.add(new ArenaSelectButton(plugin)); } if (config.isItemBettingEnabled()) { buttons.add(new ItemBettingButton(plugin)); } if (!buttons.isEmpty()) { final int[] pattern = PATTERNS[buttons.size() - 1]; for (int i = 0; i < buttons.size(); i++) { set(pattern[i], buttons.get(i)); } } set(0, 2, 3, new RequestSendButton(plugin)); set(7, 9, 3, new CancelButton(plugin)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/ArenaSelectButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class ArenaSelectButton extends BaseButton { public ArenaSelectButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Items.EMPTY_MAP).name(plugin.getLang().getMessage("GUI.settings.buttons.arena-selector.name")).build()); } @Override public void update(final Player player) { if (config.isArenaSelectingUsePermission() && !player.hasPermission(Permissions.ARENA_SELECTING) && !player.hasPermission(Permissions.SETTING_ALL)) { setLore(lang.getMessage("GUI.settings.buttons.arena-selector.lore-no-permission").split("\n")); return; } final Settings settings = settingManager.getSafely(player); final String arena = settings.getArena() != null ? settings.getArena().getName() : lang.getMessage("GENERAL.random"); final String lore = lang.getMessage("GUI.settings.buttons.arena-selector.lore", "arena", arena); setLore(lore.split("\n")); } @Override public void onClick(final Player player) { if (config.isArenaSelectingUsePermission() && !player.hasPermission(Permissions.ARENA_SELECTING) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.ARENA_SELECTING); return; } arenaManager.getGui().open(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/CancelButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.entity.Player; public class CancelButton extends BaseButton { public CancelButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Items.RED_PANE.clone()).name(plugin.getLang().getMessage("GUI.settings.buttons.cancel.name")).build()); } @Override public void onClick(final Player player) { player.closeInventory(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/ItemBettingButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; public class ItemBettingButton extends BaseButton { public ItemBettingButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Material.DIAMOND).name(plugin.getLang().getMessage("GUI.settings.buttons.item-betting.name")).build()); } @Override public void update(final Player player) { if (config.isItemBettingUsePermission() && !player.hasPermission(Permissions.ITEM_BETTING) && !player.hasPermission(Permissions.SETTING_ALL)) { setLore(lang.getMessage("GUI.settings.buttons.item-betting.lore-no-permission").split("\n")); return; } final Settings settings = settingManager.getSafely(player); final String itemBetting = settings.isItemBetting() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"); final String lore = plugin.getLang().getMessage("GUI.settings.buttons.item-betting.lore", "item_betting", itemBetting); setLore(lore.split("\n")); } @Override public void onClick(final Player player) { if (config.isItemBettingUsePermission() && !player.hasPermission(Permissions.ITEM_BETTING) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.ITEM_BETTING); return; } final Settings settings = settingManager.getSafely(player); settings.setItemBetting(!settings.isItemBetting()); settings.updateGui(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/KitSelectButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; public class KitSelectButton extends BaseButton { public KitSelectButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Material.DIAMOND_SWORD).name(plugin.getLang().getMessage("GUI.settings.buttons.kit-selector.name")).build()); } @Override public void update(final Player player) { if (config.isKitSelectingUsePermission() && !player.hasPermission(Permissions.KIT_SELECTING) && !player.hasPermission(Permissions.SETTING_ALL)) { setLore(lang.getMessage("GUI.settings.buttons.kit-selector.lore-no-permission").split("\n")); return; } final Settings settings = settingManager.getSafely(player); final String kit = settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.not-selected"); final String lore = lang.getMessage("GUI.settings.buttons.kit-selector.lore", "kit", kit); setLore(lore.split("\n")); } @Override public void onClick(final Player player) { if (config.isKitSelectingUsePermission() && !player.hasPermission(Permissions.KIT_SELECTING) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.KIT_SELECTING); return; } kitManager.getGui().open(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/OwnInventoryButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; public class OwnInventoryButton extends BaseButton { public OwnInventoryButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Material.CHEST).name(plugin.getLang().getMessage("GUI.settings.buttons.use-own-inventory.name")).build()); } @Override public void update(final Player player) { if (config.isOwnInventoryUsePermission() && !player.hasPermission(Permissions.OWN_INVENTORY) && !player.hasPermission(Permissions.SETTING_ALL)) { setLore(lang.getMessage("GUI.settings.buttons.use-own-inventory.lore-no-permission").split("\n")); return; } final Settings settings = settingManager.getSafely(player); final String ownInventory = settings.isOwnInventory() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"); final String lore = plugin.getLang().getMessage("GUI.settings.buttons.use-own-inventory.lore", "own_inventory", ownInventory); setLore(lore.split("\n")); } @Override public void onClick(final Player player) { if (config.isOwnInventoryUsePermission() && !player.hasPermission(Permissions.OWN_INVENTORY) && !player.hasPermission(Permissions.SETTING_ALL)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.OWN_INVENTORY); return; } if (!config.isKitSelectingEnabled()) { lang.sendMessage(player, "ERROR.duel.mode-fixed"); return; } final Settings settings = settingManager.getSafely(player); settings.setOwnInventory(!settings.isOwnInventory()); settings.updateGui(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/RequestDetailsButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class RequestDetailsButton extends BaseButton { public RequestDetailsButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Items.SIGN).name(plugin.getLang().getMessage("GUI.settings.buttons.details.name")).build()); } @Override public void update(final Player player) { final Settings settings = settingManager.getSafely(player); final Player target = Bukkit.getPlayer(settings.getTarget()); if (target == null) { settings.reset(); player.closeInventory(); lang.sendMessage(player, "ERROR.player.no-longer-online"); return; } final String lore = lang.getMessage("GUI.settings.buttons.details.lore", "opponent", target.getName(), "kit", settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.not-selected"), "own_inventory", settings.isOwnInventory() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"), "arena", settings.getArena() != null ? settings.getArena().getName() : lang.getMessage("GENERAL.random"), "item_betting", settings.isItemBetting() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"), "bet_amount", settings.getBet() ); setLore(lore.split("\n")); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/gui/settings/buttons/RequestSendButton.java ================================================ package me.realized.duels.gui.settings.buttons; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class RequestSendButton extends BaseButton { public RequestSendButton(final DuelsPlugin plugin) { super(plugin, ItemBuilder.of(Items.GREEN_PANE.clone()).name(plugin.getLang().getMessage("GUI.settings.buttons.send.name")).build()); } @Override public void onClick(final Player player) { final Settings settings = settingManager.getSafely(player); if (settings.getTarget() == null) { settings.reset(); player.closeInventory(); return; } final Player target = Bukkit.getPlayer(settings.getTarget()); if (target == null) { settings.reset(); player.closeInventory(); lang.sendMessage(player, "ERROR.player.no-longer-online"); return; } if (!settings.isOwnInventory() && settings.getKit() == null) { player.closeInventory(); lang.sendMessage(player, "ERROR.duel.mode-unselected"); return; } player.closeInventory(); requestManager.send(player, target, settings); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/HookManager.java ================================================ package me.realized.duels.hook; import me.realized.duels.DuelsPlugin; import me.realized.duels.hook.hooks.BountyHuntersHook; import me.realized.duels.hook.hooks.CombatLogXHook; import me.realized.duels.hook.hooks.CombatTagPlusHook; import me.realized.duels.hook.hooks.EssentialsHook; import me.realized.duels.hook.hooks.FactionsHook; import me.realized.duels.hook.hooks.LeaderHeadsHook; import me.realized.duels.hook.hooks.MVdWPlaceholderHook; import me.realized.duels.hook.hooks.McMMOHook; import me.realized.duels.hook.hooks.MyPetHook; import me.realized.duels.hook.hooks.PlaceholderHook; import me.realized.duels.hook.hooks.PvPManagerHook; import me.realized.duels.hook.hooks.SimpleClansHook; import me.realized.duels.hook.hooks.VaultHook; import me.realized.duels.hook.hooks.worldguard.WorldGuardHook; import me.realized.duels.util.hook.AbstractHookManager; public class HookManager extends AbstractHookManager { public HookManager(final DuelsPlugin plugin) { super(plugin); register(BountyHuntersHook.NAME, BountyHuntersHook.class); register(CombatLogXHook.NAME, CombatLogXHook.class); register(CombatTagPlusHook.NAME, CombatTagPlusHook.class); register(EssentialsHook.NAME, EssentialsHook.class); register(FactionsHook.NAME, FactionsHook.class); register(LeaderHeadsHook.NAME, LeaderHeadsHook.class); register(McMMOHook.NAME, McMMOHook.class); register(MVdWPlaceholderHook.NAME, MVdWPlaceholderHook.class); register(MyPetHook.NAME, MyPetHook.class); register(PlaceholderHook.NAME, PlaceholderHook.class); register(PvPManagerHook.NAME, PvPManagerHook.class); register(SimpleClansHook.NAME, SimpleClansHook.class); register(VaultHook.NAME, VaultHook.class); register(WorldGuardHook.NAME, WorldGuardHook.class); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/BountyHuntersHook.java ================================================ package me.realized.duels.hook.hooks; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import net.Indyuce.bountyhunters.api.event.BountyClaimEvent; import net.Indyuce.bountyhunters.api.event.BountyCreateEvent; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class BountyHuntersHook extends PluginHook implements Listener { public static final String NAME = "BountyHunters"; private final Config config; private final ArenaManagerImpl arenaManager; public BountyHuntersHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); try { Class.forName("net.Indyuce.bountyhunters.api.event.BountyClaimEvent"); Class.forName("net.Indyuce.bountyhunters.api.event.BountyCreateEvent"); } catch (ClassNotFoundException ex) { throw new RuntimeException("This version of " + getName() + " is not supported. Please try upgrading to the latest version."); } Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler(ignoreCancelled = true) public void on(final BountyClaimEvent event) { if (!config.isPreventBountyLoss() || !arenaManager.isInMatch(event.getClaimer())) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final BountyCreateEvent event) { final Player target = event.getBounty().getTarget().getPlayer(); if (!config.isPreventBountyLoss() || target == null || !arenaManager.isInMatch(target)) { return; } event.setCancelled(true); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/CombatLogXHook.java ================================================ package me.realized.duels.hook.hooks; import com.SirBlobman.combatlogx.api.ICombatLogX; import com.SirBlobman.combatlogx.api.event.PlayerPreTagEvent; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class CombatLogXHook extends PluginHook { public static final String NAME = "CombatLogX"; private final Config config; private final ArenaManagerImpl arenaManager; public CombatLogXHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); try { Class.forName("com.SirBlobman.combatlogx.api.event.PlayerPreTagEvent"); } catch (ClassNotFoundException ex) { throw new RuntimeException("This version of " + getName() + " is not supported. Please try upgrading to the latest version."); } Bukkit.getPluginManager().registerEvents(new CombatLogXListener(), plugin); } public boolean isTagged(final Player player) { return config.isClxPreventDuel() && ((ICombatLogX) getPlugin()).getCombatManager().isInCombat(player); } public class CombatLogXListener implements Listener { @EventHandler(ignoreCancelled = true) public void on(final PlayerPreTagEvent event) { if (!config.isClxPreventTag()) { return; } final Player player = event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/CombatTagPlusHook.java ================================================ package me.realized.duels.hook.hooks; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import net.minelink.ctplus.CombatTagPlus; import net.minelink.ctplus.event.PlayerCombatTagEvent; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class CombatTagPlusHook extends PluginHook { public static final String NAME = "CombatTagPlus"; private final Config config; private final ArenaManagerImpl arenaManager; public CombatTagPlusHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); Bukkit.getPluginManager().registerEvents(new CombatTagPlusListener(), plugin); } public boolean isTagged(final Player player) { return config.isCtpPreventDuel() && ((CombatTagPlus) getPlugin()).getTagManager().isTagged(player.getUniqueId()); } public class CombatTagPlusListener implements Listener { @EventHandler(ignoreCancelled = true) public void on(final PlayerCombatTagEvent event) { if (!config.isCtpPreventTag()) { return; } final Player player = event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/EssentialsHook.java ================================================ package me.realized.duels.hook.hooks; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.User; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import org.bukkit.Location; import org.bukkit.entity.Player; public class EssentialsHook extends PluginHook { public static final String NAME = "Essentials"; private final Config config; public EssentialsHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); } @Override public Essentials getPlugin() { return (Essentials) super.getPlugin(); } public void tryUnvanish(final Player player) { if (!config.isAutoUnvanish()) { return; } final User user = getPlugin().getUser(player); if (user != null && user.isVanished()) { user.setVanished(false); } } public void setBackLocation(final Player player, final Location location) { if (!config.isSetBackLocation()) { return; } final User user = getPlugin().getUser(player); if (user != null) { user.setLastLocation(location); } } public boolean isVanished(final Player player) { final User user; return (user = getPlugin().getUser(player)) != null && user.isVanished(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/FactionsHook.java ================================================ package me.realized.duels.hook.hooks; import com.massivecraft.factions.entity.MPlayer; import com.massivecraft.factions.event.EventFactionsPowerChange; import com.massivecraft.factions.event.PowerLossEvent; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.Log; import me.realized.duels.util.hook.PluginHook; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class FactionsHook extends PluginHook { public static final String NAME = "Factions"; private final Config config; private final ArenaManagerImpl arenaManager; public FactionsHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); Listener listener = null; if (ReflectionUtil.getClassUnsafe("com.massivecraft.factions.event.PowerLossEvent") != null) { listener = new FactionsUUIDListener(); } else if (ReflectionUtil.getClassUnsafe(("com.massivecraft.factions.event.EventFactionsPowerChange")) != null) { listener = new Factions2Listener(); } if (listener == null) { Log.error("Could not detect this version of Factions. Please contact the developer if you believe this is an error."); return; } Bukkit.getPluginManager().registerEvents(listener, plugin); } public class Factions2Listener implements Listener { @EventHandler public void on(final EventFactionsPowerChange event) { if (!config.isFNoPowerLoss()) { return; } final MPlayer mPlayer = event.getMPlayer(); final Player player = mPlayer.getPlayer(); if (player == null || !arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } public class FactionsUUIDListener implements Listener { @EventHandler public void on(final PowerLossEvent event) { if (!config.isFuNoPowerLoss()) { return; } final Player player = event.getfPlayer().getPlayer(); if (player == null || !arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/LeaderHeadsHook.java ================================================ package me.realized.duels.hook.hooks; import java.util.Arrays; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.data.UserData; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.util.hook.PluginHook; import me.robin.leaderheads.datacollectors.OnlineDataCollector; import me.robin.leaderheads.objects.BoardType; import org.bukkit.entity.Player; public class LeaderHeadsHook extends PluginHook { public static final String NAME = "LeaderHeads"; private final Config config; private final UserManagerImpl userManager; public LeaderHeadsHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.userManager = plugin.getUserManager(); // Wait for config to load plugin.doSyncAfter(() -> { new DuelWinsCollector(config.getLhWinsTitle(), config.getLhWinsCmd()); new DuelLossesCollector(config.getLhLossesTitle(), config.getLhLossesCmd()); }, 1L); } public class DuelWinsCollector extends OnlineDataCollector { DuelWinsCollector(final String title, final String command) { super("duels-wins", "Duels", BoardType.DEFAULT, title, command, Arrays.asList(null, null, null, null)); } @Override public Double getScore(final Player player) { final UserData user; return (user = userManager.get(player)) != null ? user.getWins() : 0.0; } } public class DuelLossesCollector extends OnlineDataCollector { DuelLossesCollector(final String title, final String command) { super("duels-losses", "Duels", BoardType.DEFAULT, title, command, Arrays.asList(null, null, null, null)); } @Override public Double getScore(final Player player) { final UserData user; return (user = userManager.get(player)) != null ? user.getLosses() : 0.0; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/MVdWPlaceholderHook.java ================================================ package me.realized.duels.hook.hooks; import be.maximvdw.placeholderapi.PlaceholderAPI; import be.maximvdw.placeholderapi.PlaceholderReplaceEvent; import be.maximvdw.placeholderapi.PlaceholderReplacer; import me.realized.duels.DuelsPlugin; import me.realized.duels.data.UserData; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.util.hook.PluginHook; import org.bukkit.entity.Player; public class MVdWPlaceholderHook extends PluginHook { public static final String NAME = "MVdWPlaceholderAPI"; private final UserManagerImpl userDataManager; public MVdWPlaceholderHook(final DuelsPlugin plugin) { super(plugin, NAME); this.userDataManager = plugin.getUserManager(); final Placeholders placeholders = new Placeholders(); PlaceholderAPI.registerPlaceholder(plugin, "duels_wins", placeholders); PlaceholderAPI.registerPlaceholder(plugin, "duels_losses", placeholders); PlaceholderAPI.registerPlaceholder(plugin, "duels_can_request", placeholders); } public class Placeholders implements PlaceholderReplacer { @Override public String onPlaceholderReplace(final PlaceholderReplaceEvent event) { final Player player = event.getPlayer(); if (player == null) { return "Player is required"; } final UserData user = userDataManager.get(player); if (user == null) { return null; } switch (event.getPlaceholder()) { case "duels_wins": return String.valueOf(user.getWins()); case "duels_losses": return String.valueOf(user.getLosses()); case "duels_can_request": return String.valueOf(user.canRequest()); } return null; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/McMMOHook.java ================================================ package me.realized.duels.hook.hooks; import java.util.HashMap; import java.util.Map; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachment; public class McMMOHook extends PluginHook { public static final String NAME = "mcMMO"; private final Config config; private final Map attachments = new HashMap<>(); public McMMOHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); } public void disableSkills(final Player player) { if (!config.isDisableSkills()) { return; } final PermissionAttachment attachment = attachments.computeIfAbsent(player.getUniqueId(), result -> player.addAttachment(plugin)); attachment.setPermission("mcmmo.skills.*", false); player.recalculatePermissions(); } public void enableSkills(final Player player) { if (!config.isDisableSkills()) { return; } final PermissionAttachment attachment = attachments.remove(player.getUniqueId()); if (attachment == null) { return; } attachment.remove(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/MyPetHook.java ================================================ package me.realized.duels.hook.hooks; import de.Keyle.MyPet.MyPetApi; import de.Keyle.MyPet.api.entity.MyPet; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import org.bukkit.entity.Player; public class MyPetHook extends PluginHook { public static final String NAME = "MyPet"; private final Config config; public MyPetHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); try { final Class apiClass = Class.forName("de.Keyle.MyPet.MyPetApi"); apiClass.getMethod("getMyPetManager"); final Class managerClass = Class.forName("de.Keyle.MyPet.api.repository.MyPetManager"); managerClass.getMethod("getMyPet", Player.class); } catch (ClassNotFoundException | NoSuchMethodException ex) { throw new RuntimeException("This version of " + getName() + " is not supported. Please try upgrading to the latest version."); } } public void removePet(final Player player) { if (!config.isMyPetDespawn()) { return; } final MyPet pet = MyPetApi.getMyPetManager().getMyPet(player); if (pet == null) { return; } pet.removePet(false); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/PlaceholderHook.java ================================================ package me.realized.duels.hook.hooks; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.realized.duels.DuelsPlugin; import me.realized.duels.data.UserData; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.util.hook.PluginHook; import org.bukkit.entity.Player; public class PlaceholderHook extends PluginHook { public static final String NAME = "PlaceholderAPI"; private final UserManagerImpl userDataManager; public PlaceholderHook(final DuelsPlugin plugin) { super(plugin, NAME); this.userDataManager = plugin.getUserManager(); new Placeholders().register(); } public class Placeholders extends PlaceholderExpansion { @Override public String getIdentifier() { return "duels"; } @Override public String getAuthor() { return "Realized"; } @Override public String getVersion() { return "1.0"; } @Override public boolean persist() { return true; } @Override public String onPlaceholderRequest(final Player player, final String identifier) { if (player == null) { return "Player is required"; } final UserData user = userDataManager.get(player); if (user == null) { return null; } switch (identifier) { case "wins": return String.valueOf(user.getWins()); case "losses": return String.valueOf(user.getLosses()); case "can_request": return String.valueOf(user.canRequest()); } return null; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/PvPManagerHook.java ================================================ package me.realized.duels.hook.hooks; import me.NoChance.PvPManager.Events.PlayerTagEvent; import me.NoChance.PvPManager.Managers.PlayerHandler; import me.NoChance.PvPManager.PvPManager; import me.NoChance.PvPManager.PvPlayer; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class PvPManagerHook extends PluginHook { public static final String NAME = "PvPManager"; private final Config config; private final ArenaManagerImpl arenaManager; public PvPManagerHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); try { Class.forName("me.NoChance.PvPManager.Events.PlayerTagEvent"); } catch (ClassNotFoundException ex) { throw new RuntimeException("This version of " + getName() + " is not supported. Please try upgrading to the latest version."); } Bukkit.getPluginManager().registerEvents(new PvPManagerListener(), plugin); } public boolean isTagged(final Player player) { if (config.isPmPreventDuel()) { return false; } final PlayerHandler playerHandler = ((PvPManager) getPlugin()).getPlayerHandler(); if (playerHandler == null) { return false; } final PvPlayer pvPlayer = playerHandler.get(player); return pvPlayer != null && pvPlayer.isInCombat(); } public class PvPManagerListener implements Listener { @EventHandler(ignoreCancelled = true) public void on(final PlayerTagEvent event) { if (!config.isPmPreventTag()) { return; } final Player player = event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/SimpleClansHook.java ================================================ package me.realized.duels.hook.hooks; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import net.sacredlabyrinth.phaed.simpleclans.events.AddKillEvent; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class SimpleClansHook extends PluginHook { public static final String NAME = "SimpleClans"; private final Config config; private final ArenaManagerImpl arenaManager; public SimpleClansHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); try { Class.forName("net.sacredlabyrinth.phaed.simpleclans.events.AddKillEvent"); } catch (ClassNotFoundException ex) { throw new RuntimeException("This version of " + getName() + " is not supported. Please try upgrading to the latest version."); } Bukkit.getPluginManager().registerEvents(new SimpleClansListener(), plugin); } public class SimpleClansListener implements Listener { @EventHandler(ignoreCancelled = true) public void on(final AddKillEvent event) { if (!config.isPreventKDRChange()) { return; } final Player player = event.getVictim().toPlayer(); if (player == null || !arenaManager.isInMatch(player)) { return; } event.setCancelled(true); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/VaultHook.java ================================================ package me.realized.duels.hook.hooks; import java.util.Arrays; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.util.Log; import me.realized.duels.util.hook.PluginHook; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; public class VaultHook extends PluginHook { public static final String NAME = "Vault"; @Getter private Economy economy; public VaultHook(final DuelsPlugin plugin) { super(plugin, NAME); final RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(Economy.class); if (provider == null) { Log.warn("Found no available economy plugin that supports Vault. Money betting will not be available."); return; } economy = provider.getProvider(); Log.info("Using Economy Provider: " + economy.getClass().getName()); } public boolean has(final int amount, final Player... players) { if (economy == null) { return false; } for (final Player player : players) { if (!economy.has(player, amount)) { return false; } } return true; } public void add(final int amount, final Player... players) { if (economy != null) { Arrays.stream(players).forEach(player -> economy.depositPlayer(player, amount)); } } public void remove(final int amount, final Player... players) { if (economy != null) { Arrays.stream(players).forEach(player -> economy.withdrawPlayer(player, amount)); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/hook/hooks/worldguard/WorldGuardHook.java ================================================ package me.realized.duels.hook.hooks.worldguard; import java.util.Collection; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.util.hook.PluginHook; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.entity.Player; public class WorldGuardHook extends PluginHook { public static final String NAME = "WorldGuard"; private final Config config; private final WorldGuardHandler handler; public WorldGuardHook(final DuelsPlugin plugin) { super(plugin, NAME); this.config = plugin.getConfiguration(); this.handler = ReflectionUtil.getClassUnsafe("com.sk89q.worldguard.WorldGuard") != null ? new WorldGuard7Handler() : new WorldGuard6Handler(); } public String findDuelZone(final Player player) { if (!config.isDuelzoneEnabled()) { return null; } final Collection allowedRegions = config.getDuelzones(); if (allowedRegions.isEmpty()) { return null; } return handler.findRegion(player, allowedRegions); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/inventories/InventoryManager.java ================================================ package me.realized.duels.inventories; import java.util.HashMap; import java.util.Map; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.gui.inventory.InventoryGui; import me.realized.duels.util.Loadable; import me.realized.duels.util.gui.GuiListener; import org.bukkit.entity.Player; public class InventoryManager implements Loadable { private final DuelsPlugin plugin; private final GuiListener guiListener; private final Map inventories = new HashMap<>(); private int expireTask; public InventoryManager(final DuelsPlugin plugin) { this.plugin = plugin; this.guiListener = plugin.getGuiListener(); } @Override public void handleLoad() { this.expireTask = plugin.doSyncRepeat(() -> { final long now = System.currentTimeMillis(); inventories.entrySet().removeIf(entry -> { if (now - entry.getValue().getCreation() >= 1000L * 60 * 5) { guiListener.removeGui(entry.getValue()); return true; } return false; }); }, 20L, 20L * 5).getTaskId(); } @Override public void handleUnload() { plugin.cancelTask(expireTask); inventories.clear(); } public InventoryGui get(final UUID uuid) { return inventories.get(uuid); } public void create(final Player player, final boolean dead) { // Remove previously existing gui InventoryGui gui = inventories.remove(player.getUniqueId()); if (gui != null) { guiListener.removeGui(gui); } gui = new InventoryGui(plugin, player, dead); guiListener.addGui(gui); inventories.put(player.getUniqueId(), gui); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/kit/KitImpl.java ================================================ package me.realized.duels.kit; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.event.kit.KitEquipEvent; import me.realized.duels.api.kit.Kit; import me.realized.duels.gui.BaseButton; import me.realized.duels.setting.Settings; import me.realized.duels.util.inventory.InventoryUtil; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.jetbrains.annotations.NotNull; public class KitImpl extends BaseButton implements Kit { @Getter private final String name; @Getter private final Map> items = new HashMap<>(); @Getter private boolean usePermission; @Getter private boolean arenaSpecific; @Getter private Set characteristics; @Getter @Setter(value = AccessLevel.PACKAGE) private boolean removed; public KitImpl(final DuelsPlugin plugin, final String name, final ItemStack displayed, final boolean usePermission, final boolean arenaSpecific, final Set characteristics) { super(plugin, displayed != null ? displayed : ItemBuilder .of(Material.DIAMOND_SWORD) .name("&7&l" + name) .lore("&aClick to send", "&aa duel request", "&awith this kit!") .build()); this.name = name; this.usePermission = usePermission; this.arenaSpecific = arenaSpecific; this.characteristics = characteristics; } public KitImpl(final DuelsPlugin plugin, final String name, final PlayerInventory inventory) { this(plugin, name, null, false, false, new HashSet<>()); InventoryUtil.addToMap(inventory, items); } // Never-null since if null item is passed to the constructor, a default item is passed to super @NotNull public ItemStack getDisplayed() { return super.getDisplayed(); } @Override public void setDisplayed(final ItemStack displayed) { super.setDisplayed(displayed); kitManager.saveKits(); } public boolean hasCharacteristic(final Characteristic characteristic) { return characteristics.contains(characteristic); } public void toggleCharacteristic(final Characteristic characteristic) { if (hasCharacteristic(characteristic)) { characteristics.remove(characteristic); } else { characteristics.add(characteristic); } kitManager.saveKits(); } @Override public void setUsePermission(final boolean usePermission) { this.usePermission = usePermission; kitManager.saveKits(); } @Override public void setArenaSpecific(final boolean arenaSpecific) { this.arenaSpecific = arenaSpecific; kitManager.saveKits(); } @Override public boolean equip(@NotNull final Player player) { Objects.requireNonNull(player, "player"); final KitEquipEvent event = new KitEquipEvent(player, this); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } InventoryUtil.fillFromMap(player.getInventory(), items); player.updateInventory(); return true; } @Override public void onClick(final Player player) { final String permission = String.format(Permissions.KIT, name.replace(" ", "-").toLowerCase()); if (usePermission && !player.hasPermission(Permissions.KIT_ALL) && !player.hasPermission(permission)) { lang.sendMessage(player, "ERROR.no-permission", "permission", permission); return; } final Settings settings = settingManager.getSafely(player); // Reset arena selection if this kit is incompatible with selected arena if (settings.getArena() != null && !arenaManager.isSelectable(this, settings.getArena())) { settings.setArena(null); } settings.setKit(this); settings.openGui(player); } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final KitImpl kit = (KitImpl) other; return Objects.equals(name, kit.name); } @Override public int hashCode() { return Objects.hash(name); } public enum Characteristic { SOUP, SUMO, UHC, COMBO; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/kit/KitManagerImpl.java ================================================ package me.realized.duels.kit; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.kit.KitCreateEvent; import me.realized.duels.api.event.kit.KitRemoveEvent; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.kit.KitManager; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.KitData; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.MultiPageGui; import me.realized.duels.util.inventory.ItemBuilder; import me.realized.duels.util.io.FileUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class KitManagerImpl implements Loadable, KitManager { private static final String FILE_NAME = "kits.json"; private static final String ERROR_NOT_ALPHANUMERIC = "Could not load kit %s: Name is not alphanumeric."; private static final String KITS_LOADED = "Loaded %s kit(s)."; private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final File file; private final Map kits = new LinkedHashMap<>(); @Getter private MultiPageGui gui; public KitManagerImpl(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.file = new File(plugin.getDataFolder(), FILE_NAME); } @Override public void handleLoad() throws IOException { gui = new MultiPageGui<>(plugin, lang.getMessage("GUI.kit-selector.title"), config.getKitSelectorRows(), kits.values()); gui.setSpaceFiller(Items.from(config.getKitSelectorFillerType(), config.getKitSelectorFillerData())); gui.setPrevButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.previous-page.name")).build()); gui.setNextButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.next-page.name")).build()); gui.setEmptyIndicator(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.kit-selector.buttons.empty.name")).build()); plugin.getGuiListener().addGui(gui); if (FileUtil.checkNonEmpty(file, true)) { try (final Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)) { final Map data = JsonUtil.getObjectMapper().readValue(reader, new TypeReference>() {}); if (data != null) { for (final Map.Entry entry : data.entrySet()) { if (!StringUtil.isAlphanumeric(entry.getKey())) { Log.warn(this, String.format(ERROR_NOT_ALPHANUMERIC, entry.getKey())); continue; } kits.put(entry.getKey(), entry.getValue().toKit(plugin)); } } } } Log.info(this, String.format(KITS_LOADED, kits.size())); gui.calculatePages(); } @Override public void handleUnload() { if (gui != null) { plugin.getGuiListener().removeGui(gui); } kits.clear(); } void saveKits() { final Map data = new LinkedHashMap<>(); for (final Map.Entry entry : kits.entrySet()) { data.put(entry.getKey(), KitData.fromKit(entry.getValue())); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, data); writer.flush(); } catch (IOException ex) { Log.error(this, ex.getMessage(), ex); } } @Nullable @Override public KitImpl get(@NotNull final String name) { Objects.requireNonNull(name, "name"); return kits.get(name); } public KitImpl create(@NotNull final Player creator, @NotNull final String name, final boolean override) { Objects.requireNonNull(creator, "creator"); Objects.requireNonNull(name, "name"); if (!StringUtil.isAlphanumeric(name) || (!override && kits.containsKey(name))) { return null; } final KitImpl kit = new KitImpl(plugin, name, creator.getInventory()); kits.put(name, kit); saveKits(); final KitCreateEvent event = new KitCreateEvent(creator, kit); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return kit; } @Nullable @Override public KitImpl create(@NotNull final Player creator, @NotNull final String name) { return create(creator, name, false); } @Nullable @Override public KitImpl remove(@Nullable CommandSender source, @NotNull final String name) { Objects.requireNonNull(name, "name"); final KitImpl kit = kits.remove(name); if (kit == null) { return null; } kit.setRemoved(true); plugin.getArenaManager().clearBinds(kit); saveKits(); final KitRemoveEvent event = new KitRemoveEvent(source, kit); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return kit; } @Nullable @Override public KitImpl remove(@NotNull final String name) { return remove(null, name); } @NotNull @Override public List getKits() { return Collections.unmodifiableList(Lists.newArrayList(kits.values())); } public List getNames(final boolean nokit) { final List names = new ArrayList<>(kits.keySet()); if (nokit) { names.add("-"); // Special case: Change the nokit rating } return names; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/DamageListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.util.EventUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; /** * Overrides damage cancellation by other plugins for players in a duel. */ public class DamageListener implements Listener { private final ArenaManagerImpl arenaManager; public DamageListener(final DuelsPlugin plugin) { this.arenaManager = plugin.getArenaManager(); if (plugin.getConfiguration().isForceAllowCombat()) { plugin.doSyncAfter(() -> Bukkit.getPluginManager().registerEvents(this, plugin), 1L); } } @EventHandler(priority = EventPriority.HIGHEST) public void on(final EntityDamageByEntityEvent event) { if (!event.isCancelled() || !(event.getEntity() instanceof Player)) { return; } final Player player = (Player) event.getEntity(); final Player damager = EventUtil.getDamager(event); if (damager == null) { return; } final ArenaImpl arena = arenaManager.get(player); // Only activate when winner is undeclared if (arena == null || !arenaManager.isInMatch(damager) || arena.isEndGame()) { return; } event.setCancelled(false); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/EnderpearlListener.java ================================================ package me.realized.duels.listeners; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Iterator; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.match.MatchStartEvent; import me.realized.duels.arena.ArenaManagerImpl; import org.bukkit.Bukkit; import org.bukkit.entity.EnderPearl; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.player.PlayerQuitEvent; /** * Prevents players throwing an enderpearl before entering a duel and teleporting out with kit items. */ public class EnderpearlListener implements Listener { private static final long PEARL_EXPIRY = 60 * 1000L; private final ArenaManagerImpl arenaManager; // Maps an enderpearl thrower to enderpearls thrown. private final Multimap pearls = HashMultimap.create(); public EnderpearlListener(final DuelsPlugin plugin) { this.arenaManager = plugin.getArenaManager(); Bukkit.getPluginManager().registerEvents(this, plugin); } private void removeExpired(final Player player) { final Collection pearls = this.pearls.asMap().get(player.getUniqueId()); if (pearls == null || pearls.isEmpty()) { return; } final long now = System.currentTimeMillis(); pearls.removeIf(pearl -> now - pearl.creation > PEARL_EXPIRY); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void on(final ProjectileLaunchEvent event) { if (event.getEntityType() != EntityType.ENDER_PEARL) { return; } final EnderPearl enderPearl = (EnderPearl) event.getEntity(); if (!(enderPearl.getShooter() instanceof Player)) { return; } final Player player = (Player) enderPearl.getShooter(); // Ignore pearls thrown in match if (arenaManager.isInMatch(player)) { return; } removeExpired(player); pearls.put(player.getUniqueId(), new Pearl(enderPearl)); } @EventHandler public void on(final ProjectileHitEvent event) { if (!(event.getEntity() instanceof EnderPearl)) { return; } final EnderPearl enderPearl = (EnderPearl) event.getEntity(); if (!(enderPearl.getShooter() instanceof Player)) { return; } final Collection pearls = this.pearls.asMap().get(((Player) enderPearl.getShooter()).getUniqueId()); if (pearls == null || pearls.isEmpty()) { return; } final Iterator iterator = pearls.iterator(); while (iterator.hasNext()) { final Pearl pearl = iterator.next(); if (enderPearl.equals(pearl.pearl.get())) { iterator.remove(); break; } } } @EventHandler public void on(final MatchStartEvent event) { for (final Player player : event.getPlayers()) { final Collection pearls = this.pearls.asMap().remove(player.getUniqueId()); if (pearls == null || pearls.isEmpty()) { continue; } pearls.forEach(pearl -> { final EnderPearl enderPearl = pearl.pearl.get(); if (enderPearl != null && !enderPearl.isDead()) { enderPearl.remove(); } }); } } @EventHandler public void on(final PlayerQuitEvent event) { pearls.asMap().remove(event.getPlayer().getUniqueId()); } private static class Pearl { private final long creation; private final WeakReference pearl; public Pearl(final EnderPearl pearl) { this.creation = System.currentTimeMillis(); this.pearl = new WeakReference<>(pearl); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/KitItemListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.util.Log; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.Identifiers; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Item; 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.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; /** * Prevents players from using kit items outside of a duel by checking * for an NBT tag stored in the item by Duels. */ public class KitItemListener implements Listener { // Warning sent to player attempting to use kit item private static final String WARNING = StringUtil.color("&4[Duels] Kit contents cannot be used when not in a duel."); // Warning printed on console private static final String WARNING_CONSOLE = "%s has attempted to use a kit item while not in duel, but was prevented by KitItemListener."; private final ArenaManagerImpl arenaManager; public KitItemListener(final DuelsPlugin plugin) { this.arenaManager = plugin.getArenaManager(); // Only register listener if enabled in config.yml if (plugin.getConfiguration().isProtectKitItems()) { Bukkit.getPluginManager().registerEvents(this, plugin); } } private boolean isExcluded(final Player player) { return player.isOp() || player.hasPermission(Permissions.ADMIN) || arenaManager.isInMatch(player); } private boolean isKitItem(final ItemStack item) { return item != null && item.getType() != Material.AIR && Identifiers.hasIdentifier(item); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void on(final InventoryClickEvent event) { final Player player = (Player) event.getWhoClicked(); if (isExcluded(player)) { return; } final Inventory clicked = event.getClickedInventory(); if (!(clicked instanceof PlayerInventory)) { return; } final ItemStack item = event.getCurrentItem(); if (!isKitItem(item)) { return; } event.setCurrentItem(null); player.sendMessage(WARNING); Log.warn(String.format(WARNING_CONSOLE, player.getName())); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void on(final PlayerInteractEvent event) { final Player player = event.getPlayer(); if (isExcluded(player)) { return; } final ItemStack item = event.getItem(); if (!isKitItem(item)) { return; } event.setCancelled(true); player.getInventory().remove(item); player.sendMessage(WARNING); Log.warn(String.format(WARNING_CONSOLE, player.getName())); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void on(final PlayerPickupItemEvent event) { final Player player = event.getPlayer(); if (isExcluded(player)) { return; } final Item item = event.getItem(); if (!isKitItem(item.getItemStack())) { return; } event.setCancelled(true); item.remove(); player.sendMessage(WARNING); Log.warn(String.format(WARNING_CONSOLE, player.getName())); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/KitOptionsListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.match.MatchEndEvent; import me.realized.duels.api.event.match.MatchStartEvent; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.arena.MatchImpl; import me.realized.duels.config.Config; import me.realized.duels.kit.KitImpl.Characteristic; import me.realized.duels.util.PlayerUtil; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.metadata.MetadataUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; /** * Applies kit characteristics (options) to duels. */ public class KitOptionsListener implements Listener { private static final String METADATA_KEY = "Duels-MaxNoDamageTicks"; private final DuelsPlugin plugin; private final Config config; private final ArenaManagerImpl arenaManager; public KitOptionsListener(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.arenaManager = plugin.getArenaManager(); Bukkit.getPluginManager().registerEvents(this, plugin); Bukkit.getPluginManager().registerEvents(CompatUtil.isPre1_14() ? new ComboPre1_14Listener() : new ComboPost1_14Listener(), plugin); } private boolean isEnabled(final ArenaImpl arena, final Characteristic characteristic) { final MatchImpl match = arena.getMatch(); return match != null && match.getKit() != null && match.getKit().hasCharacteristic(characteristic); } @EventHandler public void on(final EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) { return; } final Player player = (Player) event.getEntity(); final ArenaImpl arena = arenaManager.get(player); if (arena == null || !isEnabled(arena, Characteristic.SUMO)) { return; } event.setDamage(0); } @EventHandler public void on(final PlayerMoveEvent event) { final Player player = event.getPlayer(); final ArenaImpl arena = arenaManager.get(player); if (player.isDead() || arena == null || !isEnabled(arena, Characteristic.SUMO) || arena.isEndGame()) { return; } final Block block = event.getFrom().getBlock(); if (!(block.getType().name().contains("WATER") || block.getType().name().contains("LAVA"))) { return; } player.setHealth(0); } @EventHandler public void on(final PlayerInteractEvent event) { if (!event.hasItem() || !event.getAction().name().contains("RIGHT")) { return; } final Player player = event.getPlayer(); final ArenaImpl arena = arenaManager.get(player); if (arena == null || !isEnabled(arena, Characteristic.SOUP)) { return; } final ItemStack item = event.getItem(); if (item == null || item.getType() != Items.MUSHROOM_SOUP) { return; } event.setUseItemInHand(Result.DENY); if (config.isSoupCancelIfAlreadyFull() && player.getHealth() == PlayerUtil.getMaxHealth(player)) { return; } final ItemStack bowl = config.isSoupRemoveEmptyBowl() ? null : new ItemStack(Material.BOWL); if (CompatUtil.isPre1_10()) { player.getInventory().setItem(player.getInventory().getHeldItemSlot(), bowl); } else { if (event.getHand() == EquipmentSlot.OFF_HAND) { player.getInventory().setItemInOffHand(bowl); } else { player.getInventory().setItemInMainHand(bowl); } } final double regen = config.getSoupHeartsToRegen() * 2.0; final double oldHealth = player.getHealth(); final double maxHealth = PlayerUtil.getMaxHealth(player); player.setHealth(Math.min(oldHealth + regen, maxHealth)); } @EventHandler(ignoreCancelled = true) public void on(final EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player) || !(event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN)) { return; } final Player player = (Player) event.getEntity(); final ArenaImpl arena = arenaManager.get(player); if (arena == null || !isEnabled(arena, Characteristic.UHC)) { return; } event.setCancelled(true); } private class ComboPre1_14Listener implements Listener { @EventHandler public void on(final MatchStartEvent event) { final ArenaImpl arena = arenaManager.get(event.getMatch().getArena().getName()); if (arena == null || !isEnabled(arena, Characteristic.COMBO)) { return; } for (final Player player : event.getPlayers()) { MetadataUtil.put(plugin, player, METADATA_KEY, player.getMaximumNoDamageTicks()); player.setMaximumNoDamageTicks(0); } } @EventHandler public void on(final MatchEndEvent event) { final ArenaImpl arena = arenaManager.get(event.getMatch().getArena().getName()); if (arena == null || !isEnabled(arena, Characteristic.COMBO)) { return; } final MatchImpl match = arena.getMatch(); if (match == null) { return; } match.getAllPlayers().forEach(player -> { final Object value = MetadataUtil.removeAndGet(plugin, player, METADATA_KEY); if (value == null) { return; } player.setMaximumNoDamageTicks((Integer) value); }); } } private class ComboPost1_14Listener implements Listener { @EventHandler public void on(final EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof Player)) { return; } final Player player = (Player) event.getEntity(); final ArenaImpl arena = arenaManager.get(player); if (arena == null || !isEnabled(arena, Characteristic.COMBO)) { return; } plugin.doSyncAfter(() -> player.setNoDamageTicks(0), 1); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/LingerPotionListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.util.compat.CompatUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.AreaEffectCloudApplyEvent; /** * Prevents spectators from being affected by lingering potions. */ public class LingerPotionListener { private final ArenaManagerImpl arenaManager; private final SpectateManagerImpl spectateManager; public LingerPotionListener(final DuelsPlugin plugin) { this.arenaManager = plugin.getArenaManager(); this.spectateManager = plugin.getSpectateManager(); // Lingering potions were released in MC 1.9 if (CompatUtil.isPre1_9()) { return; } Bukkit.getPluginManager().registerEvents(new Post1_9Listener(), plugin); } public class Post1_9Listener implements Listener { @EventHandler public void on(final AreaEffectCloudApplyEvent event) { if (!(event.getEntity().getSource() instanceof Player)) { return; } final Player player = (Player) event.getEntity().getSource(); if (!arenaManager.isInMatch(player)) { return; } event.getAffectedEntities().removeIf(entity -> entity instanceof Player && spectateManager.isSpectating((Player) entity)); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/PotionListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.util.compat.CompatUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.inventory.ItemStack; /** * Removes empty potion bottle after consumption if enabled. */ public class PotionListener implements Listener { private final DuelsPlugin plugin; private final ArenaManagerImpl arenaManager; public PotionListener(final DuelsPlugin plugin) { this.plugin = plugin; this.arenaManager = plugin.getArenaManager(); if (plugin.getConfiguration().isRemoveEmptyBottle()) { Bukkit.getPluginManager().registerEvents(this, plugin); } } @EventHandler public void on(final PlayerItemConsumeEvent event) { final Player player = event.getPlayer(); if (!arenaManager.isInMatch(player)) { return; } final ItemStack item = event.getItem(); if (!item.getType().name().endsWith("POTION")) { return; } plugin.doSync(() -> { if (item.getAmount() <= 1) { if (CompatUtil.isPre1_10()) { player.getInventory().setItem(player.getInventory().getHeldItemSlot(), null); } else { final ItemStack held = player.getInventory().getItemInMainHand(); if (held.getType() == Material.GLASS_BOTTLE) { player.getInventory().setItemInMainHand(null); } else { player.getInventory().setItemInOffHand(null); } } } else { player.getInventory().removeItem(new ItemStack(Material.GLASS_BOTTLE, 1)); } }); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/ProjectileHitListener.java ================================================ package me.realized.duels.listeners; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.projectiles.ProjectileSource; /** * Displays a message to shooter containing hit entity's health if enabled. */ public class ProjectileHitListener implements Listener { private final Config config; private final Lang lang; private final ArenaManagerImpl arenaManager; public ProjectileHitListener(final DuelsPlugin plugin) { this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.arenaManager = plugin.getArenaManager(); if (plugin.getConfiguration().isProjectileHitMessageEnabled()) { Bukkit.getPluginManager().registerEvents(this, plugin); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void on(final EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof LivingEntity)) { return; } final Entity damager = event.getDamager(); if (!(damager instanceof Projectile) || !config.getProjectileHitMessageTypes().contains(damager.getType().name())) { return; } final ProjectileSource source = ((Projectile) damager).getShooter(); if (!(source instanceof Player)) { return; } final Player player = (Player) source; if (!arenaManager.isInMatch(player)) { return; } final LivingEntity entity = (LivingEntity) event.getEntity(); final double health = Math.max(Math.ceil(entity.getHealth() - event.getFinalDamage()) * 0.5, 0); lang.sendMessage(player, "DUEL.projectile-hit-message", "name", entity.getName(), "health", health); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/listeners/TeleportListener.java ================================================ package me.realized.duels.listeners; import java.util.Set; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Lang; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.teleport.Teleport; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; /** * Prevents players teleporting to players in a match or in spectator mode. */ public class TeleportListener implements Listener { private final Lang lang; private final ArenaManagerImpl arenaManager; private final SpectateManagerImpl spectateManager; public TeleportListener(final DuelsPlugin plugin) { this.lang = plugin.getLang(); this.arenaManager = plugin.getArenaManager(); this.spectateManager = plugin.getSpectateManager(); if (plugin.getConfiguration().isPreventTpToMatchPlayers()) { Bukkit.getPluginManager().registerEvents(this, plugin); } } private boolean isSimilar(final Location first, final Location second) { return Math.abs(first.getX() - second.getX()) + Math.abs(first.getY() - second.getY()) + Math.abs(first.getZ() - second.getZ()) < 5; } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void on(final PlayerTeleportEvent event) { final Player player = event.getPlayer(); if (player.isOp() || player.isDead() || player.hasPermission(Permissions.ADMIN) || player.hasPermission(Permissions.TP_BYPASS) || player.hasMetadata(Teleport.METADATA_KEY) || arenaManager.isInMatch(player) || spectateManager.isSpectating(player)) { return; } final Location to = event.getTo(); final Set players = arenaManager.getPlayers(); players.addAll(spectateManager.getAllSpectators()); for (final Player target : players) { if (target == null || player.equals(target) || !target.isOnline() || !isSimilar(target.getLocation(), to)) { continue; } event.setCancelled(true); lang.sendMessage(player, "ERROR.duel.prevent-teleportation"); return; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/logging/LogManager.java ================================================ package me.realized.duels.logging; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.util.DateUtil; import me.realized.duels.util.Log.LogSource; public class LogManager implements LogSource { @Getter private final Logger logger = Logger.getAnonymousLogger(); private final FileHandler handler; public LogManager(final DuelsPlugin plugin) throws IOException { final File pluginFolder = plugin.getDataFolder(); if (!pluginFolder.exists()) { pluginFolder.mkdir(); } final File folder = new File(pluginFolder, "logs"); if (!folder.exists()) { folder.mkdir(); } logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); final File file = new File(folder, DateUtil.formatDate(new Date()) + ".log"); if (!file.exists()) { file.createNewFile(); } handler = new FileHandler(file.getCanonicalPath(), true); handler.setLevel(Level.ALL); handler.setFormatter(new Formatter() { @Override public String format(final LogRecord record) { String thrown = ""; if (record.getThrown() != null) { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); record.getThrown().printStackTrace(printWriter); printWriter.close(); thrown = stringWriter.toString(); } return "[" + DateUtil.formatDatetime(record.getMillis()) + "] [" + record.getLevel().getName() + "] " + record.getMessage() + '\n' + thrown; } }); logger.addHandler(handler); } public void handleDisable() { handler.close(); logger.removeHandler(handler); } public void debug(final String s) { log(Level.INFO, "[DEBUG] " + s); } @Override public void log(final Level level, final String s) { log(level, s, null); } @Override public void log(final Level level, final String s, final Throwable thrown) { if (handler == null) { return; } if (thrown != null) { getLogger().log(level, s, thrown); } else { getLogger().log(level, s); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/player/PlayerInfo.java ================================================ package me.realized.duels.player; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; import me.realized.duels.util.PlayerUtil; import me.realized.duels.util.inventory.InventoryUtil; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; public class PlayerInfo { @Getter private final Map> items = new HashMap<>(); @Getter private final List effects; @Getter private final double health; @Getter private final int hunger; @Getter private final List extra = new ArrayList<>(); @Getter @Setter private Location location; public PlayerInfo(final List effects, final double health, final int hunger, final Location location) { this.effects = effects; this.health = health; this.hunger = hunger; this.location = location; } public PlayerInfo(final Player player, final boolean excludeInventory) { this(Lists.newArrayList(player.getActivePotionEffects()), player.getHealth(), player.getFoodLevel(), player.getLocation().clone()); if (excludeInventory) { return; } InventoryUtil.addToMap(player.getInventory(), items); } public void restore(final Player player) { final double maxHealth = PlayerUtil.getMaxHealth(player); player.addPotionEffects(effects); player.setHealth(health > maxHealth ? maxHealth : health); player.setFoodLevel(hunger); InventoryUtil.fillFromMap(player.getInventory(), items); InventoryUtil.addOrDrop(player, extra); player.updateInventory(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/player/PlayerInfoManager.java ================================================ package me.realized.duels.player; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Charsets; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.config.Config; import me.realized.duels.data.LocationData; import me.realized.duels.data.PlayerData; import me.realized.duels.hook.hooks.EssentialsHook; import me.realized.duels.teleport.Teleport; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.PlayerUtil; import me.realized.duels.util.io.FileUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerRespawnEvent; /** * Manages: * (1) player info cache for restoration after matches. * (2) lobby location for teleportation after matches. */ public class PlayerInfoManager implements Loadable { private static final String CACHE_FILE_NAME = "player-cache.json"; private static final String LOBBY_FILE_NAME = "lobby.json"; private static final String ERROR_LOBBY_LOAD = "Could not load lobby location!"; private static final String ERROR_LOBBY_SAVE = "Could not save lobby location!"; private static final String ERROR_LOBBY_DEFAULT = "Lobby location was not set, using %s's spawn location as default. Use the command /duels setlobby in-game to set the lobby location."; private final DuelsPlugin plugin; private final Config config; private final File cacheFile; private final File lobbyFile; private final Map cache = new HashMap<>(); private Teleport teleport; private EssentialsHook essentials; @Getter private Location lobby; public PlayerInfoManager(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.cacheFile = new File(plugin.getDataFolder(), CACHE_FILE_NAME); this.lobbyFile = new File(plugin.getDataFolder(), LOBBY_FILE_NAME); plugin.doSyncAfter(() -> Bukkit.getPluginManager().registerEvents(new PlayerInfoListener(), plugin), 1L); } @Override public void handleLoad() throws IOException { this.teleport = plugin.getTeleport(); this.essentials = plugin.getHookManager().getHook(EssentialsHook.class); if (FileUtil.checkNonEmpty(cacheFile, false)) { try (final Reader reader = new InputStreamReader(new FileInputStream(cacheFile), Charsets.UTF_8)) { final Map data = JsonUtil.getObjectMapper().readValue(reader, new TypeReference>() {}); if (data != null) { for (final Map.Entry entry : data.entrySet()) { cache.put(entry.getKey(), entry.getValue().toPlayerInfo()); } } } cacheFile.delete(); } if (FileUtil.checkNonEmpty(lobbyFile, false)) { try (final Reader reader = new InputStreamReader(new FileInputStream(lobbyFile), Charsets.UTF_8)) { this.lobby = JsonUtil.getObjectMapper().readValue(reader, LocationData.class).toLocation(); } catch (IOException ex) { Log.error(this, ERROR_LOBBY_LOAD, ex); } } // If lobby is not found or invalid, use the default world's spawn location for lobby. if (lobby == null || lobby.getWorld() == null) { final World world = Bukkit.getWorlds().get(0); this.lobby = world.getSpawnLocation(); Log.warn(this, String.format(ERROR_LOBBY_DEFAULT, world.getName())); } } @Override public void handleUnload() throws IOException { Bukkit.getOnlinePlayers().stream().filter(Player::isDead).forEach(player -> { final PlayerInfo info = remove(player); if (info != null) { player.spigot().respawn(); teleport.tryTeleport(player, info.getLocation()); PlayerUtil.reset(player); info.restore(player); } }); if (cache.isEmpty()) { return; } final Map data = new HashMap<>(); for (final Map.Entry entry : cache.entrySet()) { data.put(entry.getKey(), PlayerData.fromPlayerInfo(entry.getValue())); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(cacheFile), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, data); writer.flush(); } cache.clear(); } /** * Sets a lobby location at given player's location. * * @param player Player to get location for lobby * @return true if setting lobby was successful, false otherwise */ public boolean setLobby(final Player player) { final Location lobby = player.getLocation().clone(); try (final Writer writer = new OutputStreamWriter(new FileOutputStream(lobbyFile), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, LocationData.fromLocation(lobby)); writer.flush(); this.lobby = lobby; return true; } catch (IOException ex) { Log.error(this, ERROR_LOBBY_SAVE, ex); return false; } } /** * Gets cached PlayerInfo instance for given player. * * @param player Player to get cached PlayerInfo instance * @return cached PlayerInfo instance or null if not found */ public PlayerInfo get(final Player player) { return cache.get(player.getUniqueId()); } /** * Creates a cached PlayerInfo instance for given player. * * @param player Player to create a cached PlayerInfo instance * @param excludeInventory true to exclude inventory contents from being stored in PlayerInfo, false otherwise */ public void create(final Player player, final boolean excludeInventory) { final PlayerInfo info = new PlayerInfo(player, excludeInventory); if (!config.isTeleportToLastLocation()) { info.setLocation(lobby.clone()); } cache.put(player.getUniqueId(), info); } /** * Calls {@link #create(Player, boolean)} with excludeInventory defaulting to false. * * @see {@link #create(Player, boolean)} */ public void create(final Player player) { create(player, false); } /** * Removes the given player from cache. * * @param player Player to remove from cache * @return Removed PlayerInfo instance or null if not found */ public PlayerInfo remove(final Player player) { return cache.remove(player.getUniqueId()); } private class PlayerInfoListener implements Listener { // Handles case of some players causing respawn to skip somehow. @EventHandler(priority = EventPriority.HIGHEST) public void on(final PlayerJoinEvent event) { final Player player = event.getPlayer(); if (player.isDead()) { return; } final PlayerInfo info = remove(player); if (info == null) { return; } teleport.tryTeleport(player, info.getLocation()); info.restore(player); } @EventHandler(priority = EventPriority.HIGHEST) public void on(final PlayerRespawnEvent event) { final Player player = event.getPlayer(); final PlayerInfo info = get(player); if (info == null) { return; } event.setRespawnLocation(info.getLocation()); if (essentials != null) { essentials.setBackLocation(player, event.getRespawnLocation()); } plugin.doSyncAfter(() -> { // Do not remove cached data if player left while respawning. if (!player.isOnline()) { return; } remove(player); info.restore(player); }, 1L); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/queue/Queue.java ================================================ package me.realized.duels.queue; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.queue.DQueue; import me.realized.duels.gui.BaseButton; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class Queue extends BaseButton implements DQueue { @Getter private final Kit kit; @Getter private final int bet; @Getter private final List players = new LinkedList<>(); @Getter @Setter(value = AccessLevel.PACKAGE) private boolean removed; public Queue(final DuelsPlugin plugin, final Kit kit, final int bet) { super(plugin, ItemBuilder .of((plugin.getConfiguration().isInheritKitItemType() && kit != null) ? kit.getDisplayed().clone() : ItemBuilder.of(Material.DIAMOND_SWORD).build()) .name(plugin.getLang().getMessage("GUI.queues.buttons.queue.name", "kit", kit != null ? kit.getName() : plugin.getLang().getMessage("GENERAL.none"), "bet_amount", bet, "in_queue", 0, "in_match", 0)) .lore(plugin.getLang().getMessage("GUI.queues.buttons.queue.lore", "kit", kit != null ? kit.getName() : plugin.getLang().getMessage("GENERAL.none"), "bet_amount", bet, "in_queue", 0, "in_match", 0).split("\n")) .build()); this.kit = kit; this.bet = bet; } @Override public boolean isInQueue(@NotNull final Player player) { return players.stream().anyMatch(entry -> entry.getPlayer().equals(player)); } @NotNull @Override public List getQueuedPlayers() { return Collections.unmodifiableList(players.stream().sequential().map(QueueEntry::getPlayer).collect(Collectors.toList())); } void addPlayer(final QueueEntry entry) { players.add(entry); update(); queueManager.getGui().calculatePages(); } boolean removePlayer(final Player player) { if (players.removeIf(entry -> entry.getPlayer().equals(player))) { update(); queueManager.getGui().calculatePages(); return true; } return false; } boolean removeAll(final Set players) { if (this.players.removeAll(players)) { update(); return true; } return false; } public long getPlayersInMatch() { return arenaManager.getPlayersInMatch(this); } public void update() { int inQueue = players.size(); long inMatch = getPlayersInMatch(); setDisplayName(lang.getMessage("GUI.queues.buttons.queue.name", "kit", kit != null ? kit.getName() : lang.getMessage("GENERAL.none"), "bet_amount", bet, "in_queue", inQueue, "in_match", inMatch)); setLore(lang.getMessage("GUI.queues.buttons.queue.lore", "kit", kit != null ? kit.getName() : lang.getMessage("GENERAL.none"), "bet_amount", bet, "in_queue", inQueue, "in_match", inMatch).split("\n")); } @Override public void onClick(final Player player) { queueManager.addToQueue(player, this); } @Override public String toString() { return (kit != null ? kit.getName() : "none") + " ($" + bet + ")"; } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final Queue queue = (Queue) other; return bet == queue.bet && Objects.equals(kit, queue.kit); } @Override public int hashCode() { return Objects.hash(kit, bet); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/queue/QueueEntry.java ================================================ package me.realized.duels.queue; import java.util.Objects; import lombok.Getter; import me.realized.duels.setting.CachedInfo; import org.bukkit.Location; import org.bukkit.entity.Player; public class QueueEntry { @Getter private final Player player; @Getter private final CachedInfo info; QueueEntry(final Player player, final Location location, final String duelzone) { this.player = player; this.info = new CachedInfo(location, duelzone); } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final QueueEntry that = (QueueEntry) other; return Objects.equals(player, that.player); } @Override public int hashCode() { return Objects.hash(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/queue/QueueManager.java ================================================ package me.realized.duels.queue; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Charsets; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import lombok.Getter; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.queue.QueueCreateEvent; import me.realized.duels.api.event.queue.QueueJoinEvent; import me.realized.duels.api.event.queue.QueueLeaveEvent; import me.realized.duels.api.event.queue.QueueRemoveEvent; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.queue.DQueue; import me.realized.duels.api.queue.DQueueManager; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.data.QueueData; import me.realized.duels.data.UserData; import me.realized.duels.data.UserManagerImpl; import me.realized.duels.duel.DuelManager; import me.realized.duels.hook.hooks.CombatTagPlusHook; import me.realized.duels.hook.hooks.PvPManagerHook; import me.realized.duels.hook.hooks.VaultHook; import me.realized.duels.hook.hooks.worldguard.WorldGuardHook; import me.realized.duels.kit.KitManagerImpl; import me.realized.duels.setting.Settings; import me.realized.duels.spectate.SpectateManagerImpl; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.NumberUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.gui.MultiPageGui; import me.realized.duels.util.inventory.InventoryUtil; import me.realized.duels.util.inventory.ItemBuilder; import me.realized.duels.util.io.FileUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class QueueManager implements Loadable, DQueueManager, Listener { private static final String FILE_NAME = "queues.json"; private static final String QUEUES_LOADED = "Loaded %s queue(s)."; private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final UserManagerImpl userManager; private final KitManagerImpl kitManager; private final ArenaManagerImpl arenaManager; private final SpectateManagerImpl spectateManager; private final DuelManager duelManager; private final File file; private final List queues = new ArrayList<>(); private CombatTagPlusHook combatTagPlus; private PvPManagerHook pvpManager; private WorldGuardHook worldGuard; private VaultHook vault; private int queueTask; @Getter private MultiPageGui gui; public QueueManager(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.userManager = plugin.getUserManager(); this.kitManager = plugin.getKitManager(); this.arenaManager = plugin.getArenaManager(); this.spectateManager = plugin.getSpectateManager(); this.duelManager = plugin.getDuelManager(); this.file = new File(plugin.getDataFolder(), FILE_NAME); Bukkit.getPluginManager().registerEvents(this, plugin); } private boolean canFight(final Kit kit, final UserData first, final UserData second) { if (kit == null || !config.isRatingEnabled()) { return true; } if (first != null && second != null) { final int firstRating = first.getRating(kit); final int secondRating = second.getRating(kit); final int kFactor = config.getKFactor(); return NumberUtil.getChange(kFactor, firstRating, secondRating) != 0 && NumberUtil.getChange(kFactor, secondRating, firstRating) != 0; } return false; } @Override public void handleLoad() throws IOException { this.gui = new MultiPageGui<>(plugin, lang.getMessage("GUI.queues.title"), config.getQueuesRows(), queues); gui.setSpaceFiller(Items.from(config.getQueuesFillerType(), config.getQueuesFillerData())); gui.setPrevButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.queues.buttons.previous-page.name")).build()); gui.setNextButton(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.queues.buttons.next-page.name")).build()); gui.setEmptyIndicator(ItemBuilder.of(Material.PAPER).name(lang.getMessage("GUI.queues.buttons.empty.name")).build()); plugin.getGuiListener().addGui(gui); if (FileUtil.checkNonEmpty(file, true)) { try (final Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)) { final List data = JsonUtil.getObjectMapper().readValue(reader, new TypeReference>() {}); if (data != null) { data.forEach(queueData -> { final Queue queue = queueData.toQueue(plugin); if (queue != null && !queues.contains(queue)) { queues.add(queue); } }); } } } Log.info(this, String.format(QUEUES_LOADED, queues.size())); gui.calculatePages(); this.combatTagPlus = plugin.getHookManager().getHook(CombatTagPlusHook.class); this.pvpManager = plugin.getHookManager().getHook(PvPManagerHook.class); this.worldGuard = plugin.getHookManager().getHook(WorldGuardHook.class); this.vault = plugin.getHookManager().getHook(VaultHook.class); this.queueTask = plugin.doSyncRepeat(() -> { boolean update = false; for (final Queue queue : queues) { final Set remove = new HashSet<>(); for (final QueueEntry current : queue.getPlayers()) { // player is already in a match if (remove.contains(current)) { continue; } final Player player = current.getPlayer(); for (final QueueEntry opponent : queue.getPlayers()) { final Player other = opponent.getPlayer(); // opponent is already in a match or the rating difference is too high if (current.equals(opponent) || remove.contains(opponent) || !canFight(queue.getKit(), userManager.get(player), userManager.get(other))) { continue; } remove.add(current); remove.add(opponent); final Settings setting = new Settings(plugin); if (queue.getKit() != null) { setting.setKit(kitManager.get(queue.getKit().getName())); } else { setting.setOwnInventory(true); } setting.setBet(queue.getBet()); setting.getCache().put(player.getUniqueId(), current.getInfo()); setting.getCache().put(other.getUniqueId(), opponent.getInfo()); final String kit = queue.getKit() != null ? queue.getKit().getName() : lang.getMessage("GENERAL.none"); lang.sendMessage(player, "QUEUE.found-opponent", "name", other.getName(), "kit", kit, "bet_amount", queue.getBet()); lang.sendMessage(other, "QUEUE.found-opponent", "name", player.getName(), "kit", kit, "bet_amount", queue.getBet()); duelManager.startMatch(player, other, setting, null, queue); break; } } if (queue.removeAll(remove) && !update) { update = true; } } if (update) { gui.calculatePages(); } }, 20L, 40L).getTaskId(); } @Override public void handleUnload() { plugin.cancelTask(queueTask); if (gui != null) { plugin.getGuiListener().removeGui(gui); } queues.clear(); } private void saveQueues() { final List data = new ArrayList<>(); for (final Queue queue : queues) { data.add(new QueueData(queue)); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, data); writer.flush(); } catch (IOException ex) { Log.error(this, ex.getMessage(), ex); } } @Nullable @Override public Queue get(@Nullable final Kit kit, final int bet) { return queues.stream().filter(queue -> Objects.equals(kit, queue.getKit()) && queue.getBet() == bet).findFirst().orElse(null); } @Nullable @Override public Queue get(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return queues.stream().filter(queue -> queue.isInQueue(player)).findFirst().orElse(null); } @Nullable public Queue randomQueue() { return !queues.isEmpty() ? queues.get(ThreadLocalRandom.current().nextInt(queues.size())) : null; } @Nullable @Override public Queue create(@Nullable final CommandSender source, @Nullable final Kit kit, final int bet) { final Queue queue = new Queue(plugin, kit, bet); if (queues.contains(queue)) { return null; } queues.add(queue); saveQueues(); final QueueCreateEvent event = new QueueCreateEvent(source, queue); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return queue; } @Nullable @Override public Queue create(@Nullable final Kit kit, final int bet) { return create(null, kit, bet); } @Nullable @Override public Queue remove(@Nullable final CommandSender source, @Nullable final Kit kit, final int bet) { return remove(source, get(kit, bet)); } @Nullable @Override public Queue remove(@Nullable final Kit kit, final int bet) { return remove(null, kit, bet); } @NotNull @Override public List getQueues() { return Collections.unmodifiableList(queues); } @Override public boolean isInQueue(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return queues.stream().anyMatch(queue -> queue.isInQueue(player)); } @Override public boolean addToQueue(@NotNull final Player player, @NotNull final DQueue queue) { Objects.requireNonNull(player, "player"); Objects.requireNonNull(queue, "queue"); return queue(player, (Queue) queue); } @Nullable @Override public DQueue removeFromQueue(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return remove(player); } public Queue remove(final CommandSender source, final Queue queue) { if (queue == null || !queues.remove(queue)) { return null; } saveQueues(); queue.getPlayers().forEach(entry -> lang.sendMessage(entry.getPlayer(), "QUEUE.remove")); queue.getPlayers().clear(); queue.setRemoved(true); final QueueRemoveEvent event = new QueueRemoveEvent(source, queue); Bukkit.getPluginManager().callEvent(event); gui.calculatePages(); return queue; } public boolean queue(final Player player, final Queue queue) { final Queue found = get(player); if (found != null) { if (found.equals(queue)) { queue.removePlayer(player); lang.sendMessage(player, "QUEUE.remove"); return false; } lang.sendMessage(player, "ERROR.queue.already-in"); return false; } if (spectateManager.isSpectating(player)) { lang.sendMessage(player, "ERROR.spectate.already-spectating.sender"); return false; } if (arenaManager.isInMatch(player)) { lang.sendMessage(player, "ERROR.duel.already-in-match.sender"); return false; } if (config.isRequiresClearedInventory() && InventoryUtil.hasItem(player)) { lang.sendMessage(player, "ERROR.duel.inventory-not-empty"); return false; } if (config.isPreventCreativeMode() && player.getGameMode() == GameMode.CREATIVE) { lang.sendMessage(player, "ERROR.duel.in-creative-mode"); return false; } if ((combatTagPlus != null && combatTagPlus.isTagged(player)) || (pvpManager != null && pvpManager.isTagged(player))) { lang.sendMessage(player, "ERROR.duel.is-tagged"); return false; } String duelzone = null; if (worldGuard != null && config.isDuelzoneEnabled() && (duelzone = worldGuard.findDuelZone(player)) == null) { lang.sendMessage(player, "ERROR.duel.not-in-duelzone", "regions", config.getDuelzones()); return false; } if (queue.getBet() > 0 && vault != null && !vault.has(queue.getBet(), player)) { lang.sendMessage(player, "ERROR.queue.not-enough-money", "bet_amount", queue.getBet()); return false; } final QueueJoinEvent event = new QueueJoinEvent(player, queue); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } queue.addPlayer(new QueueEntry(player, player.getLocation().clone(), duelzone)); final String kit = queue.getKit() != null ? queue.getKit().getName() : lang.getMessage("GENERAL.none"); lang.sendMessage(player, "QUEUE.add", "kit", kit, "bet_amount", queue.getBet()); return true; } public Queue remove(final Player player) { for (final Queue queue : queues) { if (queue.removePlayer(player)) { final QueueLeaveEvent event = new QueueLeaveEvent(player, queue); Bukkit.getPluginManager().callEvent(event); lang.sendMessage(player, "QUEUE.remove"); return queue; } } return null; } @EventHandler public void on(final PlayerQuitEvent event) { remove(event.getPlayer()); } @EventHandler(ignoreCancelled = true) public void on(final PlayerCommandPreprocessEvent event) { final String command = event.getMessage().substring(1).split(" ")[0].toLowerCase(); if (!isInQueue(event.getPlayer()) || !config.getQueueBlacklistedCommands().contains(command)) { return; } event.setCancelled(true); lang.sendMessage(event.getPlayer(), "QUEUE.prevent.command", "command", event.getMessage()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/queue/sign/QueueSignImpl.java ================================================ package me.realized.duels.queue.sign; import java.util.Objects; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import me.realized.duels.api.queue.sign.QueueSign; import me.realized.duels.queue.Queue; import me.realized.duels.util.StringUtil; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; public class QueueSignImpl implements QueueSign { @Getter private final Location location; @Getter private final String[] lines; @Getter private final Queue queue; @Getter @Setter(value = AccessLevel.PACKAGE) private boolean removed; private int lastInQueue; private long lastInMatch; public QueueSignImpl(final Location location, final String format, final Queue queue) { this.location = location; this.queue = queue; final String[] data = {"", "", "", ""}; if (format != null) { final String[] lines = format.split("\n"); System.arraycopy(lines, 0, data, 0, lines.length); } this.lines = data; final Block block = location.getBlock(); if (!(block.getState() instanceof Sign)) { return; } final Sign sign = (Sign) block.getState(); sign.setLine(0, replace(lines[0], 0, 0)); sign.setLine(1, replace(lines[1], 0, 0)); sign.setLine(2, replace(lines[2], 0, 0)); sign.setLine(3, replace(lines[3], 0, 0)); sign.update(); } private String replace(final String line, final int inQueue, final long inMatch) { return StringUtil.color(line.replace("%in_queue%", String.valueOf(inQueue)).replace("%in_match%", String.valueOf(inMatch))); } public void update() { final Block block = location.getBlock(); if (!(block.getState() instanceof Sign)) { return; } final Sign sign = (Sign) block.getState(); if (queue.isRemoved()) { sign.setType(Material.AIR); sign.update(); return; } final int inQueue = queue.getPlayers().size(); final long inMatch = queue.getPlayersInMatch(); if (lastInQueue == inQueue && lastInMatch == inMatch) { return; } this.lastInQueue = inQueue; this.lastInMatch = inMatch; sign.setLine(0, replace(lines[0], inQueue, inMatch)); sign.setLine(1, replace(lines[1], inQueue, inMatch)); sign.setLine(2, replace(lines[2], inQueue, inMatch)); sign.setLine(3, replace(lines[3], inQueue, inMatch)); sign.update(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final QueueSignImpl queueSign = (QueueSignImpl) o; return Objects.equals(queue, queueSign.getQueue()); } @Override public int hashCode() { return Objects.hash(queue); } @Override public String toString() { return StringUtil.parse(location); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/queue/sign/QueueSignManagerImpl.java ================================================ package me.realized.duels.queue.sign; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.event.queue.sign.QueueSignCreateEvent; import me.realized.duels.api.event.queue.sign.QueueSignRemoveEvent; import me.realized.duels.api.queue.sign.QueueSign; import me.realized.duels.api.queue.sign.QueueSignManager; import me.realized.duels.config.Lang; import me.realized.duels.data.QueueSignData; import me.realized.duels.queue.Queue; import me.realized.duels.queue.QueueManager; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.io.FileUtil; import me.realized.duels.util.json.JsonUtil; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class QueueSignManagerImpl implements Loadable, QueueSignManager, Listener { private static final String FILE_NAME = "signs.json"; private static final String SIGNS_LOADED = "Loaded %s queue sign(s)."; private final DuelsPlugin plugin; private final Lang lang; private final QueueManager queueManager; private final File file; private final Map signs = new HashMap<>(); private int updateTask; public QueueSignManagerImpl(final DuelsPlugin plugin) { this.plugin = plugin; this.lang = plugin.getLang(); this.queueManager = plugin.getQueueManager(); this.file = new File(plugin.getDataFolder(), FILE_NAME); Bukkit.getPluginManager().registerEvents(this, plugin); } @Override public void handleLoad() throws IOException { if (FileUtil.checkNonEmpty(file, true)) { try (final Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)) { final List data = JsonUtil.getObjectMapper().readValue(reader, new TypeReference>() {}); if (data != null) { data.forEach(queueSignData -> { final QueueSignImpl queueSign = queueSignData.toQueueSign(plugin); if (queueSign != null) { signs.put(queueSign.getLocation(), queueSign); } }); } } } Log.info(this, String.format(SIGNS_LOADED, signs.size())); this.updateTask = plugin.doSyncRepeat(() -> signs.entrySet().removeIf(entry -> { entry.getValue().update(); return entry.getValue().getQueue().isRemoved(); }), 20L, 20L).getTaskId(); } @Override public void handleUnload() { plugin.cancelTask(updateTask); signs.clear(); } private void saveQueueSigns() { final List data = new ArrayList<>(); for (final QueueSignImpl sign : signs.values()) { if (sign.getQueue().isRemoved()) { continue; } data.add(new QueueSignData(sign)); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { JsonUtil.getObjectWriter().writeValue(writer, data); writer.flush(); } catch (IOException ex) { Log.error(this, ex.getMessage(), ex); } } @Nullable @Override public QueueSignImpl get(@NotNull final Sign sign) { Objects.requireNonNull(sign, "sign"); return get(sign.getLocation()); } public QueueSignImpl get(final Location location) { return signs.get(location); } public boolean create(final Player creator, final Location location, final Queue queue) { if (get(location) != null) { return false; } final QueueSignImpl created; final String kitName = queue.getKit() != null ? queue.getKit().getName() : lang.getMessage("GENERAL.none"); signs.put(location, created = new QueueSignImpl(location, lang.getMessage("SIGN.format", "kit", kitName, "bet_amount", queue.getBet()), queue)); signs.values().stream().filter(sign -> sign.equals(created)).forEach(QueueSignImpl::update); saveQueueSigns(); final QueueSignCreateEvent event = new QueueSignCreateEvent(creator, created); Bukkit.getPluginManager().callEvent(event); return true; } public QueueSignImpl remove(final Player source, final Location location) { final QueueSignImpl queueSign = signs.remove(location); if (queueSign == null) { return null; } queueSign.setRemoved(true); saveQueueSigns(); final QueueSignRemoveEvent event = new QueueSignRemoveEvent(source, queueSign); Bukkit.getPluginManager().callEvent(event); return queueSign; } public Collection getSigns() { return signs.values(); } @NotNull @Override public List getQueueSigns() { return Lists.newArrayList(getSigns()); } @EventHandler public void on(final PlayerInteractEvent event) { final Block block; if (!event.hasBlock() || !((block = event.getClickedBlock()).getState() instanceof Sign)) { return; } final Player player = event.getPlayer(); final QueueSignImpl sign = get(block.getLocation()); if (sign == null || !queueManager.queue(player, sign.getQueue())) { return; } signs.values().stream().filter(queueSign -> queueSign.equals(sign)).forEach(QueueSignImpl::update); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void on(final BlockBreakEvent event) { final Block block = event.getBlock(); if (!(block.getState() instanceof Sign) || get(block.getLocation()) == null) { return; } final Player player = event.getPlayer(); if (!player.hasPermission(Permissions.ADMIN)) { lang.sendMessage(player, "ERROR.no-permission", "permission", Permissions.ADMIN); return; } lang.sendMessage(player, "ERROR.sign.cancel-break"); event.setCancelled(true); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/request/RequestImpl.java ================================================ package me.realized.duels.request; import java.util.UUID; import lombok.Getter; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.kit.Kit; import me.realized.duels.api.request.Request; import me.realized.duels.setting.Settings; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; public class RequestImpl implements Request { @Getter private final UUID sender; @Getter private final UUID target; @Getter private final Settings settings; @Getter private final long creation; RequestImpl(final Player sender, final Player target, final Settings setting) { this.sender = sender.getUniqueId(); this.target = target.getUniqueId(); this.settings = setting.lightCopy(); this.creation = System.currentTimeMillis(); } @Nullable @Override public Kit getKit() { return settings.getKit(); } @Nullable @Override public Arena getArena() { return settings.getArena(); } @Override public boolean canBetItems() { return settings.isItemBetting(); } @Override public int getBet() { return settings.getBet(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/request/RequestManager.java ================================================ package me.realized.duels.request; import java.util.HashMap; import java.util.Map; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.api.event.request.RequestSendEvent; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.setting.Settings; import me.realized.duels.util.Loadable; import me.realized.duels.util.TextBuilder; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent.Action; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; public class RequestManager implements Loadable, Listener { private final Config config; private final Lang lang; private final Map> requests = new HashMap<>(); public RequestManager(final DuelsPlugin plugin) { this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); Bukkit.getPluginManager().registerEvents(this, plugin); } @Override public void handleLoad() {} @Override public void handleUnload() { requests.clear(); } private Map get(final Player player, final boolean create) { Map cached = requests.get(player.getUniqueId()); if (cached == null && create) { requests.put(player.getUniqueId(), cached = new HashMap<>()); return cached; } return cached; } public void send(final Player sender, final Player target, final Settings settings) { final RequestImpl request = new RequestImpl(sender, target, settings); final RequestSendEvent event = new RequestSendEvent(sender, target, request); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } get(sender, true).put(target.getUniqueId(), request); final String kit = settings.getKit() != null ? settings.getKit().getName() : lang.getMessage("GENERAL.not-selected"); final String ownInventory = settings.isOwnInventory() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"); final String arena = settings.getArena() != null ? settings.getArena().getName() : lang.getMessage("GENERAL.random"); final int betAmount = settings.getBet(); final String itemBetting = settings.isItemBetting() ? lang.getMessage("GENERAL.enabled") : lang.getMessage("GENERAL.disabled"); lang.sendMessage(sender, "COMMAND.duel.request.send.sender", "name", target.getName(), "kit", kit, "own_inventory", ownInventory, "arena", arena, "bet_amount", betAmount, "item_betting", itemBetting); lang.sendMessage(target, "COMMAND.duel.request.send.receiver", "name", sender.getName(), "kit", kit, "own_inventory", ownInventory, "arena", arena, "bet_amount", betAmount, "item_betting", itemBetting); final String path = "COMMAND.duel.request.send.clickable-text."; TextBuilder .of(lang.getMessage(path + "info.text"), null, null, Action.SHOW_TEXT, lang.getMessage(path + "info.hover-text")) .add(lang.getMessage(path + "accept.text"), ClickEvent.Action.RUN_COMMAND, "/duel accept " + sender.getName(), Action.SHOW_TEXT, lang.getMessage(path + "accept.hover-text")) .add(lang.getMessage(path + "deny.text"), ClickEvent.Action.RUN_COMMAND, "/duel deny " + sender.getName(), Action.SHOW_TEXT, lang.getMessage(path + "deny.hover-text")) .send(target); TextBuilder.of(lang.getMessage(path + "extra.text"), null, null, Action.SHOW_TEXT, lang.getMessage(path + "extra.hover-text")).send(target); } public RequestImpl get(final Player sender, final Player target) { final Map cached = get(sender, false); if (cached == null) { return null; } final RequestImpl request = cached.get(target.getUniqueId()); if (request == null) { return null; } if (System.currentTimeMillis() - request.getCreation() >= config.getExpiration() * 1000L) { cached.remove(target.getUniqueId()); return null; } return request; } public boolean has(final Player sender, final Player target) { return get(sender, target) != null; } public RequestImpl remove(final Player sender, final Player target) { final Map cached = get(sender, false); if (cached == null) { return null; } final RequestImpl request = cached.remove(target.getUniqueId()); if (request == null) { return null; } if (System.currentTimeMillis() - request.getCreation() >= config.getExpiration() * 1000L) { cached.remove(target.getUniqueId()); return null; } return request; } @EventHandler public void on(final PlayerQuitEvent event) { requests.remove(event.getPlayer().getUniqueId()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/setting/CachedInfo.java ================================================ package me.realized.duels.setting; import lombok.Getter; import lombok.Setter; import org.bukkit.Location; public class CachedInfo { @Getter @Setter private Location location; @Getter @Setter private String duelzone; public CachedInfo(final Location location, final String duelzone) { this.location = location; this.duelzone = duelzone; } CachedInfo() { this(null, null); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/setting/Settings.java ================================================ package me.realized.duels.setting; import java.util.HashMap; import java.util.Map; import java.util.UUID; import lombok.Getter; import lombok.Setter; import me.realized.duels.DuelsPlugin; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.gui.settings.SettingsGui; import me.realized.duels.kit.KitImpl; import org.bukkit.Location; import org.bukkit.entity.Player; public class Settings { private final DuelsPlugin plugin; private final SettingsGui gui; @Getter private UUID target; @Getter private KitImpl kit; @Getter @Setter private ArenaImpl arena; @Getter @Setter private int bet; @Getter @Setter private boolean itemBetting; @Getter private boolean ownInventory; @Getter private Map cache = new HashMap<>(); public Settings(final DuelsPlugin plugin, final Player player) { this.plugin = plugin; this.gui = player != null ? plugin.getGuiListener().addGui(player, new SettingsGui(plugin)) : null; // If kits are disabled, then ownInventory is enabled by default. this.ownInventory = !plugin.getConfiguration().isKitSelectingEnabled(); } public Settings(final DuelsPlugin plugin) { this(plugin, null); } public void reset() { target = null; kit = null; arena = null; bet = 0; itemBetting = false; ownInventory = !plugin.getConfiguration().isKitSelectingEnabled(); } public void setTarget(final Player target) { if (this.target != null && !this.target.equals(target.getUniqueId())) { reset(); } this.target = target.getUniqueId(); } public void updateGui(final Player player) { if (gui != null) { gui.update(player); } } public void openGui(final Player player) { gui.open(player); } public void setBaseLoc(final Player player) { cache.computeIfAbsent(player.getUniqueId(), result -> new CachedInfo()).setLocation(player.getLocation().clone()); } public Location getBaseLoc(final Player player) { final CachedInfo info = cache.get(player.getUniqueId()); if (info == null) { return null; } return info.getLocation(); } public void setDuelzone(final Player player, final String duelzone) { cache.computeIfAbsent(player.getUniqueId(), result -> new CachedInfo()).setDuelzone(duelzone); } public String getDuelzone(final Player player) { final CachedInfo info = cache.get(player.getUniqueId()); if (info == null) { return null; } return info.getDuelzone(); } public void setKit(final KitImpl kit) { this.kit = kit; this.ownInventory = false; } public void setOwnInventory(final boolean ownInventory) { this.ownInventory = ownInventory; if (ownInventory) { this.kit = null; } } // Don't copy the gui since it won't be required to start a match public Settings lightCopy() { final Settings copy = new Settings(plugin); copy.target = target; copy.kit = kit; copy.arena = arena; copy.bet = bet; copy.itemBetting = itemBetting; copy.ownInventory = ownInventory; copy.cache = new HashMap<>(cache); return copy; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/setting/SettingsManager.java ================================================ package me.realized.duels.setting; import java.util.HashMap; import java.util.Map; import java.util.UUID; import me.realized.duels.DuelsPlugin; import me.realized.duels.util.Loadable; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; public class SettingsManager implements Loadable, Listener { private final DuelsPlugin plugin; private final Map cache = new HashMap<>(); public SettingsManager(final DuelsPlugin plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @Override public void handleLoad() {} @Override public void handleUnload() { cache.clear(); } // Only one Settings instance stays in memory while player is online; no need for manual removal of gui from GuiListener public Settings getSafely(final Player player) { return cache.computeIfAbsent(player.getUniqueId(), result -> new Settings(plugin, player)); } @EventHandler public void on(final PlayerQuitEvent event) { cache.remove(event.getPlayer().getUniqueId()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/shaded/bstats/Metrics.java ================================================ package me.realized.duels.shaded.bstats; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HttpsURLConnection; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicePriority; /** * bStats collects some data for plugin authors. *

* Check out https://bStats.org/ to learn more about bStats! */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Metrics { static { // 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', '.', 'b', 'u', 'k', 'k', 'i', 't'}); final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); // We want to make sure nobody just copy & pastes the example and use the wrong package names if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); } } } // The version of this bStats class public static final int B_STATS_VERSION = 1; // The url to which the data is sent private static final String URL = "https://bStats.org/submitData/bukkit"; // Is bStats enabled on this server? private boolean enabled; // Should failed requests be logged? private static boolean logFailedRequests; // Should the sent data be logged? private static boolean logSentData; // Should the response text be logged? private static boolean logResponseStatusText; // The uuid of the server private static String serverUUID; // The plugin private final Plugin plugin; // The plugin id private final int pluginId; // A list with all custom charts private final List charts = new ArrayList<>(); /** * Class constructor. * * @param plugin The plugin which stats should be submitted. * @param pluginId The id of the plugin. * It can be found at What is my plugin id? */ public Metrics(Plugin plugin, int pluginId) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null!"); } this.plugin = plugin; this.pluginId = pluginId; // Get the config file File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); File configFile = new File(bStatsFolder, "config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check if the config file exists if (!config.isSet("serverUuid")) { // Add default values config.addDefault("enabled", true); // Every server gets it's unique random id. config.addDefault("serverUuid", UUID.randomUUID().toString()); // Should failed request be logged? config.addDefault("logFailedRequests", false); // Should the sent data be logged? config.addDefault("logSentData", false); // Should the response text be logged? config.addDefault("logResponseStatusText", false); // Inform the server owners about bStats config.options().header( "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)" ).copyDefaults(true); try { config.save(configFile); } catch (IOException ignored) { } } // Load the data enabled = config.getBoolean("enabled", true); serverUUID = config.getString("serverUuid"); logFailedRequests = config.getBoolean("logFailedRequests", false); logSentData = config.getBoolean("logSentData", false); logResponseStatusText = config.getBoolean("logResponseStatusText", false); if (enabled) { boolean found = false; // Search for all other bStats Metrics classes to see if we are the first one for (Class service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; } catch (NoSuchFieldException ignored) { } } // Register our service Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); if (!found) { // We are the first! startSubmitting(); } } } /** * Checks if bStats is enabled. * * @return Whether bStats is enabled or not. */ public boolean isEnabled() { return enabled; } /** * Adds a custom chart. * * @param chart The chart to add. */ public void addCustomChart(CustomChart chart) { if (chart == null) { throw new IllegalArgumentException("Chart cannot be null!"); } charts.add(chart); } /** * Starts the Scheduler which submits our data every 30 minutes. */ private void startSubmitting() { final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!plugin.isEnabled()) { // Plugin was disabled timer.cancel(); return; } // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) Bukkit.getScheduler().runTask(plugin, () -> submitData()); } }, 1000 * 60 * 5, 1000 * 60 * 30); // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! // WARNING: Just don't do it! } /** * Gets the plugin specific data. * This method is called using Reflection. * * @return The plugin specific data. */ public JsonObject getPluginData() { JsonObject data = new JsonObject(); // NOTE: Modified to append '-' to pluginName as someone has registered 'Duels' already. String pluginName = plugin.getDescription().getName() + "-"; String pluginVersion = plugin.getDescription().getVersion(); data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("id", pluginId); // Append the id of the plugin data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin JsonArray customCharts = new JsonArray(); for (CustomChart customChart : charts) { // Add the data of the custom charts JsonObject chart = customChart.getRequestJsonObject(); if (chart == null) { // If the chart is null, we skip it continue; } customCharts.add(chart); } data.add("customCharts", customCharts); return data; } /** * Gets the server specific data. * * @return The server specific data. */ private JsonObject getServerData() { // Minecraft specific data int playerAmount; try { // Around MC 1.8 the return type was changed to a collection from an array, // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; } catch (Exception e) { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; String bukkitVersion = Bukkit.getVersion(); String bukkitName = Bukkit.getName(); // OS/Java specific data String javaVersion = System.getProperty("java.version"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String osVersion = System.getProperty("os.version"); int coreCount = Runtime.getRuntime().availableProcessors(); JsonObject data = new JsonObject(); data.addProperty("serverUUID", serverUUID); data.addProperty("playerAmount", playerAmount); data.addProperty("onlineMode", onlineMode); data.addProperty("bukkitVersion", bukkitVersion); data.addProperty("bukkitName", bukkitName); data.addProperty("javaVersion", javaVersion); data.addProperty("osName", osName); data.addProperty("osArch", osArch); data.addProperty("osVersion", osVersion); data.addProperty("coreCount", coreCount); return data; } /** * Collects the data and sends it afterwards. */ private void submitData() { final JsonObject data = getServerData(); JsonArray pluginData = new JsonArray(); // Search for all other bStats Metrics classes to get their plugin data for (Class service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { try { Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } else { // old bstats version compatibility try { Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); jsonStringGetter.setAccessible(true); String jsonString = (String) jsonStringGetter.invoke(plugin); JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); pluginData.add(object); } } catch (ClassNotFoundException e) { // minecraft version 1.14+ if (logFailedRequests) { this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); } } } } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } } catch (NoSuchFieldException ignored) { } } data.add("plugins", pluginData); // Create a new thread for the connection to the bStats server new Thread(() -> { try { // Send the data sendData(plugin, data); } catch (Exception e) { // Something went wrong! :( if (logFailedRequests) { plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); } } }).start(); } /** * Sends the data to the bStats server. * * @param plugin Any plugin. It's just used to get a logger instance. * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Plugin plugin, JsonObject data) throws Exception { if (data == null) { throw new IllegalArgumentException("Data cannot be null!"); } if (Bukkit.isPrimaryThread()) { throw new IllegalAccessException("This method must not be called from the main thread!"); } if (logSentData) { plugin.getLogger().info("Sending data to bStats: " + data); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data 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) { plugin.getLogger().info("Sent data to bStats and received response: " + builder); } } /** * Gzips the given String. * * @param str The string to gzip. * @return The gzipped String. * @throws IOException If the compression failed. */ 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(); } /** * Represents a custom chart. */ public static abstract class CustomChart { // The id of the chart final String chartId; /** * Class constructor. * * @param chartId The id of the chart. */ CustomChart(String chartId) { if (chartId == null || chartId.isEmpty()) { throw new IllegalArgumentException("ChartId cannot be null or empty!"); } this.chartId = chartId; } private JsonObject getRequestJsonObject() { JsonObject chart = new JsonObject(); chart.addProperty("chartId", chartId); try { JsonObject data = getChartData(); if (data == null) { // If the data is null we don't send the chart. return null; } chart.add("data", data); } catch (Throwable t) { if (logFailedRequests) { Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); } return null; } return chart; } protected abstract JsonObject getChartData() throws Exception; } /** * Represents a custom simple pie. */ public static 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 { JsonObject data = new JsonObject(); String value = callable.call(); if (value == null || value.isEmpty()) { // Null = skip the chart return null; } data.addProperty("value", value); return data; } } /** * Represents a custom advanced pie. */ public static 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 { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); 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) { continue; // Skip this invalid } allSkipped = false; values.addProperty(entry.getKey(), entry.getValue()); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom drilldown pie. */ public static 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 { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean reallyAllSkipped = true; for (Map.Entry> entryValues : map.entrySet()) { JsonObject value = new JsonObject(); boolean allSkipped = true; for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { value.addProperty(valueEntry.getKey(), valueEntry.getValue()); allSkipped = false; } if (!allSkipped) { reallyAllSkipped = false; values.add(entryValues.getKey(), value); } } if (reallyAllSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom single line chart. */ public static 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 { JsonObject data = new JsonObject(); int value = callable.call(); if (value == 0) { // Null = skip the chart return null; } data.addProperty("value", value); return data; } } /** * Represents a custom multi line chart. */ public static 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 { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); 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) { continue; // Skip this invalid } allSkipped = false; values.addProperty(entry.getKey(), entry.getValue()); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom simple bar chart. */ public static 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 { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } for (Map.Entry entry : map.entrySet()) { JsonArray categoryValues = new JsonArray(); categoryValues.add(new JsonPrimitive(entry.getValue())); values.add(entry.getKey(), categoryValues); } data.add("values", values); return data; } } /** * Represents a custom advanced bar chart. */ public static 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 { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); 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) { continue; // Skip this invalid } allSkipped = false; JsonArray categoryValues = new JsonArray(); for (int categoryValue : entry.getValue()) { categoryValues.add(new JsonPrimitive(categoryValue)); } values.add(entry.getKey(), categoryValues); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/spectate/SpectateManagerImpl.java ================================================ package me.realized.duels.spectate; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; import me.realized.duels.DuelsPlugin; import me.realized.duels.Permissions; import me.realized.duels.api.arena.Arena; import me.realized.duels.api.event.spectate.SpectateEndEvent; import me.realized.duels.api.event.spectate.SpectateStartEvent; import me.realized.duels.api.spectate.SpectateManager; import me.realized.duels.api.spectate.Spectator; import me.realized.duels.arena.ArenaImpl; import me.realized.duels.arena.ArenaManagerImpl; import me.realized.duels.arena.MatchImpl; import me.realized.duels.config.Config; import me.realized.duels.config.Lang; import me.realized.duels.hook.hooks.EssentialsHook; import me.realized.duels.hook.hooks.MyPetHook; import me.realized.duels.player.PlayerInfo; import me.realized.duels.player.PlayerInfoManager; import me.realized.duels.teleport.Teleport; import me.realized.duels.util.BlockUtil; import me.realized.duels.util.Loadable; import me.realized.duels.util.PlayerUtil; import me.realized.duels.util.compat.CompatUtil; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SpectateManagerImpl implements Loadable, SpectateManager { private final DuelsPlugin plugin; private final Config config; private final Lang lang; private final ArenaManagerImpl arenaManager; private final PlayerInfoManager playerManager; // Map UUID to a spectator private final Map spectators = new HashMap<>(); // Map arena to a collection of spectators private final Multimap arenas = HashMultimap.create(); private Teleport teleport; private MyPetHook myPet; private EssentialsHook essentials; public SpectateManagerImpl(final DuelsPlugin plugin) { this.plugin = plugin; this.config = plugin.getConfiguration(); this.lang = plugin.getLang(); this.arenaManager = plugin.getArenaManager(); this.playerManager = plugin.getPlayerManager(); Bukkit.getPluginManager().registerEvents(new SpectateListener(), plugin); } @Override public void handleLoad() { // Late-init since SpectateManager is loaded before below variables are loaded this.teleport = plugin.getTeleport(); this.myPet = plugin.getHookManager().getHook(MyPetHook.class); this.essentials = plugin.getHookManager().getHook(EssentialsHook.class); } @Override public void handleUnload() { spectators.clear(); } @Nullable @Override public SpectatorImpl get(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return spectators.get(player.getUniqueId()); } @Override public boolean isSpectating(@NotNull final Player player) { Objects.requireNonNull(player, "player"); return get(player) != null; } @NotNull @Override public Result startSpectating(@NotNull final Player player, @NotNull final Player target) { Objects.requireNonNull(player, "player"); Objects.requireNonNull(target, "target"); if (isSpectating(player)) { return Result.ALREADY_SPECTATING; } if (plugin.getQueueManager().isInQueue(player)) { return Result.IN_QUEUE; } if (arenaManager.isInMatch(player)) { return Result.IN_MATCH; } final ArenaImpl arena = arenaManager.get(target); if (arena == null) { return Result.TARGET_NOT_IN_MATCH; } final SpectatorImpl spectator = new SpectatorImpl(player, target, arena); final SpectateStartEvent event = new SpectateStartEvent(player, spectator); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return Result.EVENT_CANCELLED; } final MatchImpl match = arena.getMatch(); // Hide from players in match if (match != null && !essentials.isVanished(player)) { match.getAllPlayers() .stream() .filter(arenaPlayer -> arenaPlayer.isOnline() && arenaPlayer.canSee(player)) .forEach(arenaPlayer -> { if (CompatUtil.hasHidePlayer()) { arenaPlayer.hidePlayer(plugin, player); } else { arenaPlayer.hidePlayer(player); } }); } // Remove pet before teleport if (myPet != null) { myPet.removePet(player); } // Cache current player state to return to after spectating is over playerManager.create(player); PlayerUtil.reset(player); // Teleport before putting in map to prevent teleport being cancelled teleport.tryTeleport(player, target.getLocation().clone().add(0, 2, 0)); spectators.put(player.getUniqueId(), spectator); arenas.put(arena, spectator); if (!config.isSpecUseSpectatorGamemode()) { player.setGameMode(GameMode.ADVENTURE); player.setAllowFlight(true); player.setFlying(true); } else { player.setGameMode(GameMode.SPECTATOR); } if (CompatUtil.hasSetCollidable()) { player.setCollidable(false); } else { player.spigot().setCollidesWithEntities(false); } if (config.isSpecAddInvisibilityEffect()) { player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false, false)); } // Broadcast to the arena that player has begun spectating if player does not have the SPEC_ANON permission. if (!player.hasPermission(Permissions.SPEC_ANON)) { arena.getMatch().getAllPlayers().forEach(matchPlayer -> lang.sendMessage(matchPlayer, "SPECTATE.arena-broadcast", "name", player.getName())); } return Result.SUCCESS; } /** * Puts player out of spectator mode. * * @param player Player to put out of spectator mode * @param spectator {@link SpectatorImpl} instance associated to this player */ public void stopSpectating(final Player player, final SpectatorImpl spectator) { spectators.remove(player.getUniqueId()); arenas.remove(spectator.getArena(), spectator); player.setGameMode(GameMode.SURVIVAL); player.setFlying(false); player.setAllowFlight(false); PlayerUtil.reset(player); if (CompatUtil.hasSetCollidable()) { player.setCollidable(true); } else { player.spigot().setCollidesWithEntities(true); } final PlayerInfo info = playerManager.remove(player); if (info != null) { teleport.tryTeleport(player, info.getLocation()); info.restore(player); } else { teleport.tryTeleport(player, playerManager.getLobby()); } final MatchImpl match = spectator.getArena().getMatch(); // Show to players in match if (match != null && !essentials.isVanished(player)) { match.getAllPlayers() .stream() .filter(Player::isOnline) .forEach(arenaPlayer -> { if (CompatUtil.hasHidePlayer()) { arenaPlayer.showPlayer(plugin, player); } else { arenaPlayer.showPlayer(player); } }); } final SpectateEndEvent event = new SpectateEndEvent(player, spectator); Bukkit.getPluginManager().callEvent(event); } /** * Puts player out of spectator mode. * * @see #stopSpectating(Player, SpectatorImpl) */ @Override public void stopSpectating(@NotNull final Player player) { Objects.requireNonNull(player, "player"); stopSpectating(player, get(player)); } /** * Puts all spectators of the given {@link ArenaImpl} out of spectator mode. * * @param arena {@link ArenaImpl} to end spectating */ public void stopSpectating(final ArenaImpl arena) { final Collection spectators = arenas.asMap().remove(arena); if (spectators == null || spectators.isEmpty()) { return; } spectators.forEach(spectator -> { final Player player = Bukkit.getPlayer(spectator.getUuid()); if (player == null) { return; } stopSpectating(player, spectator); lang.sendMessage(player, "SPECTATE.match-end"); }); } @NotNull @Override public List getSpectators(@NotNull final Arena arena) { Objects.requireNonNull(arena, "arena"); return Collections.unmodifiableList(Lists.newArrayList(getSpectatorsImpl(arena))); } public Collection getSpectatorsImpl(final Arena arena) { return arenas.asMap().getOrDefault(arena, Collections.emptyList()); } public Collection getAllSpectators() { return spectators.values() .stream() .map(spectator -> Bukkit.getPlayer(spectator.getUuid())) .collect(Collectors.toList()); } private class SpectateListener implements Listener { @EventHandler public void on(final PlayerQuitEvent event) { final Player player = event.getPlayer(); final SpectatorImpl spectator = get(player); if (spectator == null) { return; } stopSpectating(player, spectator); } @EventHandler(ignoreCancelled = true) public void on(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); if (!isSpectating(player)) { return; } final String command = event.getMessage().substring(1).split(" ")[0].toLowerCase(); if (command.equalsIgnoreCase("spectate") || command.equalsIgnoreCase("spec") || config.getSpecWhitelistedCommands().contains(command)) { return; } event.setCancelled(true); lang.sendMessage(player, "SPECTATE.prevent.command", "command", event.getMessage()); } @EventHandler(ignoreCancelled = true) public void on(final PlayerTeleportEvent event) { final Player player = event.getPlayer(); final SpectatorImpl spectator = get(player); if (spectator == null) { return; } event.setCancelled(true); lang.sendMessage(player, "SPECTATE.prevent.teleportation"); } @EventHandler(ignoreCancelled = true) public void on(final PlayerInteractEvent event) { if (!isSpectating(event.getPlayer())) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final PlayerPickupItemEvent event) { if (!isSpectating(event.getPlayer())) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final EntityDamageByEntityEvent event) { final Player player; if (event.getDamager() instanceof Player) { player = (Player) event.getDamager(); } else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Player) { player = (Player) ((Projectile) event.getDamager()).getShooter(); } else { return; } if (!isSpectating(player)) { return; } event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(final EntityDamageEvent event) { if (!(event.getEntity() instanceof Player) || !isSpectating((Player) event.getEntity())) { return; } event.setCancelled(true); } // Prevents spectators (in adventure mode) blocking players from placing blocks. @EventHandler public void on(final BlockCanBuildEvent event) { if (!CompatUtil.hasGetPlayer() || config.isSpecUseSpectatorGamemode()) { return; } final Player player = event.getPlayer(); if (player == null || BlockUtil.near(player, event.getBlock(), 0, 2)) { return; } final ArenaImpl arena = arenaManager.get(player); if (arena == null) { return; } for (final SpectatorImpl spectator : getSpectatorsImpl(arena)) { final Player specPlayer = spectator.getPlayer(); if (specPlayer == null) { continue; } if (BlockUtil.near(specPlayer, event.getBlock(), 1, 2)) { event.setBuildable(true); break; } } } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/spectate/SpectatorImpl.java ================================================ package me.realized.duels.spectate; import java.util.Objects; import java.util.UUID; import lombok.Getter; import me.realized.duels.api.spectate.Spectator; import me.realized.duels.arena.ArenaImpl; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; public class SpectatorImpl implements Spectator { @Getter private final UUID uuid; @Getter private final UUID targetUuid; @Getter private final String targetName; @Getter private final ArenaImpl arena; SpectatorImpl(final Player owner, final Player target, final ArenaImpl arena) { this.uuid = owner.getUniqueId(); this.targetUuid = target.getUniqueId(); this.targetName = target.getName(); this.arena = arena; } @Nullable @Override public Player getPlayer() { return Bukkit.getPlayer(uuid); } @Nullable @Override public Player getTarget() { return Bukkit.getPlayer(targetUuid); } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final SpectatorImpl spectator = (SpectatorImpl) other; return Objects.equals(uuid, spectator.uuid); } @Override public int hashCode() { return Objects.hash(uuid); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/teleport/Teleport.java ================================================ package me.realized.duels.teleport; import me.realized.duels.DuelsPlugin; import me.realized.duels.hook.hooks.EssentialsHook; import me.realized.duels.util.Loadable; import me.realized.duels.util.Log; import me.realized.duels.util.metadata.MetadataUtil; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; /** * Handles force teleporting of players. */ public final class Teleport implements Loadable, Listener { public static final String METADATA_KEY = "Duels-Teleport"; private final DuelsPlugin plugin; private EssentialsHook essentials; public Teleport(final DuelsPlugin plugin) { this.plugin = plugin; } @Override public void handleLoad() { this.essentials = plugin.getHookManager().getHook(EssentialsHook.class); // Late-register the listener to override previously registered listeners plugin.doSyncAfter(() -> plugin.registerListener(this), 1L); } @Override public void handleUnload() {} /** * Attempts to force-teleport a player by storing a metadata value in the player before teleportation * and uncancelling the teleport by the player in a MONITOR-priority listener if cancelled by other plugins. * * @param player Player to force-teleport to a location * @param location Location to force-teleport the player */ public void tryTeleport(final Player player, final Location location) { if (location == null || location.getWorld() == null) { Log.warn(this, "Could not teleport " + player.getName() + "! Location is null"); return; } if (essentials != null) { essentials.setBackLocation(player, location); } MetadataUtil.put(plugin, player, METADATA_KEY, location.clone()); if (!player.teleport(location)) { Log.warn(this, "Could not teleport " + player.getName() + "! Player is dead or is vehicle"); } } @EventHandler(priority = EventPriority.MONITOR) public void on(final PlayerTeleportEvent event) { final Player player = event.getPlayer(); final Object value = MetadataUtil.removeAndGet(plugin, player, METADATA_KEY); // Only handle the case where teleport is cancelled and player has force teleport metadata value if (!event.isCancelled() || value == null) { return; } event.setCancelled(false); event.setTo((Location) value); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/BlockUtil.java ================================================ package me.realized.duels.util; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.util.BlockIterator; public final class BlockUtil { private BlockUtil() {} public static T getTargetBlock(final Player player, final Class type, final int range) { final BlockIterator iterator = new BlockIterator(player, range); while (iterator.hasNext()) { final Block block = iterator.next(); if (type.isInstance(block.getState())) { return type.cast(block.getState()); } } return null; } public static boolean near(final Player player, final Block block, final int hDiff, final int vDiff) { int pX = player.getLocation().getBlockX(); int pY = player.getLocation().getBlockY(); int pZ = player.getLocation().getBlockZ(); int bX = block.getLocation().getBlockX(); int bY = block.getLocation().getBlockY(); int bZ = block.getLocation().getBlockZ(); return Math.abs(pX - bX) <= hDiff && Math.abs(pY - bY) <= vDiff && Math.abs(pZ - bZ) <= hDiff; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/DateUtil.java ================================================ package me.realized.duels.util; import java.text.SimpleDateFormat; import java.util.Date; public final class DateUtil { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); private DateUtil() {} public static String formatDate(final Date date) { return DATE_FORMAT.format(date); } public static String formatDatetime(final long millis) { return TIMESTAMP_FORMAT.format(millis); } public static String format(long seconds) { if (seconds <= 0) { return "updating..."; } long years = seconds / 31556952; seconds -= years * 31556952; long months = seconds / 2592000; seconds -= months * 2592000; long weeks = seconds / 604800; seconds -= weeks * 604800; long days = seconds / 86400; seconds -= days * 86400; long hours = seconds / 3600; seconds -= hours * 3600; long minutes = seconds / 60; seconds -= minutes * 60; StringBuilder sb = new StringBuilder(); if (years > 0) { sb.append(years).append("yr"); } if (months > 0) { sb.append(months).append("mo"); } if (weeks > 0) { sb.append(weeks).append("w"); } if (days > 0) { sb.append(days).append("d"); } if (hours > 0) { sb.append(hours).append("h"); } if (minutes > 0) { sb.append(minutes).append("m"); } if (seconds > 0) { sb.append(seconds).append("s"); } return sb.toString(); } public static String formatMilliseconds(long ms) { if (ms < 1000) { return "0 second"; } long seconds = ms / 1000 + (ms % 1000 > 0 ? 1 : 0); long years = seconds / 31556952; seconds -= years * 31556952; long months = seconds / 2592000; seconds -= months * 2592000; long weeks = seconds / 604800; seconds -= weeks * 604800; long days = seconds / 86400; seconds -= days * 86400; long hours = seconds / 3600; seconds -= hours * 3600; long minutes = seconds / 60; seconds -= minutes * 60; StringBuilder builder = new StringBuilder(); if (years > 0) { builder.append(years).append(years > 1 ? " years" : " year"); } if (months > 0) { if (years > 0) { builder.append(" "); } builder.append(months).append(months > 1 ? " months" : " month"); } if (weeks > 0) { if (years + months > 0) { builder.append(" "); } builder.append(weeks).append(weeks > 1 ? " weeks" : " week"); } if (days > 0) { if (years + months + weeks > 0) { builder.append(" "); } builder.append(days).append(days > 1 ? " days" : " day"); } if (hours > 0) { if (years + months + weeks + days > 0) { builder.append(" "); } builder.append(hours).append(hours > 1 ? " hours" : " hour"); } if (minutes > 0) { if (years + months + weeks + days + hours > 0) { builder.append(" "); } builder.append(minutes).append(minutes > 1 ? " minutes" : " minute"); } if (seconds > 0) { if (years + months + weeks + days + hours + minutes > 0) { builder.append(" "); } builder.append(seconds).append(seconds > 1 ? " seconds" : " second"); } return builder.toString(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/EnumUtil.java ================================================ package me.realized.duels.util; import java.util.Arrays; public final class EnumUtil { private EnumUtil() {} public static > E getByName(final String name, Class clazz) { return clazz.cast(Arrays.stream(clazz.getEnumConstants()).filter(type -> type.name().equalsIgnoreCase(name)).findFirst().orElse(null)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/EventUtil.java ================================================ package me.realized.duels.util; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityDamageByEntityEvent; public final class EventUtil { public static Player getDamager(final EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Player) { return (Player) event.getDamager(); } else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Player) { return (Player) ((Projectile) event.getDamager()).getShooter(); } return null; } private EventUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/Loadable.java ================================================ package me.realized.duels.util; public interface Loadable { void handleLoad() throws Exception; void handleUnload() throws Exception; } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/Log.java ================================================ package me.realized.duels.util; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; public final class Log { private static final String PLUGIN_WARN = "[%s] &c%s"; private static final String PLUGIN_ERROR = "[%s] &4&l%s"; private static final List sources = new ArrayList<>(); private Log() {} public static void addSource(final LogSource source) { sources.add(source); } public static void clearSources() { sources.clear(); } public static void info(final String s) { for (final LogSource source : sources) { source.log(Level.INFO, s); } } public static void info(final Loadable loadable, final String s) { for (final LogSource source : sources) { source.log(Level.INFO, loadable.getClass().getSimpleName() + ": " + s); } } public static void warn(final String s) { for (final LogSource source : sources) { if (source instanceof Plugin) { Bukkit.getConsoleSender().sendMessage(StringUtil.color(String.format(PLUGIN_WARN, ((Plugin) source).getName(), s))); } else { source.log(Level.WARNING, s); } } } public static void warn(final Loadable loadable, final String s) { warn(loadable.getClass().getSimpleName() + ": " + s); } public static void error(final String s, final Throwable thrown) { for (final LogSource source : sources) { if (source instanceof Plugin) { Bukkit.getConsoleSender().sendMessage(StringUtil.color(String.format(PLUGIN_ERROR, ((Plugin) source).getName(), s))); } else if (thrown != null) { source.log(Level.SEVERE, s, thrown); } else { source.log(Level.SEVERE, s); } } } public static void error(final String s) { error(s, null); } public static void error(final Loadable loadable, final String s, final Throwable thrown) { error(loadable.getClass().getSimpleName() + ": " + s, thrown); } public static void error(final Loadable loadable, final String s) { error(loadable, s, null); } public interface LogSource { void log(final Level level, final String s); void log(final Level level, final String s, final Throwable thrown); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/NumberUtil.java ================================================ package me.realized.duels.util; import java.util.OptionalInt; public final class NumberUtil { /** * Copy of {@link Integer#parseInt(String)} (String)} but returns an empty {@link OptionalInt} instead of throwing a {@link NumberFormatException}. * * @param s String to parse. * @return {@link OptionalInt} instance with parsed value inside or empty if string is invalid. */ public static OptionalInt parseInt(final String s) { if (s == null) { return OptionalInt.empty(); } int result = 0; boolean negative = false; int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; int multmin; int digit; if (len > 0) { char firstChar = s.charAt(0); if (firstChar < '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') { return OptionalInt.empty(); } if (len == 1) { // Cannot have lone "+" or "-" return OptionalInt.empty(); } i++; } multmin = limit / 10; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.charAt(i++), 10); if (digit < 0) { return OptionalInt.empty(); } if (result < multmin) { return OptionalInt.empty(); } result *= 10; if (result < limit + digit) { return OptionalInt.empty(); } result -= digit; } } else { return OptionalInt.empty(); } return OptionalInt.of(negative ? result : -result); } public static int getChange(final int k, final int winnerRating, final int loserRating) { final double wr = r(winnerRating); final double lr = r(loserRating); return (int) Math.floor(k * (1 - (wr / (wr + lr)))); } private static double r(final int rating) { return Math.pow(10.0, rating / 400.0); } public static boolean isLower(String version, String otherVersion) { version = version.replace("-SNAPSHOT", "").replace(".", ""); otherVersion = otherVersion.replace("-SNAPSHOT", "").replace(".", ""); return NumberUtil.parseInt(version).orElse(0) < NumberUtil.parseInt(otherVersion).orElse(0); } private NumberUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/PlayerUtil.java ================================================ package me.realized.duels.util; import me.realized.duels.util.compat.CompatUtil; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public final class PlayerUtil { private static final double DEFAULT_MAX_HEALTH = 20.0D; private static final float DEFAULT_EXHAUSTION = 0.0F; private static final float DEFAULT_SATURATION = 5.0F; private static final int DEFAULT_MAX_FOOD_LEVEL = 20; public static double getMaxHealth(final Player player) { if (CompatUtil.isPre1_9()) { return player.getMaxHealth(); } else { final AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); if (attribute == null) { return DEFAULT_MAX_HEALTH; } return attribute.getValue(); } } private static void setMaxHealth(final Player player) { player.setHealth(getMaxHealth(player)); } public static void reset(final Player player) { player.setFireTicks(0); player.getActivePotionEffects().forEach(effect -> player.removePotionEffect(effect.getType())); setMaxHealth(player); player.setExhaustion(DEFAULT_EXHAUSTION); player.setSaturation(DEFAULT_SATURATION); player.setFoodLevel(DEFAULT_MAX_FOOD_LEVEL); player.setItemOnCursor(null); final Inventory top = player.getOpenInventory().getTopInventory(); if (top.getType() == InventoryType.CRAFTING) { top.clear(); } player.getInventory().setArmorContents(new ItemStack[4]); player.getInventory().clear(); player.updateInventory(); } private PlayerUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/Reloadable.java ================================================ package me.realized.duels.util; public interface Reloadable {} ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/StringUtil.java ================================================ package me.realized.duels.util; import java.util.Collection; import java.util.List; import java.util.TreeMap; import java.util.regex.Pattern; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.ChatColor; import org.bukkit.Location; public final class StringUtil { private static final Pattern ALPHANUMERIC = Pattern.compile("^[a-zA-Z0-9_]+$"); private static final TreeMap ROMAN_NUMERALS = new TreeMap<>(); private static final boolean COMMONS_LANG3; static { ROMAN_NUMERALS.put(1000, "M"); ROMAN_NUMERALS.put(900, "CM"); ROMAN_NUMERALS.put(500, "D"); ROMAN_NUMERALS.put(400, "CD"); ROMAN_NUMERALS.put(100, "C"); ROMAN_NUMERALS.put(90, "XC"); ROMAN_NUMERALS.put(50, "L"); ROMAN_NUMERALS.put(40, "XL"); ROMAN_NUMERALS.put(10, "X"); ROMAN_NUMERALS.put(9, "IX"); ROMAN_NUMERALS.put(5, "V"); ROMAN_NUMERALS.put(4, "IV"); ROMAN_NUMERALS.put(1, "I"); COMMONS_LANG3 = ReflectionUtil.getClassUnsafe(" org.apache.commons.lang3.StringUtils") != null; } private StringUtil() {} // Source: https://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java public static String toRoman(final int number) { if (number <= 0) { return String.valueOf(number); } int key = ROMAN_NUMERALS.floorKey(number); if (number == key) { return ROMAN_NUMERALS.get(number); } return ROMAN_NUMERALS.get(key) + toRoman(number - key); } public static String fromList(final List list) { StringBuilder builder = new StringBuilder(); if (list != null && !list.isEmpty()) { for (int i = 0; i < list.size(); i++) { builder.append(list.get(i).toString()).append(i + 1 != list.size() ? "\n" : ""); } } return builder.toString(); } public static String parse(final Location location) { return "(" + location.getBlockX() + ", " + location.getBlockY() + ", " + location.getBlockZ() + ")"; } public static String color(final String input) { return ChatColor.translateAlternateColorCodes('&', input); } public static List color(final List input) { input.replaceAll(s -> s = color(s)); return input; } public static boolean isAlphanumeric(final String input) { return ALPHANUMERIC.matcher(input.replace(" ", "")).matches(); } // In some versions of spigot, commons-lang3 is not available public static String join(final Object[] array, final String separator, final int startIndex, final int endIndex) { if (COMMONS_LANG3) { return org.apache.commons.lang3.StringUtils.join(array, separator, startIndex, endIndex); } else { return org.apache.commons.lang.StringUtils.join(array, separator, startIndex, endIndex); } } public static String join(final Collection collection, final String separator) { if (COMMONS_LANG3) { return org.apache.commons.lang3.StringUtils.join(collection, separator); } else { return org.apache.commons.lang.StringUtils.join(collection, separator); } } public static String capitalize(final String s) { if (COMMONS_LANG3) { return org.apache.commons.lang3.StringUtils.capitalize(s); } else { return org.apache.commons.lang.StringUtils.capitalize(s); } } public static boolean containsIgnoreCase(final String str, final String searchStr) { if (COMMONS_LANG3) { return org.apache.commons.lang3.StringUtils.containsIgnoreCase(str, searchStr); } else { return org.apache.commons.lang.StringUtils.containsIgnoreCase(str, searchStr); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/TextBuilder.java ================================================ package me.realized.duels.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.entity.Player; public final class TextBuilder { private final List list = new ArrayList<>(); private TextBuilder(final String base, final ClickEvent.Action clickAction, final String clickValue, final HoverEvent.Action hoverAction, final String hoverValue ) { if (base == null) { return; } Arrays.stream(TextComponent.fromLegacyText(base)).forEach(component -> { if (clickValue != null) { component.setClickEvent(new ClickEvent(clickAction, clickValue)); } if (hoverValue != null) { component.setHoverEvent(new HoverEvent(hoverAction, TextComponent.fromLegacyText(hoverValue))); } list.add(component); }); } public static TextBuilder of(final String base, final ClickEvent.Action clickAction, final String clickValue, final HoverEvent.Action hoverAction, final String hoverValue ) { return new TextBuilder(base, clickAction, clickValue, hoverAction, hoverValue); } public static TextBuilder of(final String base) { return of(base, null, null, null, null); } public TextBuilder add(final String text) { if (text == null) { return this; } list.addAll(Arrays.asList(TextComponent.fromLegacyText(text))); return this; } public TextBuilder add(final String text, final ClickEvent.Action action, final String value) { if (text == null || value == null) { return this; } Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> { component.setClickEvent(new ClickEvent(action, value)); list.add(component); }); return this; } public TextBuilder add(final String text, final HoverEvent.Action action, final String value) { if (text == null || value == null) { return this; } Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> { component.setHoverEvent(new HoverEvent(action, TextComponent.fromLegacyText(value))); list.add(component); }); return this; } public TextBuilder add(final String text, final ClickEvent.Action clickAction, final String clickValue, final HoverEvent.Action hoverAction, final String hoverValue ) { if (text == null) { return this; } Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> { if (clickValue != null) { component.setClickEvent(new ClickEvent(clickAction, clickValue)); } if (hoverValue != null) { component.setHoverEvent(new HoverEvent(hoverAction, TextComponent.fromLegacyText(hoverValue))); } list.add(component); }); return this; } public TextBuilder setClickEvent(final ClickEvent.Action action, final String value) { if (value == null) { return this; } list.forEach(component -> component.setClickEvent(new ClickEvent(action, value))); return this; } public TextBuilder setHoverEvent(final HoverEvent.Action action, final String value) { if (value == null) { return this; } list.forEach(component -> component.setHoverEvent(new HoverEvent(action, TextComponent.fromLegacyText(value)))); return this; } public void send(final Collection players) { final BaseComponent[] message = list.toArray(new BaseComponent[0]); players.forEach(player -> { if (player.isOnline()) { player.spigot().sendMessage(message); } }); } public void send(final Player... players) { send(Arrays.asList(players)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/UUIDUtil.java ================================================ package me.realized.duels.util; import java.util.UUID; import java.util.regex.Pattern; public final class UUIDUtil { private static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"); private UUIDUtil() {} public static UUID parseUUID(final String s) { if (s == null || !UUID_PATTERN.matcher(s).matches()) { return null; } return UUID.fromString(s); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/UpdateChecker.java ================================================ package me.realized.duels.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.function.BiConsumer; import org.bukkit.plugin.Plugin; public final class UpdateChecker { private static final String API_URL = "https://api.spigotmc.org/legacy/update.php?resource=%s"; private final Plugin plugin; private final int id; public UpdateChecker(final Plugin plugin, final int id) { this.plugin = plugin; this.id = id; } public void check(final BiConsumer callback) { final String currentVersion = plugin.getDescription().getVersion(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(String.format(API_URL, id)).openStream()))) { final String latestVersion = reader.readLine(); if (latestVersion == null) { return; } final boolean updateAvailable = NumberUtil.isLower(currentVersion, latestVersion); callback.accept(updateAvailable, updateAvailable ? latestVersion : currentVersion); } catch (IOException ignored) {} }); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/collection/StreamUtil.java ================================================ package me.realized.duels.util.collection; import java.util.Iterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class StreamUtil { public static Stream asStream(final Iterable iterable) { return asStream(iterable.spliterator()); } public static Stream asStream(final Iterator iterator) { return asStream(Spliterators.spliteratorUnknownSize(iterator, 0)); } public static Stream asStream(final Spliterator spliterator) { return StreamSupport.stream(spliterator, false); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/command/AbstractCommand.java ================================================ package me.realized.duels.util.command; import com.google.common.collect.Lists; import java.text.MessageFormat; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.Getter; import me.realized.duels.api.command.SubCommand; import me.realized.duels.util.StringUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public abstract class AbstractCommand

implements TabCompleter { protected final P plugin; @Getter private final String name; @Getter private final String usage; @Getter private final String description; @Getter private final String permission; @Getter private final boolean playerOnly; @Getter private final int length; @Getter private final List aliases; private Map> children; protected AbstractCommand(final P plugin, final String name, final String usage, final String description, final String permission, final int length, final boolean playerOnly, final String... aliases) { this.plugin = plugin; this.name = name; this.usage = usage; this.description = description; this.permission = permission; this.length = length; this.playerOnly = playerOnly; final List names = Lists.newArrayList(aliases); names.add(name); this.aliases = Collections.unmodifiableList(names); } protected AbstractCommand(final P plugin, final SubCommand sub) { this(plugin, sub.getName(), sub.getUsage(), sub.getDescription(), sub.getPermission(), sub.getLength(), sub.isPlayerOnly(), sub.getAliases()); } @SafeVarargs public final void child(final AbstractCommand

... commands) { if (commands == null || commands.length == 0) { return; } if (children == null) { children = new HashMap<>(); } for (final AbstractCommand

child : commands) { for (String alias : child.getAliases()) { alias = alias.toLowerCase(); if (children.containsKey(alias)) { continue; } children.put(alias, child); } } } public boolean isChild(final String name) { return children != null && children.get(name.toLowerCase()) != null; } private PluginCommand getCommand() { final PluginCommand pluginCommand = plugin.getCommand(name); if (pluginCommand == null) { throw new IllegalArgumentException("Command is not registered in plugin.yml"); } return pluginCommand; } public final void register() { final PluginCommand pluginCommand = getCommand(); pluginCommand.setExecutor((sender, command, label, args) -> { if (isPlayerOnly() && !(sender instanceof Player)) { handleMessage(sender, MessageType.PLAYER_ONLY); return true; } if (permission != null && !sender.hasPermission(getPermission())) { handleMessage(sender, MessageType.NO_PERMISSION, permission); return true; } if (executeFirst(sender, label, args)) { return true; } if (args.length > 0 && children != null) { final AbstractCommand

child = children.get(args[0].toLowerCase()); if (child == null) { handleMessage(sender, MessageType.SUB_COMMAND_INVALID, label, args[0]); return true; } if (child.isPlayerOnly() && !(sender instanceof Player)) { handleMessage(sender, MessageType.PLAYER_ONLY); return true; } if (child.getPermission() != null && !sender.hasPermission(child.getPermission())) { handleMessage(sender, MessageType.NO_PERMISSION, child.getPermission()); return true; } if (args.length < child.length) { handleMessage(sender, MessageType.SUB_COMMAND_USAGE, label, child.getUsage(), child.getDescription()); return true; } child.execute(sender, label, args); return true; } execute(sender, label, args); return true; }); pluginCommand.setTabCompleter((sender, command, alias, args) -> { if (children != null && args.length > 1) { final AbstractCommand

child = children.get(args[0].toLowerCase()); if (child != null) { final List result = child.onTabComplete(sender, command, alias, args); if (result != null) { return result; } } } return onTabComplete(sender, command, alias, args); }); } @Override public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (args.length == 0) { return null; } if (args.length == 1 && children != null) { return children.values().stream() .map(AbstractCommand::getName) .filter(childName -> childName.startsWith(args[0].toLowerCase())) .distinct() .sorted(String::compareTo) .collect(Collectors.toList()); } return null; } protected boolean executeFirst(final CommandSender sender, final String label, final String[] args) { return false; } protected abstract void execute(final CommandSender sender, final String label, final String[] args); protected void handleMessage(final CommandSender sender, final MessageType type, final String... args) { sender.sendMessage(type.defaultMessage.format(args)); } protected enum MessageType { PLAYER_ONLY("&cThis command can only be executed by a player!"), NO_PERMISSION("&cYou need the following permission: {0}"), SUB_COMMAND_INVALID("&c''{1}'' is not a valid sub command. Type /{0} for help."), SUB_COMMAND_USAGE("&cUsage: /{0} {1} - {2}"); private final MessageFormat defaultMessage; MessageType(final String defaultMessage) { this.defaultMessage = new MessageFormat(StringUtil.color(defaultMessage)); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/CompatUtil.java ================================================ package me.realized.duels.util.compat; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; public final class CompatUtil { private static final boolean ATTRIBUTES, ITEM_FLAGS, SEND_TITLE, HIDE_PLAYER, SET_COLLIDABLE, GET_PLAYER; static { ATTRIBUTES = ReflectionUtil.getMethodUnsafe(ItemMeta.class, "getAttributeModifiers") != null; ITEM_FLAGS = ReflectionUtil.getClassUnsafe("org.bukkit.inventory.ItemFlag") != null; SEND_TITLE = ReflectionUtil.getMethodUnsafe(Player.class, "sendTitle", String.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE) != null; HIDE_PLAYER = ReflectionUtil.getMethodUnsafe(Player.class, "hidePlayer", Plugin.class, Player.class) != null; SET_COLLIDABLE = ReflectionUtil.getMethodUnsafe(LivingEntity.class, "setCollidable", Boolean.TYPE) != null; GET_PLAYER = ReflectionUtil.getMethodUnsafe(BlockCanBuildEvent.class, "getPlayer") != null; } public static boolean is1_13() { return ReflectionUtil.getMajorVersion() == 13; } public static boolean isPre1_14() { return ReflectionUtil.getMajorVersion() < 14; } public static boolean isPre1_13() { return ReflectionUtil.getMajorVersion() < 13; } public static boolean isPre1_12() { return ReflectionUtil.getMajorVersion() < 12; } public static boolean isPre1_10() { return ReflectionUtil.getMajorVersion() < 10; } public static boolean isPre1_9() { return ReflectionUtil.getMajorVersion() < 9; } public static boolean hasAttributes() { return ATTRIBUTES; } public static boolean hasItemFlag() { return ITEM_FLAGS; } public static boolean hasSendTitle() { return SEND_TITLE; } public static boolean hasHidePlayer() { return HIDE_PLAYER; } public static boolean hasSetCollidable() { return SET_COLLIDABLE; } public static boolean hasGetPlayer() { return GET_PLAYER; } private CompatUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Identifiers.java ================================================ package me.realized.duels.util.compat; import me.realized.duels.DuelsPlugin; import me.realized.duels.util.compat.nbt.NBT; import org.bukkit.NamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; public final class Identifiers { private static transient final String DUELS_ITEM_IDENTIFIER = "DuelsKitContent"; public static ItemStack addIdentifier(final ItemStack item) { if (CompatUtil.isPre1_14()) { return NBT.setItemString(item, DUELS_ITEM_IDENTIFIER, true); } final NamespacedKey key = new NamespacedKey(DuelsPlugin.getInstance(), DUELS_ITEM_IDENTIFIER); final ItemMeta meta = item.getItemMeta(); meta.getPersistentDataContainer().set(key, PersistentDataType.BYTE, (byte) 1); item.setItemMeta(meta); return item; } public static boolean hasIdentifier(final ItemStack item) { if (CompatUtil.isPre1_14()) { return NBT.hasItemKey(item, DUELS_ITEM_IDENTIFIER); } final NamespacedKey key = new NamespacedKey(DuelsPlugin.getInstance(), DUELS_ITEM_IDENTIFIER); final ItemMeta meta = item.getItemMeta(); return meta.getPersistentDataContainer().has(key, PersistentDataType.BYTE); } public static ItemStack removeIdentifier(final ItemStack item) { if (CompatUtil.isPre1_14()) { return NBT.removeItemTag(item, DUELS_ITEM_IDENTIFIER); } final NamespacedKey key = new NamespacedKey(DuelsPlugin.getInstance(), DUELS_ITEM_IDENTIFIER); final ItemMeta meta = item.getItemMeta(); meta.getPersistentDataContainer().remove(key); item.setItemMeta(meta); return item; } private Identifiers() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Inventories.java ================================================ package me.realized.duels.util.compat; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.inventory.Inventory; public final class Inventories { private static final Field CB_INVENTORY; private static final Field CB_INVENTORY_TITLE; private static final Method CHAT_SERIALIZER_A; static { CB_INVENTORY = ReflectionUtil.getDeclaredField(ReflectionUtil.getCBClass("inventory.CraftInventory"), "inventory"); CB_INVENTORY_TITLE = ReflectionUtil.getDeclaredField(ReflectionUtil.getCBClass("inventory.CraftInventoryCustom$MinecraftInventory"), "title"); CHAT_SERIALIZER_A = CompatUtil.is1_13() ? ReflectionUtil.getMethod(ReflectionUtil.getNMSClass("IChatBaseComponent$ChatSerializer"), "a", String.class) : null; } public static void setTitle(final Inventory inventory, final String title) { try { Object value = title; // In 1.13, title field was changed to IChatBaseComponent, but the change was reverted in 1.14. if (CHAT_SERIALIZER_A != null) { value = CHAT_SERIALIZER_A.invoke(null, "{\"text\": \"" + title + "\"}"); } CB_INVENTORY_TITLE.set(CB_INVENTORY.get(inventory), value); } catch (IllegalAccessException | InvocationTargetException ex) { ex.printStackTrace(); } } private Inventories() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Items.java ================================================ package me.realized.duels.util.compat; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionType; public final class Items { private static final String PANE = "STAINED_GLASS_PANE"; public static final ItemStack ORANGE_PANE; public static final ItemStack BLUE_PANE; public static final ItemStack RED_PANE; public static final ItemStack GRAY_PANE; public static final ItemStack WHITE_PANE; public static final ItemStack GREEN_PANE; public static final ItemStack HEAD; public static final Material SKELETON_HEAD; public static final ItemStack OFF; public static final ItemStack ON; public static final Material MUSHROOM_SOUP; public static final Material EMPTY_MAP; public static final Material SIGN; public static final ItemStack HEAL_SPLASH_POTION; public static final ItemStack WATER_BREATHING_POTION; public static final ItemStack ENCHANTED_GOLDEN_APPLE; static { ORANGE_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 1) : ItemBuilder.of(Material.ORANGE_STAINED_GLASS_PANE)).name(" ").build(); BLUE_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 11) : ItemBuilder.of(Material.BLUE_STAINED_GLASS_PANE)).name(" ").build(); RED_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 14) : ItemBuilder.of(Material.RED_STAINED_GLASS_PANE)).build(); GRAY_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 7) : ItemBuilder.of(Material.GRAY_STAINED_GLASS_PANE)).name(" ").build(); WHITE_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 0) : ItemBuilder.of(Material.WHITE_STAINED_GLASS_PANE)).name(" ").build(); GREEN_PANE = (CompatUtil.isPre1_13() ? ItemBuilder.of(PANE, 1, (short) 5) : ItemBuilder.of(Material.LIME_STAINED_GLASS_PANE)).build(); HEAD = (CompatUtil.isPre1_13() ? ItemBuilder.of("SKULL_ITEM", 1, (short) 3) : ItemBuilder.of(Material.PLAYER_HEAD)).build(); SKELETON_HEAD = CompatUtil.isPre1_13() ? Material.matchMaterial("SKULL_ITEM") : Material.SKELETON_SKULL; OFF = (CompatUtil.isPre1_13() ? ItemBuilder.of("INK_SACK", 1, (short) 8) : ItemBuilder.of(Material.GRAY_DYE)).build(); ON = (CompatUtil.isPre1_13() ? ItemBuilder.of("INK_SACK", 1, (short) 10) : ItemBuilder.of(Material.LIME_DYE)).build(); MUSHROOM_SOUP = CompatUtil.isPre1_13() ? Material.matchMaterial("MUSHROOM_SOUP") : Material.MUSHROOM_STEW; EMPTY_MAP = CompatUtil.isPre1_13() ? Material.matchMaterial("EMPTY_MAP") : Material.MAP; SIGN = CompatUtil.isPre1_14() ? Material.matchMaterial("SIGN") : Material.OAK_SIGN; HEAL_SPLASH_POTION = (CompatUtil.isPre1_9() ? ItemBuilder.of(Material.POTION, 1, (short) 16421) : ItemBuilder.of(Material.SPLASH_POTION).potion( PotionType.INSTANT_HEAL, false, true)).build(); WATER_BREATHING_POTION = (CompatUtil.isPre1_9() ? ItemBuilder.of(Material.POTION, 1, (short) 8237) : ItemBuilder.of(Material.POTION).potion( PotionType.WATER_BREATHING, false, false)).build(); ENCHANTED_GOLDEN_APPLE = CompatUtil.isPre1_13() ? ItemBuilder.of(Material.GOLDEN_APPLE, 1, (short) 1).build() : ItemBuilder.of(Material.ENCHANTED_GOLDEN_APPLE).build(); } public static boolean equals(final ItemStack item, final ItemStack other) { return item.getType() == other.getType() && getDurability(item) == getDurability(other); } public static ItemStack from(final String type, final short data) { if (type.equalsIgnoreCase("STAINED_GLASS_PANE") && !CompatUtil.isPre1_13()) { return ItemBuilder.of(Panes.from(data)).name(" ").build(); } return ItemBuilder.of(type, 1, data).name(" ").build(); } public static short getDurability(final ItemStack item) { if (CompatUtil.isPre1_13()) { return item.getDurability(); } final ItemMeta meta; return ((meta = item.getItemMeta()) == null) ? 0 : (short) ((Damageable) meta).getDamage(); } public static void setDurability(final ItemStack item, final short durability) { if (CompatUtil.isPre1_13()) { item.setDurability(durability); return; } final ItemMeta meta = item.getItemMeta(); if (meta != null) { ((Damageable) meta).setDamage(durability); item.setItemMeta(meta); } } public static boolean isHealSplash(final ItemStack item) { if (CompatUtil.isPre1_9()) { return Items.equals(Items.HEAL_SPLASH_POTION, item); } if (item.getType() != Material.SPLASH_POTION) { return false; } final PotionMeta meta = (PotionMeta) item.getItemMeta(); return meta != null && meta.getBasePotionData().getType() == PotionType.INSTANT_HEAL; } private Items() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Panes.java ================================================ package me.realized.duels.util.compat; import java.util.HashMap; import java.util.Map; import org.bukkit.Material; public final class Panes { private static final Map DATA_TO_PANE = new HashMap<>(); static { DATA_TO_PANE.put((short) 0, "WHITE_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 1, "ORANGE_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 2, "MAGENTA_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 3, "LIGHT_BLUE_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 4, "YELLOW_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 5, "LIME_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 6, "PINK_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 7, "GRAY_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 8, "LIGHT_GRAY_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 9, "CYAN_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 10, "PURPLE_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 11, "BLUE_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 12, "BROWN_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 13, "GREEN_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 14, "RED_STAINED_GLASS_PANE"); DATA_TO_PANE.put((short) 15, "BLACK_STAINED_GLASS_PANE"); } public static Material from(final short data) { return Material.getMaterial(DATA_TO_PANE.get(data)); } private Panes() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Skulls.java ================================================ package me.realized.duels.util.compat; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.mojang.authlib.GameProfile; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.entity.Player; import org.bukkit.inventory.meta.SkullMeta; import org.jetbrains.annotations.NotNull; /** * Caches the GameProfile stored in EntityHuman instance to prevent Mojang server lookup. */ public final class Skulls { private static final Method GET_PROFILE; private static final Field PROFILE; private static final Method SET_PROFILE; private static final LoadingCache cache = CacheBuilder.newBuilder() .maximumSize(1000) .weakKeys() .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader() { @Override public GameProfile load(@NotNull final Player player) throws InvocationTargetException, IllegalAccessException { return getProfile(player); } } ); static { final Class CB_PLAYER = ReflectionUtil.getCBClass("entity.CraftPlayer"); GET_PROFILE = ReflectionUtil.getMethod(CB_PLAYER, "getProfile"); final Class CB_SKULL_META = ReflectionUtil.getCBClass("inventory.CraftMetaSkull"); PROFILE = ReflectionUtil.getDeclaredField(CB_SKULL_META, "profile"); SET_PROFILE = ReflectionUtil.getDeclaredMethodUnsafe(CB_SKULL_META, "setProfile", GameProfile.class); } private static GameProfile getProfile(final Player player) throws InvocationTargetException, IllegalAccessException { return (GameProfile) GET_PROFILE.invoke(player); } /** * Sets given player as the owner of the given skull using cached GameProfile information of the player. * * @param meta SkullMeta of the skull to set owner * @param player Player to display on skull */ public static void setProfile(final SkullMeta meta, final Player player) { // In 1.15.2 and above, setOwningPlayer was optimized to use online player's cached GameProfile. if (SET_PROFILE != null) { meta.setOwningPlayer(player); return; } // Caching is only used for MC versions 1.8 - 1.15.1. try { final GameProfile cached = cache.get(player); PROFILE.set(meta, cached); } catch (Exception ex) { ex.printStackTrace(); } } private Skulls() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/Titles.java ================================================ package me.realized.duels.util.compat; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import me.realized.duels.util.StringUtil; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.entity.Player; public final class Titles { private static Method GET_HANDLE; private static Field PLAYER_CONNECTION; private static Method SEND_PACKET; private static Class TITLE_ACTIONS; private static Constructor TITLE_PACKET_FULL_CONSTRUCTOR; private static Constructor TITLE_PACKET_CONSTRUCTOR; private static Class CHAT_SERIALIZER; static { // Use Player#sendTitle for 1.11+ if (!CompatUtil.hasSendTitle()) { final Class CB_PLAYER = ReflectionUtil.getCBClass("entity.CraftPlayer"); GET_HANDLE = ReflectionUtil.getMethod(CB_PLAYER, "getHandle"); final Class NMS_PLAYER = ReflectionUtil.getNMSClass("EntityPlayer"); PLAYER_CONNECTION = ReflectionUtil.getField(NMS_PLAYER, "playerConnection"); final Class NMS_PLAYER_CONNECTION = ReflectionUtil.getNMSClass("PlayerConnection"); final Class NMS_PACKET = ReflectionUtil.getNMSClass("Packet"); SEND_PACKET = ReflectionUtil.getMethod(NMS_PLAYER_CONNECTION, "sendPacket", NMS_PACKET); final Class TITLE_PACKET = ReflectionUtil.getNMSClass("PacketPlayOutTitle"); final Class CHAT_COMPONENT = ReflectionUtil.getNMSClass("IChatBaseComponent"); TITLE_ACTIONS = ReflectionUtil.getNMSClass("PacketPlayOutTitle$EnumTitleAction"); // For v1_8_R1, EnumTitleAction is not an inner class of PacketPlayOutTitle if (TITLE_ACTIONS == null) { TITLE_ACTIONS = ReflectionUtil.getNMSClass("EnumTitleAction", false); } TITLE_PACKET_FULL_CONSTRUCTOR = ReflectionUtil.getConstructor(TITLE_PACKET, TITLE_ACTIONS, CHAT_COMPONENT, int.class, int.class, int.class); TITLE_PACKET_CONSTRUCTOR = ReflectionUtil.getConstructor(TITLE_PACKET, TITLE_ACTIONS, CHAT_COMPONENT); CHAT_SERIALIZER = ReflectionUtil.getNMSClass("ChatComponentText"); } } private Titles() {} public static void send(final Player player, final String title, final String subtitle, final int fadeIn, final int stay, final int fadeOut) { if (CompatUtil.hasSendTitle()) { player.sendTitle(StringUtil.color(title), subtitle != null ? StringUtil.color(subtitle) : null, fadeIn, stay, fadeOut); } else { try { final Object connection = PLAYER_CONNECTION.get(GET_HANDLE.invoke(player)); final Object[] actions = TITLE_ACTIONS.getEnumConstants(); SEND_PACKET.invoke(connection, TITLE_PACKET_FULL_CONSTRUCTOR.newInstance(actions[2], null, fadeIn, stay, fadeOut)); Object text = CHAT_SERIALIZER.getConstructor(String.class).newInstance(StringUtil.color(title)); SEND_PACKET.invoke(connection, TITLE_PACKET_CONSTRUCTOR.newInstance(actions[0], text)); if (subtitle != null) { text = CHAT_SERIALIZER.getConstructor(String.class).newInstance(StringUtil.color(subtitle)); SEND_PACKET.invoke(connection, TITLE_PACKET_CONSTRUCTOR.newInstance(actions[1], text)); } } catch (Exception ex) { ex.printStackTrace(); } } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/compat/nbt/NBT.java ================================================ package me.realized.duels.util.compat.nbt; import java.lang.reflect.Method; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataContainer; /** * Used to store kit item identifiers in items for versions 1.8 - 1.13. For 1.14 and above, {@link PersistentDataContainer} is used instead. */ public final class NBT { private static final Method AS_NMS_COPY; private static final Method AS_BUKKIT_COPY; private static final Class TAG_COMPOUND; private static final Method GET_TAG; private static final Method SET_TAG; private static final Method SET_STRING; private static final Method REMOVE; private static final Method HAS_KEY; static { final Class CB_ITEMSTACK = ReflectionUtil.getCBClass("inventory.CraftItemStack"); final Class NMS_ITEMSTACK = ReflectionUtil.getNMSClass("ItemStack"); AS_NMS_COPY = ReflectionUtil.getMethod(CB_ITEMSTACK, "asNMSCopy", ItemStack.class); AS_BUKKIT_COPY = ReflectionUtil.getMethod(CB_ITEMSTACK, "asBukkitCopy", NMS_ITEMSTACK); TAG_COMPOUND = ReflectionUtil.getNMSClass("NBTTagCompound"); GET_TAG = ReflectionUtil.getMethod(NMS_ITEMSTACK, "getTag"); SET_TAG = ReflectionUtil.getMethod(NMS_ITEMSTACK, "setTag", TAG_COMPOUND); SET_STRING = ReflectionUtil.getMethod(TAG_COMPOUND, "setString", String.class, String.class); REMOVE = ReflectionUtil.getMethod(TAG_COMPOUND, "remove", String.class); HAS_KEY = ReflectionUtil.getMethod(TAG_COMPOUND, "hasKey", String.class); } public static ItemStack setItemString(final ItemStack item, final String key, final Object value) { try { final Object nmsItem = AS_NMS_COPY.invoke(null, item); Object tag = GET_TAG.invoke(nmsItem); if (tag == null) { tag = TAG_COMPOUND.newInstance(); } SET_STRING.invoke(tag, key, value.toString()); SET_TAG.invoke(nmsItem, tag); return (ItemStack) AS_BUKKIT_COPY.invoke(null, nmsItem); } catch (Exception ex) { ex.printStackTrace(); return item; } } public static ItemStack removeItemTag(final ItemStack item, final String key) { try { final Object nmsItem = AS_NMS_COPY.invoke(null, item); Object tag = GET_TAG.invoke(nmsItem); if (tag == null) { return item; } REMOVE.invoke(tag, key); SET_TAG.invoke(nmsItem, tag); return (ItemStack) AS_BUKKIT_COPY.invoke(null, nmsItem); } catch (Exception ex) { ex.printStackTrace(); return item; } } public static boolean hasItemKey(final ItemStack item, final String key) { try { final Object nmsItem = AS_NMS_COPY.invoke(null, item); if (nmsItem == null) { return false; } final Object tag = GET_TAG.invoke(nmsItem); return tag != null && (boolean) HAS_KEY.invoke(tag, key); } catch (Exception ex) { ex.printStackTrace(); return false; } } private NBT() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/config/AbstractConfiguration.java ================================================ package me.realized.duels.util.config; import com.google.common.base.Charsets; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.realized.duels.util.Loadable; import me.realized.duels.util.config.convert.Converter; import me.realized.duels.util.reflect.ReflectionUtil; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfigurationOptions; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; public abstract class AbstractConfiguration

implements Loadable { private static final String CONVERT_START = "[!] Converting your current configuration (%s) to the new version..."; private static final String CONVERT_SAVE = "[!] Your old configuration was stored as %s."; private static final String CONVERT_DONE = "[!] Conversion complete!"; private static final Pattern KEY_PATTERN = Pattern.compile("^([ ]*)([^ \"]+)[:].*$"); private static final Pattern COMMENT_PATTERN = Pattern.compile("^([ ]*[#].*)|[ ]*$"); protected final P plugin; private final String name; private final File file; private FileConfiguration configuration; public AbstractConfiguration(final P plugin, final String name) { this.plugin = plugin; this.name = name + ".yml"; this.file = new File(plugin.getDataFolder(), this.name); } @Override public void handleLoad() throws Exception { if (!file.exists()) { plugin.saveResource(name, true); } loadValues(configuration = YamlConfiguration.loadConfiguration(file)); } @Override public void handleUnload() {} protected abstract void loadValues(final FileConfiguration configuration) throws Exception; protected int getLatestVersion() throws Exception { final InputStream stream = plugin.getClass().getResourceAsStream("/" + name); if (stream == null) { throw new IllegalStateException(plugin.getName() + "'s jar file was replaced, but a reload was called! Please restart your server instead when updating this plugin."); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8))) { return YamlConfiguration.loadConfiguration(reader).getInt("config-version", -1); } } protected FileConfiguration convert(final Converter converter) throws IOException { plugin.getLogger().info(String.format(CONVERT_START, name)); final Map oldValues = new HashMap<>(); for (final String key : configuration.getKeys(true)) { if (key.equals("config-version")) { continue; } final Object value = configuration.get(key); if (value instanceof MemorySection) { continue; } oldValues.put(key, value); } if (converter != null) { converter.renamedKeys().forEach((old, changed) -> { final Object previous = oldValues.get(old); if (previous != null) { oldValues.remove(old); oldValues.put(changed, previous); } }); } final String newName = name.replace(".yml", "") + "-" + System.currentTimeMillis() + ".yml"; final File copied = Files.copy(file.toPath(), new File(plugin.getDataFolder(), newName).toPath()).toFile(); plugin.getLogger().info(String.format(CONVERT_SAVE, copied.getName())); plugin.saveResource(name, true); // Loads comments of the new configuration file try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charsets.UTF_8))) { final Multimap> comments = LinkedListMultimap.create(); final List currentComments = new ArrayList<>(); String line; Matcher matcher; while ((line = reader.readLine()) != null) { if ((matcher = KEY_PATTERN.matcher(line)).find() && !COMMENT_PATTERN.matcher(line).matches()) { comments.put(matcher.group(2), Lists.newArrayList(currentComments)); currentComments.clear(); } else if (COMMENT_PATTERN.matcher(line).matches()) { currentComments.add(line); } } configuration = YamlConfiguration.loadConfiguration(file); final FileConfigurationOptions options = configuration.options(); options.header(null); final Method method = ReflectionUtil.getDeclaredMethodUnsafe(FileConfigurationOptions.class, "parseComments", Boolean.TYPE); if (method != null) { try { method.invoke(options, false); } catch (IllegalAccessException | InvocationTargetException ignored) {} } // Transfer values from the old configuration for (Map.Entry entry : oldValues.entrySet()) { final String key = entry.getKey(); final Object value = configuration.get(key); if ((value != null && !(value instanceof MemorySection)) || transferredSections().stream().anyMatch(section -> key.startsWith(section + "."))) { configuration.set(key, entry.getValue()); } } final List commentlessData = Lists.newArrayList(configuration.saveToString().split("\n")); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8))) { for (final String data : commentlessData) { matcher = KEY_PATTERN.matcher(data); if (matcher.find()) { final String key = matcher.group(2); final Collection> result = comments.get(key); if (result != null) { final List> commentData = Lists.newArrayList(result); if (!commentData.isEmpty()) { for (final String comment : commentData.get(0)) { writer.write(comment); writer.newLine(); } commentData.remove(0); comments.replaceValues(key, commentData); } } } writer.write(data); if (commentlessData.indexOf(data) + 1 < commentlessData.size()) { writer.newLine(); } else if (!currentComments.isEmpty()) { writer.newLine(); } } // Handles comments at the end of the file without any key for (final String comment : currentComments) { writer.write(comment); if (currentComments.indexOf(comment) + 1 < currentComments.size()) { writer.newLine(); } } writer.flush(); } plugin.getLogger().info(CONVERT_DONE); } return configuration; } protected Set transferredSections() { return Collections.emptySet(); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/config/convert/Converter.java ================================================ package me.realized.duels.util.config.convert; import java.util.Map; public interface Converter { Map renamedKeys(); } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/function/Pair.java ================================================ package me.realized.duels.util.function; import lombok.Getter; import lombok.Setter; public class Pair { @Getter @Setter private K key; @Getter @Setter private V value; public Pair(final K key, final V value) { this.key = key; this.value = value; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/function/TriFunction.java ================================================ package me.realized.duels.util.function; import java.util.Objects; import java.util.function.Function; @FunctionalInterface public interface TriFunction { R apply(S s, T t, U u); default TriFunction andThen(Function after) { Objects.requireNonNull(after); return (S s, T t, U u) -> after.apply(apply(s, t, u)); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/gui/AbstractGui.java ================================================ package me.realized.duels.util.gui; import java.util.HashMap; import java.util.Map; import java.util.Set; import lombok.Getter; import me.realized.duels.util.inventory.Slots; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.java.JavaPlugin; public abstract class AbstractGui

{ protected final P plugin; @Getter private final long creation; private final Map>> buttons = new HashMap<>(); public AbstractGui(final P plugin) { this.plugin = plugin; this.creation = System.currentTimeMillis(); } public abstract void open(final Player... players); public abstract boolean isPart(final Inventory inventory); public abstract void on(final Player player, final Inventory top, final InventoryClickEvent event); public void on(final Player player, final Inventory inventory, final InventoryCloseEvent event) {} public void on(final Player player, final Set rawSlots, final InventoryDragEvent event) { event.setCancelled(true); } public Button

get(final Inventory inventory, final int slot) { final Map> buttons; return (buttons = this.buttons.get(inventory)) != null ? buttons.get(slot) : null; } public void set(final Inventory inventory, final int slot, final Button

button) { buttons.computeIfAbsent(inventory, result -> new HashMap<>()).put(slot, button); inventory.setItem(slot, button.getDisplayed()); } public void set(final Inventory inventory, final int from, final int to, final int height, final Button

button) { Slots.run(from, to, height, slot -> set(inventory, slot, button)); } public void set(final Inventory inventory, final int from, final int to, final Button

button) { Slots.run(from, to, slot -> set(inventory, slot, button)); } public void remove(final Inventory inventory) { buttons.remove(inventory); } public Button

remove(final Inventory inventory, final int slot) { final Map> buttons; return (buttons = this.buttons.get(inventory)) != null ? buttons.remove(slot) : null; } public void update(final Player player, final Inventory inventory, final Button

button) { final Map> cached = buttons.get(inventory); if (cached == null) { return; } button.update(player); cached.entrySet().stream().filter(entry -> entry.getValue().equals(button)).findFirst().ifPresent(entry -> inventory.setItem(entry.getKey(), button.getDisplayed())); } public void update(final Player player) { buttons.forEach((inventory, data) -> data.forEach((slot, button) -> { button.update(player); inventory.setItem(slot, button.getDisplayed()); })); } public void clear() { buttons.keySet().forEach(Inventory::clear); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/gui/Button.java ================================================ package me.realized.duels.util.gui; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import lombok.Getter; import lombok.Setter; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import me.realized.duels.util.compat.Skulls; import me.realized.duels.util.inventory.ItemBuilder; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; public class Button

{ protected final P plugin; @Getter @Setter private ItemStack displayed; public Button(final P plugin, final ItemStack displayed) { this.plugin = plugin; this.displayed = displayed; } protected void editMeta(final Consumer consumer) { final ItemMeta meta = getDisplayed().getItemMeta(); consumer.accept(meta); getDisplayed().setItemMeta(meta); } protected void setDisplayName(final String name) { editMeta(meta -> meta.setDisplayName(StringUtil.color(name))); } protected void setLore(final List lore) { editMeta(meta -> meta.setLore(StringUtil.color(lore))); } protected void setLore(final String... lore) { setLore(Arrays.asList(lore)); } protected void setOwner(final Player player) { if (Items.equals(displayed, Items.HEAD)) { editMeta(meta -> Skulls.setProfile((SkullMeta) meta, player)); } } protected void setGlow(final boolean glow) { // Normal golden apples do not have enchantment glint even with an enchantment applied, so we change the item type. if (displayed.getType().name().endsWith("GOLDEN_APPLE")) { final ItemStack item = glow ? Items.ENCHANTED_GOLDEN_APPLE.clone() : ItemBuilder.of(Material.GOLDEN_APPLE).build(); item.setItemMeta(getDisplayed().getItemMeta()); setDisplayed(item); return; } editMeta(meta -> { if (glow) { meta.addEnchant(Enchantment.DURABILITY, 1, false); if (CompatUtil.hasItemFlag()) { meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } } else { meta.removeEnchant(Enchantment.DURABILITY); if (CompatUtil.hasItemFlag()) { meta.removeItemFlags(ItemFlag.HIDE_ENCHANTS); } } }); } public void update(final Player player) {} public void onClick(final Player player) {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/gui/GuiListener.java ================================================ package me.realized.duels.util.gui; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import me.realized.duels.util.Loadable; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.java.JavaPlugin; public class GuiListener

implements Loadable, Listener { private final Multimap> privateGuis = HashMultimap.create(); private final List> publicGuis = new ArrayList<>(); public GuiListener(final P plugin) { Bukkit.getPluginManager().registerEvents(this, plugin); } @Override public void handleLoad() {} @Override public void handleUnload() { privateGuis.values().forEach(AbstractGui::clear); privateGuis.clear(); publicGuis.forEach(AbstractGui::clear); publicGuis.clear(); } public void addGui(final AbstractGui

gui) { publicGuis.add(gui); } /** * @param removeSameType Prevents memory leaks in case of gui open failing for guis that remove themselves on inventory close. */ public > T addGui(final Player player, final T gui, final boolean removeSameType) { if (removeSameType) { final Collection> guis = privateGuis.asMap().get(player.getUniqueId()); if (guis != null) { guis.removeIf(cached -> gui.getClass().isInstance(cached)); } } privateGuis.put(player.getUniqueId(), gui); return gui; } public > T addGui(final Player player, final T gui) { return addGui(player, gui, false); } public void removeGui(final AbstractGui

gui) { gui.clear(); publicGuis.remove(gui); } public void removeGui(final Player player, final AbstractGui

gui) { gui.clear(); final Collection> guis = privateGuis.asMap().get(player.getUniqueId()); if (guis != null) { guis.remove(gui); } } private List> get(final Player player) { final List> guis = Lists.newArrayList(publicGuis); if (privateGuis.containsKey(player.getUniqueId())) { guis.addAll(privateGuis.get(player.getUniqueId())); } return guis; } @EventHandler public void on(final InventoryClickEvent event) { final Player player = (Player) event.getWhoClicked(); final Inventory top = player.getOpenInventory().getTopInventory(); for (final AbstractGui

gui : get(player)) { if (gui.isPart(top)) { gui.on(player, top, event); break; } } } @EventHandler public void on(final InventoryDragEvent event) { final Player player = (Player) event.getWhoClicked(); final Inventory inventory = event.getInventory(); for (final AbstractGui

gui : get(player)) { if (gui.isPart(inventory)) { gui.on(player, event.getRawSlots(), event); break; } } } @EventHandler public void on(final InventoryCloseEvent event) { final Player player = (Player) event.getPlayer(); final Inventory inventory = event.getInventory(); for (final AbstractGui

gui : get(player)) { if (gui.isPart(inventory)) { gui.on(player, event.getInventory(), event); break; } } } @EventHandler public void on(final PlayerQuitEvent event) { privateGuis.removeAll(event.getPlayer().getUniqueId()); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/gui/MultiPageGui.java ================================================ package me.realized.duels.util.gui; import com.google.common.collect.Lists; import java.util.Collection; import java.util.function.Consumer; import lombok.Getter; import lombok.Setter; import me.realized.duels.util.compat.Inventories; import me.realized.duels.util.compat.Items; import me.realized.duels.util.inventory.InventoryBuilder; import me.realized.duels.util.inventory.Slots; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; public class MultiPageGui

extends AbstractGui

{ private final String title; private final int size, prevPageSlot, nextPageSlot; // Note: Referenced Collection! @Getter private final Collection> buttons; private PageNode first; @Setter private ItemStack spaceFiller; @Setter private ItemStack prevButton; @Setter private ItemStack nextButton; @Setter private ItemStack emptyIndicator; public MultiPageGui(final P plugin, final String title, final int rows, final Collection> buttons) { super(plugin); if (title == null || title.isEmpty()) { throw new IllegalArgumentException("title cannot be null or empty"); } this.title = title; if (rows <= 0 || rows > 5) { throw new IllegalArgumentException("rows out of range, must be between 1 - 5"); } this.size = rows * 9 + 9; this.prevPageSlot = size - 9; this.nextPageSlot = size - 1; if (buttons == null) { throw new IllegalArgumentException("buttons cannot be null"); } this.buttons = buttons; } /** * Recalculates the pages for this {@link MultiPageGui}. */ public void calculatePages() { // The max size an inventory can contain. final int maxSize = size - 9; // Total pages calculated based on the size of the buttons collection at this point of call. final int totalPages = buttons.size() / maxSize + (buttons.size() % maxSize > 0 ? 1 : 0); // If first time calculating, init first PageNode if (first == null) { first = createPage(1, totalPages); } // Case: The updated buttons collection is empty. if (totalPages == 0) { first.setEmpty(); return; } int i = 0; int pageNum = 1; int slot = 0; PageNode last = null; for (final Button

button : buttons) { if (i % maxSize == 0) { final PageNode prev = last; if (last == null) { last = first; } else { if (last.next == null) { last.next = createPage(pageNum, totalPages); } last = last.next; } last.setTitle(title + " (" + pageNum + "/" + totalPages + ")"); last.clear(); if (prev != null) { last.previous = prev; last.inventory.setItem(prevPageSlot, prevButton); prev.next = last; prev.inventory.setItem(nextPageSlot, nextButton); } slot = 0; pageNum++; } set(last.inventory, slot, button); i++; slot++; } if (last != null) { last.resetNext(); } } private PageNode createPage(final int page, final int total) { return new PageNode(InventoryBuilder .of(title + " (" + page + "/" + total + ")", size) .fillRange(prevPageSlot, nextPageSlot + 1, getSpaceFiller()) .build()); } private ItemStack getSpaceFiller() { return spaceFiller != null ? spaceFiller : Items.WHITE_PANE.clone(); } @Override public void open(final Player... players) { for (final Player player : players) { player.openInventory(first.inventory); } } @Override public boolean isPart(final Inventory inventory) { return first.isPart(inventory); } @Override public void on(final Player player, final Inventory top, final InventoryClickEvent event) { final Inventory clicked = event.getClickedInventory(); if (clicked == null) { return; } event.setCancelled(true); if (!clicked.equals(top)) { return; } final PageNode node = first.find(clicked); if (node == null) { return; } final int slot = event.getSlot(); if (slot == nextPageSlot && node.next != null) { player.openInventory(node.next.inventory); } else if (slot == prevPageSlot && node.previous != null) { player.openInventory(node.previous.inventory); } else { final Button

button = get(clicked, slot); if (button == null) { return; } button.onClick(player); } } private class PageNode { private final Inventory inventory; private PageNode previous, next; PageNode(final Inventory inventory) { this.inventory = inventory; } void setEmpty() { setTitle(title); final ItemStack item = inventory.getItem(4); if (item != null && item.isSimilar(emptyIndicator)) { return; } clear(); resetBottom(); inventory.setItem(4, emptyIndicator); remove(inventory); resetNext(); } void resetNext() { if (next == null) { return; } inventory.setItem(nextPageSlot, getSpaceFiller()); forEach(node -> { if (node.equals(this)) { return; } remove(node.inventory); Lists.newArrayList(node.inventory.getViewers()).forEach(HumanEntity::closeInventory); }); next = null; } void setTitle(final String title) { Inventories.setTitle(inventory, title); } void clear() { remove(inventory); for (int slot = 0; slot < inventory.getSize() - 9; slot++) { inventory.setItem(slot, null); } } void resetBottom() { Slots.run(prevPageSlot, nextPageSlot + 1, slot -> inventory.setItem(slot, getSpaceFiller())); } void forEach(final Consumer consumer) { consumer.accept(this); if (next != null) { next.forEach(consumer); } } PageNode find(final Inventory inventory) { if (this.inventory.equals(inventory)) { return this; } if (next != null) { return next.find(inventory); } return null; } boolean isPart(final Inventory inventory) { return find(inventory) != null; } // boolean hasViewers() { // if (!inventory.getViewers().isEmpty()) { // return true; // } // // return next != null && !next.hasViewers(); // } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/gui/SinglePageGui.java ================================================ package me.realized.duels.util.gui; import me.realized.duels.util.StringUtil; import me.realized.duels.util.inventory.InventoryBuilder; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.java.JavaPlugin; public class SinglePageGui

extends AbstractGui

{ protected final Inventory inventory; public SinglePageGui(final P plugin, final String title, final int rows) { super(plugin); this.inventory = InventoryBuilder.of(StringUtil.color(title), rows * 9).build(); } protected void set(final int slot, final Button

button) { set(inventory, slot, button); } protected void set(final int from, final int to, final int height, final Button

button) { set(inventory, from, to, height, button); } public void update(final Player player, final Button

button) { update(player, inventory, button); } @Override public void open(final Player... players) { for (final Player player : players) { update(player); player.openInventory(inventory); } } @Override public boolean isPart(final Inventory inventory) { return inventory.equals(this.inventory); } @Override public void on(final Player player, final Inventory top, final InventoryClickEvent event) { final Inventory clicked = event.getClickedInventory(); if (clicked == null) { return; } event.setCancelled(true); if (!clicked.equals(top)) { return; } final Button

button = get(inventory, event.getSlot()); if (button == null) { return; } button.onClick(player); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/hook/AbstractHookManager.java ================================================ package me.realized.duels.util.hook; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public abstract class AbstractHookManager

{ protected final P plugin; private final Map>, PluginHook

> hooks = new HashMap<>(); public AbstractHookManager(final P plugin) { this.plugin = plugin; } protected void register(final String name, final Class> clazz) { final Plugin target = Bukkit.getPluginManager().getPlugin(name); if (target == null || !target.isEnabled()) { return; } try { if (hooks.putIfAbsent(clazz, clazz.getConstructor(plugin.getClass()).newInstance(plugin)) != null) { plugin.getLogger().warning("Failed to hook into " + name + ": There was already a hook registered with same name"); return; } plugin.getLogger().info("Successfully hooked into '" + name + "'!"); } catch (Throwable throwable) { if (throwable.getCause() != null) { throwable = throwable.getCause(); } plugin.getLogger().warning("Failed to hook into " + name + ": " + throwable.getMessage()); } } public > T getHook(Class clazz) { return clazz != null ? clazz.cast(hooks.get(clazz)) : null; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/hook/PluginHook.java ================================================ package me.realized.duels.util.hook; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public class PluginHook

{ protected final P plugin; private final String name; public PluginHook(final P plugin, final String name) { this.plugin = plugin; this.name = name; } public String getName() { return name; } public Plugin getPlugin() { return Bukkit.getPluginManager().getPlugin(name); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/inventory/InventoryBuilder.java ================================================ package me.realized.duels.util.inventory; import org.bukkit.Bukkit; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public final class InventoryBuilder { private final Inventory inventory; private InventoryBuilder(final String title, final int size) { this.inventory = Bukkit.createInventory(null, size, title); } public static InventoryBuilder of(final String title, final int size) { return new InventoryBuilder(title, size); } public InventoryBuilder set(final int slot, final ItemStack item) { inventory.setItem(slot, item); return this; } public InventoryBuilder fillRange(final int from, final int to, final ItemStack item) { Slots.run(from, to, slot -> inventory.setItem(slot, item)); return this; } public Inventory build() { return inventory; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/inventory/InventoryUtil.java ================================================ package me.realized.duels.util.inventory; import com.google.common.collect.ObjectArrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public final class InventoryUtil { private static final String INVENTORY_IDENTIFIER = "INVENTORY"; private static final String ARMOR_IDENTIFIER = "ARMOR"; public static void addToMap(final PlayerInventory inventory, final Map> items) { final Map contents = new HashMap<>(); for (int i = 0; i < inventory.getSize(); i++) { final ItemStack item = inventory.getItem(i); if (item == null || item.getType() == Material.AIR) { continue; } contents.put(i, item.clone()); } items.put(INVENTORY_IDENTIFIER, contents); final Map armorContents = new HashMap<>(); for (int i = inventory.getArmorContents().length - 1; i >= 0; i--) { final ItemStack item = inventory.getArmorContents()[i]; if (item == null || item.getType() == Material.AIR) { continue; } armorContents.put(4 - i, inventory.getArmorContents()[i].clone()); } items.put(ARMOR_IDENTIFIER, armorContents); } public static void fillFromMap(final PlayerInventory inventory, final Map> items) { final Map inventoryItems = items.get(INVENTORY_IDENTIFIER); if (inventoryItems != null) { for (final Map.Entry entry : inventoryItems.entrySet()) { inventory.setItem(entry.getKey(), entry.getValue().clone()); } } final Map armorItems = items.get(ARMOR_IDENTIFIER); if (armorItems != null) { final ItemStack[] armor = new ItemStack[4]; armorItems.forEach((slot, item) -> armor[4 - slot] = item.clone()); inventory.setArmorContents(armor); } } public static boolean hasItem(final Player player) { final PlayerInventory inventory = player.getInventory(); for (final ItemStack item : ObjectArrays.concat(inventory.getArmorContents(), inventory.getContents(), ItemStack.class)) { if (item != null && item.getType() != Material.AIR) { return true; } } return false; } public static boolean addOrDrop(final Player player, final Collection items) { if (items.isEmpty()) { return false; } final Map result = player.getInventory().addItem(items.stream().filter(Objects::nonNull).toArray(ItemStack[]::new)); if (!result.isEmpty()) { result.values().forEach(item -> player.getWorld().dropItemNaturally(player.getLocation(), item)); } return true; } public static ItemStack getItemInHand(final Player player) { return player.getInventory().getItem(player.getInventory().getHeldItemSlot()); } private InventoryUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/inventory/ItemBuilder.java ================================================ package me.realized.duels.util.inventory; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import me.realized.duels.util.EnumUtil; import me.realized.duels.util.StringUtil; import me.realized.duels.util.compat.CompatUtil; import me.realized.duels.util.compat.Items; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.attribute.AttributeModifier.Operation; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; public final class ItemBuilder { private final ItemStack result; private ItemBuilder(final Material type, final int amount, final short durability) { this.result = new ItemStack(type, amount); Items.setDurability(result, durability); } private ItemBuilder(final String type, final int amount, final short durability) { this(Material.matchMaterial(type), amount, durability); } private ItemBuilder(final ItemStack item) { this.result = item; } public static ItemBuilder of(final Material type) { return of(type, 1); } public static ItemBuilder of(final Material type, final int amount) { return of(type, amount, (short) 0); } public static ItemBuilder of(final Material type, final int amount, final short durability) { return new ItemBuilder(type, amount, durability); } public static ItemBuilder of(final String type, final int amount, final short durability) { return new ItemBuilder(type, amount, durability); } public static ItemBuilder of(final ItemStack item) { return new ItemBuilder(item); } public ItemBuilder editMeta(final Consumer consumer) { final ItemMeta meta = result.getItemMeta(); consumer.accept(meta); result.setItemMeta(meta); return this; } public ItemBuilder name(final String name) { return editMeta(meta -> meta.setDisplayName(StringUtil.color(name))); } public ItemBuilder lore(final List lore) { return editMeta(meta -> meta.setLore(StringUtil.color(lore))); } public ItemBuilder lore(final String... lore) { return lore(Arrays.asList(lore)); } public ItemBuilder enchant(final Enchantment enchantment, final int level) { result.addUnsafeEnchantment(enchantment, level); return this; } public ItemBuilder unbreakable() { return editMeta(meta -> { if (CompatUtil.isPre1_12()) { meta.spigot().setUnbreakable(true); } else { meta.setUnbreakable(true); } }); } public ItemBuilder head(final String owner) { return editMeta(meta -> { if (owner != null && Items.equals(Items.HEAD, result)) { final SkullMeta skullMeta = (SkullMeta) meta; skullMeta.setOwner(owner); } }); } public ItemBuilder leatherArmorColor(final String color) { return editMeta(meta -> { final LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) meta; if (color != null) { leatherArmorMeta.setColor(DyeColor.valueOf(color).getColor()); } }); } public ItemBuilder potion(final PotionType type, final boolean extended, final boolean upgraded) { PotionMeta meta = (PotionMeta) result.getItemMeta(); meta.setBasePotionData(new PotionData(type, extended, upgraded)); result.setItemMeta(meta); return this; } public ItemBuilder attribute(final String name, final int operation, final double amount, final String slotName) { return editMeta(meta -> { final Attribute attribute = EnumUtil.getByName(attributeNameToEnum(name), Attribute.class); if (attribute == null) { return; } final AttributeModifier modifier; if (slotName != null) { final EquipmentSlot slot = EnumUtil.getByName(slotName, EquipmentSlot.class); if (slot == null) { return; } modifier = new AttributeModifier(UUID.randomUUID(), name, amount, Operation.values()[operation], slot); } else { modifier = new AttributeModifier(UUID.randomUUID(), name, amount, Operation.values()[operation]); } meta.addAttributeModifier(attribute, modifier); }); } private String attributeNameToEnum(String name) { int len = name.length(); int capitalLetterIndex = -1; for (int i = 0; i < len; i++) { if (Character.isUpperCase(name.charAt(i))) { capitalLetterIndex = i; break; } } if (capitalLetterIndex != -1) { name = name.substring(0, capitalLetterIndex) + "_" + name.substring(capitalLetterIndex); } return name.replace(".", "_").toUpperCase(); } public ItemStack build() { return result; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/inventory/ItemUtil.java ================================================ package me.realized.duels.util.inventory; import java.io.ByteArrayInputStream; import java.io.IOException; import org.bukkit.inventory.ItemStack; import org.bukkit.util.io.BukkitObjectInputStream; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; public final class ItemUtil { public static ItemStack itemFrom64(final String data) { try { final ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); try (final BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { return (ItemStack) dataInput.readObject(); } } catch (ClassNotFoundException | IOException ex) { ex.printStackTrace(); return null; } } private ItemUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/inventory/Slots.java ================================================ package me.realized.duels.util.inventory; import java.util.function.Consumer; public final class Slots { private Slots() {} public static void run(final int from, final int to, final int height, final Consumer action) { for (int h = 0; h < height; h++) { for (int slot = from; slot < to; slot++) { action.accept(slot + h * 9); } } } public static void run(final int from, final int to, final Consumer action) { for (int slot = from; slot < to; slot++) { action.accept(slot); } } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/io/FileUtil.java ================================================ package me.realized.duels.util.io; import java.io.File; import java.io.IOException; public final class FileUtil { public static boolean checkNonEmpty(final File file, final boolean create) throws IOException { if (!file.exists()) { if (create) { file.createNewFile(); } return false; } return file.length() > 0; } private FileUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/json/DefaultBasedDeserializer.java ================================================ package me.realized.duels.util.json; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.ResolvableDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; public abstract class DefaultBasedDeserializer extends StdDeserializer implements ResolvableDeserializer { private final Class target; protected final JsonDeserializer defaultDeserializer; public DefaultBasedDeserializer(final Class target, final JsonDeserializer defaultDeserializer) { super(target); this.target = target; this.defaultDeserializer = defaultDeserializer; } public Class getTarget() { return target; } @Override public void resolve(final DeserializationContext context) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(context); } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/json/JsonUtil.java ================================================ package me.realized.duels.util.json; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.core.util.Separators; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.module.SimpleModule; import java.lang.reflect.InvocationTargetException; import org.jetbrains.annotations.NotNull; public final class JsonUtil { private static final ObjectMapper OBJECT_MAPPER; private static final ObjectWriter OBJECT_WRITER; static { final JsonFactory factory = new JsonFactory(); factory.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); factory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); OBJECT_MAPPER = new ObjectMapper(factory); OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); OBJECT_MAPPER.setVisibility(PropertyAccessor.ALL, Visibility.NONE); OBJECT_MAPPER.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); OBJECT_WRITER = OBJECT_MAPPER.writer(buildDefaultPrettyPrinter()); } public static ObjectMapper getObjectMapper() { return OBJECT_MAPPER; } public static ObjectWriter getObjectWriter() { return OBJECT_WRITER; } public static void registerDeserializer(final Class type, final Class> deserializerClass) { final SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer modifyDeserializer(final DeserializationConfig config, final BeanDescription description, final JsonDeserializer deserializer) { if (description.getBeanClass().equals(type)) { try { return deserializerClass.getConstructor(JsonDeserializer.class).newInstance(deserializer); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { ex.printStackTrace(); return deserializer; } } return deserializer; } }); OBJECT_MAPPER.registerModule(module); } private static PrettyPrinter buildDefaultPrettyPrinter() { DefaultPrettyPrinter printer = new DefaultPrettyPrinter() { @Override public DefaultPrettyPrinter withSeparators(Separators separators) { _separators = separators; _objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " "; return this; } @NotNull @Override public DefaultPrettyPrinter createInstance() { return new DefaultPrettyPrinter(this); } }; printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); printer.indentObjectsWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); return printer; } private JsonUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/metadata/MetadataUtil.java ================================================ package me.realized.duels.util.metadata; import org.bukkit.entity.Entity; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; public final class MetadataUtil { private MetadataUtil() {} public static Object get(final Plugin plugin, final Entity entity, final String key) { return entity.getMetadata(key).stream().filter(value -> value.getOwningPlugin().equals(plugin)).findFirst().map(MetadataValue::value).orElse(null); } public static void put(final Plugin plugin, final Entity entity, final String key, final Object data) { entity.setMetadata(key, new FixedMetadataValue(plugin, data)); } public static void remove(final Plugin plugin, final Entity entity, final String key) { entity.removeMetadata(key, plugin); } public static Object removeAndGet(final Plugin plugin, final Entity entity, final String key) { final Object value = get(plugin, entity, key); remove(plugin, entity, key); return value; } } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/reflect/ReflectionUtil.java ================================================ package me.realized.duels.util.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import me.realized.duels.util.Log; import me.realized.duels.util.NumberUtil; import org.bukkit.Bukkit; public final class ReflectionUtil { private static final String PACKAGE_VERSION; private static final int MAJOR_VERSION; static { final String packageName = Bukkit.getServer().getClass().getPackage().getName(); PACKAGE_VERSION = packageName.substring(packageName.lastIndexOf('.') + 1); MAJOR_VERSION = NumberUtil.parseInt(PACKAGE_VERSION.split("_")[1]).orElse(0); } public static int getMajorVersion() { return MAJOR_VERSION; } public static Class getClassUnsafe(final String name) { try { return Class.forName(name); } catch (ClassNotFoundException ex) { return null; } } public static Method getMethodUnsafe(final Class clazz, final String name, final Class... parameters) { try { return clazz.getMethod(name, parameters); } catch (NoSuchMethodException ex) { return null; } } public static Class getNMSClass(final String name, final boolean logError) { try { return Class.forName("net.minecraft" + (getMajorVersion() < 17 ? (".server." + PACKAGE_VERSION) : "") + "." + name); } catch (ClassNotFoundException ex) { if (logError) { Log.error(ex.getMessage(), ex); } return null; } } public static Class getNMSClass(final String name) { return getNMSClass(name, true); } public static Class getCBClass(final String path, final boolean logError) { try { return Class.forName("org.bukkit.craftbukkit." + PACKAGE_VERSION + "." + path); } catch (ClassNotFoundException ex) { if (logError) { Log.error(ex.getMessage(), ex); } return null; } } public static Class getCBClass(final String path) { return getCBClass(path, true); } public static Method getMethod(final Class clazz, final String name, final Class... parameters) { try { return clazz.getMethod(name, parameters); } catch (NoSuchMethodException ex) { Log.error(ex.getMessage(), ex); return null; } } private static Method findDeclaredMethod(final Class clazz, final String name, final Class... parameters) throws NoSuchMethodException { final Method method = clazz.getDeclaredMethod(name, parameters); method.setAccessible(true); return method; } public static Method getDeclaredMethod(final Class clazz, final String name, final Class... parameters) { try { return findDeclaredMethod(clazz, name, parameters); } catch (NoSuchMethodException ex) { Log.error(ex.getMessage(), ex); return null; } } public static Method getDeclaredMethodUnsafe(final Class clazz, final String name, final Class... parameters) { try { return findDeclaredMethod(clazz, name, parameters); } catch (NoSuchMethodException ex) { return null; } } public static Field getField(final Class clazz, final String name) { try { return clazz.getField(name); } catch (NoSuchFieldException ex) { Log.error(ex.getMessage(), ex); return null; } } public static Field getDeclaredField(final Class clazz, final String name) { try { final Field field = clazz.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException ex) { Log.error(ex.getMessage(), ex); return null; } } public static Constructor getConstructor(final Class clazz, final Class... parameters) { try { return clazz.getConstructor(parameters); } catch (NoSuchMethodException ex) { Log.error(ex.getMessage(), ex); return null; } } private ReflectionUtil() {} } ================================================ FILE: duels-plugin/src/main/java/me/realized/duels/util/yaml/YamlUtil.java ================================================ package me.realized.duels.util.yaml; import org.bukkit.configuration.file.YamlConstructor; import org.bukkit.configuration.file.YamlRepresenter; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; public final class YamlUtil { private static transient final Yaml BUKKIT_YAML; private static transient final Yaml YAML; static { final DumperOptions options = new DumperOptions(); options.setIndent(2); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); final Representer yamlRepresenter = new YamlRepresenter(); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); BUKKIT_YAML = new Yaml(new YamlBukkitConstructor(), yamlRepresenter, options); YAML = new Yaml(options); } public static String yamlDump(final Object object) { return YAML.dump(object); } public static String bukkitYamlDump(final Object object) { return BUKKIT_YAML.dump(object); } public static T yamlLoad(final String yaml) { return YAML.load(yaml); } public static T bukkitYamlLoad(final String yaml) { return BUKKIT_YAML.load(yaml); } public static T yamlLoadAs(final String yaml, final Class type) { return YAML.loadAs(yaml, type); } public static T bukkitYamlLoadAs(final String yaml, final Class type) { return BUKKIT_YAML.loadAs(yaml, type); } private static class YamlBukkitConstructor extends YamlConstructor { public YamlBukkitConstructor() { this.yamlConstructors.put(new Tag(Tag.PREFIX + "org.bukkit.inventory.ItemStack"), yamlConstructors.get(Tag.MAP)); } } private YamlUtil() {} } ================================================ FILE: duels-plugin/src/main/resources/config.yml ================================================ # DO NOT EDIT THIS VALUE! config-version: 12 # If set to 'true', a notification and a download link will be printed on both console and in-game when a new update is available. # default: true check-for-updates: true # NOTE: The following options will only activate if the message '[Duels] Hooked into !' is displayed on console. # If the plugin in the following list is enabled on your server but Duels fails to hook into them, # please contact the developer with the errors displayed on console. supported-plugins: CombatTagPlus: # If set to 'true', players will not be able to duel while combat tagged. # default: true prevent-duel-if-tagged: true # If set to 'true', players will not be combat tagged while in duel. # default: true prevent-tag-in-duel: true PvPManager: # If set to 'true', players will not be able to duel while combat tagged. # default: true prevent-duel-if-tagged: true # If set to 'true', players will not be combat tagged while in duel. # default: true prevent-tag-in-duel: true CombatLogX: # If set to 'true', players will not be able to duel while combat tagged. # default: true prevent-duel-if-tagged: true # If set to 'true', players will not be combat tagged while in duel. # default: true prevent-tag-in-duel: true Essentials: # If set to 'true', players in vanish will be automatically unvanished at the start of a duel. # default: true auto-unvanish: true # If set to 'true', players will not be able to use '/back' to teleport back to the arena after dying in a duel. # default: true set-back-location: true mcMMO: # If set to 'true', usage of mcMMO skills and abilities will be prohibited while in a duel. # default: true disable-skills-in-duel: true FactionsUUID: # If set to 'true', players will experience no power loss when they die in a duel. # default: true no-power-loss-in-duel: true Factions: # If set to 'true', players will experience no power loss when they die in a duel. # default: true no-power-loss-in-duel: true WorldGuard: duelzone: # If set to 'true', players will be able to use duel only in the regions listed below. # default: false enabled: false # List of regions to allow dueling. regions: [spawn, lobby] MyPet: # If set to 'true', player's pet will despawn when entering a duel. # default: false despawn-pet-in-duel: false BountyHunters: # If set to 'true', player will not lose bounty even if they die in a duel. # default: true prevent-bounty-loss-in-duel: true SimpleClans: # If set to 'true', SimpleClans KDR will not be affected by duels. # default: true prevent-kdr-change: true LeaderHeads: wins: menu: # Menu title for the leaderboard 'duelsre-wins'. # default: 'Duel Wins' title: 'Duel Wins' # Menu open command for the leaderboard 'duelsre-wins'. # default: 'openwins' open-command: 'openwins' losses: menu: # Menu title for the leaderboard 'duelsre-losses'. # default: 'Duel Losses' title: 'Duel Losses' # Menu open command for the leaderboard 'duelsre-losses'. # default: 'openlosses' open-command: 'openlosses' request: # If set to 'true', players will need to have a cleared inventory in order to send or accept a duel request. # default: false requires-cleared-inventory: false # If set to 'true', players in creative mode will be prohibited from dueling. # default: false prevent-creative-mode: false use-own-inventory: # If set to 'true', players will be able to choose to enable or disable own inventory duel through the Request Settings GUI. # NOTE: If set to 'false', Kit Selector will first open instead of Request Settings GUI when initiating a duel request. # default: true enabled: true # If set to 'true', players will drop their inventory items on death in an own inventory duel. # WARNING: Players will NOT have their inventories restored after the duel if this option is enabled! # Increase 'teleport-delay' so that the winner has time to pick up dropped items. # default: false drop-inventory-items: false # If set to 'true', players without the permission 'duels.use.own-inventory' will not be able to enable own inventory option. # default: false use-permission: false kit-selecting: # If set to 'true', players will be able to choose a kit they wish to fight with through the Kit Selector GUI. # default: true enabled: true # If set to 'true', players without the permission 'duels.use.kit-select' will not be able to select a kit. # default: false use-permission: false arena-selecting: # If set to 'true', players will be able to choose an arena they wish to fight in through the Arena Selector GUI. # default: true enabled: true # If set to 'true', players without the permission 'duels.use.arena-select' will not be able to select an arena. # default: false use-permission: false item-betting: # If set to 'true', players will be able to choose to enable or disable item betting in the Request Settings GUI. # default: true enabled: true # If set to 'true', players without the permission 'duels.use.item-betting' will not be able to enable item betting. # default: false use-permission: false money-betting: # If set to 'true', players will be able to bet money on their duel by using the command '/duel [player] [bet amount]'. # default: true enabled: true # If set to 'true', players without the permission 'duels.use.money-betting' will not be able to bet money on their duel. # default: false use-permission: false # Request expiration, in seconds. # default: 30 expiration: 30 duel: match: # The max duration of a match, in minutes. Setting it to -1 will disable duration limit. # default: -1 max-duration: -1 start-commands: # If set to 'true', the commands listed below will run FOR EACH player at the start of a match. # default: false enabled: false # If set to 'true', start commands will run only for matches started through the queue system. # default: false queue-matches-only: false # Available placeholders: # %player% - Name of the player entering the match commands: - 'broadcast %player% is entering a duel!' end-commands: # If set to 'true', the commands listed below will run at the end of a match. # default: false enabled: false # If set to 'true', end commands will run only for matches started through the queue system. # default: false queue-matches-only: false # Available placeholders: # %winner% - Name of the winner of the match # %loser% - Name of the loser of the match commands: - 'give %winner% diamond 1' - 'give %loser% dirt 1' projectile-hit-message: # If set to 'true', a message from lang.yml will be sent to the shooter of the projectile. # default: true enabled: true # Projectile types to display the message. types: [ARROW, TIPPED_ARROW, SPECTRAL_ARROW, TRIDENT] # If set to 'true', players in duel will not be able to open any kind of inventories except their own. # default: true prevent-inventory-open: true # If set to 'true', the kit items will be attached a special NBT tag to identify an item generated by Duels. # This tag will be used to eliminate any possible uses of kit items outside of a duel through KitItemListener. # NOTE: Setting this option to 'false' only disables KitItemListener. The NBT tags will still be attached in case it is re-enabled. # default: true protect-kit-items: true # If set to 'true', the empty bottle will be automatically removed when a potion is consumed. # NOTE: Only active for players in a duel! # default: true remove-empty-bottle: true # If set to 'true', players will not be able to teleport to players in duel. # NOTE: This was implemented to patch an exploit regarding the '/tpa' command. Bypass permission - duels.teleport.bypass # default: true prevent-teleport-to-match-players: true # If set to 'true', players in the same faction/team/gang/party will be able to attack each other if they are in a duel. # default: true force-allow-combat: true # If set to 'true', players will be required to stay in the position where they have sent or accepted the request in order for the duel to start. # default: false cancel-if-moved: false # List of worlds to disable dueling. blacklisted-worlds: - 'world_name_here' # If set to 'true', players will be teleported to the location where they were before the duel instead of duel lobby. # default: false teleport-to-last-location: false # Seconds to wait before teleporting the winner after the duel. # default: 5 teleport-delay: 5 # If set to 'true', a firework will spawn at the winner's location when a duel ends. # default: true spawn-firework: true # If set to 'true', the duel end message will be sent only to the players in duel & spectators of the duel. # default: false arena-only-end-message: false # If set to 'true', players will be sent a clickable message that displays the inventories at the end of a duel. # default: true display-inventories: true # If set to 'true', players in duel will not be able to drop items. # default: false prevent-item-drop: false # If set to 'true', players in duel will not be able to pickup items on the ground. # default: false prevent-item-pickup: false limit-teleportation: # If set to 'true', teleportation while in duel will be limited to the distance specified below. # NOTE: Teleportation caused by an enderpearl is excluded from prevention. # default: true enabled: true # The max distance players can teleport while in a duel. '-1' to prevent all teleportation. # NOTE: If players are getting stuck, try increasing this value. # default: 5.0 distance-allowed: 5.0 # If set to 'true', only commands listed in 'whitelisted-commands' will be usable while in a duel. # default: false block-all-commands: false # List of commands to allow while in a duel. # NOTE: Only active if 'block-all-commands' is enabled! whitelisted-commands: - 'msg' - 'r' - 'w' - 'pm' - 'reply' - 'tell' - 'whisper' - 'list' - 'ban' - 'kick' - 'mute' - 'tempban' # List of commands to block while in a duel. # NOTE: Only active if 'block-all-commands' is disabled! blacklisted-commands: - 'heal' - 'eheal' - 'essentials:heal' - 'essentials:eheal' - 'kit' - 'ekit' - 'kits' - 'ekits' - 'essentials:kit' - 'essentials:ekit' - 'essentials:kits' - 'essentials:ekits' - 'enderchest' - 'echest' - 'eechest' - 'eenderchest' - 'endersee' - 'eendersee' - 'ec' - 'eec' - 'essentials:enderchest' - 'essentials:echest' - 'essentials:eechest' - 'essentials:eenderchest' - 'essentials:endersee' - 'essentials:eendersee' - 'essentials:ec' - 'essentials:eec' - 'tpaccept' - 'etpaccept' - 'tpyes' - 'etpyes' - 'essentials:tpaccept' - 'essentials:etpaccept' - 'essentials:tpyes' - 'essentials:etpyes' - 'tpahere' - 'etpahere' - 'essentials:tpahere' - 'essentials:etpahere' - 'back' - 'eback' - 'return' - 'ereturn' - 'essentials:back' - 'essentials:eback' - 'essentials:return' - 'essentials:ereturn' - 'sethome' - 'esethome' - 'createhome' - 'ecreatehome' - 'essentials:sethome' - 'essentials:esethome' - 'essentials:createhome' - 'essentials:ecreatehome' - 'spawn' - 'espawn' - 'essentials:spawn' - 'essentials:espawn' - 'vault' - 'chest' - 'pv' - 'playervaults' - 'playervaults:vault' - 'playervaults:chest' - 'playervaults:pv' - 'playervaults:playervaults' queue: # List of commands to block while in a queue. blacklisted-commands: [] rating: # If set to 'true', player's rating will change after match based on their opponent. # default: true enabled: true # "The K factor is a measure of how strong a match will impact the players’ ratings." # Source: https://metinmediamath.wordpress.com/2013/11/27/how-to-calculate-the-elo-rating-including-example/ # default: 32 k-factor: 32 # The default rating for all kits. # default: 1400 default-rating: 1400 # If set to 'true', only matches started through the queue system will modify the rating of the players. # default: false queue-matches-only: false spectate: # If set to 'true', players will be required to have a cleared inventory in order to start spectating. # default: false requires-cleared-inventory: false # If set to 'true', players will be in spectator gamemode while spectating. # default: false use-spectator-gamemode: false # If set to 'true', players spectating will receive invisibility effect. # NOTE: This option will not take effect if use-spectator-gamemode is set to true. # default: true add-invisibility-effect: true # List of commands to allow while spectating. whitelisted-commands: - 'msg' - 'r' - 'w' - 'pm' - 'reply' - 'tell' - 'whisper' - 'list' - 'ban' - 'kick' - 'mute' - 'tempban' countdown: # If set to 'true', a countdown will occur for the length of the messages list. # default: true enabled: true # Available placeholders: # %opponent% - Name of the opponent of the match # %opponent_rating% - Rating of the opponent # %kit% - Name of the kit used in this match. If players are using their own inventory, it will display 'none' # %arena% - Name of the arena used for this match. messages: - '&7Starting in &f5 &7seconds!' - '&7Starting in &f4 &7seconds!' - '&7Starting in &f3 &7seconds!' - '&7Starting in &f2 &7seconds!' - '&7Starting in &f1 &7second!' - '&7Now in a match against &f%opponent%&7(&a%opponent_rating%&7) with kit &3%kit% &7in arena &e%arena%&7.' # Titles to display along with the countdown. Must have the same size as the countdown list size. titles: - '&f&l5' - '&f&l4' - '&e&l3' - '&6&l2' - '&c&l1' - '&a&lGO!' prevent: # If set to 'true', movements will be cancelled while the countdown is ongoing. # default: true movement: true # If set to 'true', shooting projectiles (such as arrows/snowballs) will be blocked while the countdown is ongoing. # default: true launch-projectile: true # If set to 'true', attacking players will be prohibited while the countdown is ongoing. # default: true pvp: true # If set to 'true', block interaction will be cancelled while the countdown is ongoing. # default: true interact: true stats: # If set to 'true', kit ratings of a player will be displayed when the command '/duel stats' is executed. # default: true display-kit-ratings: true # If set to 'true', the nokit(own inventory) rating of a player will be displayed when the command '/duel stats' is executed. # default: false display-nokit-rating: false # If set to 'true', past matches of a player will be displayed when the command '/duel stats' is executed. # default: true display-past-matches: true # Max amount of matches to display & store in the userdata file. # default: 5 matches-to-display: 5 top: # /duel top update interval, in minutes. # default: 5 update-interval: 5 # Type and identifier of the data displayed in /duel top [wins|losses|kit]. displayed-replacers: wins: type: 'Wins' identifier: 'wins' losses: type: 'Losses' identifier: 'losses' kit: type: '%kit%' identifier: 'rating' no-kit: type: 'Own Inventory' identifier: 'rating' guis: kit-selector: # Amount of rows to display in one page of the kit selector GUI. # NOTE: Must be between 1 - 5! # default: 2 rows: 2 # Item used to fill empty spaces in the kit selector GUI. space-filler-item: type: STAINED_GLASS_PANE data: 0 arena-selector: # Amount of rows to display in one page of the arena selector GUI. # NOTE: Must be between 1 - 5! # default: 3 rows: 3 # Item used to fill empty spaces in the arena selector GUI. space-filler-item: type: STAINED_GLASS_PANE data: 0 settings: # Item used to fill empty spaces in the settings GUI. space-filler-item: type: STAINED_GLASS_PANE data: 0 queues: # Amount of rows to display in one page of the queues GUI. # NOTE: Must be between 1 - 5! # default: 2 rows: 2 # Item used to fill empty spaces in the queues GUI. space-filler-item: type: STAINED_GLASS_PANE data: 0 # If set to 'true', the type of the queue's displayed item will be its kit's displayed item type. # default: true inherit-kit-item-type: true soup: # Amount of hearts to regenerate on soup consume. # default: 3.5 hearts-to-regen: 3.5 # If set to 'true', the empty bowl will be automatically removed when a soup is consumed. # NOTE: Only active for players in a duel! # default: true remove-empty-bowl: true # If set to 'true', soup will not consume if player's health is already full. # NOTE: Only active for players in a duel! # default: true cancel-if-already-full: true # List of sound types: # 1.7.x - 1.8.x: https://jd.bukkit.org/org/bukkit/Sound.html # 1.9.x - 1.12.2+: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html sounds: # Remove this sound if your server version is above 1.8! countdown-ongoing-sound-1-8: type: NOTE_PIANO pitch: 0.95 volume: 1.0 trigger-messages: - '&7Starting in &f5 &7seconds!' - '&7Starting in &f4 &7seconds!' - '&7Starting in &f3 &7seconds!' - '&7Starting in &f2 &7seconds!' - '&7Starting in &f1 &7second!' # Remove this sound if your server version is 1.8! countdown-ongoing-sound-1-9: type: BLOCK_NOTE_PLING pitch: 0.95 volume: 1.0 trigger-messages: - '&7Starting in &f5 &7seconds!' - '&7Starting in &f4 &7seconds!' - '&7Starting in &f3 &7seconds!' - '&7Starting in &f2 &7seconds!' - '&7Starting in &f1 &7second!' # Remove this sound if your server version is above 1.8! countdown-end-sound-1-8: type: NOTE_PIANO pitch: 1.9 volume: 1.0 trigger-messages: - '&7Now in a match against &f%opponent%&7(&a%opponent_rating%&7) with kit &3%kit% &7in arena &e%arena%&7.' # Remove this sound if your server version is 1.8! countdown-end-sound-1-9: type: BLOCK_NOTE_PLING pitch: 1.9 volume: 1.0 trigger-messages: - '&7Now in a match against &f%opponent%&7(&a%opponent_rating%&7) with kit &3%kit% &7in arena &e%arena%&7.' ================================================ FILE: duels-plugin/src/main/resources/lang.yml ================================================ # DO NOT EDIT THIS VALUE! config-version: 11 # Define placeholders usable in any message below. # Example: Adding 'PREFIX: "[Cool]"' below and then putting '{PREFIX}' in a message will display '[Cool]' when the message is sent in game. STRINGS: PREFIX: '&9[Duels]' LINE: '&9&m------------------------------------&r' HALF_LINE: '&9&m----------------&r' FAIL_PREFIX: '&cFailed to start the match:' GENERAL: true: '&atrue' false: '&cfalse' enabled: '&aenabled' disabled: '&cdisabled' not-selected: 'Not Selected' random: 'Random' none: 'none' kit-selector: 'Kit Selector' arena-selector: 'Arena Selector' item-betting: 'Item Betting' betting: 'Betting' ERROR: no-permission: '{PREFIX} &cNope! You are lacking the following permission: ''%permission%''' data: load-failure: '{PREFIX} &cCould not load your duel stats. Please try re-logging.' not-loaded: '{PREFIX} &cUsers are still under load, please try again later.' not-found: '{PREFIX} &c%name% has no duel stats available.' top: no-data-available: '{PREFIX} &cThere were no data available.' player: not-found: '{PREFIX} &c%name% is not online.' no-longer-online: '{PREFIX} &cThat player is no longer online.' arena: not-found: '{PREFIX} &cNo arena exists with the name ''%name%''.' already-exists: '{PREFIX} &cAn arena named ''%name%'' already exists.' delete-failure: '{PREFIX} &cCannot delete an arena that is currently in use. Please disable it first using the command ''/duels toggle %name%''' invalid-position: '{PREFIX} &cPosition must be 1 or 2.' no-position-set: '{PREFIX} &cArena ''%name%'' have no positions set.' kit: not-found: '{PREFIX} &cNo kit exists with the name ''%name%''.' already-exists: '{PREFIX} &cA kit named ''%name%'' already exists.' empty-hand: '{PREFIX} &cYou must be holding an item to use this command.' duel: is-self: '{PREFIX} &cYou cannot duel yourself.' inventory-not-empty: '{PREFIX} &cYou must have a cleared inventory to use this command.' in-creative-mode: '{PREFIX} &cYou cannot duel in creative mode.' in-blacklisted-world: '{PREFIX} &cYou cannot duel in this world.' is-tagged: '{PREFIX} &cYou cannot duel while combat tagged.' not-in-duelzone: '{PREFIX} &cYou can only duel in the following regions: %regions%' requests-disabled: '{PREFIX} &c%name% is currently not accepting duel requests.' already-has-request: '{PREFIX} &cYou already have a request sent to %name%.' no-request: '{PREFIX} &cYou do not have a request from %name%.' already-in-match: sender: '{PREFIX} &cYou cannot do this while in a duel.' target: '{PREFIX} &c%name% is already in a duel.' already-in-queue: '{PREFIX} &cYou cannot do this while in a queue.' prevent-teleportation: '{PREFIX} &cCannot teleport to a player in a duel.' mode-unselected: '{PREFIX} &cYou must either choose a kit or enable own inventory mode.' mode-fixed: '{PREFIX} &cYou are not allowed to disable own inventory mode.' spectate: already-spectating: sender: '{PREFIX} &cYou cannot do this while in spectator mode.' target: '{PREFIX} &c%name% is in spectator mode.' not-in-match: '{PREFIX} &c%name% is not in a duel.' setting: disabled-option: '{PREFIX} &c%option% is currently disabled.' arena-not-applicable: '{PREFIX} &cYou cannot use kit %kit% on arena %arena%.' inventory-view: not-a-uuid: '{PREFIX} &c%input% is not a valid UUID.' not-found: '{PREFIX} &cNo inventory exists with the UUID ''%uuid%''.' queue: not-found: '{PREFIX} &cNo queue exists with kit %kit% and bet $%bet_amount%.' already-exists: '{PREFIX} &cA queue with kit ''%kit%'' and bet $%bet_amount% already exists.' already-in: '{PREFIX} &cYou are already in a queue!' not-in-queue: '{PREFIX} &cYou are not in a queue.' not-enough-money: '{PREFIX} &cYou need $%bet_amount% to join that queue.' no-queues-available: '{PREFIX} &cNo queues are available.' sign: not-a-sign: '{PREFIX} &cThe block you are looking at is not a sign!' not-found: '{PREFIX} &cThat sign is not a queue sign!' already-exists: '{PREFIX} &cThat sign is already a queue sign! To remove, use the command ''/duels delsign''' cancel-break: '{PREFIX} &cYou cannot break a queue sign manually! Please use the command ''/duels delsign''' sound: not-found: '{PREFIX} &cNo sound exists with the name ''%name%''.' command: invalid-sub-command: '{PREFIX} &c''%argument%'' is not a valid sub command. Please type ''/%command%'' for help.' invalid-option: '{PREFIX} &c''%option%'' is not a valid option. Available options are: %available_options%' invalid-action: '{PREFIX} &c''%action%'' is not a valid action. Available actions are: %available_actions%' not-enough-money: '{PREFIX} &cYou do not have enough money to bet!' lobby-save-failure: '{PREFIX} &cCould not save lobby location. Please check the console for more information.' name-not-alphanumeric: '{PREFIX} &c''%name%'' is not alphanumeric.' COMMAND: duel: usage: - '{LINE}' - '&f/%command% [player] &e- &7Sends a duel request to player.' - '&f/%command% [player] &e- &7Sends a duel request with a bet.' - '&f/%command% [accept | deny] [player] &e- &7Accepts or denies a duel request.' - '&f/%command% stats &e- &7Displays your duel stats.' - '&f/%command% toggle &e- &7Enable or disable receiving duel requests.' - '&f/%command% top [-|wins|losses|kit] &e- &7Displays top wins, losses, or rating for the kit.' - '{LINE}' request: send: sender: - '{LINE}' - '&7Duel request sent to &f%name%&7.' - '&6- &7Kit: &3%kit%' - '&7Own Inventory: &r%own_inventory%' - '&6- &7Arena: &e%arena%' - '&6- &7Bet: &6$%bet_amount%' - '&6- &7Item Betting: &r%item_betting%' - '{LINE}' receiver: - '{LINE}' - '&7Duel request received from &f%name%&7.' - '&6- &7Kit: &3%kit%' - '&7Own Inventory: &r%own_inventory%' - '&6- &7Arena: &e%arena%' - '&6- &7Bet: &6$%bet_amount%' - '&6- &7Item Betting: &r%item_betting%' clickable-text: info: text: '&7Click to ' hover-text: '' accept: text: '&a&l[ACCEPT] ' hover-text: '&7Click to &aaccept &7this request.' deny: text: '&c&l[DENY]' hover-text: '&7Click to &cdeny &7this request.' extra: text: '{LINE}' hover-text: '' accept: sender: '{PREFIX} &f%name% &7has accepted your duel request.' receiver: '{PREFIX} &7Accepted the duel request from &f%name%&7.' deny: sender: '{PREFIX} &7Your duel request to &f%name% &7was denied.' receiver: '{PREFIX} &7Denied the duel request from &f%name%&7.' stats: displayed: - '{LINE}' - '&7Stats of &f%name% &e-' - '&7Wins: &a%wins%' - '&7Losses: &c%losses%' - '&7W/L Ratio: &b%wl_ratio%' - '&7Requests: &r%requests_enabled%' # NOTE: Ratings will only display if either 'display-kit-ratings' or 'display-nokit-rating' is enabled in the configuration. rating: header: '&7Ratings &e-' format: '&f%type%&7: &b%rating%' footer: '' # NOTE: Past matches will only display if 'display-past-matches' is enabled in the configuration. match: header: '&7Recent Matches &e-' format: '&a%winner% &fvs &c%loser% &6[Hover Me!]' hover-text: - '&7Kit: &3%kit%' - '&7Duration: &a%duration%' - '&7Time: &f%time% ago' - '&7Health: &d%health%❤' footer: '{LINE}' toggle: enabled: '{PREFIX} &aYou are now receiving duel requests.' disabled: '{PREFIX} &cYou are no longer accepting duel requests.' top: next-update: '{PREFIX} &7Next update: &f%remaining%' header: '{HALF_LINE} &7Top &f10 &7%type% {HALF_LINE}' display-format: '&e%rank%. &f%name% &e- &f%score% &7%identifier%' footer: '{HALF_LINE} &7Top &f10 &7%type% {HALF_LINE}' duels: usage: - '{LINE}' - '&f/%command% help &e- &7Displays this page.' - '&f/%command% help arena &e- &7Displays a list of arena commands.' - '&f/%command% help kit &e- &7Displays a list of kit commands.' - '&f/%command% help queue &e- &7Displays a list of queue commands.' - '&f/%command% help sign &e- &7Displays a list of sign commands.' - '&f/%command% help user &e- &7Displays a list of user edit commands.' - '&f/%command% help extra &e- &7Displays a list of extra commands.' - '{LINE}' help: arena: - '{HALF_LINE} &fArena Commands {HALF_LINE}' - '&f/%command% create [name] &e- &7Creates an arena with given name.' - '&f/%command% set [name] [1|2] &e- &7Sets the teleport position of an arena.' - '&f/%command% delete [name] &e- &7Deletes an arena.' - '&f/%command% info [name] &e- &7Displays a list of information about the selected arena.' - '&f/%command% toggle [name] &e- &7Enables or disables an arena.' - '&f/%command% tp [name] <1|2> &e- &7Teleports to an arena.' - '&f/%command% list &e- &7Displays the list of all arenas.' - '{HALF_LINE} &fArena Commands {HALF_LINE}' kit: - '{HALF_LINE} &fKit Commands {HALF_LINE}' - '&f/%command% savekit <-o> [name] &e- &7Saves a kit with given name.' - '&f/%command% loadkit [name] &e- &7Loads the selected kit to your inventory.' - '&f/%command% deletekit [name] &e- &7Deletes a kit.' - '&f/%command% setitem [name] &e- &7Sets the displayed item for selected kit.' - '&f/%command% options [kit] &e- &7Opens the options gui for selected kit.' - '&f/%command% bind [kit] &e- &7Opens the arena bind gui for selected kit.' - '&f/%command% list &e- &7Displays the list of all kits.' - '{HALF_LINE} &fKit Commands {HALF_LINE}' queue: - '{HALF_LINE} &fQueue Sign Commands {HALF_LINE}' - '&f/%command% createqueue [bet] [-|kit] &e- &7Creates a queue with bet and kit.' - '&f/%command% deletequeue &e- &7Deletes the queue with bet and kit.' - '&f/%command% list &e- &7Displays a list of available queues.' - '{HALF_LINE} &fQueue Sign Commands {HALF_LINE}' sign: - '{HALF_LINE} &fQueue Sign Commands {HALF_LINE}' - '&f/%command% addsign [bet] [-|kit] &e- &7Creates a queue sign with bet and kit.' - '&f/%command% delsign &e- &7Deletes the queue sign you are looking at.' - '&f/%command% list &e- &7Displays a list of queue signs.' - '{HALF_LINE} &fQueue Sign Commands {HALF_LINE}' user: - '{HALF_LINE} &fUser Edit Commands {HALF_LINE}' - '&f/%command% setrating [name] [-|kit] [amount] &e- &7Sets player''s rating for kit.' - '&f/%command% edit [name] [add|remove|set] [wins|losses] [amount] &e- &7Edits player''s stats.' - '&f/%command% resetrating [name] [-|kit|all] &e- &7Resets all or specified kit''s rating for player.' - '&f/%command% reset [name] &e- &7Resets player''s stats.' - '{HALF_LINE} &fUser Edit Commands {HALF_LINE}' extra: - '{HALF_LINE} &fExtra Commands {HALF_LINE}' - '&f/%command% setlobby &e- &7Sets duel lobby location.' - '&f/%command% lobby &e- &7Teleports to duel lobby.' - '&f/%command% playsound [name] &e- &7Plays the selected sound if defined in config.' - '&f/%command% reload &e- &7Reloads the plugin or the specified module.' - '{HALF_LINE} &fExtra Commands {HALF_LINE}' create: '{PREFIX} &7Arena &e%name% &7was successfully created. To set spawnpoints for this arena, use the command &f/duels set %name% 1' delete: '{PREFIX} &7Arena &e%name% &7was successfully removed.' set: '{PREFIX} &7Set position &f%position% &7for arena &e%name% &7at &f%location%&7.' toggle: '{PREFIX} &7Arena &e%name% &7is now &r%state%&7.' teleport: '{PREFIX} &7You have been teleported to arena &e%name%&7''s position &f%position%&7.' save-kit: '{PREFIX} &7Kit &3%name% &7was successfully saved.' delete-kit: '{PREFIX} &7Kit &3%name% &7was successfully removed.' load-kit: '{PREFIX} &7Kit &3%name% &7was loaded in your inventory.' set-item: '{PREFIX} &7Kit &3%name%&7''s displayed item was changed to your held item.' create-queue: '{PREFIX} &7Created a queue with kit &3%kit% &7and bet &6$%bet_amount%&7.' delete-queue: '{PREFIX} &7Deleted a queue with kit &3%kit% &7and bet &6$%bet_amount%&7.' add-sign: '{PREFIX} &7Created queue sign at &f%location% &7with kit &3%kit% &7and bet &6$%bet_amount%&7.' del-sign: '{PREFIX} &7Deleted queue sign at &f%location% &7with kit &3%kit% &7and bet &6$%bet_amount%&7.' set-lobby: '{PREFIX} &7Duel lobby set at your current location.' lobby: '{PREFIX} &7You have been teleported to lobby!' edit: '{PREFIX} &7Following action has been executed for &f%name%&7: &f%action% %amount% %type%' set-rating: '{PREFIX} &f%name%&7''s rating for kit &3%kit% &7was set to &a%rating%&7.' reset-rating: '{PREFIX} &7Reset &f%name%&7''s rating for kit &3%kit%&7.' reset: '{PREFIX} &7Reset &f%name%&7''s stats.' info: - '{HALF_LINE} &7Arena &e%name% {HALF_LINE}' - '&7In Use: &r%in_use%' - '&7Disabled: &r%disabled%' - '&7Bound Kits: &3%kits%' - '&7Positions: &f%positions%' - '&7Players: &f%players%' - '{HALF_LINE} &7Arena &e%name% {HALF_LINE}' list: - '{LINE}' - '&4DARK RED&7: Disabled arena' - '&9BLUE&7: Arena without spawn positions set' - '&aGREEN&7: Available arena' - '&cRED&7: Arena in use' - '&7Arenas: &r%arenas%' - '&7Kits: &f%kits%' - '&7Queues: &b%queues%' - '&7Queue Signs: &f%queue_signs%' - '&7Duel lobby is located at &f%lobby%&7.' - '{LINE}' spectate: usage: - '{LINE}' - '&f/spectate [player] &e- &7Spectates the a player in duel.' - '{LINE}' start-spectate: '{PREFIX} &7Now spectating &f%name%&7 vs &f%opponent%&7 in arena &e%arena%&7. Type &f/spectate &7to stop spectating.' stop-spectate: '{PREFIX} &7You are no longer spectating &f%name%&7.' sub-command-usage: '{PREFIX} &f/%command% %usage% &e- &7%description%' DUEL: start-failure: mode-unselected: '{FAIL_PREFIX} &cYou must either choose a kit or enable own inventory.' player-is-dead: '{FAIL_PREFIX} You or your opponent is not alive!' in-blacklisted-world: '{FAIL_PREFIX} You or your opponent is in a blacklisted world!' is-tagged: '{FAIL_PREFIX} You or your opponent is in combat!' player-moved: '{FAIL_PREFIX} You or your opponent moved after sending/accepting the request!' not-in-duelzone: '{FAIL_PREFIX} You or your opponent moved out of the duelzone sending/accepting the request!' in-creative-mode: '{FAIL_PREFIX} You or your opponent is in creative mode!' no-arena-available: '{FAIL_PREFIX} No arenas are currently available. Please try again later.' arena-in-use: '{FAIL_PREFIX} That arena is already in use. Please select a different arena.' arena-not-applicable: '{FAIL_PREFIX} You cannot use kit %kit% on this arena.' not-enough-money: '{FAIL_PREFIX} You or your opponent does not have $%bet_amount%.' prevent: item-drop: '&cYou cannot drop items while in a duel.' command: '&cYou cannot use ''%command%'' while in a duel.' teleportation: '&cYou cannot teleport while in a duel.' inventory-open: '&cYou cannot open inventories while in a duel.' projectile-hit-message: '{PREFIX} &f%name% &7is now at &d%health%❤&7!' on-end: tie: '{PREFIX} &7Tie Game!' plugin-disable: '{PREFIX} &cPlugin is disabling! Ending match automatically.' opponent-defeat: '{PREFIX} &f%winner% &a(%winner_rating%) (+%change%) &7has defeated &f%loser% &c(%loser_rating%) (-%change%) &7on kit &3%kit% &7with &d%health%❤' inventories: message: '&7Inventories (click on the name to view): ' name-color: '&b' reward: money: message: '{PREFIX} &7You have received &6$%money% &7for winning against &f%name%&7!' title: '&eYOU WON &6$%money%&e!' items: message: '{PREFIX} &7You have received &f%name%&7''s items for winning!' QUEUE: prevent: command: '&cYou cannot use ''%command%'' while in a queue.' add: '{PREFIX} &7You have been added to the queue for kit &3%kit% &7and bet &6$%bet_amount%&7. Click the sign again or type &f/queue leave &7to leave the queue.' remove: '{PREFIX} &7You have been removed from the queue.' found-opponent: '{PREFIX} &7Opponent found: &f%name%&7! Starting match with kit &3%kit% &7and a bet of &6$%bet_amount%&7...' SIGN: format: - '&a[Click to Join]' - '&3%kit%&f:&e$%bet_amount%' - '&f&l%in_queue% IN QUEUE' - '&f&l%in_match% IN MATCH' SPECTATE: arena-broadcast: '{PREFIX} &f%name% &7is now spectating the match!' match-end: '{PREFIX} &7The match you were spectating has ended.' prevent: command: '&cYou cannot use ''%command%'' while in spectator mode.' teleportation: '&cYou cannot teleport while in spectator mode.' GUI: settings: title: 'Request Settings' buttons: details: name: '&9Request Details' lore: - '&7Opponent: &f%opponent%' - '&7Kit: &3%kit%' - '&7Own Inventory: &r%own_inventory%' - '&7Arena: &e%arena%' - '&7Bet Items: &r%item_betting%' - '&7Bet: &6$%bet_amount%' - ' ' - '&7To change the bet' - '&7amount, please type' - '&b/duel %opponent% [amount]' kit-selector: name: '&9Kit Selection' lore: - '&7Selected Kit: &3%kit%' - ' ' - '&aClick to Change Kit!' lore-no-permission: - '&cYou do not have permission to' - '&cuse this option.' use-own-inventory: name: '&9Use Own Inventory' lore: - '&7Own Inventory: &r%own_inventory%' - ' ' - '&aClick to Toggle Own Inventory!' lore-no-permission: - '&cYou do not have permission to' - '&cuse this option.' arena-selector: name: '&9Arena Selection' lore: - '&7Selected Arena: &e%arena%' - ' ' - '&aClick to Change Arena!' lore-no-permission: - '&cYou do not have permission to' - '&cuse this option.' item-betting: name: '&9Allow Betting Items' lore: - '&7Item Betting: &r%item_betting%' - ' ' - '&aClick to Toggle Item Betting!' lore-no-permission: - '&cYou do not have permission to' - '&cuse this option.' send: name: '&a&lSEND REQUEST' cancel: name: '&c&lCANCEL' kit-selector: title: 'Kit Selection' buttons: previous-page: name: '&aPrevious Page' next-page: name: '&aNext Page' empty: name: '&cThis page is empty.' arena-selector: title: 'Arena Selection' buttons: arena: name: '&e%name%' lore-available: - '&aAvailable' lore-unavailable: - '&cUnavailable' previous-page: name: '&aPrevious Page' next-page: name: '&aNext Page' empty: name: '&cThis page is empty.' queues: title: 'Available Queues' buttons: queue: name: '&3%kit%' lore: - '&7Bet: &6$%bet_amount%' - '&7In Queue: &f%in_queue%' - '&7In Match: &f%in_match%' - ' ' - '&a&lClick to Queue!' previous-page: name: '&aPrevious Page' next-page: name: '&aNext Page' empty: name: '&cThis page is empty.' item-betting: title: 'Winner Takes All!' buttons: head: name: '&e%name%' state: name-ready: '&a&lREADY' name-not-ready: '&7&lNOT READY' details: name: '&9Match Details' lore: - '&7Kit: &3%kit%' - '&7Arena: &e%arena%' - '&7Bet: &6$%bet_amount%' cancel: name: '&c&lCLICK TO CANCEL' lore: - '&7Click or close inventory' - '&7to cancel the match.' inventory-view: title: '&e%name%' buttons: head: name: '&e%name%' potion-counter: name: '&d%potions% Health Potions' effects: name: '&bPotion Effects' lore-format: '&7%type% %amplifier% (%duration%s)' hunger: name: '&6%hunger% bars' health: name: '&c%health% ❤' options: title: 'Kit: %kit%' buttons: option: name: '&b%name%' lore: - ' ' - '&7Status: &r%state%' - ' ' - '&r&lCLICK TO TOGGLE' bind: title: 'Kit: %kit%' buttons: arena: name: '&e%arena%' lore-bound: - '&7Bound Kits: &3%kits%' - ' ' - '&a&lBOUND' - ' ' - '&r&lCLICK TO TOGGLE' lore-not-bound: - '&7Bound Kits: &3%kits%' - ' ' - '&c&lNOT BOUND' - ' ' - '&r&lCLICK TO TOGGLE' ================================================ FILE: duels-plugin/src/main/resources/plugin.yml ================================================ name: Duels main: me.realized.duels.DuelsPlugin version: @VERSION@ softdepend: [BountyHunters, CombatLogX, CombatTagPlus, Essentials, Factions, LeaderHeads, mcMMO, MVdWPlaceholderAPI, MyPet, PlaceholderAPI, PvPManager, SimpleClans, Vault, WorldGuard, Multiverse-Core] # Multiverse-Core added as soft-depend due to locations being null when Duels is loaded first. # Add any world management plugins to softdepend list if arena doesn't load properly in the generated world. api-version: 1.14 author: Realized website: https://www.spigotmc.org/resources/duels.20171/ description: An ultimate solution to server owners wanting to create a duel system. commands: duel: description: Send, accept, or deny a duel request. aliases: [1v1] queue: description: Join or leave a queue. aliases: [q] spectate: description: Spectate a duel. aliases: [spec] duels: description: Administrative command of Duels. aliases: [ds] permissions: duels.*: children: duels.admin: true duels.admin: children: duels.default: true duels.stats.others: true duels.kits.*: true duels.teleport.bypass: true duels.spectate: true duels.spectate.anonymously: true duels.use.*: true duels.queue: true duels.default: children: duels.duel: true duels.stats: true duels.toggle: true duels.top: true duels.duel: default: true ================================================ FILE: duels-worldguard/build.gradle ================================================ dependencies { api 'org.spigotmc:spigot-api:1.14.4-R0.1-SNAPSHOT' } ================================================ FILE: duels-worldguard/src/main/java/me/realized/duels/hook/hooks/worldguard/WorldGuardHandler.java ================================================ package me.realized.duels.hook.hooks.worldguard; import java.util.Collection; import org.bukkit.entity.Player; public interface WorldGuardHandler { String findRegion(final Player player, final Collection regions); } ================================================ FILE: duels-worldguard-v6/build.gradle ================================================ dependencies { implementation ('com.sk89q:worldguard:6.1.1-SNAPSHOT') { exclude group: 'org.bukkit', module: 'bukkit' } implementation project(':duels-worldguard') } ================================================ FILE: duels-worldguard-v6/src/main/java/me/realized/duels/hook/hooks/worldguard/WorldGuard6Handler.java ================================================ package me.realized.duels.hook.hooks.worldguard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.Collection; import org.bukkit.entity.Player; public class WorldGuard6Handler implements WorldGuardHandler { @Override public String findRegion(final Player player, final Collection regions) { for (final ProtectedRegion region : WorldGuardPlugin.inst().getRegionManager(player.getWorld()).getApplicableRegions(player.getLocation())) { if (regions.contains(region.getId())) { return region.getId(); } } return null; } } ================================================ FILE: duels-worldguard-v7/build.gradle ================================================ dependencies { implementation ('com.sk89q.worldguard:worldguard-bukkit:7.0.0') { exclude group: 'org.bukkit', module: 'bukkit' } implementation project(':duels-worldguard') } ================================================ FILE: duels-worldguard-v7/src/main/java/me/realized/duels/hook/hooks/worldguard/WorldGuard7Handler.java ================================================ package me.realized.duels.hook.hooks.worldguard; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.Collection; import org.bukkit.Location; import org.bukkit.entity.Player; public class WorldGuard7Handler implements WorldGuardHandler { @Override public String findRegion(final Player player, final Collection regions) { final Location location = player.getLocation(); final BlockVector3 vector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); for (final ProtectedRegion region : WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(player.getWorld())) .getApplicableRegions(vector)) { if (regions.contains(region.getId())) { return region.getId(); } } return null; } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Sat Dec 25 01:36:54 KST 2021 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ rootProject.name = 'Duels' include 'duels-worldguard' include 'duels-worldguard-v6' include 'duels-worldguard-v7' include 'duels-api' include 'duels-plugin'