Compare commits

..
63 Commits
Author SHA1 Message Date
NotAlexNoyle 97205b5c8a Point submodules at canonical Gitea repositories 2026-11-01 12:50:58 -05:00
NotAlexNoyle 85f2c48eec Update canonical Gitea links 2026-10-29 09:17:23 -04:00
NotAlexNoyle 18409233ba Exclude CODEOWNERS from language statistics 2026-10-28 15:32:11 -04:00
NotAlexNoyle 9200aa1ed7 Add CODEOWNERS (one staff approval) 2026-10-28 15:32:10 -04:00
NotAlexNoyle f411be36ae Update BkCommonLib API 2026-10-18 15:01:49 -04:00
NotAlexNoyle 33f61a7e9d Update dependencies 2026-10-18 13:10:20 -04:00
NotAlexNoyle 2baf35e35b Store only creative inventories per MyWorlds group and leave survival to MyWorlds 2026-10-02 11:51:32 -04:00
NotAlexNoyleandClaude Fable 5 2dc348ff18 Two-line kts and config comments, refresh README
License headers unchanged. Convert build script banners to // form,
trim config comments to two lines, document commands and permissions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 16:17:04 -04:00
NotAlexNoyle 3f6d7bbca2 Fix logic 2026-08-17 10:44:08 -04:00
NotAlexNoyle 2c09c3a6ea Fix region crossing 2026-08-12 07:08:22 -04:00
NotAlexNoyleandClaude Fable 5 d9b4dc94bb Trust pre-validated internal gamemode switches
The LOWEST listener cancelled every disallowed creative switch, including
plugin-driven ones flagged internal, contradicting the comments claiming
internal switches skip the cancel. /gmic and the published policy's
changeGameMode now pre-validate against GameModePolicy before switching,
and the listener trusts internal switches so an authority-approved
restore (Spawn-OG /spawnback) can no longer be self-cancelled.
changeGameMode returns whether the switch stuck.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 08:46:23 -04:00
NotAlexNoyle 4918fa4d3a Fix spawn rules 2026-08-08 10:39:54 -04:00
NotAlexNoyle 9b5bceceed Fix experience rewards with VotingPlugin 2026-08-03 09:27:56 -04:00
NotAlexNoyleandClaude Opus 5 970caf7eaf Require the toggle permission for creative, not just a region
Being inside a creative region was licence enough, so an ordinary player
who reached creative by any other route kept it there. Creative now needs
gamemodeinventories.toggle as well: the permission says who, the region
says where. gamemodeinventories.anywhere still ignores both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 23:48:45 -04:00
NotAlexNoyleandClaude Opus 5 bdc47e5cd0 Refuse adventure in survival worlds, drop the config defaults map
Adventure was the one gamemode nothing corrected: the policy never
sanctioned it, but no enforcement point acted on that, so it stuck until
the player's next login. onGameModeChange now cancels it in the worlds
listed under restrict_adventure_worlds. Minigame worlds stay off that list
because BuildBattle-OG, Duels-OG, and Spleef-OG put their players in
adventure deliberately.

config.yml is the only description of what this plugin reads. The defaults
map was a second copy of that list in code, kept in step by hand, so the
bundled config.yml is now the schema the deployed one is checked against.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 23:40:08 -04:00
NotAlexNoyleandClaude Opus 5 5ded3f116b Publish GameModePolicy as the single gamemode authority
Region and permission rules were duplicated between this plugin's listener
and every consumer that needed the same answer. GameModePolicy now owns
them, the listener delegates, and the policy is registered with the Bukkit
services manager so other plugins enforce the same rule.

Login is deferred to Spawn-OG when it is installed: it normalizes gamemode
inside a safety transaction that also relocates the player, and forcing
survival underneath it raced that transaction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 08:39:45 -04:00
NotAlexNoyle a642dea54c Add GameModeInventories.anywhere permission, enhance region messages and region switching behavior 2026-07-27 12:02:06 -04:00
NotAlexNoyle e9dc7932f8 New messages, drop ChatColor API 2026-07-27 11:46:47 -04:00
NotAlexNoyle 9913afdc1a Merge pull request #4 from true-og/agent/restrict-creative-to-worldguard-regions
Restrict creative mode to configured WorldGuard regions
2026-07-24 13:25:30 -04:00
NotAlexNoyle 34bab1ea1a Restrict creative mode to configured regions 2026-07-24 13:20:59 -04:00
NotAlexNoyle ae276e6d26 Configure allowed creative regions 2026-07-24 13:20:15 -04:00
NotAlexNoyle ff5aa3f647 Translate configured color codes 2026-07-24 13:19:55 -04:00
NotAlexNoyle 372b8fb087 Declare WorldGuard creative-region permission 2026-07-24 13:19:35 -04:00
NotAlexNoyle e8bd88e66f Add WorldGuard API dependency 2026-07-24 13:19:25 -04:00
NotAlexNoyle fa561678f6 Spotless formatting 2026-07-24 12:47:49 -04:00
NotAlexNoyle fccc2a224c Merge pull request #3 from true-og/agent/add-gmic-command
Add /gmic creative mode toggle
2026-07-24 12:40:54 -04:00
NotAlexNoyle 12f41844b4 Preserve plugin metadata 2026-07-24 12:39:26 -04:00
NotAlexNoyle 79bab7f408 Implement gmic creative mode toggle 2026-07-24 12:38:56 -04:00
NotAlexNoyle 83db2dfa6a Add gmic command alias and permission 2026-07-24 12:38:19 -04:00
NotAlexNoyle be3a5d5a29 Fix SLF4J once and for all 2026-04-24 11:13:23 -04:00
NotAlexNoyle 316d9466ca Fix SLF4J order 2026-04-24 08:50:26 -04:00
NotAlexNoyle 6b0180912f Fix SLF4J noop warnings 2026-04-23 14:03:57 -04:00
NotAlexNoyle ad9ec1edb8 Fix SLF4J binding 2026-04-23 12:04:39 -04:00
NotAlexNoyle 90f8991290 Release GameModeInventories-OG 2026-04-16 15:02:12 -04:00
NotAlexNoyle 820fdcaacf Copy config file to plugins folder if it does not exist 2026-03-25 10:58:15 -04:00
NotAlexNoyle 170cb092dd Merge pull request #2 from true-og/codex/fix-config-file-reading-and-remove-writing
Load canonical read-only config.yml and stop automatic writes
2026-03-24 11:31:48 -04:00
NotAlexNoyle 92284c7520 Fix config loading to be read-only and file-backed 2026-03-24 11:31:07 -04:00
NotAlexNoyle 04b9c8e839 Formatting 2026-03-23 14:36:28 -04:00
NotAlexNoyle 1386f51859 Merge pull request #1 from true-og/codex/remove-config.yml-modifications
Stop mutating config.yml at runtime
2026-03-23 14:20:56 -04:00
NotAlexNoyle 06e23cf789 Stop mutating config.yml at runtime 2026-03-23 14:20:25 -04:00
NotAlexNoyle 724f01ad74 Add live TrueOG Network config files, update shadow to 8.3.9 2026-03-23 13:54:49 -04:00
NotAlexNoyle bc0a89526e Update gradle to 8.14.3 and shadow to 8.3.6 2025-09-21 08:45:20 -04:00
NotAlexNoyle 232745c824 Maven -> Gradle 2025-07-04 04:17:07 -04:00
NotAlexNoyle 3a360d9dfe Fix build 2024-12-11 07:41:32 -05:00
Eccentric Devotion f124b280ba Merge pull request #18 from NotAlexNoyle/proposal
Propose GPLv3 at project root
2023-01-20 18:21:11 +13:00
NotAlexNoyle 6f491fd750 Propose GPLv3 at project root 2023-01-19 15:56:45 -05:00
Eccentric Devotion c29bc82a1d Update pom.xml 2022-12-11 15:54:06 +13:00
Eccentric Devotion ec13c22624 Update LogBlock dependency 2022-10-07 14:28:40 +13:00
Eccentric Devotion d32560c2eb Bump version number to 3.4.3 2022-07-02 20:08:52 +12:00
BuildTools ee0679e478 Update for 1.19, remove apache.commons usage 2022-06-16 09:10:00 +12:00
Eccentric Devotion 11de141061 #17 If player head is missing an owner profile, set the skull meta to null 2022-04-25 09:31:46 +12:00
Eccentric Devotion 812204ac2e Bump version to 3.4.2 2022-04-25 09:30:36 +12:00
Eccentric Devotion 87b9b04669 Update CoreProtect.jar 2022-04-25 09:30:10 +12:00
Eccentric Devotion 482e94f573 #16 Only process chunks in enabled worlds 2022-04-12 22:50:38 +12:00
Eccentric Devotion 0ee3fcb8d5 #16 Only create a block list and cache it if there are saved blocks 2022-04-12 22:50:28 +12:00
Eccentric Devotion 38b9b896f8 Remove these as they're not dependencies... 2022-04-11 12:31:48 +12:00
Eccentric Devotion f76aae8852 Use HikariCP for all connections 2022-04-11 12:25:06 +12:00
Eccentric Devotion 0559a042d0 Bump version to 3.4.1, update some dependencies, stop shading libraries 2022-04-11 11:25:43 +12:00
Eccentric Devotion 7dce5b9f25 Use the server logger for console messages 2022-04-11 11:24:48 +12:00
Eccentric Devotion f733358848 Use try-with-resources for SQL queries 2022-04-11 10:56:35 +12:00
Eccentric Devotion e59a752f5f Update Spigot to 1.18-R0.1-SNAPSHOT 2021-12-11 16:37:16 +13:00
Eccentric Devotion cab71e2490 Update dependencies 2021-12-06 13:46:59 +13:00
Eccentric Devotion 6f30fddb4a Merge pull request #14 from eccentricdevotion/v3.0
1.18 update
2021-12-06 13:31:08 +13:00
73 changed files with 6713 additions and 3205 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.gitea/CODEOWNERS linguist-detectable=false
+3
View File
@@ -0,0 +1,3 @@
# Pull requests request review from the eligible staff team(s).
# One approval from either an Admin or Developer satisfies branch protection.
* @trueog/Admins @trueog/Developers
+36 -25
View File
@@ -1,32 +1,43 @@
/target
!/target/GameModeInventories.jar
# Compiled class file
*.class
# osx noise
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# macOS system files
.DS_Store
profile
# xcode noise
build/*
*.mode1
*.mode1v3
*.mode2v3
*.perspective
*.perspectivev3
*.pbxuser
*.xcworkspace
xcuserdata
# gradle build output files
build/
.gradle/
# svn & cvs
.svn
CVS
# other stuff
.classpath
# eclipse project files
.settings/
.project
.settings
nb-configuration.xml
.classpath
bin/
# IntelliJ files
.idea/
/target/
*.iml
*.iml
# Vendored compile-only APIs under libs/ are tracked on purpose.
!libs/*/*.jar
+6
View File
@@ -0,0 +1,6 @@
[submodule "libs/MyWorlds"]
path = libs/MyWorlds
url = https://git.trueog.net/trueog/MyWorlds
[submodule "libs/Utilities-OG"]
path = libs/Utilities-OG
url = https://git.trueog.net/trueog/Utilities-OG
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+37 -18
View File
@@ -1,29 +1,48 @@
## GameModeInventories
A CraftBukkit plugin for Minecraft Server.
## GameModeInventories-OG
Allow players to have separate inventories for each game mode (Creative, Survival and Adventure).
This plugin (and the GMIDatabaseConverter plugin) are available for download as a single ZIP file from the [GameModeInventories page on BukkitDev](http://dev.bukkit.org/bukkit-plugins/gamemodeinventories).
This is a [TrueOG Network](https://trueog.net) maintained soft fork of [eccentricdevotion/GameModeInventories](https://github.com/eccentricdevotion/GameModeInventories).
### Warning
### Changes from Upstream
This version of GameModeInventories uses a different storage format when saving inventories. Before installing this version, you should first run the [GMIDatabaseConverter](https://github.com/eccentricdevotion/GMIDatabaseConverter/blob/master/README.md) plugin on your CraftBukkit 1.6.4 server to update your GameModeInventories database.
- Build system migrated from Maven to Gradle (Kotlin DSL), Gradle 8.14.3, Shadow 8.3.9, Spotless with TrueOG Network's eclipse-based Java Formatting.
- `config.yml` is read-only at runtime — the plugin no longer mutates or rewrites it. A default `config.yml` is copied into the plugin folder on first run if missing.
- Compatible with [NoClip-OG](https://git.trueog.net/trueog/NoClip-OG) (1.3.0+). When `restrict_spectator` is enabled, players holding the `noclip.use` permission are exempt from the restriction so NoClip's creative/spectator toggle works without being cancelled or spamming chat.
- Creative is staff only: it needs `gamemodeinventories.toggle` *and* a region in `creative_regions`, or `gamemodeinventories.anywhere` to ignore both. Spectator needs `gamemodeinventories.spectator` or `noclip.use`. Adventure is refused in `restrict_adventure_worlds`.
- Gamemode rules live in one place, `api/GameModePolicy`, which every enforcement point in the plugin asks. It is published for other plugins so they enforce the same rule instead of reimplementing it: fetch it from the Bukkit services manager, or reflectively via `GameModeInventories#getGameModePolicy()`. `mayUse(player, gameMode, location)` answers for any gamemode; survival is always allowed, adventure never is.
- Creative is enforced on movement and teleports, judged at the destination, and unsanctioned creative is forced back to survival with one-time fall protection. Gamemode switches pre-validated through the policy (`internalGameModeChange`) are trusted rather than policed a second time.
- Login is deferred to [Spawn-OG](https://git.trueog.net/trueog/Spawn-OG) when it is installed. It normalizes gamemode inside a safety transaction that also relocates the player, so forcing survival underneath it would race that transaction. Spawn-OG also uses the policy and `internalGameModeChange` to hand creative or spectator back after a rescue or `/spawnback` return. Without Spawn-OG, GameModeInventories-OG still forces survival on join for creative players outside a creative region.
- Only the **creative** inventory is stored here, one per bundle (a bundle is a MyWorlds inventory group, so world/world_nether/world_the_end share one). The **survival** inventory is owned by MyWorlds in Purpur's RocksDB, so no inventory is ever stored in two places and the two stores cannot diverge. On the creative boundary GMI saves the outgoing creative inventory at `LOW` and loads the incoming one at `HIGH`, so MyWorlds (which saves/restores survival at the same priorities) always captures the outgoing inventory before the incoming one is loaded. Creative follows the bundle on a world change too (saved for the world left, loaded for the world entered via `PlayerProfileAppliedEvent`), and is persisted on quit, shutdown and login. `(uuid, gamemode, bundle)` is unique, and a failed creative swap or legacy bundle assignment refuses (kick or no enable) rather than hand out a wrong inventory. Spectator and adventure are transient (not persisted). Death inventories are parked in a `deaths` table, keyed by bundle and game mode, and are added back (never overwriting what the player holds) when they are next in that bundle and mode; if parking fails the normal drops are kept. Without MyWorlds the bundle is the world name and players are switched to survival before a cross-world teleport.
- Dropped LogBlock integration. Block-removal logging now runs exclusively through CoreProtect / CoreProtect-OG.
- Targets Purpur API 1.19.4 (Java 17, GraalVM toolchain).
### How do I update my GMI database?
### Commands
**_Before_** upgrading your server to CraftBukkit 1.7.x and installing GameModeInventories version 2.x, you should run GMIDatabaseConverter on your **1.6.4** server.
| Command | Description | Permission |
| --- | --- | --- |
| `/gmi [option]` (alias `/gmic`) | Toggle creative mode, or change config options | `gamemodeinventories.toggle` / `gamemodeinventories.anywhere` to toggle; `gamemodeinventories.admin` for config |
1. Install GMIDatabaseConverter.jar to the server's plugins folder
2. Start the server
* The plugin will attempt to find and backup your old GameModeInventories database file
* It will then read the existing inventory data
* The existing data will be converted to the new format
* The new data will be written back to the database
3. Once conversion is complete, you can update your GameModeInventories plugin to version 2.x and restart the server
4. If you are satisfied that GameModeInventories version 2.x is functioning correctly, you can safely remove GMIDatabaseConverter
### Permissions
- `gamemodeinventories.use` - Separate per-gamemode inventories (default: true)
- `gamemodeinventories.toggle` - Toggle creative via `/gmic` inside a `creative_regions` region (default: op)
- `gamemodeinventories.anywhere` - Hold and toggle creative anywhere, exempt from forced survival (default: op)
- `gamemodeinventories.spectator` - Hold spectator mode (default: op)
- `gamemodeinventories.death` - Keep separate death handling (default: op)
- `gamemodeinventories.bypass` - Bypass restrictions enabled under `bypass` in the config (default: op)
- `gamemodeinventories.admin` - Change config options via `/gmi` (default: op)
### Why did you change the storage format?
### Compilation and Build
The format change is a result of code changes removing the reliance on using net.minecraft.server and org.craftbukkit code directly within the plugin (instead of using only the Bukkit API). This led to the plugin breaking with every Minecraft/CraftBukkit update. These code changes mean the plugin should no longer break between versions.
This project uses Gradle. To build the plugin:
```bash
./gradlew build
```
This produces the plugin jar in the `build/libs` directory. It is normally built as a submodule of Spawn-OG, which compiles against its API.
### License
GPL v3 or later. Inventory serialization derives from work by eccentric_nz, drtshock, and Kristian S. Stangeland (aadnk); the bundled `JSON` package is JSON.org code under its own license.
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/bash
# Fetch all submodule content.
git submodule update --force --recursive --init
+117
View File
@@ -0,0 +1,117 @@
// ------------------------------ Plugins ------------------------------
plugins {
id("java") // Import Java plugin.
id("java-library") // Import Java Library plugin.
id("com.diffplug.spotless") version "8.1.0" // Import Spotless plugin.
id("com.gradleup.shadow") version "8.3.9" // Import Shadow plugin.
id("checkstyle") // Import Checkstyle plugin.
eclipse // Import Eclipse plugin.
}
// --------------------------- JDK / Kotlin ----------------------------
java {
sourceCompatibility = JavaVersion.VERSION_17 // Compile with JDK 17 compatibility.
toolchain { // Select Java toolchain.
languageVersion.set(JavaLanguageVersion.of(17)) // Use JDK 17.
vendor.set(JvmVendorSpec.GRAAL_VM) // Use GraalVM CE.
}
}
// ----------------------------- Metadata ------------------------------
group = "me.eccentric_nz.gamemodeinventories" // Declare bundle identifier.
version = "3.5.1" // Declare plugin version (will be in .jar).
val apiVersion = "1.19" // Declare minecraft server target version.
// ----------------------------- Resources -----------------------------
tasks.named<ProcessResources>("processResources") {
val props = mapOf("version" to project.version, "apiVersion" to apiVersion)
inputs.properties(props) // Indicates to rerun if version changes.
filesMatching("plugin.yml") { expand(props) }
from("LICENSE") { into("/") } // Bundle licenses into jarfiles.
}
// ---------------------------- Repos ----------------------------------
repositories {
mavenCentral() // Import the Maven Central Maven Repository.
maven("https://ci.mg-dev.eu/plugin/repository/everything/") // BKCommonLib.
gradlePluginPortal() // Import the Gradle Plugin Portal Maven Repository.
maven { url = uri("https://repo.purpurmc.org/snapshots") } // Import the PurpurMC Maven Repository.
maven("https://hub.spigotmc.org/nexus/content/groups/public/")
maven { url = uri("https://maven.playpro.com/") }
maven { url = uri("https://maven.enginehub.org/repo/") }
}
// ---------------------- Java project deps ----------------------------
dependencies {
compileOnly("org.purpurmc.purpur:purpur-api:1.19.4-R0.1-SNAPSHOT") // Declare Purpur API version to be packaged.
compileOnly("net.coreprotect:coreprotect:22.4") // Import the CoreProtect API.
compileOnly("com.sk89q.worldguard:worldguard-bukkit:7.0.9") // Import the WorldGuard API.
compileOnly(project(":libs:MyWorlds")) // Import MyWorlds API (git submodule, built from source).
compileOnly("com.bergerkiller.bukkit:BKCommonLib:1.19.4-v2") // Import BKCommonLib API from its Maven repository.
implementation("com.zaxxer:HikariCP:5.0.1")
implementation("org.slf4j:slf4j-api:2.0.17") // Bundle a relocated SLF4J API for shaded dependencies.
implementation("org.slf4j:slf4j-nop:2.0.17") // Provide a relocated no-op SLF4J backend to avoid provider warnings.
}
// ---------------------- Reproducible jars ----------------------------
tasks.withType<AbstractArchiveTask>().configureEach { // Ensure reproducible .jars
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}
// ----------------------------- Shadow --------------------------------
tasks.shadowJar {
archiveClassifier.set("") // Use empty string instead of null.
exclude("io.github.miniplaceholders.*") // Exclude the MiniPlaceholders package from being shadowed.
exclude("org/purpurmc/**", "org/spigotmc/**")
isEnableRelocation = true
relocationPrefix = "${project.group}.shadow"
minimize {
// SLF4J discovers providers through META-INF/services, so Shadow's static minimizer cannot see this usage.
exclude(dependency("org.slf4j:slf4j-nop:.*"))
}
// relocate("com.zaxxer.hikari", "${project.group}.shadow.hikari")
mergeServiceFiles()
}
tasks.jar { archiveClassifier.set("part") } // Applies to root jarfile only.
tasks.build { dependsOn(tasks.spotlessApply, tasks.shadowJar) } // Build depends on spotless and shadow.
// --------------------------- Javac opts -------------------------------
tasks.withType<JavaCompile>().configureEach {
options.compilerArgs.add("-parameters") // Enable reflection for java code.
options.isFork = true // Run javac in its own process.
options.compilerArgs.add("-Xlint:deprecation") // Trigger deprecation warning messages.
options.encoding = "UTF-8" // Use UTF-8 file encoding.
}
// ----------------------------- Auto Formatting ------------------------
spotless {
java {
eclipse().configFile("config/formatter/eclipse-java-formatter.xml") // Eclipse java formatting.
leadingTabsToSpaces() // Convert leftover leading tabs to spaces.
removeUnusedImports() // Remove imports that aren't being called.
}
kotlinGradle {
ktfmt().kotlinlangStyle().configure { it.setMaxWidth(120) } // JetBrains Kotlin formatting.
target("build.gradle.kts", "settings.gradle.kts") // Gradle files to format.
}
}
checkstyle {
toolVersion = "10.18.1" // Declare checkstyle version to use.
configFile = file("config/checkstyle/checkstyle.xml") // Point checkstyle to config file.
isIgnoreFailures = true // Don't fail the build if checkstyle does not pass.
isShowViolations = true // Show the violations in any IDE with the checkstyle plugin.
}
tasks.named("compileJava") {
dependsOn("spotlessApply") // Run spotless before compiling with the JDK.
}
tasks.named("spotlessCheck") {
dependsOn("spotlessApply") // Run spotless before checking if spotless ran.
}
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
<property name="severity" value="error"/>
</module>
<module name="TreeWalker">
<module name="FinalLocalVariable"/>
<module name="AvoidStarImport"/>
<module name="Indentation">
<property name="severity" value="ignore"/>
</module>
</module>
<module name="RegexpSingleline">
<property name="format" value="\borg\.junit\.jupiter\.api\.Assertions\.fail\s*\(\s*&quot;Not yet implemented&quot;\s*\)\s*;"/>
<property name="message" value="Remove placeholder fail() and implement the test."/>
<property name="ignoreCase" value="true"/>
<property name="severity" value="warning"/>
</module>
<module name="RegexpSingleline">
<property name="format" value="(?&lt;!\w)fail\s*\(\s*&quot;Not yet implemented&quot;\s*\)\s*;"/>
<property name="message" value="Remove placeholder fail() and implement the test."/>
<property name="severity" value="warning"/>
</module>
</module>
+404
View File
@@ -0,0 +1,404 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="23">
<profile kind="CodeFormatterProfile" name="TrueOG Network Formatting" version="23">
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_with_spaces" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_before_code_block" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_switch_case_expressions" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_record_components" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_logical_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_annotation_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_record_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_abstract_method" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.keep_enum_constant_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.keep_anonymous_type_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_switch_case_expressions" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_shift_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_code_block" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_parameters" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_loops" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_simple_for_body_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_switch_case_arrow_operator" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_enum_constant" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.text_block_indentation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_module_statements" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.align_tags_names_descriptions" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_if_then_body_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_permitted_types" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_annotations" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_assertion_message_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines" value="2147483647"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_not_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_arguments" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_permitted_types_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_record_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment.javadoc_do_not_separate_block_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_tag_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_record_constructor" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_string_concatenation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_shift_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_shift_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_simple_do_while_body_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_record_components" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_additive_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_simple_getter_setter_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case_after_arrow" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_record_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_relational_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_logical_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_record_declaration" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_default" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_method_body" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.keep_switch_body_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_switch_case_with_arrow" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.align_tags_descriptions_grouped" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_method_body_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_loop_body_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_type_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_additive_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_constructor" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_relational_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_record_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_relational_operator" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.align_arrows_in_switch_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_additive_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.align_selector_in_method_invocation_on_expression_first_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_record_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_switch_case_with_arrow_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_switch_case_with_colon" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_after_code_block" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_default" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_between_different_tags" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_additive_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_conditional_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_shift_operator" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.keep_code_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_record_components" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_record_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_assignment_operator" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_switch_case_with_arrow" value="20"/>
<setting id="org.eclipse.jdt.core.formatter.keep_lambda_body_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method" value="49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_record_constructor_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assertion_message" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_logical_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_record_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_relational_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_last_class_body_declaration" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_simple_while_body_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_logical_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_statement_group_in_switch" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_permitted_types" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_enum_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_code_block" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_string_concatenation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="120"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
</profile>
</profiles>
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# 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 ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# 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
if ! command -v java >/dev/null 2>&1
then
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
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@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=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 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!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Submodule
+1
Submodule libs/MyWorlds added at 659627d65e.
+1
Submodule libs/Utilities-OG added at 8b5c86cc9c.
-143
View File
@@ -1,143 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.eccentric_nz.gamemodeinventories</groupId>
<artifactId>GameModeInventories</artifactId>
<version>3.4.0</version>
<name>GameModeInventories</name>
<!-- use a profile here so that the Jenkins build can fetch the
CoreProtect dependency locally - there is no repo available! -->
<profiles>
<profile>
<id>jenkins</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
</profile>
</profiles>
<repositories>
<repository>
<id>Spigot</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>Bromley Massive</id>
<url>http://tardisjenkins.duckdns.org:8080/plugin/repository/everything/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<build>
<finalName>GameModeInventories</finalName>
<plugins>
<!-- Shade all Libs -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0-SNAPSHOT</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
<createDependencyReducedPom>false</createDependencyReducedPom>
<artifactSet>
<includes>
<include>org.slf4j:slf4j-api</include>
<include>org.slf4j:slf4j-simple</include>
<include>com.zaxxer:*</include>
<include>org.javassist:javassist</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.zaxxer</pattern>
<shadedPattern>me.eccentric_nz.com.zaxxer</shadedPattern>
</relocation>
<relocation>
<pattern>org.slf4j</pattern>
<shadedPattern>me.eccentric_nz.org.slf4j</shadedPattern>
</relocation>
<relocation>
<pattern>org.javassist</pattern>
<shadedPattern>me.eccentric_nz.org.javassist</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<!-- Make a Jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.18-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.26.0-GA</version>
</dependency>
<!-- SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.coreprotect</groupId>
<artifactId>CoreProtect</artifactId>
<version>19.5</version>
<type>jar</type>
<scope>system</scope>
<systemPath>${basedir}/lib/CoreProtect.jar</systemPath>
</dependency>
<dependency>
<groupId>de.diddiz</groupId>
<artifactId>LogBlock</artifactId>
<version>1.16.1.1</version>
<type>jar</type>
<scope>system</scope>
<systemPath>${basedir}/lib/LogBlock.jar</systemPath>
</dependency>
</dependencies>
</project>
+22
View File
@@ -0,0 +1,22 @@
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}
rootProject.name = "GameModeInventories-OG"
// Fetch submodule content before the libraries below are wired in as subprojects.
ProcessBuilder("sh", "bootstrap.sh").directory(rootDir).inheritIO().start().let {
if (it.waitFor() != 0) throw GradleException("bootstrap.sh failed")
}
// Every git submodule under libs/ with a Gradle build becomes :libs:<name>, like Template-OG.
file("libs")
.listFiles()
?.filter { it.isDirectory && !it.name.startsWith(".") && file("${it.path}/build.gradle.kts").exists() }
?.forEach { dir ->
include(":libs:${dir.name}")
project(":libs:${dir.name}").projectDir = dir
}
@@ -3,12 +3,6 @@
*/
package me.eccentric_nz.gamemodeinventories;
/**
* @author eccentric_nz
*/
public enum GMIDebug {
ERROR,
INFO,
ALL
ERROR, INFO, ALL
}
@@ -1,99 +1,191 @@
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import com.zaxxer.hikari.HikariDataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.eccentric_nz.gamemodeinventories.api.GameModePolicy;
import me.eccentric_nz.gamemodeinventories.database.*;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
public class GameModeInventories extends JavaPlugin {
public static GameModeInventories plugin;
public final String MY_PLUGIN_NAME = ChatColor.GOLD + "[GameModeInventories] " + ChatColor.RESET;
public final Component MY_PLUGIN_NAME = Component.text("[GameModeInventories] ", NamedTextColor.GOLD);
private final HashMap<String, List<String>> creativeBlocks = new HashMap<>();
private final List<Material> blackList = new ArrayList<>();
private final List<Material> noTrackList = new ArrayList<>();
private final List<String> points = new ArrayList<>();
private final List<UUID> stands = new ArrayList<>();
private final Set<UUID> internalSwitches = new HashSet<>();
public BukkitTask recordingTask;
private GameModeInventoriesInventory inventoryHandler;
private GameModeInventoriesBundles bundles;
private GameModePolicy gameModePolicy;
private GameModeInventoriesBlock block;
private GameModeInventoriesMessage m;
private GameModeInventoriesBlockLogger blockLogger;
private GMIDebug db_level;
private String prefix;
private HikariDataSource dataSource;
private FileConfiguration canonicalConfig;
@Override
public void onDisable() {
getServer().getOnlinePlayers().forEach((p) -> {
if (p.hasPermission("gamemodeinventories.use")) {
if (p.isOnline()) {
inventoryHandler.switchInventories(p, p.getGameMode());
if (inventoryHandler != null) {
getServer().getOnlinePlayers().forEach((p) -> {
// Persist creative inventories on shutdown; survival is saved by MyWorlds and
// the server
if (p.hasPermission("gamemodeinventories.use") && p.isOnline()
&& p.getGameMode().equals(GameMode.CREATIVE))
{
inventoryHandler.saveCreative(p, getBundles().of(p.getWorld()));
}
}
});
new GameModeInventoriesStand(this).saveStands();
new GameModeInventoriesQueueDrain(this).forceDrainQueue();
});
}
if (hasDatabaseConnection()) {
new GameModeInventoriesStand(this).saveStands();
new GameModeInventoriesQueueDrain(this).forceDrainQueue();
dataSource.close();
}
}
@Override
public void onEnable() {
plugin = this;
PluginManager pm = Bukkit.getServer().getPluginManager();
loadCanonicalConfig();
if (canonicalConfig == null) {
pm.disablePlugin(this);
return;
}
Version bukkitversion = getServerVersion(getServer().getVersion());
Version minversion = new Version("1.13");
// check CraftBukkit version
if (bukkitversion.compareTo(minversion) >= 0) {
saveDefaultConfig();
GameModeInventoriesConfig tc = new GameModeInventoriesConfig(this);
tc.checkConfig();
loadDatabase();
if (!hasDatabaseConnection()) {
getLogger().log(Level.SEVERE, "Database setup failed, disabling plugin.");
pm.disablePlugin(this);
return;
}
// update database add and populate block fields
if (!getConfig().getBoolean("blocks_conversion_done")) {
new GameModeInventoriesBlocksConverter(this).convertBlocksTable();
getConfig().set("blocks_conversion_done", true);
saveConfig();
System.out.println("[GameModeInventories] Blocks conversion successful :)");
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Blocks conversion successful :)");
plugin.getLogger().log(Level.INFO,
"[GameModeInventories] config.yml is immutable; leaving blocks_conversion_done unchanged.");
}
// check if creative world exists
if (getConfig().getBoolean("creative_world.switch_to")) {
World creative = getServer().getWorld(getConfig().getString("creative_world.world"));
if (creative == null) {
getConfig().set("creative_world.switch_to", false);
saveConfig();
System.out.println("[GameModeInventories] Creative world specified in the config was not found, disabling world switching!");
plugin.getLogger().log(Level.INFO,
"[GameModeInventories] Creative world specified in the config was not found; world switching will stay disabled until config.yml is updated manually.");
}
}
block = new GameModeInventoriesBlock(this);
m = new GameModeInventoriesMessage(this);
m.getMessages();
m.updateMessages();
try {
db_level = GMIDebug.valueOf(getConfig().getString("debug_level"));
} catch (IllegalArgumentException e) {
db_level = GMIDebug.ERROR;
}
bundles = new GameModeInventoriesBundles(this);
inventoryHandler = new GameModeInventoriesInventory(this);
// If legacy slots cannot be bundled, serving inventories would read empty, so
// refuse to enable
if (!inventoryHandler.assignLegacySlotsTo(bundles.of(getServer().getWorlds().get(0)))) {
getLogger().severe(
"[GameModeInventories] Could not assign legacy inventory slots, disabling to avoid serving empty inventories");
pm.disablePlugin(this);
return;
}
// Published before the listeners so anything reacting to enable can read it.
gameModePolicy = new GameModePolicy(this);
getServer().getServicesManager().register(GameModePolicy.class, gameModePolicy, this,
ServicePriority.Normal);
pm.registerEvents(new GameModeInventoriesListener(this), this);
pm.registerEvents(new GameModeInventoriesChunkLoadListener(this), this);
pm.registerEvents(new GameModeInventoriesDeath(this), this);
if (bundles.usesMyWorlds()) {
pm.registerEvents(new GameModeInventoriesMyWorldsListener(this), this);
}
pm.registerEvents(new GameModeInventoriesBlockListener(this), this);
if (getConfig().getBoolean("track_creative_place.dont_track_is_whitelist")) {
pm.registerEvents(new GameModeInventoriesTrackWhiteListener(this), this);
} else {
pm.registerEvents(new GameModeInventoriesTrackBlackListener(this), this);
}
pm.registerEvents(new GameModeInventoriesPistonListener(this), this);
pm.registerEvents(new GameModeInventoriesCommandListener(this), this);
pm.registerEvents(new GameModeInventoriesWorldListener(this), this);
@@ -108,137 +200,305 @@ public class GameModeInventories extends JavaPlugin {
loadNoTrackList();
setUpBlockLogger();
actionRecorderTask();
} else {
getServer().getConsoleSender().sendMessage(MY_PLUGIN_NAME + ChatColor.RED + "This plugin requires CraftBukkit/Spigot 1.9 or higher, disabling...");
message(getServer().getConsoleSender(), Component
.text("This plugin requires CraftBukkit/Spigot 1.9 or higher, disabling...", NamedTextColor.RED));
pm.disablePlugin(this);
}
}
private void loadCanonicalConfig() {
File configFile = new File(getDataFolder(), "config.yml");
if (!configFile.exists()) {
saveResource("config.yml", false);
getLogger().log(Level.INFO, "Copied default config.yml to " + configFile.getAbsolutePath());
}
canonicalConfig = YamlConfiguration.loadConfiguration(configFile);
}
@Override
public FileConfiguration getConfig() {
return (canonicalConfig != null) ? canonicalConfig : super.getConfig();
}
private Version getServerVersion(String s) {
Pattern pat = Pattern.compile("\\((.+?)\\)", Pattern.DOTALL);
Matcher mat = pat.matcher(s);
String v;
if (mat.find()) {
String[] split = mat.group(1).split(" ");
String[] tmp = split[1].split("-");
if (tmp.length > 1) {
v = tmp[0];
} else {
v = split[1];
}
} else {
v = "1.7.10";
}
return new Version(v);
}
/**
* Sets up the database.
*/
private void loadDatabase() {
String dbtype = getConfig().getString("storage.database");
prefix = getConfig().getString("storage.prefix");
try {
if (dbtype.equals("sqlite")) {
String path = getDataFolder() + File.separator + "GMI.db";
GameModeInventoriesConnectionPool pool = new GameModeInventoriesConnectionPool(path);
GameModeInventoriesSQLiteConnectionPool pool = new GameModeInventoriesSQLiteConnectionPool(this);
dataSource = pool.getHikari();
GameModeInventoriesSQLite sqlite = new GameModeInventoriesSQLite(this);
sqlite.createTables();
} else {
GameModeInventoriesConnectionPool pool = new GameModeInventoriesConnectionPool();
GameModeInventoriesMySQLConnectionPool pool = new GameModeInventoriesMySQLConnectionPool(this);
dataSource = pool.getHikari();
GameModeInventoriesMySQL mysql = new GameModeInventoriesMySQL(this);
mysql.createTables();
}
} catch (ClassNotFoundException e) {
getServer().getConsoleSender().sendMessage(MY_PLUGIN_NAME + "Connection and Tables Error: " + e);
message(getServer().getConsoleSender(), Component.text("Connection and Tables Error: " + e));
}
}
/**
* Loads block logger support if available
*/
public Connection getDatabaseConnection() {
Connection con = null;
if (dataSource == null) {
debug("Could not get database connection: datasource is not initialized");
return null;
}
try {
con = dataSource.getConnection();
} catch (SQLException e) {
debug("Could not get database connection: " + e.getMessage());
}
return con;
}
public boolean hasDatabaseConnection() {
return dataSource != null && !dataSource.isClosed();
}
// Loads block logger support if available.
public void setUpBlockLogger() {
blockLogger = new GameModeInventoriesBlockLogger(this);
blockLogger.enableLogger();
}
public GameModeInventoriesBlockLogger getBlockLogger() {
return blockLogger;
}
// The gamemode rules this server enforces; also on the services manager, and
// plugins that cannot compile against this one reach it via this getter.
public GameModePolicy getGameModePolicy() {
return gameModePolicy;
}
// Flags plugin driven mode changes so forced Survival stays quiet.
public void internalGameModeChange(Player p, GameMode mode) {
internalSwitches.add(p.getUniqueId());
try {
p.setGameMode(mode);
} finally {
internalSwitches.remove(p.getUniqueId());
}
}
public boolean isInternalGameModeChange(Player p) {
return internalSwitches.contains(p.getUniqueId());
}
// Sends a message to a player or the console with the plugin prefix in front.
public void message(Audience audience, Component body) {
// empty root keeps the gold prefix from bleeding into the message body
audience.sendMessage(Component.empty().append(MY_PLUGIN_NAME).append(body));
}
public void debug(Object o, GMIDebug b) {
if (getConfig().getBoolean("debug") == true) {
if (b.equals(db_level) || b.equals(GMIDebug.ALL)) {
getServer().getConsoleSender().sendMessage(MY_PLUGIN_NAME + "Debug: " + o);
message(getServer().getConsoleSender(), Component.text("Debug: " + o));
}
}
}
public void debug(Object o) {
debug(o, GMIDebug.ERROR);
}
public GameModeInventoriesInventory getInventoryHandler() {
return inventoryHandler;
}
public GameModeInventoriesBundles getBundles() {
return bundles;
}
public GameModeInventoriesBlock getBlock() {
return block;
}
public HashMap<String, List<String>> getCreativeBlocks() {
return creativeBlocks;
}
public List<Material> getBlackList() {
return blackList;
}
private void loadBlackList() {
List<String> bl = getConfig().getStringList("blacklist");
bl.forEach((s) -> {
try {
blackList.add(Material.valueOf(s));
} catch (IllegalArgumentException iae) {
getServer().getConsoleSender().sendMessage(MY_PLUGIN_NAME + m.getMessage().get("INVALID_MATERIAL") + " " + s);
message(getServer().getConsoleSender(), m.get("INVALID_MATERIAL").append(Component.text(" " + s)));
}
});
}
public List<Material> getNoTrackList() {
return noTrackList;
}
private void loadNoTrackList() {
List<String> ntl = getConfig().getStringList("track_creative_place.dont_track");
ntl.forEach((s) -> {
try {
noTrackList.add(Material.valueOf(s));
} catch (IllegalArgumentException iae) {
getServer().getConsoleSender().sendMessage(MY_PLUGIN_NAME + m.getMessage().get("INVALID_MATERIAL_TRACK") + " " + s);
message(getServer().getConsoleSender(),
m.get("INVALID_MATERIAL_TRACK").append(Component.text(" " + s)));
}
});
}
public List<String> getPoints() {
return points;
}
public List<UUID> getStands() {
return stands;
}
public GameModeInventoriesMessage getM() {
return m;
}
public String getPrefix() {
return prefix;
}
public void actionRecorderTask() {
int recorder_tick_delay = 3;
// we schedule it once, it will reschedule itself
recordingTask = getServer().getScheduler().runTaskLaterAsynchronously(this, new GameModeInventoriesRecordingTask(this), recorder_tick_delay);
recordingTask = getServer().getScheduler().runTaskLaterAsynchronously(this,
new GameModeInventoriesRecordingTask(this), recorder_tick_delay);
}
}
@@ -3,97 +3,93 @@
*/
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesQueueData;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesRecordingQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesMySQLConnectionPool;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesQueueData;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesRecordingQueue;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBlock {
private final GameModeInventories plugin;
public GameModeInventoriesBlock(GameModeInventories plugin) {
this.plugin = plugin;
}
public void addBlock(String gmiwc, String l) {
GameModeInventoriesQueueData data = new GameModeInventoriesQueueData(gmiwc, l);
if (GameModeInventoriesConnectionPool.isIsMySQL()) {
if (GameModeInventoriesMySQLConnectionPool.isIsMySQL()) {
GameModeInventoriesRecordingQueue.addToQueue(data);
} else {
saveBlockNow(data);
}
if (plugin.getCreativeBlocks().containsKey(gmiwc)) {
plugin.getCreativeBlocks().get(gmiwc).add(l);
} else {
plugin.getCreativeBlocks().put(gmiwc, new ArrayList<>(Arrays.asList(l)));
}
}
public void removeBlock(String gmiwc, String l) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
String deleteQuery = "DELETE FROM " + plugin.getPrefix() + "blocks WHERE worldchunk = ? AND location = ?";
ps = connection.prepareStatement(deleteQuery);
String deleteQuery = "DELETE FROM " + plugin.getPrefix() + "blocks WHERE worldchunk = ? AND location = ?";
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement ps = connection.prepareStatement(deleteQuery);)
{
ps.setString(1, gmiwc);
ps.setString(2, l);
ps.executeUpdate();
if (GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not remove block, " + e);
} finally {
try {
if (ps != null) {
ps.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not remove block, " + e);
}
plugin.getLogger().log(Level.WARNING, "Could not remove block, " + e);
}
if (plugin.getCreativeBlocks().containsKey(gmiwc)) {
plugin.getCreativeBlocks().get(gmiwc).remove(l);
}
}
private void saveBlockNow(GameModeInventoriesQueueData data) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
String insertQuery = "INSERT INTO " + plugin.getPrefix() + "blocks (worldchunk, location) VALUES (?,?)";
ps = connection.prepareStatement(insertQuery);
String insertQuery = "INSERT INTO " + plugin.getPrefix() + "blocks (worldchunk, location) VALUES (?,?)";
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement ps = connection.prepareStatement(insertQuery);)
{
ps.setString(1, data.getWorldChunk());
ps.setString(2, data.getLocation());
ps.executeUpdate();
} catch (SQLException e) {
System.err.println("Could not save block, " + e);
} finally {
try {
if (ps != null) {
ps.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not remove block, " + e);
}
plugin.getLogger().log(Level.WARNING, "Could not save block, " + e);
}
}
}
@@ -3,6 +3,7 @@
*/
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.GameModeInventoriesMessage.Arg;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -20,143 +21,259 @@ import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.player.PlayerInteractEvent;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBlockListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesBlockListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void onItemSpawn(ItemSpawnEvent event) {
if (!plugin.getConfig().getBoolean("no_falling_drops")) {
return;
}
event.getEntity().getNearbyEntities(0.5, 0.5, 0.5).forEach((e) -> {
if (e instanceof FallingBlock) {
event.setCancelled(true);
}
});
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.hasItem()) {
Material mat = event.getItem().getType();
Player p = event.getPlayer();
if (p.getGameMode().equals(GameMode.SURVIVAL)) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled") || !plugin.getConfig().getBoolean("track_creative_place.no_seeds_from_pumpkin")) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")
|| !plugin.getConfig().getBoolean("track_creative_place.no_seeds_from_pumpkin"))
{
return;
}
if (mat.equals(Material.SHEARS)) {
Block pumpkin = event.getClickedBlock();
if (pumpkin == null) {
return;
}
if (!pumpkin.getType().equals(Material.PUMPKIN)) {
return;
}
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(pumpkin.getWorld().getName())) {
if (!plugin.getConfig().getStringList("track_creative_place.worlds")
.contains(pumpkin.getWorld().getName()))
{
return;
}
String gmiwc = pumpkin.getWorld().getName() + "," + pumpkin.getChunk().getX() + "," + pumpkin.getChunk().getZ();
String gmiwc = pumpkin.getWorld().getName() + "," + pumpkin.getChunk().getX() + ","
+ pumpkin.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(pumpkin.getLocation().toString())) {
event.setCancelled(true);
}
}
}
if (!p.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
if (plugin.getConfig().getBoolean("no_golem_spawn")) {
Block pumpkin = event.getClickedBlock();
if (pumpkin != null && pumpkin.getType().equals(Material.PUMPKIN)) {
// check blocks around pumpkin
if (mat.equals(Material.SHEARS) && GameModeInventoriesConstructedMob.checkBlocks(Material.PUMPKIN, pumpkin)) {
if (mat.equals(Material.SHEARS)
&& GameModeInventoriesConstructedMob.checkBlocks(Material.PUMPKIN, pumpkin))
{
event.setCancelled(true);
}
}
}
if (plugin.getConfig().getBoolean("track_creative_place.enabled")) {
if (mat.equals(Material.ARMOR_STAND)) {
Block b = event.getClickedBlock();
if (b != null) {
if (plugin.getConfig().getStringList("track_creative_place.worlds").contains(b.getWorld().getName())) {
if (plugin.getConfig().getStringList("track_creative_place.worlds")
.contains(b.getWorld().getName()))
{
Location l = b.getLocation();
if (l != null) {
String gmip = l.getBlockX() + "," + l.getBlockZ();
plugin.getPoints().add(gmip);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
if (plugin.getPoints().contains(gmip)) {
plugin.getPoints().remove(gmip);
}
}, 600L);
}
}
}
}
}
if (!plugin.getConfig().getBoolean("creative_blacklist")) {
return;
}
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR)) {
if (plugin.getBlackList().contains(mat) && !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin)) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
|| event.getAction().equals(Action.RIGHT_CLICK_AIR))
{
if (plugin.getBlackList().contains(mat)
&& !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin))
{
event.setCancelled(true);
event.setUseItemInHand(Result.DENY);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + String.format(plugin.getM().getMessage().get("NO_CREATIVE_PLACE"), mat.toString()));
plugin.message(p, plugin.getM().get("NO_CREATIVE_PLACE", new Arg("material", mat.toString())));
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBedrockBreak(BlockBreakEvent event) {
if (plugin.getConfig().getBoolean("break_bedrock")) {
return;
}
if (!event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
return;
}
Block br = event.getBlock();
if (!br.getType().equals(Material.BEDROCK)) {
return;
}
if (br.getLocation().getY() < 5) {
event.setCancelled(true);
} else if (br.getWorld().getEnvironment().equals(Environment.NETHER) && br.getLocation().getY() > 122) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
if (plugin.getConfig().getBoolean("track_creative_place.enabled")) {
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(event.getLocation().getWorld().getName())) {
if (!plugin.getConfig().getStringList("track_creative_place.worlds")
.contains(event.getLocation().getWorld().getName()))
{
return;
}
for (Block b : event.blockList()) {
if (plugin.getNoTrackList().contains(b.getType())) {
continue;
}
String gmiwc = b.getWorld().getName() + "," + b.getChunk().getX() + "," + b.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
continue;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(b.getLocation().toString())) {
event.setYield(0);
event.setCancelled(true);
return;
}
}
}
}
}
@@ -3,79 +3,66 @@
*/
package me.eccentric_nz.gamemodeinventories;
import de.diddiz.LogBlock.Consumer;
import de.diddiz.LogBlock.LogBlock;
import java.util.logging.Level;
import net.coreprotect.CoreProtect;
import net.coreprotect.CoreProtectAPI;
import org.bukkit.plugin.PluginManager;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBlockLogger {
private final GameModeInventories plugin;
private CoreProtectAPI coreProtectAPI = null;
private Consumer logBlockConsumer = null;
private GMIBlockLogger whichLogger;
private boolean logging = false;
public GameModeInventoriesBlockLogger(GameModeInventories plugin) {
this.plugin = plugin;
}
public CoreProtectAPI getCoreProtectAPI() {
return coreProtectAPI;
}
public Consumer getLogBlockConsumer() {
return logBlockConsumer;
}
public GMIBlockLogger getWhichLogger() {
return whichLogger;
}
public boolean isLogging() {
return logging;
}
public void enableLogger() {
PluginManager pm = plugin.getServer().getPluginManager();
if (pm.isPluginEnabled("CoreProtect")) {
CoreProtect cp = (CoreProtect) pm.getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (cp == null || !(cp instanceof CoreProtect)) {
if (cp == null) {
return;
}
// Check that the API is enabled
CoreProtectAPI CoreProtect = cp.getAPI();
if (CoreProtect.isEnabled() == false) {
CoreProtectAPI api = cp.getAPI();
if (!api.isEnabled()) {
return;
}
// Check that a compatible version of the API is loaded
if (CoreProtect.APIVersion() < 6) {
if (api.APIVersion() < 6) {
return;
}
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "Connecting to CoreProtect");
coreProtectAPI = CoreProtect;
whichLogger = GMIBlockLogger.CORE_PROTECT;
plugin.getLogger().log(Level.INFO, "Connecting to CoreProtect");
coreProtectAPI = api;
logging = true;
}
if (pm.isPluginEnabled("LogBlock")) {
LogBlock lb = (LogBlock) pm.getPlugin("LogBlock");
if (lb != null) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "Connecting to LogBlock");
logBlockConsumer = lb.getConsumer();
whichLogger = GMIBlockLogger.LOG_BLOCK;
logging = true;
}
}
}
public enum GMIBlockLogger {
CORE_PROTECT,
LOG_BLOCK
}
}
@@ -16,54 +16,89 @@
*/
package me.eccentric_nz.gamemodeinventories;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBukkitSerialization {
public static String toDatabase(ItemStack[] inventory) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Write the size of the inventory
try (BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream)) {
// Write the size of the inventory
dataOutput.writeInt(inventory.length);
// Save every element in the list
for (ItemStack is : inventory) {
// check for player heads with no data...
if (is != null && is.getType().equals(Material.PLAYER_HEAD)) {
if (is.hasItemMeta()) {
SkullMeta skullMeta = (SkullMeta) is.getItemMeta();
if (skullMeta.getOwnerProfile() == null) {
is.setItemMeta(null);
}
}
}
dataOutput.writeObject(is);
}
// Serialize that array
}
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (IOException e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
public static ItemStack[] fromDatabase(String data) throws IOException {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
ItemStack[] inventory;
try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) {
int size = dataInput.readInt();
inventory = new ItemStack[size];
// Read the serialized inventory
for (int i = 0; i < size; i++) {
inventory[i] = (ItemStack) dataInput.readObject();
}
}
return inventory;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e);
}
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2014 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories;
import org.bukkit.World;
// Names a world's inventory bundle: its MyWorlds group, else the world itself
public final class GameModeInventoriesBundles {
private final boolean myWorlds;
public GameModeInventoriesBundles(GameModeInventories plugin) {
myWorlds = plugin.getServer().getPluginManager().isPluginEnabled("MyWorlds") && MyWorldsBundles.available();
plugin.getLogger().info("[GameModeInventories] Inventory bundles: "
+ (myWorlds ? "MyWorlds inventory groups" : "one per world"));
}
public boolean usesMyWorlds() {
return myWorlds;
}
public String of(World world) {
if (myWorlds) {
String group = MyWorldsBundles.of(world);
if (group != null) {
return group;
}
}
return world.getName();
}
}
@@ -5,16 +5,20 @@ package me.eccentric_nz.gamemodeinventories;
import org.bukkit.entity.Player;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBypass {
public static boolean canBypass(Player p, String bypass, GameModeInventories plugin) {
if (p.hasPermission("gamemodeinventories.bypass") || p.isOp()) {
return plugin.getConfig().getBoolean("bypass." + bypass);
} else {
return false;
}
}
}
@@ -10,52 +10,80 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.ChunkLoadEvent;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesChunkLoadListener implements Listener {
private final GameModeInventories plugin;
private boolean firstLogin = true;
public GameModeInventoriesChunkLoadListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
Chunk chunk = event.getChunk();
String world = chunk.getWorld().getName();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(world)) {
return;
}
String gmiwc = chunk.getWorld().getName() + "," + chunk.getX() + "," + chunk.getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
new GameModeInventoriesBlockLoader(plugin, gmiwc).runTaskAsynchronously(plugin);
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
if (firstLogin) {
firstLogin = false;
Chunk[] chunks = event.getPlayer().getWorld().getLoadedChunks();
for (Chunk c : chunks) {
String gmiwc = c.getWorld().getName() + "," + c.getX() + "," + c.getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
new GameModeInventoriesBlockLoader(plugin, gmiwc).runTaskAsynchronously(plugin);
}
}
} else {
Chunk chunk = event.getPlayer().getLocation().getChunk();
String gmiwc = chunk.getWorld().getName() + "," + chunk.getX() + "," + chunk.getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
plugin.debug(gmiwc, GMIDebug.ALL);
new GameModeInventoriesBlockLoader(plugin, gmiwc).runTaskAsynchronously(plugin);
}
}
}
}
@@ -3,46 +3,62 @@
*/
package me.eccentric_nz.gamemodeinventories;
import org.bukkit.ChatColor;
import java.util.List;
import me.eccentric_nz.gamemodeinventories.GameModeInventoriesMessage.Arg;
import org.bukkit.GameMode;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import java.util.List;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesCommandListener implements Listener {
private final GameModeInventories plugin;
private final List<String> blacklist;
public GameModeInventoriesCommandListener(GameModeInventories plugin) {
this.plugin = plugin;
this.blacklist = plugin.getConfig().getStringList("commands");
for (int i = 0, l = this.blacklist.size(); i < l; ++i) {
this.blacklist.set(i, this.blacklist.get(i).toLowerCase());
}
}
@EventHandler(ignoreCancelled = true)
public void onCommandUse(PlayerCommandPreprocessEvent event) {
if (!event.getPlayer().getGameMode().equals(GameMode.CREATIVE) || !plugin.getConfig().getBoolean("command_blacklist") || GameModeInventoriesBypass.canBypass(event.getPlayer(), "commands", plugin)) {
if (!event.getPlayer().getGameMode().equals(GameMode.CREATIVE)
|| !plugin.getConfig().getBoolean("command_blacklist")
|| GameModeInventoriesBypass.canBypass(event.getPlayer(), "commands", plugin))
{
return;
}
String message = event.getMessage();
// get the command from the message
String[] args = message.split(" ");
if (args.length > 0) {
String command = args[0].substring(1).toLowerCase();
if (blacklist.contains(command)) {
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
event.getPlayer().sendMessage(plugin.MY_PLUGIN_NAME + String.format(plugin.getM().getMessage().get("NO_CREATIVE_COMMAND"), ChatColor.GREEN + "/" + command + ChatColor.RESET));
plugin.message(event.getPlayer(),
plugin.getM().get("NO_CREATIVE_COMMAND", new Arg("command", "/" + command)));
}
}
}
}
}
@@ -1,7 +1,14 @@
package me.eccentric_nz.gamemodeinventories;
import com.google.common.collect.ImmutableList;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import net.kyori.adventure.text.Component;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -10,13 +17,6 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.StringUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class GameModeInventoriesCommands implements CommandExecutor, TabCompleter {
private final GameModeInventories plugin;
@@ -24,6 +24,7 @@ public class GameModeInventoriesCommands implements CommandExecutor, TabComplete
private final ImmutableList<String> ROOT_SUBS;
public GameModeInventoriesCommands(GameModeInventories plugin) {
this.plugin = plugin;
firstArgs.put("armor", "armor");
firstArgs.put("attached_block", "track_creative_place.attached_block");
@@ -58,125 +59,229 @@ public class GameModeInventoriesCommands implements CommandExecutor, TabComplete
firstArgs.put("track_creative_place", "track_creative_place.enabled");
firstArgs.put("xp", "xp");
ROOT_SUBS = ImmutableList.copyOf(firstArgs.keySet());
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("gmi")) {
if (args.length == 0) {
sender.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("HELP"));
if (label.equalsIgnoreCase("gmic")) {
if (!(sender instanceof Player player)) {
plugin.message(sender, Component.text("This command can only be used by a player."));
return true;
}
final GameMode target = player.getGameMode().equals(GameMode.CREATIVE) ? GameMode.SURVIVAL
: GameMode.CREATIVE;
// the toggle permission is often per region, so a denial may be local;
// anywhere holders are sanctioned by policy even without toggle
if (!player.hasPermission("gamemodeinventories.toggle")
&& !player.hasPermission("gamemodeinventories.anywhere"))
{
sendDenial(player, target);
return true;
}
// the region rule is enforced here, before the switch: the
// listener trusts internal switches and no longer cancels them
if (target.equals(GameMode.CREATIVE)
&& !plugin.getGameModePolicy().mayUseCreativeAt(player, player.getLocation()))
{
sendDenial(player, target);
return true;
}
// pre-validated above, so the region listener trusts this
// internal switch; other plugins may still cancel it
plugin.internalGameModeChange(player, target);
if (!player.getGameMode().equals(target)) {
// another plugin cancelled the event
sendDenial(player, target);
}
return true;
}
if (args.length == 0) {
plugin.message(sender, plugin.getM().get("HELP"));
return true;
}
if (sender.hasPermission("gamemodeinventories.admin")) {
String option = args[0].toLowerCase(Locale.ENGLISH);
if (args.length == 1 && firstArgs.containsKey(option)) {
boolean bool = !plugin.getConfig().getBoolean(firstArgs.get(option));
plugin.getConfig().set(firstArgs.get(option), bool);
sender.sendMessage(plugin.MY_PLUGIN_NAME + String.format(plugin.getM().getMessage().get("CONFIG_SET"), option, bool));
plugin.saveConfig();
plugin.message(sender, Component.text(
"config.yml is immutable; update '" + option + "' manually if you want to change it."));
return true;
} else if (args.length == 2 && option.equals("kit")) {
String uuid = "00000000-0000-0000-0000-000000000000";
Player p = (Player) sender;
Connection connection = null;
PreparedStatement statement = null;
ResultSet rsInv = null;
ResultSet rsNewInv = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
if (connection != null && !connection.isClosed()) {
statement = connection.prepareStatement("SELECT id FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = 'SURVIVAL'");
if (args[1].toLowerCase().equals("save")) {
String inv = GameModeInventoriesBukkitSerialization.toDatabase(p.getInventory().getContents());
PreparedStatement ps;
// get their current gamemode inventory from database
statement.setString(1, uuid);
rsInv = statement.executeQuery();
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id FROM "
+ plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = 'SURVIVAL'");)
{
if (args[1].toLowerCase().equals("save")) {
String inv = GameModeInventoriesBukkitSerialization
.toDatabase(p.getInventory().getContents());
// get their current gamemode inventory from database
statement.setString(1, uuid);
try (ResultSet rsInv = statement.executeQuery();) {
int id;
if (rsInv.next()) {
String updateQuery = "UPDATE " + plugin.getPrefix()
+ "inventories SET inventory = ? WHERE id = ?";
// update it with their current inventory
id = rsInv.getInt("id");
String updateQuery = "UPDATE " + plugin.getPrefix() + "inventories SET inventory = ? WHERE id = ?";
ps = connection.prepareStatement(updateQuery);
ps.setString(1, inv);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
} else {
// there is no 'kit' inventory saved yet so make one with the player's current inventory
String insertQuery = "INSERT INTO " + plugin.getPrefix() + "inventories (uuid, player, gamemode, inventory) VALUES (?, 'kit', 'SURVIVAL', ?)";
ps = connection.prepareStatement(insertQuery);
ps.setString(1, uuid);
ps.setString(2, inv);
ps.executeUpdate();
ps.close();
}
p.sendMessage(plugin.MY_PLUGIN_NAME + "Kit inventory saved.");
} else {
// load
statement = connection.prepareStatement("SELECT " + plugin.getPrefix() + "inventory FROM inventories WHERE uuid = ? AND gamemode = 'SURVIVAL'");
statement.setString(1, uuid);
rsNewInv = statement.executeQuery();
if (rsNewInv.next()) {
try {
// set the inventory to the kit
String savedinventory = rsNewInv.getString("inventory");
ItemStack[] i;
if (savedinventory.startsWith("[")) {
i = GameModeInventoriesJSONSerialization.toItemStacks(savedinventory);
} else {
i = GameModeInventoriesBukkitSerialization.fromDatabase(savedinventory);
}
p.getInventory().setContents(i);
} catch (IOException e) {
plugin.debug("Could not set inventory for kit, " + e);
try (PreparedStatement ps = connection.prepareStatement(updateQuery);) {
ps.setString(1, inv);
ps.setInt(2, id);
ps.executeUpdate();
}
} else {
// there is no 'kit' inventory saved yet so make one with the player's current
// inventory
String insertQuery = "INSERT INTO " + plugin.getPrefix()
+ "inventories (uuid, player, gamemode, inventory) VALUES (?, 'kit', 'SURVIVAL', ?)";
try (PreparedStatement ps = connection.prepareStatement(insertQuery);) {
ps.setString(1, uuid);
ps.setString(2, inv);
ps.executeUpdate();
}
}
p.sendMessage(plugin.MY_PLUGIN_NAME + "Kit inventory loaded.");
plugin.message(p, Component.text("Kit inventory saved."));
}
} else {
plugin.debug("Connection was " + ((connection == null) ? "NULL" : "closed"));
// load
try (PreparedStatement loadStatement = connection
.prepareStatement("SELECT " + plugin.getPrefix()
+ "inventory FROM inventories WHERE uuid = ? AND gamemode = 'SURVIVAL'");)
{
loadStatement.setString(1, uuid);
try (ResultSet rsNewInv = loadStatement.executeQuery();) {
if (rsNewInv.next()) {
try {
// set the inventory to the kit
String savedinventory = rsNewInv.getString("inventory");
ItemStack[] i;
if (savedinventory.startsWith("[")) {
i = GameModeInventoriesJSONSerialization.toItemStacks(savedinventory);
} else {
i = GameModeInventoriesBukkitSerialization.fromDatabase(savedinventory);
}
p.getInventory().setContents(i);
} catch (IOException e) {
plugin.debug("Could not set inventory for kit, " + e);
}
}
plugin.message(p, Component.text("Kit inventory loaded."));
}
}
}
} catch (SQLException e) {
plugin.debug("Could not " + args[1].toLowerCase() + " inventory for kit, " + e);
} finally {
try {
if (rsInv != null) {
rsInv.close();
}
if (rsNewInv != null) {
rsNewInv.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not remove block, " + e);
}
}
return true;
}
} else {
sender.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_PERMISSION"));
plugin.message(sender, plugin.getM().get("NO_PERMISSION"));
return true;
}
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
if (args.length <= 1) {
return partial(args[0], ROOT_SUBS);
if (label.equalsIgnoreCase("gmic")) {
return ImmutableList.of();
}
if (args.length <= 1) {
return partial(args[0], ROOT_SUBS);
}
return ImmutableList.of();
}
// Tells the player why the toggle failed - Creative denials name the region.
private void sendDenial(Player player, GameMode target) {
final String key = target.equals(GameMode.CREATIVE) ? "NO_CREATIVE_REGION" : "NO_PERMISSION";
plugin.message(player, plugin.getM().get(key));
}
private List<String> partial(String token, Collection<String> from) {
return StringUtil.copyPartialMatches(token, from, new ArrayList<>(from.size()));
}
}
}
@@ -3,215 +3,102 @@
*/
package me.eccentric_nz.gamemodeinventories;
import org.bukkit.ChatColor;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author eccentric_nz
*/
// Checks the deployed config.yml against the canonical one bundled in the jar; there is no defaults
// map, so the bundled file is the only description of what this plugin reads. Nothing is written back, ever.
public class GameModeInventoriesConfig {
private final GameModeInventories plugin;
HashMap<String, String> strOptions = new HashMap<>();
HashMap<String, Integer> intOptions = new HashMap<>();
HashMap<String, Boolean> boolOptions = new HashMap<>();
List<String> containers = new ArrayList<>();
List<String> bl = new ArrayList<>();
List<String> com = new ArrayList<>();
List<String> wor = new ArrayList<>();
List<String> no = new ArrayList<>();
private final FileConfiguration config;
private final File configFile;
public GameModeInventoriesConfig(GameModeInventories plugin) {
this.plugin = plugin;
configFile = new File(plugin.getDataFolder(), "config.yml");
config = YamlConfiguration.loadConfiguration(configFile);
// string
strOptions.put("debug_level", "ERROR");
strOptions.put("storage.mysql.server", "localhost");
strOptions.put("storage.mysql.port", "3306");
strOptions.put("storage.mysql.database", "GMI");
strOptions.put("storage.mysql.user", "bukkit");
strOptions.put("storage.mysql.password", "mysecurepassword");
strOptions.put("storage.database", "sqlite");
strOptions.put("storage.prefix", "");
strOptions.put("creative_world.world", "creative");
strOptions.put("creative_world.location", "last_known");
// int
intOptions.put("storage.mysql.pool_size", 10);
// boolean
boolOptions.put("armor", true);
boolOptions.put("break_bedrock", false);
boolOptions.put("bypass.inventories", true);
boolOptions.put("bypass.items", true);
boolOptions.put("bypass.blacklist", false);
boolOptions.put("bypass.commands", false);
boolOptions.put("bypass.survival", false);
boolOptions.put("bypass.trades", false);
boolOptions.put("command_blacklist", false);
boolOptions.put("creative_blacklist", false);
boolOptions.put("debug", false);
boolOptions.put("dont_spam_chat", false);
boolOptions.put("enderchest", true);
boolOptions.put("no_creative_pvp", false);
boolOptions.put("no_drops", false);
boolOptions.put("no_falling_drops", false);
boolOptions.put("no_pickups", false);
boolOptions.put("no_villager_trade", false);
boolOptions.put("no_wither_spawn", false);
boolOptions.put("no_golem_spawn", false);
boolOptions.put("remove_potions", true);
boolOptions.put("restrict_creative", false);
boolOptions.put("restrict_spectator", false);
boolOptions.put("save_on_death", true);
boolOptions.put("creative_world.switch_to", false);
boolOptions.put("track_creative_place.break_no_drop", false);
boolOptions.put("track_creative_place.enabled", true);
boolOptions.put("track_creative_place.no_piston_move", false);
boolOptions.put("track_creative_place.attached_block", false);
boolOptions.put("track_creative_place.no_seeds_from_pumpkin", false);
boolOptions.put("track_creative_place.dont_track_is_whitelist", false);
boolOptions.put("xp", true);
boolOptions.put("uuid_conversion_done", false);
boolOptions.put("blocks_conversion_done", false);
boolOptions.put("storage.mysql.test_connection", false);
boolOptions.put("storage.mysql.useSSL", true);
containers.add("ANVIL");
containers.add("BARREL");
containers.add("BEACON");
containers.add("BEE_NEST");
containers.add("BEEHIVE");
containers.add("BLACK_SHULKER_BOX");
containers.add("BLAST_FURNACE");
containers.add("BLUE_SHULKER_BOX");
containers.add("BREWING_STAND");
containers.add("BROWN_SHULKER_BOX");
containers.add("CAMPFIRE");
containers.add("CARTOGRAPHY_TABLE");
containers.add("CHEST");
containers.add("CHIPPED_ANVIL");
containers.add("COMPOSTER");
containers.add("CYAN_SHULKER_BOX");
containers.add("DAMAGED_ANVIL");
containers.add("DISPENSER");
containers.add("DROPPER");
containers.add("ENCHANTING_TABLE");
containers.add("ENDER_CHEST");
containers.add("FLETCHING_TABLE");
containers.add("FURNACE");
containers.add("GRAY_SHULKER_BOX");
containers.add("GREEN_SHULKER_BOX");
containers.add("GRINDSTONE");
containers.add("HOPPER");
containers.add("JUKEBOX");
containers.add("LECTERN");
containers.add("LIGHT_BLUE_SHULKER_BOX");
containers.add("LIGHT_GRAY_SHULKER_BOX");
containers.add("LIME_SHULKER_BOX");
containers.add("LOOM");
containers.add("MAGENTA_SHULKER_BOX");
containers.add("ORANGE_SHULKER_BOX");
containers.add("PINK_SHULKER_BOX");
containers.add("PURPLE_SHULKER_BOX");
containers.add("RED_SHULKER_BOX");
containers.add("SHULKER_BOX");
containers.add("SMITHING_TABLE");
containers.add("SMOKER");
containers.add("SOUL_CAMPFIRE");
containers.add("STONECUTTER");
containers.add("TRAPPED_CHEST");
containers.add("WHITE_SHULKER_BOX");
containers.add("YELLOW_SHULKER_BOX");
bl.add("TNT");
bl.add("BEDROCK");
bl.add("LAVA_BUCKET");
com.add("give");
com.add("i");
com.add("buy");
com.add("sell");
wor.add("world");
no.add("STONE");
no.add("DIRT");
this.configFile = new File(plugin.getDataFolder(), "config.yml");
}
public void checkConfig() {
int i = 0;
// string values
for (Map.Entry<String, String> entry : strOptions.entrySet()) {
if (!config.contains(entry.getKey())) {
plugin.getConfig().set(entry.getKey(), entry.getValue());
i++;
}
if (!configFile.exists()) {
plugin.getLogger().log(Level.SEVERE, "config.yml was not found at " + configFile.getAbsolutePath()
+ ". This plugin only reads config.yml and will not generate or modify it.");
return;
}
// int values
for (Map.Entry<String, Integer> entry : intOptions.entrySet()) {
if (!config.contains(entry.getKey())) {
plugin.getConfig().set(entry.getKey(), entry.getValue());
i++;
}
YamlConfiguration canonical = loadCanonical();
if (canonical == null) {
plugin.getLogger().log(Level.SEVERE,
"The canonical config.yml is missing from the jar; deployed options cannot be checked.");
return;
}
// boolean values
for (Map.Entry<String, Boolean> entry : boolOptions.entrySet()) {
if (!config.contains(entry.getKey())) {
if (entry.getKey().equals("track_creative_place.enabled")) {
// check for previous enrty
if (plugin.getConfig().contains("track_creative_place")) {
plugin.getConfig().set(entry.getKey(), plugin.getConfig().getBoolean("track_creative_place"));
} else {
plugin.getConfig().set(entry.getKey(), entry.getValue());
}
}
plugin.getConfig().set(entry.getKey(), entry.getValue());
i++;
}
FileConfiguration deployed = plugin.getConfig();
List<String> missing = canonical.getKeys(true).stream().filter(key -> !canonical.isConfigurationSection(key))
.filter(key -> !deployed.contains(key)).toList();
missing.forEach(key -> plugin.getLogger().log(Level.WARNING, "Missing config option: " + key));
if (!missing.isEmpty()) {
plugin.getLogger().log(Level.WARNING, "config.yml is immutable; " + missing.size()
+ " option(s) are missing and were not written automatically. Copy them from the jar's config.yml.");
}
if (!config.contains("containers")) {
plugin.getConfig().set("containers", containers);
i++;
}
if (!config.contains("blacklist")) {
plugin.getConfig().set("blacklist", bl);
i++;
} else if (plugin.getConfig().getStringList("blacklist").contains("ZOMBIE_PIGMAN_SPAWN_EGG")) {
List<String> black = plugin.getConfig().getStringList("blacklist");
black.remove("ZOMBIE_PIGMAN_SPAWN_EGG");
black.add("ZOMBIFIED_PIGLIN_SPAWN_EGG");
plugin.getConfig().set("blacklist", black);
i++;
}
if (!config.contains("commands")) {
plugin.getConfig().set("commands", com);
i++;
}
if (!config.contains("track_creative_place.worlds")) {
plugin.getConfig().set("track_creative_place.worlds", wor);
i++;
}
if (!config.contains("track_creative_place.dont_track")) {
plugin.getConfig().set("track_creative_place.dont_track", no);
i++;
}
if (config.contains("storage.mysql.url")) {
String url = config.getString("storage.mysql.url");
// mysql://localhost:3306/GMI
String[] split = url.split("/");
String[] sp = split[2].split(":");
plugin.getConfig().set("storage.mysql.server", sp[0]);
plugin.getConfig().set("storage.mysql.port", sp[1]);
plugin.getConfig().set("storage.mysql.database", split[3]);
plugin.getConfig().set("storage.mysql.url", null);
}
if (i > 0) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "Added " + ChatColor.AQUA + i + ChatColor.RESET + " new items to config");
}
plugin.saveConfig();
warnAboutLegacyOptions(deployed);
}
private YamlConfiguration loadCanonical() {
try (InputStream resource = plugin.getResource("config.yml")) {
if (resource == null) {
return null;
}
return YamlConfiguration.loadConfiguration(new InputStreamReader(resource, StandardCharsets.UTF_8));
} catch (Exception error) {
plugin.getLogger().log(Level.SEVERE, "Could not read the canonical config.yml: " + error.getMessage());
return null;
}
}
private void warnAboutLegacyOptions(FileConfiguration deployed) {
if (deployed.getStringList("blacklist").contains("ZOMBIE_PIGMAN_SPAWN_EGG")) {
plugin.getLogger().log(Level.WARNING,
"config.yml still contains ZOMBIE_PIGMAN_SPAWN_EGG; update it manually to ZOMBIFIED_PIGLIN_SPAWN_EGG if needed.");
}
if (deployed.contains("storage.mysql.url")) {
plugin.getLogger().log(Level.WARNING,
"Legacy storage.mysql.url is still present in config.yml; update it manually because automatic migration is disabled.");
}
}
}
@@ -1,16 +1,17 @@
package me.eccentric_nz.gamemodeinventories;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import java.util.Arrays;
import java.util.List;
public class GameModeInventoriesConstructedMob {
public static boolean checkBlocks(Material trigger, Block block) {
switch (trigger) {
case PUMPKIN:
case CARVED_PUMPKIN:
case JACK_O_LANTERN:
@@ -20,100 +21,217 @@ public class GameModeInventoriesConstructedMob {
return isWither(block, trigger);
default:
return false;
}
}
private static final List<BlockFace> faces = Arrays.asList(BlockFace.DOWN, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.UP);
private static final List<BlockFace> faces = Arrays.asList(BlockFace.DOWN, BlockFace.EAST, BlockFace.NORTH,
BlockFace.WEST, BlockFace.SOUTH, BlockFace.UP);
private static boolean isGolem(Block block) {
BlockFace direction = BlockFace.DOWN;
for (BlockFace face : faces) {
if (block.getRelative(face).getType().equals(Material.IRON_BLOCK) && block.getRelative(face, 2).equals(Material.IRON_BLOCK)) {
if (block.getRelative(face).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(face, 2).equals(Material.IRON_BLOCK))
{
direction = face;
break;
}
}
switch (direction) {
case DOWN:
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getType()
.equals(Material.IRON_BLOCK))
{
return true;
} else if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getType().equals(Material.IRON_BLOCK)) {
} else if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getType()
.equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
case EAST:
if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.EAST).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.EAST).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.EAST).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.EAST).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
case NORTH:
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.NORTH).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.WEST).getRelative(BlockFace.NORTH).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.NORTH).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.WEST).getRelative(BlockFace.NORTH).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
case WEST:
if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.WEST).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.WEST).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.WEST).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.WEST).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
case SOUTH:
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.SOUTH).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.WEST).getRelative(BlockFace.SOUTH).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.SOUTH).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.WEST).getRelative(BlockFace.SOUTH).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
case UP:
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.UP).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.WEST).getRelative(BlockFace.UP).getType().equals(Material.IRON_BLOCK)) {
if (block.getRelative(BlockFace.EAST).getRelative(BlockFace.UP).getType().equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.WEST).getRelative(BlockFace.UP).getType()
.equals(Material.IRON_BLOCK))
{
return true;
} else if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP).getType().equals(Material.IRON_BLOCK) && block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getType().equals(Material.IRON_BLOCK)) {
} else if (block.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP).getType()
.equals(Material.IRON_BLOCK)
&& block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getType()
.equals(Material.IRON_BLOCK))
{
return true;
}
default:
return false;
}
}
private static boolean isWither(Block block, Material trigger) {
Block skull = block;
// get middle skull
for (BlockFace face : faces) {
if (block.getRelative(face).getType().equals(trigger) && block.getRelative(face, 2).getType().equals(trigger)) {
if (block.getRelative(face).getType().equals(trigger)
&& block.getRelative(face, 2).getType().equals(trigger))
{
skull = block.getRelative(face);
break;
}
}
BlockFace direction = BlockFace.DOWN;
for (BlockFace face : faces) {
if (skull.getRelative(face).getType().equals(Material.SOUL_SAND) && skull.getRelative(face, 2).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(face).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(face, 2).getType().equals(Material.SOUL_SAND))
{
direction = face;
break;
}
}
switch (direction) {
case DOWN:
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getType()
.equals(Material.SOUL_SAND))
{
return true;
} else if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getType().equals(Material.SOUL_SAND)) {
} else if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getType()
.equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
case EAST:
if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.EAST).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.EAST).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.EAST).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.EAST).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
case NORTH:
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.NORTH).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.WEST).getRelative(BlockFace.NORTH).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.NORTH).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.WEST).getRelative(BlockFace.NORTH).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
case WEST:
if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.WEST).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.WEST).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.WEST).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.WEST).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
case SOUTH:
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.SOUTH).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.WEST).getRelative(BlockFace.SOUTH).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.SOUTH).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.WEST).getRelative(BlockFace.SOUTH).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
case UP:
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.UP).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.WEST).getRelative(BlockFace.UP).getType().equals(Material.SOUL_SAND)) {
if (skull.getRelative(BlockFace.EAST).getRelative(BlockFace.UP).getType().equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.WEST).getRelative(BlockFace.UP).getType()
.equals(Material.SOUL_SAND))
{
return true;
} else if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP).getType().equals(Material.SOUL_SAND) && skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getType().equals(Material.SOUL_SAND)) {
} else if (skull.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP).getType()
.equals(Material.SOUL_SAND)
&& skull.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getType()
.equals(Material.SOUL_SAND))
{
return true;
}
default:
return false;
}
}
}
@@ -1,18 +1,19 @@
package me.eccentric_nz.gamemodeinventories;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import org.bukkit.GameMode;
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.PlayerDeathEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
public class GameModeInventoriesDeath implements Listener {
@@ -21,74 +22,133 @@ public class GameModeInventoriesDeath implements Listener {
private final GameMode mode;
public GameModeInventoriesDeath(GameModeInventories plugin) {
this.plugin = plugin;
ServerValues sv = getServerForceGamemode();
force = sv.getForce();
mode = sv.getMode();
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
assert (event.getEntity() instanceof Player);
Player p = event.getEntity();
if (p.hasPermission("gamemodeinventories.death") && plugin.getConfig().getBoolean("save_on_death")) {
// save their inventory
plugin.getInventoryHandler().saveOnDeath(p);
event.getDrops().clear();
// Only suppress vanilla drops when the inventory was actually parked, else the
// items are lost
if (plugin.getInventoryHandler().saveOnDeath(p)) {
event.getDrops().clear();
}
}
if (p.getGameMode().equals(GameMode.CREATIVE) && plugin.getConfig().getBoolean("no_drops")) {
event.getDrops().clear();
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player p = event.getPlayer();
if (p.hasPermission("gamemodeinventories.use") && force) {
p.setGameMode(mode);
plugin.internalGameModeChange(p, mode);
}
}
@EventHandler
public void onRespawn(PlayerRespawnEvent event) {
Player p = event.getPlayer();
if (p.hasPermission("gamemodeinventories.death") && plugin.getConfig().getBoolean("save_on_death")) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
plugin.getInventoryHandler().restoreOnSpawn(p);
});
}
}
/**
* Gets the server values for force-gamemode and gamemode.
*
* @return whether the value is true or false.
*/
// A parked death inventory returns once the player is back in its world
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldChange(PlayerChangedWorldEvent event) {
Player p = event.getPlayer();
if (p.hasPermission("gamemodeinventories.death") && plugin.getConfig().getBoolean("save_on_death")) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
if (p.isOnline()) {
plugin.getInventoryHandler().restoreOnSpawn(p);
}
});
}
}
// reads force-gamemode and gamemode from server.properties
private ServerValues getServerForceGamemode() {
FileInputStream in = null;
ServerValues sv = new ServerValues();
try {
Properties properties = new Properties();
String path = "server.properties";
in = new FileInputStream(path);
properties.load(in);
sv.setForce(properties.getProperty("force-gamemode").equalsIgnoreCase("true"));
GameMode gmode = GameMode.valueOf(properties.getProperty("gamemode").toUpperCase(Locale.ENGLISH));
// Missing keys mean the vanilla defaults, not a crash on enable
sv.setForce(properties.getProperty("force-gamemode", "false").equalsIgnoreCase("true"));
GameMode gmode = GameMode
.valueOf(properties.getProperty("gamemode", "survival").toUpperCase(Locale.ENGLISH));
sv.setMode(gmode);
} catch (FileNotFoundException ex) {
plugin.debug("Could not find server.properties!");
} catch (IOException ex) {
plugin.debug("Could not read server.properties!");
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
plugin.debug("Could not close server.properties!");
}
}
return sv;
}
public class ServerValues {
@@ -97,19 +157,29 @@ public class GameModeInventoriesDeath implements Listener {
private GameMode mode;
public boolean getForce() {
return force;
}
public void setForce(boolean force) {
this.force = force;
}
public GameMode getMode() {
return mode;
}
public void setMode(GameMode mode) {
this.mode = mode;
}
}
}
@@ -3,6 +3,9 @@
*/
package me.eccentric_nz.gamemodeinventories;
import java.util.Arrays;
import java.util.List;
import net.kyori.adventure.text.Component;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
@@ -13,67 +16,104 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import java.util.Arrays;
import java.util.List;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesEntityListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesEntityListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void onArmorStandPlace(CreatureSpawnEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
if (event.getEntityType().equals(EntityType.ARMOR_STAND)) {
Location l = event.getLocation();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(l.getWorld().getName())) {
return;
}
List<String> locs = Arrays.asList(l.getBlockX() + "," + l.getBlockZ(), (l.getBlockX()) + "," + (l.getBlockZ() - 1), (l.getBlockX() - 1) + "," + (l.getBlockZ()), (l.getBlockX()) + "," + (l.getBlockZ() + 1), (l.getBlockX() + 1) + "," + (l.getBlockZ()));
List<String> locs = Arrays.asList(l.getBlockX() + "," + l.getBlockZ(),
(l.getBlockX()) + "," + (l.getBlockZ() - 1), (l.getBlockX() - 1) + "," + (l.getBlockZ()),
(l.getBlockX()) + "," + (l.getBlockZ() + 1), (l.getBlockX() + 1) + "," + (l.getBlockZ()));
for (String p : locs) {
if (plugin.getPoints().contains(p)) {
plugin.getStands().add(event.getEntity().getUniqueId());
plugin.getPoints().remove(p);
break;
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onArmorStandBreakOrCreativePVP(EntityDamageByEntityEvent event) {
if (plugin.getConfig().getBoolean("no_creative_pvp") && event.getEntityType().equals(EntityType.PLAYER)) {
Entity attacker = event.getDamager();
if (attacker instanceof Player player) {
if (player.getGameMode().equals(GameMode.CREATIVE)) {
event.setCancelled(true);
return;
}
}
}
if (plugin.getConfig().getBoolean("track_creative_place.enabled") && event.getEntityType().equals(EntityType.ARMOR_STAND)) {
if (event.getEntity().getLastDamageCause() != null && plugin.getStands().contains(event.getEntity().getUniqueId())) {
if (plugin.getConfig().getBoolean("track_creative_place.enabled")
&& event.getEntityType().equals(EntityType.ARMOR_STAND))
{
if (event.getEntity().getLastDamageCause() != null
&& plugin.getStands().contains(event.getEntity().getUniqueId()))
{
event.setCancelled(true);
String message = plugin.getM().getMessage().get("NO_CREATIVE_BREAK");
Component message = plugin.getM().get("NO_CREATIVE_BREAK");
if (plugin.getConfig().getBoolean("track_creative_place.break_no_drop")) {
event.getEntity().remove();
message = plugin.getM().getMessage().get("NO_CREATIVE_DROPS");
message = plugin.getM().get("NO_CREATIVE_DROPS");
}
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
Entity damager = event.getDamager();
if (damager instanceof Player player) {
player.sendMessage(plugin.MY_PLUGIN_NAME + message);
plugin.message(player, message);
}
}
}
}
}
}
@@ -6,349 +6,520 @@
*/
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import org.bukkit.GameMode;
import org.bukkit.entity.*;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.GameMode;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.inventory.InventoryHolder;
// Owns only the CREATIVE inventory per bundle. Survival lives in Purpur's RocksDB through MyWorlds, so no
// inventory is ever stored in two places and the two stores cannot diverge.
public class GameModeInventoriesInventory {
private static final String CREATIVE = GameMode.CREATIVE.name();
private final GameModeInventories plugin;
private final boolean saveXP;
private final boolean saveArmour;
private final boolean saveEnderChest;
private final boolean potions;
GameModeInventoriesXPCalculator xpc;
public GameModeInventoriesInventory(GameModeInventories plugin) {
this.plugin = plugin;
saveXP = this.plugin.getConfig().getBoolean("xp");
saveArmour = this.plugin.getConfig().getBoolean("armor");
saveEnderChest = this.plugin.getConfig().getBoolean("enderchest");
potions = this.plugin.getConfig().getBoolean("remove_potions");
}
public void switchInventories(Player player, GameMode newGM) {
// Persists the player's current (creative) inventory for this bundle. Kicks on
// failure so an unsaved
// creative inventory is never silently dropped or overwritten later.
public void saveCreative(Player player, String bundle) {
String uuid = player.getUniqueId().toString();
String name = player.getName();
String currentGM = player.getGameMode().name();
if (saveXP) {
xpc = new GameModeInventoriesXPCalculator(player);
}
GameModeInventoriesXPCalculator xpc = saveXP ? new GameModeInventoriesXPCalculator(player) : null;
String inv = GameModeInventoriesBukkitSerialization.toDatabase(player.getInventory().getContents());
Connection connection = null;
PreparedStatement statement = null;
ResultSet rsInv = null;
PreparedStatement ps = null;
ResultSet idRS = null;
PreparedStatement psx = null;
PreparedStatement psa = null;
PreparedStatement pse = null;
ResultSet rsNewInv = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
if (connection != null && !connection.isClosed()) {
statement = connection.prepareStatement("SELECT * FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = ?");
// get their current gamemode inventory from database
statement.setString(1, uuid);
statement.setString(2, currentGM);
rsInv = statement.executeQuery();
int id = 0;
if (rsInv.next()) {
// update it with their current inventory
id = rsInv.getInt("id");
String updateQuery = "UPDATE " + plugin.getPrefix() + "inventories SET inventory = ? WHERE id = ?";
ps = connection.prepareStatement(updateQuery);
ps.setString(1, inv);
ps.setInt(2, id);
ps.executeUpdate();
} else {
// they haven't got an inventory saved yet so make one with their current inventory
String insertQuery = "INSERT INTO " + plugin.getPrefix() + "inventories (uuid, player, gamemode, inventory) VALUES (?, ?, ?, ?)";
ps = connection.prepareStatement(insertQuery, PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, uuid);
ps.setString(2, name);
ps.setString(3, currentGM);
ps.setString(4, inv);
ps.executeUpdate();
idRS = ps.getGeneratedKeys();
if (idRS.next()) {
id = idRS.getInt(1);
}
}
if (saveXP) {
// get players XP
int a = xpc.getCurrentExp();
String xpQuery = "UPDATE " + plugin.getPrefix() + "inventories SET xp = ? WHERE id = ?";
psx = connection.prepareStatement(xpQuery);
psx.setInt(1, a);
psx.setInt(2, id);
psx.executeUpdate();
}
if (saveArmour) {
// get players armour
String arm = GameModeInventoriesBukkitSerialization.toDatabase(player.getInventory().getArmorContents());
String armourQuery = "UPDATE " + plugin.getPrefix() + "inventories SET armour = ? WHERE id = ?";
psa = connection.prepareStatement(armourQuery);
psa.setString(1, arm);
psa.setInt(2, id);
psa.executeUpdate();
}
if (saveEnderChest) {
// get players enderchest
Inventory ec = player.getEnderChest();
if (ec != null) {
String ender = GameModeInventoriesBukkitSerialization.toDatabase(ec.getContents());
String enderQuery = "UPDATE " + plugin.getPrefix() + "inventories SET enderchest = ? WHERE id = ?";
pse = connection.prepareStatement(enderQuery);
pse.setString(1, ender);
pse.setInt(2, id);
pse.executeUpdate();
}
}
if (potions && currentGM.equals("CREATIVE") && !newGM.equals(GameMode.CREATIVE)) {
// remove all potion effects
player.getActivePotionEffects().forEach((effect) -> {
player.removePotionEffect(effect.getType());
});
}
// check if they have an inventory for the new gamemode
try {
statement.setString(1, uuid);
statement.setString(2, newGM.name());
rsNewInv = statement.executeQuery();
int amount;
if (rsNewInv.next()) {
// set their inventory to the saved one
String savedinventory = rsNewInv.getString("inventory");
ItemStack[] stacks;
if (savedinventory.startsWith("[")) {
stacks = GameModeInventoriesJSONSerialization.toItemStacks(savedinventory);
} else {
stacks = GameModeInventoriesBukkitSerialization.fromDatabase(savedinventory);
}
player.getInventory().setContents(stacks);
amount = rsNewInv.getInt("xp");
if (saveArmour) {
String savedarmour = rsNewInv.getString("armour");
if (savedarmour != null) {
ItemStack[] a;
if (savedarmour.startsWith("[")) {
a = GameModeInventoriesJSONSerialization.toItemStacks(savedarmour);
} else {
a = GameModeInventoriesBukkitSerialization.fromDatabase(savedarmour);
}
player.getInventory().setArmorContents(a);
}
}
if (saveEnderChest) {
String savedender = rsNewInv.getString("enderchest");
if (savedender == null || savedender.equals("[Null]") || savedender.equals("") || savedender.isEmpty()) {
// empty inventory
savedender = "[\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\"]";
}
ItemStack[] e;
if (savedender.startsWith("[")) {
e = GameModeInventoriesJSONSerialization.toItemStacks(savedender);
} else {
e = GameModeInventoriesBukkitSerialization.fromDatabase(savedender);
}
Inventory echest = player.getEnderChest();
echest.setContents(e);
}
} else {
// start with an empty inventory
player.getInventory().clear();
if (saveArmour) {
player.getInventory().setBoots(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setHelmet(null);
}
if (saveEnderChest) {
Inventory echest = player.getEnderChest();
echest.clear();
}
amount = 0;
}
int xp = saveXP ? xpc.getCurrentExp() : 0;
String arm = saveArmour
? GameModeInventoriesBukkitSerialization.toDatabase(player.getInventory().getArmorContents())
: null;
String ender = (saveEnderChest && player.getEnderChest() != null)
? GameModeInventoriesBukkitSerialization.toDatabase(player.getEnderChest().getContents())
: null;
if (saveXP) {
xpc.setExp(amount);
}
player.updateInventory();
} catch (IOException ex) {
GameModeInventories.plugin.debug("Could not restore inventory on gamemode change, " + ex);
}
} else {
GameModeInventories.plugin.debug("Database connection was NULL or closed");
}
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not save inventory on gamemode change, " + e);
} finally {
try (Connection connection = plugin.getDatabaseConnection()) {
connection.setAutoCommit(false);
try {
if (rsNewInv != null) {
rsNewInv.close();
}
if (pse != null) {
pse.close();
}
if (psa != null) {
psa.close();
}
if (psx != null) {
psx.close();
}
if (idRS != null) {
idRS.close();
}
if (ps != null) {
ps.close();
}
if (rsInv != null) {
rsInv.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not close resultsets, statements or connection, " + e);
saveSlot(connection, uuid, name, CREATIVE, bundle, inv, xp, arm, ender);
connection.commit();
} catch (Exception e) {
connection.rollback();
throw e;
} finally {
connection.setAutoCommit(true);
}
} catch (Exception e) {
GameModeInventories.plugin.debug("Could not save creative inventory, kicking to avoid losing it, " + e);
player.kickPlayer("Inventory sync failed, please rejoin");
}
}
public void saveOnDeath(Player p) {
// Loads the player's creative inventory for this bundle, or clears it when none
// is stored. Kicks on failure.
public void loadCreative(Player player, String bundle) {
String uuid = player.getUniqueId().toString();
GameModeInventoriesXPCalculator xpc = saveXP ? new GameModeInventoriesXPCalculator(player) : null;
try (Connection connection = plugin.getDatabaseConnection()) {
LoadedSlot dest = readSlot(connection, uuid, CREATIVE, bundle);
applyCreative(player, dest, xpc);
} catch (Exception e) {
GameModeInventories.plugin
.debug("Could not load creative inventory, kicking to avoid a wrong profile, " + e);
player.kickPlayer("Inventory sync failed, please rejoin");
}
}
// Removes potion effects the player picked up in creative, matching the old
// leave-creative behavior.
public void clearCreativePotions(Player player) {
if (potions) {
player.getActivePotionEffects().forEach((effect) -> player.removePotionEffect(effect.getType()));
}
}
// The decoded contents of one (uuid, gamemode, bundle) slot, or null when none
// is stored.
private static final class LoadedSlot {
final ItemStack[] inv;
final ItemStack[] arm;
final ItemStack[] ender;
final int xp;
LoadedSlot(ItemStack[] inv, ItemStack[] arm, ItemStack[] ender, int xp) {
this.inv = inv;
this.arm = arm;
this.ender = ender;
this.xp = xp;
}
}
private static ItemStack[] decode(String s) throws IOException {
return s.startsWith("[") ? GameModeInventoriesJSONSerialization.toItemStacks(s)
: GameModeInventoriesBukkitSerialization.fromDatabase(s);
}
// Reads and fully decodes a slot before anything is applied. Null when the
// player has none yet.
private LoadedSlot readSlot(Connection connection, String uuid, String gamemode, String bundle)
throws SQLException, IOException
{
try (PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = ? AND bundle = ?");)
{
statement.setString(1, uuid);
statement.setString(2, gamemode);
statement.setString(3, bundle);
try (ResultSet rs = statement.executeQuery();) {
if (!rs.next()) {
return null;
}
ItemStack[] inv = decode(rs.getString("inventory"));
int xp = rs.getInt("xp");
ItemStack[] arm = null;
if (saveArmour) {
String savedarmour = rs.getString("armour");
if (savedarmour != null) {
arm = decode(savedarmour);
}
}
ItemStack[] ender = null;
if (saveEnderChest) {
String savedender = rs.getString("enderchest");
if (savedender == null || savedender.equals("[Null]") || savedender.isEmpty()) {
savedender = "[\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\"]";
}
ender = decode(savedender);
}
return new LoadedSlot(inv, arm, ender, xp);
}
}
}
// Upserts one (uuid, gamemode, bundle) slot with the given contents.
private void saveSlot(Connection connection, String uuid, String name, String gamemode, String bundle, String inv,
int xp, String arm, String ender) throws SQLException
{
int id;
try (PreparedStatement select = connection.prepareStatement(
"SELECT id FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = ? AND bundle = ?");)
{
select.setString(1, uuid);
select.setString(2, gamemode);
select.setString(3, bundle);
try (ResultSet rs = select.executeQuery();) {
if (rs.next()) {
id = rs.getInt("id");
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE " + plugin.getPrefix() + "inventories SET inventory = ? WHERE id = ?");)
{
ps.setString(1, inv);
ps.setInt(2, id);
ps.executeUpdate();
}
} else {
try (PreparedStatement ps = connection.prepareStatement(
"INSERT INTO " + plugin.getPrefix()
+ "inventories (uuid, player, gamemode, inventory, bundle) VALUES (?, ?, ?, ?, ?)",
PreparedStatement.RETURN_GENERATED_KEYS);)
{
ps.setString(1, uuid);
ps.setString(2, name);
ps.setString(3, gamemode);
ps.setString(4, inv);
ps.setString(5, bundle);
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys();) {
id = keys.next() ? keys.getInt(1) : 0;
}
}
}
}
}
if (saveXP) {
try (PreparedStatement ps = connection
.prepareStatement("UPDATE " + plugin.getPrefix() + "inventories SET xp = ? WHERE id = ?");)
{
ps.setInt(1, xp);
ps.setInt(2, id);
ps.executeUpdate();
}
}
if (saveArmour && arm != null) {
try (PreparedStatement ps = connection
.prepareStatement("UPDATE " + plugin.getPrefix() + "inventories SET armour = ? WHERE id = ?");)
{
ps.setString(1, arm);
ps.setInt(2, id);
ps.executeUpdate();
}
}
if (saveEnderChest && ender != null) {
try (PreparedStatement ps = connection
.prepareStatement("UPDATE " + plugin.getPrefix() + "inventories SET enderchest = ? WHERE id = ?");)
{
ps.setString(1, ender);
ps.setInt(2, id);
ps.executeUpdate();
}
}
}
// Puts the decoded creative slot onto the player, or clears everything when
// there was none.
private void applyCreative(Player player, LoadedSlot dest, GameModeInventoriesXPCalculator xpc) {
if (dest == null) {
player.getInventory().clear();
if (saveArmour) {
player.getInventory().setBoots(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setHelmet(null);
}
if (saveEnderChest) {
player.getEnderChest().clear();
}
if (saveXP) {
xpc.setExp(0);
}
player.updateInventory();
return;
}
player.getInventory().setContents(dest.inv);
if (saveArmour && dest.arm != null) {
player.getInventory().setArmorContents(dest.arm);
}
if (saveEnderChest && dest.ender != null) {
player.getEnderChest().setContents(dest.ender);
}
if (saveXP) {
xpc.setExp(dest.xp);
}
player.updateInventory();
}
// Pre-bundle slots were used everywhere, so they join the main bundle. False
// when the migration could not run.
public boolean assignLegacySlotsTo(String bundle) {
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement ps = connection.prepareStatement(
"UPDATE " + plugin.getPrefix() + "inventories SET bundle = ? WHERE bundle IS NULL");)
{
ps.setString(1, bundle);
int moved = ps.executeUpdate();
if (moved > 0) {
plugin.getLogger().info(
"[GameModeInventories] Assigned " + moved + " legacy inventory slots to bundle " + bundle);
}
return true;
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not assign legacy inventory slots to a bundle, " + e);
return false;
}
}
// Parks a death's inventory under its bundle and mode. Always inserts, so an
// earlier unrestored death is never
// overwritten. Returns true only when the row is durably written, so the caller
// can keep vanilla drops otherwise.
public boolean saveOnDeath(Player p) {
String uuid = p.getUniqueId().toString();
String name = p.getName();
String gm = p.getGameMode().name();
String bundle = plugin.getBundles().of(p.getWorld());
String inv = GameModeInventoriesBukkitSerialization.toDatabase(p.getInventory().getContents());
String arm = GameModeInventoriesBukkitSerialization.toDatabase(p.getInventory().getArmorContents());
Connection connection = null;
PreparedStatement statement = null;
ResultSet rsInv = null;
PreparedStatement ps = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.prepareStatement("SELECT id FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = ?");
// get their current gamemode inventory from database
statement.setString(1, uuid);
statement.setString(2, gm);
rsInv = statement.executeQuery();
if (rsInv.isBeforeFirst() && rsInv.next()) {
// update it with their current inventory
int id = rsInv.getInt("id");
String updateQuery = "UPDATE " + plugin.getPrefix() + "inventories SET inventory = ?, armour = ? WHERE id = ?";
ps = connection.prepareStatement(updateQuery);
ps.setString(1, inv);
ps.setString(2, arm);
ps.setInt(3, id);
} else {
// they haven't got an inventory saved yet so make one with their current inventory
String invQuery = "INSERT INTO " + plugin.getPrefix() + "inventories (uuid, player, gamemode, inventory, armour) VALUES (?, ?, ?, ?, ?,)";
ps = connection.prepareStatement(invQuery);
ps.setString(1, uuid);
ps.setString(2, name);
ps.setString(3, gm);
ps.setString(4, inv);
ps.setString(5, arm);
}
ps.executeUpdate();
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement ps = connection.prepareStatement("INSERT INTO " + plugin.getPrefix()
+ "deaths (uuid, player, gamemode, world, inventory, armour) VALUES (?, ?, ?, ?, ?, ?)");)
{
ps.setString(1, uuid);
ps.setString(2, name);
ps.setString(3, gm);
// The 'world' column holds the inventory bundle, so a shared group restores
// anywhere in it
ps.setString(4, bundle);
ps.setString(5, inv);
ps.setString(6, arm);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not save inventories on player death, " + e);
} finally {
try {
if (ps != null) {
ps.close();
}
if (rsInv != null) {
rsInv.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not close resultsets, statements or connection, " + e);
}
return false;
}
}
// Returns the oldest death parked in this bundle and mode, added to the player
// without discarding what they hold.
public void restoreOnSpawn(Player p) {
String uuid = p.getUniqueId().toString();
String gm = p.getGameMode().name();
// restore their inventory
Connection connection = null;
PreparedStatement statement = null;
ResultSet rsInv = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.prepareStatement("SELECT * FROM " + plugin.getPrefix() + "inventories WHERE uuid = ? AND gamemode = ?");
// get their current gamemode inventory from database
String bundle = plugin.getBundles().of(p.getWorld());
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + plugin.getPrefix()
+ "deaths WHERE uuid = ? AND world = ? AND gamemode = ? ORDER BY id LIMIT 1");)
{
statement.setString(1, uuid);
statement.setString(2, gm);
rsInv = statement.executeQuery();
if (rsInv.next()) {
statement.setString(2, bundle);
statement.setString(3, gm);
try (ResultSet rs = statement.executeQuery();) {
if (!rs.next()) {
return;
}
int id = rs.getInt("id");
ItemStack[] i;
ItemStack[] a;
try {
// set their inventory to the saved one
String savedinventory = rsInv.getString("inventory");
ItemStack[] i;
if (savedinventory.startsWith("[")) {
i = GameModeInventoriesJSONSerialization.toItemStacks(savedinventory);
} else {
i = GameModeInventoriesBukkitSerialization.fromDatabase(savedinventory);
}
p.getInventory().setContents(i);
String savedarmour = rsInv.getString("armour");
ItemStack[] a;
if (savedarmour.startsWith("[")) {
a = GameModeInventoriesJSONSerialization.toItemStacks(savedarmour);
} else {
a = GameModeInventoriesBukkitSerialization.fromDatabase(savedarmour);
}
p.getInventory().setArmorContents(a);
i = decode(rs.getString("inventory"));
a = decode(rs.getString("armour"));
} catch (IOException e) {
GameModeInventories.plugin.debug("Could not restore inventories on respawn, " + e);
return;
}
giveOrDrop(p, i);
giveOrDrop(p, a);
try (PreparedStatement clear = connection
.prepareStatement("DELETE FROM " + plugin.getPrefix() + "deaths WHERE id = ?");)
{
clear.setInt(1, id);
clear.executeUpdate();
}
}
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not restore inventories on respawn, " + e);
} finally {
try {
if (rsInv != null) {
rsInv.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not close resultsets, statements or connection, " + e);
}
}
}
// Adds items to the player, dropping any that do not fit, so a restore never
// clobbers what they already hold.
private void giveOrDrop(Player p, ItemStack[] items) {
if (items == null) {
return;
}
for (ItemStack item : items) {
if (item == null || item.getType().isAir()) {
continue;
}
p.getInventory().addItem(item).values()
.forEach(leftover -> p.getWorld().dropItem(p.getLocation(), leftover));
}
}
public boolean isInstanceOf(Entity e) {
return e instanceof PoweredMinecart || e instanceof StorageMinecart || e instanceof HopperMinecart || e instanceof ItemFrame || e instanceof ArmorStand;
return e instanceof PoweredMinecart || e instanceof StorageMinecart || e instanceof HopperMinecart
|| e instanceof ItemFrame || e instanceof ArmorStand;
}
public boolean isInstanceOf(InventoryHolder h) {
return (h instanceof AbstractHorse);
}
}
@@ -16,115 +16,176 @@
*/
package me.eccentric_nz.gamemodeinventories;
import java.util.*;
import java.util.logging.Level;
import me.eccentric_nz.gamemodeinventories.JSON.JSONArray;
import me.eccentric_nz.gamemodeinventories.JSON.JSONException;
import me.eccentric_nz.gamemodeinventories.JSON.JSONObject;
import org.bukkit.Bukkit;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.inventory.ItemStack;
import java.util.*;
/**
* Fancy JSON serialization mostly by evilmidget38.
*
* @author eccentric_nz
*/
// Fancy JSON serialization mostly by evilmidget38.
public class GameModeInventoriesJSONSerialization {
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<>();
Iterator<String> keys = object.keys();
while (keys.hasNext()) {
String key = keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
public static String toString(ItemStack[] inv) {
List<String> result = new ArrayList<>();
List<ConfigurationSerializable> items = new ArrayList<>();
items.addAll(Arrays.asList(inv));
items.forEach((cs) -> {
if (cs == null) {
result.add("null");
} else {
result.add(new JSONObject(serialize(cs)).toString());
}
});
JSONArray json_array = new JSONArray(result);
return json_array.toString();
}
public static ItemStack[] toItemStacks(String s) {
JSONArray json = new JSONArray(s);
List<ItemStack> contents = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
String piece = json.getString(i);
if (piece.equalsIgnoreCase("null")) {
contents.add(null);
} else {
try {
ItemStack item = (ItemStack) deserialize(toMap(new JSONObject(piece)));
contents.add(item);
} catch (JSONException e) {
System.err.println("There was a JSON error: " + e.getMessage());
Bukkit.getLogger().log(Level.WARNING, "There was a JSON error: " + e.getMessage());
}
}
}
ItemStack[] items = new ItemStack[contents.size()];
for (int x = 0; x < contents.size(); x++) {
items[x] = contents.get(x);
}
return items;
}
public static Map<String, Object> serialize(ConfigurationSerializable cs) {
Map<String, Object> serialized = recreateMap(cs.serialize());
serialized.entrySet().forEach((entry) -> {
if (entry.getValue() instanceof ConfigurationSerializable configurationSerializable) {
entry.setValue(serialize(configurationSerializable));
}
});
serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass()));
serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY,
ConfigurationSerialization.getAlias(cs.getClass()));
return serialized;
}
public static Map<String, Object> recreateMap(Map<String, Object> original) {
Map<String, Object> map = new HashMap<>();
original.entrySet().forEach((entry) -> {
map.put(entry.getKey(), entry.getValue());
});
return map;
}
public static ConfigurationSerializable deserialize(Map<String, Object> map) {
map.entrySet().forEach((entry) -> {
if (entry.getValue() instanceof Map map1 && map1.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
if (entry.getValue() instanceof Map map1
&& map1.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY))
{
entry.setValue(deserialize((Map) entry.getValue()));
}
});
return ConfigurationSerialization.deserializeObject(map);
}
}
@@ -1,6 +1,17 @@
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -12,6 +23,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
@@ -20,205 +32,571 @@ import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class GameModeInventoriesListener implements Listener {
private final GameModeInventories plugin;
List<Material> containers = new ArrayList<>();
private final List<Material> containers = new ArrayList<>();
private final Map<UUID, Location> pendingModeCheckLocations = new HashMap<>();
private final Set<UUID> protectedFromForcedFall = new HashSet<>();
public GameModeInventoriesListener(GameModeInventories plugin) {
this.plugin = plugin;
for (String m : this.plugin.getConfig().getStringList("containers")) {
try {
containers.add(Material.valueOf(m));
} catch (IllegalArgumentException e) {
System.out.println(plugin.MY_PLUGIN_NAME + "Illegal material name " + m + " in containers list!");
plugin.getLogger().log(Level.INFO, "Illegal material name " + m + " in containers list!");
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
@EventHandler(priority = EventPriority.LOWEST)
public void rememberMoveDestination(PlayerMoveEvent event) {
rememberModeCheckLocation(event.getPlayer(), event.getTo());
}
@EventHandler(priority = EventPriority.LOWEST)
public void rememberTeleportDestination(PlayerTeleportEvent event) {
rememberModeCheckLocation(event.getPlayer(), event.getTo());
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onGameModeChange(PlayerGameModeChangeEvent event) {
Player p = event.getPlayer();
GameMode newGM = event.getNewGameMode();
if (newGM.equals(GameMode.SPECTATOR) && plugin.getConfig().getBoolean("restrict_spectator") && !p.hasPermission("gamemodeinventories.spectator")) {
// Internal switches (/gmic, the policy's changeGameMode) are pre-validated
// and trusted; only external routes (/gamemode, other plugins) are policed.
boolean internal = plugin.isInternalGameModeChange(p);
if (!internal && newGM.equals(GameMode.CREATIVE) && !canUseCreativeAt(p, modeCheckLocation(p))) {
// cancelling leaves them in the mode they were already in
event.setCancelled(true);
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_SPECTATOR"));
plugin.message(p, plugin.getM().get("NO_CREATIVE_REGION"));
return;
}
if (!internal && newGM.equals(GameMode.SPECTATOR) && !plugin.getGameModePolicy().mayUseSpectator(p)) {
event.setCancelled(true);
plugin.message(p, plugin.getM().get("NO_SPECTATOR"));
return;
}
// Cancelled rather than corrected, so adventure cannot stick in a world that
// is meant to stay survival.
if (!internal && newGM.equals(GameMode.ADVENTURE)
&& !plugin.getGameModePolicy().mayUseAdventureAt(p.getLocation()))
{
event.setCancelled(true);
plugin.message(p, plugin.getM().get("NO_ADVENTURE"));
return;
}
if (p.hasPermission("gamemodeinventories.use")) {
if (p.isOnline()) {
plugin.getInventoryHandler().switchInventories(p, newGM);
// The creative inventory is swapped by the LOW/HIGH handlers below; survival is
// MyWorlds' job
if (newGM.equals(GameMode.CREATIVE) && plugin.getConfig().getBoolean("creative_world.switch_to")) {
// get spawn location
Location loc = plugin.getServer().getWorld(plugin.getConfig().getString("creative_world.world")).getSpawnLocation();
Location loc = plugin.getServer().getWorld(plugin.getConfig().getString("creative_world.world"))
.getSpawnLocation();
if (plugin.getConfig().getString("creative_world.location").equals("last_known")) {
//get last known position in world
String uuid = p.getUniqueId().toString();
// player changed worlds, record last location
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
if (connection != null && !connection.isClosed()) {
// check if the player has a record for this world
statement = connection.prepareStatement("SELECT * FROM " + plugin.getPrefix() + "worlds WHERE uuid = ? AND world = ?");
statement.setString(1, uuid);
statement.setString(2, plugin.getConfig().getString("creative_world.world"));
rs = statement.executeQuery();
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM " + plugin.getPrefix() + "worlds WHERE uuid = ? AND world = ?");)
{
statement.setString(1, uuid);
statement.setString(2, plugin.getConfig().getString("creative_world.world"));
try (ResultSet rs = statement.executeQuery();) {
if (rs.next()) {
World w = plugin.getServer().getWorld(rs.getString("world"));
if (w != null) {
double x = rs.getDouble("x");
double y = rs.getDouble("y");
double z = rs.getDouble("z");
float yaw = rs.getFloat("yaw");
float pitch = rs.getFloat("pitch");
// send to last location
loc = new Location(w, x, y, z, yaw, pitch);
}
}
}
} catch (SQLException e) {
plugin.debug("Could not get creative world location, " + e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not close resultsets, statements or connection [worlds], " + e);
}
}
}
if (loc != null) {
p.teleport(loc);
}
}
}
}
}
// Save the outgoing creative inventory at LOW, before any HIGH handler loads
// the incoming one over live.
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onLeaveCreative(PlayerGameModeChangeEvent event) {
Player p = event.getPlayer();
if (!p.hasPermission("gamemodeinventories.use")) {
return;
}
if (p.getGameMode().equals(GameMode.CREATIVE) && !event.getNewGameMode().equals(GameMode.CREATIVE)) {
plugin.getInventoryHandler().saveCreative(p, plugin.getBundles().of(p.getWorld()));
plugin.getInventoryHandler().clearCreativePotions(p);
}
}
// Load the incoming creative inventory at HIGH, after every LOW handler has
// saved the outgoing one.
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEnterCreative(PlayerGameModeChangeEvent event) {
Player p = event.getPlayer();
if (!p.hasPermission("gamemodeinventories.use")) {
return;
}
if (!p.getGameMode().equals(GameMode.CREATIVE) && event.getNewGameMode().equals(GameMode.CREATIVE)) {
plugin.getInventoryHandler().loadCreative(p, plugin.getBundles().of(p.getWorld()));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void clearMoveDestination(PlayerMoveEvent event) {
pendingModeCheckLocations.remove(event.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR)
public void clearTeleportDestination(PlayerTeleportEvent event) {
pendingModeCheckLocations.remove(event.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMove(PlayerMoveEvent event) {
Location to = event.getTo();
if (to == null) {
return;
}
Player player = event.getPlayer();
if (protectedFromForcedFall.contains(player.getUniqueId()) && player.isOnGround()) {
protectedFromForcedFall.remove(player.getUniqueId());
}
Location from = event.getFrom();
if (player.getGameMode().equals(GameMode.CREATIVE) && (from.getBlockX() != to.getBlockX()
|| from.getBlockY() != to.getBlockY() || from.getBlockZ() != to.getBlockZ())
&& !canUseCreativeAt(player, to))
{
forceSurvival(player);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onTeleportCreativeRestriction(PlayerTeleportEvent event) {
Player player = event.getPlayer();
Location to = event.getTo();
if (to != null && player.getGameMode().equals(GameMode.CREATIVE) && !canUseCreativeAt(player, to)) {
plugin.getServer().getScheduler().runTask(plugin, () -> forceSurvival(player));
}
}
// A creative player rejoins holding the survival profile MyWorlds loaded, so
// swap in their creative inventory
// before anything (like a forced-survival check) runs next tick.
@EventHandler(priority = EventPriority.LOW)
public void onJoinLoadCreative(PlayerJoinEvent event) {
Player p = event.getPlayer();
if (p.getGameMode().equals(GameMode.CREATIVE) && p.hasPermission("gamemodeinventories.use")) {
plugin.getInventoryHandler().loadCreative(p, plugin.getBundles().of(p.getWorld()));
}
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
// Spawn-OG normalizes logins in a transaction that also relocates; forcing
// survival underneath would race it, so this only covers servers without it.
if (plugin.getServer().getPluginManager().isPluginEnabled("Spawn-OG")) {
return;
}
Player player = event.getPlayer();
if (player.getGameMode().equals(GameMode.CREATIVE) && !canUseCreativeAt(player, player.getLocation())) {
plugin.getServer().getScheduler().runTask(plugin, () -> forceSurvival(player));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFallDamage(EntityDamageEvent event) {
if (event.getCause().equals(EntityDamageEvent.DamageCause.FALL) && event.getEntity() instanceof Player player
&& protectedFromForcedFall.remove(player.getUniqueId()))
{
event.setCancelled(true);
player.setFallDistance(0.0F);
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
Player p = event.getPlayer();
protectedFromForcedFall.remove(p.getUniqueId());
pendingModeCheckLocations.remove(p.getUniqueId());
// Persist a creative inventory on quit; survival is saved by MyWorlds and the
// server
if (p.getGameMode().equals(GameMode.CREATIVE) && p.hasPermission("gamemodeinventories.use")) {
plugin.getInventoryHandler().saveCreative(p, plugin.getBundles().of(p.getWorld()));
}
}
// Say why when another plugin drops a player out of Creative.
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onForcedSurvival(PlayerGameModeChangeEvent event) {
final Player p = event.getPlayer();
// at MONITOR the change is not applied, so getGameMode() is the old mode
if (!event.getNewGameMode().equals(GameMode.SURVIVAL) || !p.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
// only plugin driven Creative removal counts, not /gamemode
if (!event.getCause().equals(PlayerGameModeChangeEvent.Cause.PLUGIN) || plugin.isInternalGameModeChange(p)) {
return;
}
if (p.hasPermission("gamemodeinventories.toggle") || p.hasPermission("gamemodeinventories.anywhere")) {
return;
}
plugin.message(p, plugin.getM().get("FORCED_SURVIVAL"));
}
@EventHandler(ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
if (plugin.getConfig().getBoolean("restrict_creative")) {
Block b = event.getClickedBlock();
if (b != null) {
Player p = event.getPlayer();
if (p.isSneaking() && isBlock(p.getInventory().getItemInMainHand().getType())) {
return;
}
Material m = b.getType();
GameMode gm = p.getGameMode();
if (gm.equals(GameMode.CREATIVE) && containers.contains(m) && !GameModeInventoriesBypass.canBypass(p, "inventories", plugin) && event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
if (gm.equals(GameMode.CREATIVE) && containers.contains(m)
&& !GameModeInventoriesBypass.canBypass(p, "inventories", plugin)
&& event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
{
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_CREATIVE_INVENTORY"));
plugin.message(p, plugin.getM().get("NO_CREATIVE_INVENTORY"));
}
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent event) {
if (plugin.getConfig().getBoolean("no_drops")) {
Inventory inv = event.getInventory();
if (inv.getType().equals(InventoryType.WORKBENCH)) {
Player p = (Player) event.getPlayer();
if (p.getGameMode().equals(GameMode.CREATIVE) && !GameModeInventoriesBypass.canBypass(p, "inventories", plugin)) {
if (p.getGameMode().equals(GameMode.CREATIVE)
&& !GameModeInventoriesBypass.canBypass(p, "inventories", plugin))
{
boolean empty = true;
for (ItemStack is : inv.getContents()) {
if (!is.getType().isAir()) {
empty = false;
}
}
if (!empty) {
inv.clear();
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_WORKBENCH_DROPS"));
plugin.message(p, plugin.getM().get("NO_WORKBENCH_DROPS"));
}
}
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityClick(PlayerInteractEntityEvent event) {
if (plugin.getConfig().getBoolean("restrict_creative")) {
Entity entity = event.getRightClicked();
Player p = event.getPlayer();
if (p.getGameMode().equals(GameMode.CREATIVE) && plugin.getInventoryHandler().isInstanceOf(entity) && !GameModeInventoriesBypass.canBypass(p, "inventories", plugin)) {
if (p.getGameMode().equals(GameMode.CREATIVE) && plugin.getInventoryHandler().isInstanceOf(entity)
&& !GameModeInventoriesBypass.canBypass(p, "inventories", plugin))
{
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_CREATIVE_INVENTORY"));
plugin.message(p, plugin.getM().get("NO_CREATIVE_INVENTORY"));
}
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
//treat it the same as interacting with an entity in general
onEntityClick((PlayerInteractEntityEvent) event);
onEntityClick(event);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDrop(PlayerDropItemEvent event) {
if (plugin.getConfig().getBoolean("no_drops")) {
Player p = event.getPlayer();
GameMode gm = p.getGameMode();
if (gm.equals(GameMode.CREATIVE) && !GameModeInventoriesBypass.canBypass(p, "items", plugin)) {
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_PLAYER_DROPS"));
plugin.message(p, plugin.getM().get("NO_PLAYER_DROPS"));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void noPickup(EntityPickupItemEvent event) {
if (event.getEntity() instanceof Player player && plugin.getConfig().getBoolean("no_pickups")) {
GameMode gm = player.getGameMode();
if (gm.equals(GameMode.CREATIVE) && !GameModeInventoriesBypass.canBypass(player, "items", plugin)) {
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
player.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_CREATIVE_PICKUP"));
plugin.message(player, plugin.getM().get("NO_CREATIVE_PICKUP"));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void noHorseInventory(InventoryOpenEvent event) {
if (plugin.getConfig().getBoolean("restrict_creative") && plugin.getInventoryHandler().isInstanceOf(event.getInventory().getHolder())) {
if (plugin.getConfig().getBoolean("restrict_creative")
&& plugin.getInventoryHandler().isInstanceOf(event.getInventory().getHolder()))
{
Player p = (Player) event.getPlayer();
GameMode gm = p.getGameMode();
if (gm.equals(GameMode.CREATIVE) && !GameModeInventoriesBypass.canBypass(p, "inventories", plugin)) {
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_CREATIVE_HORSE"));
plugin.message(p, plugin.getM().get("NO_CREATIVE_HORSE"));
}
}
}
}
// Both region and permission rules live in GameModePolicy so this plugin and
// its consumers cannot drift apart on where creative is allowed.
private boolean canUseCreativeAt(Player player, Location location) {
return plugin.getGameModePolicy().mayUseCreativeAt(player, location);
}
private Location modeCheckLocation(Player player) {
return pendingModeCheckLocations.getOrDefault(player.getUniqueId(), player.getLocation());
}
private void rememberModeCheckLocation(Player player, Location location) {
if (location != null) {
pendingModeCheckLocations.put(player.getUniqueId(), location);
}
}
private void forceSurvival(Player player) {
// the anywhere permission keeps a player in whatever mode they chose
if (!player.isOnline() || player.getGameMode().equals(GameMode.SURVIVAL)
|| player.hasPermission("gamemodeinventories.anywhere"))
{
return;
}
protectedFromForcedFall.add(player.getUniqueId());
player.setFallDistance(0.0F);
// flagged as plugin driven so the generic notice does not double up
plugin.internalGameModeChange(player, GameMode.SURVIVAL);
plugin.message(player, plugin.getM().get("FORCED_SURVIVAL"));
plugin.getServer().getScheduler().runTask(plugin, () -> {
if (player.isOnline() && player.isOnGround()) {
protectedFromForcedFall.remove(player.getUniqueId());
}
});
}
private boolean isBlock(Material m) {
return !m.isAir() && m.isBlock();
}
}
@@ -3,19 +3,26 @@
*/
package me.eccentric_nz.gamemodeinventories;
import org.bukkit.ChatColor;
import java.io.*;
import java.util.HashMap;
import java.util.IllegalFormatException;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesMessage {
// Matches the colour codes of messages.yml files predating the MiniMessage
// switch.
private static final Pattern LEGACY_CODES = Pattern.compile("[&§][0-9a-fk-orA-FK-OR]");
private final GameModeInventories plugin;
private final HashMap<String, String> message = new HashMap<>();
private final FileConfiguration messagesConfig;
@@ -23,88 +30,215 @@ public class GameModeInventoriesMessage {
HashMap<String, String> messageOptions = new HashMap<>();
public GameModeInventoriesMessage(GameModeInventories plugin) {
this.plugin = plugin;
messagesFile = getMessagesFile();
messagesConfig = YamlConfiguration.loadConfiguration(messagesFile);
messageOptions.put("CONFIG_SET", "%s was set to: %s");
messageOptions.put("HELP", "There is no help! Just switch game modes, and your inventory/armor/xp will change.");
messageOptions.put("INVALID_MATERIAL", "Invalid material in blacklist");
messageOptions.put("INVALID_MATERIAL_TRACK", "Invalid material in dont_track list");
messageOptions.put("NO_CREATIVE_BREAK", "You cannot break blocks that were placed in CREATIVE gamemode!");
messageOptions.put("NO_CREATIVE_COMMAND", "You are not allowed to use %s in CREATIVE!");
messageOptions.put("NO_CREATIVE_DROPS", "Blocks that were placed in CREATIVE gamemode, do not give drops!");
messageOptions.put("NO_CREATIVE_HORSE", "You are not allowed to access horse inventories in CREATIVE!");
messageOptions.put("NO_CREATIVE_INVENTORY", "You are not allowed to access inventories in CREATIVE!");
messageOptions.put("NO_CREATIVE_PICKUP", "You are not allowed to pick up items in CREATIVE!");
messageOptions.put("NO_CREATIVE_PLACE", "%s placement is disabled in CREATIVE gamemode!");
messageOptions.put("NO_PERMISSION", "You do not have permission to run that command!");
messageOptions.put("NO_PLAYER_DROPS", "You are not allowed to drop items in CREATIVE!");
messageOptions.put("NO_WORKBENCH_DROPS", "Workbenches do not drop items in CREATIVE!");
messageOptions.put("NO_SPECTATOR", "You are not allowed to be a SPECTATOR!");
messageOptions.put("NO_TRADE", "You are not allowed to trade with villagers in CREATIVE!");
messageOptions.put("CONFIG_SET", "<green><option> was set to: <value>");
messageOptions.put("FORCED_SURVIVAL",
"<red>Notice: <gold>You were switched to Survival mode because you do not have permission for Creative mode here.");
messageOptions.put("HELP",
"<gold>Simply switch game modes, and your inventory, armor and xp will change with you.");
messageOptions.put("INVALID_MATERIAL", "<red>Error: <gold>Invalid material in blacklist");
messageOptions.put("INVALID_MATERIAL_TRACK", "<red>Error: <gold>Invalid material in dont_track list");
messageOptions.put("NO_CREATIVE_BREAK",
"<red>Error: <gold>You cannot break blocks that were placed in Creative mode!");
messageOptions.put("NO_CREATIVE_COMMAND",
"<red>Error: <gold>You are not allowed to use <green><command></green> in Creative mode!");
messageOptions.put("NO_CREATIVE_DROPS",
"<red>Error: <gold>Blocks that were placed in Creative mode do not give drops!");
messageOptions.put("NO_CREATIVE_HORSE",
"<red>Error: <gold>You are not allowed to access horse inventories in Creative mode!");
messageOptions.put("NO_CREATIVE_INVENTORY",
"<red>Error: <gold>You are not allowed to access inventories in Creative mode!");
messageOptions.put("NO_CREATIVE_PICKUP",
"<red>Error: <gold>You are not allowed to pick up items in Creative mode!");
messageOptions.put("NO_CREATIVE_PLACE", "<red>Error: <gold><material> placement is disabled in Creative mode!");
messageOptions.put("NO_CREATIVE_REGION",
"<red>Error: <gold>You do not have permission to enter Creative mode in this region!");
messageOptions.put("NO_PERMISSION", "<red>Error: <gold>You do not have permission to run that command!");
messageOptions.put("NO_PLAYER_DROPS", "<red>Error: <gold>You are not allowed to drop items in Creative mode!");
messageOptions.put("NO_WORKBENCH_DROPS", "<red>Error: <gold>Workbenches do not drop items in Creative mode!");
messageOptions.put("NO_SPECTATOR", "<red>Error: <gold>You are not allowed to be a Spectator!");
messageOptions.put("NO_ADVENTURE", "<red>Error: <gold>Adventure mode is not allowed in this world!");
messageOptions.put("NO_TRADE",
"<red>Error: <gold>You are not allowed to trade with villagers in Creative mode!");
}
public void getMessages() {
messagesConfig.getKeys(false).forEach((m) -> {
message.put(m, messagesConfig.getString(m));
String configuredMessage = messagesConfig.getString(m);
if (configuredMessage != null) {
// stored raw - get() picks MiniMessage or the legacy reader per message
message.put(m, configuredMessage);
}
});
}
public HashMap<String, String> getMessage() {
return message;
// Gets a message as a component - args fill any placeholders the message
// declares.
public Component get(String key, Arg... args) {
String raw = message.get(key);
if (raw == null) {
raw = messageOptions.getOrDefault(key, key);
}
if (LEGACY_CODES.matcher(raw).find()) {
// messages.yml predates the MiniMessage switch, so read it the old way
return legacy(raw, args);
}
final TagResolver.Builder resolvers = TagResolver.builder();
for (Arg arg : args) {
// unparsed, so player supplied text cannot smuggle in tags of its own
resolvers.resolver(Placeholder.unparsed(arg.name(), arg.value()));
}
return MiniMessage.miniMessage().deserialize(raw, resolvers.build());
}
private Component legacy(String raw, Arg... args) {
String formatted = raw;
if (args.length > 0) {
final Object[] values = new Object[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = args[i].value();
}
try {
formatted = String.format(raw, values);
} catch (IllegalFormatException e) {
plugin.debug("Could not format legacy message '" + raw + "', " + e.getMessage());
}
}
return LegacyComponentSerializer.legacyAmpersand().deserialize(formatted);
}
private File getMessagesFile() {
File file = new File(plugin.getDataFolder(), "messages.yml");
InputStream in = plugin.getResource("messages.yml");
if (!file.exists()) {
OutputStream out;
try {
out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
try {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException io) {
System.err.println("[GameModeInventories] Could not save the file (" + file.toString() + ").");
plugin.getLogger().log(Level.WARNING,
"[GameModeInventories] Could not save the file (" + file.toString() + ").");
} finally {
try {
out.close();
} catch (IOException e) {
}
}
} catch (FileNotFoundException e) {
System.err.println("[GameModeInventories] File not found.");
plugin.getLogger().log(Level.WARNING, "[GameModeInventories] File not found.");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
return file;
}
public void updateMessages() {
// message values
int m = 0;
for (Map.Entry<String, String> entry : messageOptions.entrySet()) {
if (!messagesConfig.contains(entry.getKey())) {
plugin.getConfig().set(entry.getKey(), entry.getValue());
messagesConfig.set(entry.getKey(), entry.getValue());
message.put(entry.getKey(), entry.getValue());
m++;
}
}
if (m > 0) {
try {
messagesConfig.save(messagesFile);
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "Added " + ChatColor.AQUA + m + ChatColor.RESET + " new items to messages.yml");
plugin.getLogger().log(Level.INFO, "Added " + m + " new items to messages.yml");
} catch (IOException ex) {
plugin.debug("Could not save messages.yml, " + ex.getMessage());
}
}
}
// A message placeholder - name matches a MiniMessage tag, falls back to legacy
// %s.
public record Arg(String name, String value) {
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2014 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories;
import com.bergerkiller.bukkit.mw.events.PlayerProfileAppliedEvent;
import org.bukkit.GameMode;
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.PlayerChangedWorldEvent;
// The one class compiled against MyWorlds, registered only when it is present. Creative follows the bundle too,
// so a world change swaps the creative inventory just like a game mode change does.
public class GameModeInventoriesMyWorldsListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesMyWorldsListener(GameModeInventories plugin) {
this.plugin = plugin;
}
// Before MyWorlds loads the destination's survival profile, save the creative
// inventory of the world being left.
@EventHandler(priority = EventPriority.NORMAL)
public void onWorldChange(PlayerChangedWorldEvent event) {
Player p = event.getPlayer();
if (p.getGameMode().equals(GameMode.CREATIVE) && p.hasPermission("gamemodeinventories.use")) {
plugin.getInventoryHandler().saveCreative(p, plugin.getBundles().of(event.getFrom()));
}
}
// MyWorlds loads the destination survival profile at MONITOR and then fires
// this; a creative player gets the
// destination bundle's creative inventory loaded over it.
@EventHandler(priority = EventPriority.MONITOR)
public void onProfileApplied(PlayerProfileAppliedEvent event) {
Player p = event.getPlayer();
if (p.getGameMode().equals(GameMode.CREATIVE) && p.hasPermission("gamemodeinventories.use")) {
plugin.getInventoryHandler().loadCreative(p, plugin.getBundles().of(p.getWorld()));
}
}
}
@@ -3,6 +3,8 @@
*/
package me.eccentric_nz.gamemodeinventories;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
@@ -10,12 +12,6 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import java.util.ArrayList;
import java.util.List;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesPhysicsListener implements Listener {
private final GameModeInventories plugin;
@@ -24,6 +20,7 @@ public class GameModeInventoriesPhysicsListener implements Listener {
private final List<Material> plates = new ArrayList<>();
public GameModeInventoriesPhysicsListener(GameModeInventories plugin) {
this.plugin = plugin;
willDrop.add(Material.ACACIA_BUTTON);
willDrop.add(Material.ACACIA_DOOR);
@@ -174,35 +171,63 @@ public class GameModeInventoriesPhysicsListener implements Listener {
plates.add(Material.OAK_PRESSURE_PLATE);
plates.add(Material.SPRUCE_PRESSURE_PLATE);
plates.add(Material.STONE_PRESSURE_PLATE);
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
if (block == null) {
return;
}
if (!willDrop.contains(block.getType())) {
return;
}
if (!plugin.getConfig().getBoolean("track_creative_place.enabled") || !plugin.getConfig().getBoolean("track_creative_place.attached_block")) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")
|| !plugin.getConfig().getBoolean("track_creative_place.attached_block"))
{
return;
}
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
if (doors.contains(block.getType()) && plates.contains(event.getChangedType())) {
return;
}
if (willDrop.contains(block.getType())) {
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
// check if the block was placed in creative
if (plugin.getCreativeBlocks().get(gmiwc).contains(event.getBlock().getLocation().toString())) {
event.setCancelled(true);
}
}
}
}
@@ -3,6 +3,8 @@
*/
package me.eccentric_nz.gamemodeinventories;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
@@ -10,18 +12,13 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import java.util.ArrayList;
import java.util.List;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesPistonListener implements Listener {
private final GameModeInventories plugin;
private final List<Material> wouldDrop = new ArrayList<>();
public GameModeInventoriesPistonListener(GameModeInventories plugin) {
this.plugin = plugin;
wouldDrop.add(Material.ACACIA_DOOR);
wouldDrop.add(Material.ACACIA_PRESSURE_PLATE);
@@ -104,66 +101,118 @@ public class GameModeInventoriesPistonListener implements Listener {
wouldDrop.add(Material.WHITE_BED); // Still Breaks
wouldDrop.add(Material.WHITE_TULIP);
wouldDrop.add(Material.YELLOW_BED);
}
@EventHandler(ignoreCancelled = true)
public void onPistonExtend(BlockPistonExtendEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
if (plugin.getConfig().getBoolean("track_creative_place.no_piston_move")) {
Block block = event.getBlock();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
for (Block b : event.getBlocks()) {
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + ","
+ block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(b.getLocation().toString())) {
if (wouldDrop.contains(b.getType())) {
event.setCancelled(true);
plugin.debug("Cancelled piston extension because one of the moved blocks would drop an item");
return;
} else if (plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
// update the location of the moved block
plugin.getCreativeBlocks().get(gmiwc).remove(b.getLocation().toString());
plugin.getCreativeBlocks().get(gmiwc).add(b.getRelative(event.getDirection()).getLocation().toString());
plugin.getCreativeBlocks().get(gmiwc)
.add(b.getRelative(event.getDirection()).getLocation().toString());
} else {
event.setCancelled(true);
plugin.debug("Cancelled piston extension because one of the moved blocks was a CREATIVE placed block");
plugin.debug(
"Cancelled piston extension because one of the moved blocks was a CREATIVE placed block");
}
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPistonRetract(BlockPistonRetractEvent event) {
if (!event.isSticky()) {
return;
}
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
Block block = event.getBlock();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(block.getRelative(event.getDirection(), 2).getLocation().toString())) {
if (plugin.getCreativeBlocks().get(gmiwc)
.contains(block.getRelative(event.getDirection(), 2).getLocation().toString()))
{
if (plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
// update the location of the moved block
plugin.getCreativeBlocks().get(gmiwc).remove(block.getRelative(event.getDirection(), 2).getLocation().toString());
plugin.getCreativeBlocks().get(gmiwc).add(block.getRelative(event.getDirection()).getLocation().toString());
plugin.getCreativeBlocks().get(gmiwc)
.remove(block.getRelative(event.getDirection(), 2).getLocation().toString());
plugin.getCreativeBlocks().get(gmiwc)
.add(block.getRelative(event.getDirection()).getLocation().toString());
} else {
event.setCancelled(true);
plugin.debug("Cancelled piston retraction because the moved block was a CREATIVE placed block");
}
}
}
}
@@ -3,84 +3,82 @@
*/
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.logging.Level;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesStand {
private final GameModeInventories plugin;
private Connection connection = null;
public GameModeInventoriesStand(GameModeInventories plugin) {
this.plugin = plugin;
}
public void loadStands() {
PreparedStatement statement = null;
ResultSet rs = null;
if (plugin.getConfig().getBoolean("track_creative_place.enabled")) {
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.prepareStatement("SELECT uuid FROM " + plugin.getPrefix() + "stands");
rs = statement.executeQuery();
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement statement = connection
.prepareStatement("SELECT uuid FROM " + plugin.getPrefix() + "stands");
ResultSet rs = statement.executeQuery();)
{
if (rs.isBeforeFirst()) {
while (rs.next()) {
plugin.getStands().add(UUID.fromString(rs.getString("uuid")));
}
}
// clear stands
statement = connection.prepareStatement("DELETE FROM " + plugin.getPrefix() + "stands");
statement.executeUpdate();
} catch (SQLException e) {
System.err.println("Could not load stands, " + e);
} finally {
try {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException ex) {
plugin.debug("Error closing stands statement or resultset: " + ex.getMessage());
try (PreparedStatement ps = connection
.prepareStatement("DELETE FROM " + plugin.getPrefix() + "stands");)
{
ps.executeUpdate();
}
} catch (SQLException e) {
plugin.getLogger().log(Level.WARNING, "Could not load stands, " + e);
}
}
}
public void saveStands() {
PreparedStatement ps = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
ps = connection.prepareStatement("INSERT INTO " + plugin.getPrefix() + "stands (uuid) VALUES (?)");
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement ps = connection
.prepareStatement("INSERT INTO " + plugin.getPrefix() + "stands (uuid) VALUES (?)");)
{
for (UUID uuid : plugin.getStands()) {
ps.setString(1, uuid.toString());
ps.executeUpdate();
}
} catch (SQLException e) {
System.err.println("Could not save stands, " + e);
} finally {
try {
if (ps != null) {
ps.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException ex) {
plugin.debug("Error closing stands statement: " + ex.getMessage());
}
plugin.getLogger().log(Level.WARNING, "Could not save stands, " + e);
}
}
}
@@ -3,7 +3,8 @@
*/
package me.eccentric_nz.gamemodeinventories;
import de.diddiz.LogBlock.Actor;
import me.eccentric_nz.gamemodeinventories.GameModeInventoriesMessage.Arg;
import net.kyori.adventure.text.Component;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -16,106 +17,167 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesTrackBlackListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesTrackBlackListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
Player p = event.getPlayer();
Block block = event.getBlock();
if (block.getType().isAir()) {
return;
}
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
if (plugin.getNoTrackList().contains(block.getType())) {
return;
}
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
if (p.getGameMode().equals(GameMode.CREATIVE)) {
plugin.getBlock().removeBlock(gmiwc, block.getLocation().toString());
} else {
String message;
Component message;
if (plugin.getConfig().getBoolean("track_creative_place.break_no_drop")) {
// remove the location from the creative blocks list because we're removing the block!
// remove the location from the creative blocks list because we're removing the
// block
plugin.getBlock().removeBlock(gmiwc, block.getLocation().toString());
if (plugin.getBlockLogger().isLogging()) {
Location loc = block.getLocation();
String pname = p.getName();
switch (plugin.getBlockLogger().getWhichLogger()) {
case CORE_PROTECT: // log the block removal
Material type = block.getType();
BlockData data = block.getBlockData();
plugin.getBlockLogger().getCoreProtectAPI().logRemoval(pname, loc, type, data);
break;
case LOG_BLOCK:
plugin.getBlockLogger().getLogBlockConsumer().queueBlockBreak(Actor.actorFromEntity(p), block.getState());
break;
default:
break;
}
Material type = block.getType();
BlockData data = block.getBlockData();
plugin.getBlockLogger().getCoreProtectAPI().logRemoval(pname, loc, type, data);
}
block.setType(Material.AIR);
block.getDrops().clear();
message = plugin.getM().getMessage().get("NO_CREATIVE_DROPS");
message = plugin.getM().get("NO_CREATIVE_DROPS");
} else {
event.setCancelled(true);
message = plugin.getM().getMessage().get("NO_CREATIVE_BREAK");
message = plugin.getM().get("NO_CREATIVE_BREAK");
}
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + message);
plugin.message(p, message);
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Player p = event.getPlayer();
if (!p.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
Material mat = event.getBlock().getType();
if ((mat.equals(Material.WITHER_SKELETON_SKULL) || mat.equals(Material.WITHER_SKELETON_WALL_SKULL)) && plugin.getConfig().getBoolean("no_wither_spawn") && GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock())) {
if ((mat.equals(Material.WITHER_SKELETON_SKULL) || mat.equals(Material.WITHER_SKELETON_WALL_SKULL))
&& plugin.getConfig().getBoolean("no_wither_spawn")
&& GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock()))
{
event.setCancelled(true);
} else if ((mat.equals(Material.CARVED_PUMPKIN) || mat.equals(Material.JACK_O_LANTERN)) && plugin.getConfig().getBoolean("no_golem_spawn") && GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock())) {
} else if ((mat.equals(Material.CARVED_PUMPKIN) || mat.equals(Material.JACK_O_LANTERN))
&& plugin.getConfig().getBoolean("no_golem_spawn")
&& GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock()))
{
event.setCancelled(true);
}
if (plugin.getConfig().getBoolean("creative_blacklist") && plugin.getBlackList().contains(mat) && !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin)) {
if (plugin.getConfig().getBoolean("creative_blacklist") && plugin.getBlackList().contains(mat)
&& !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin))
{
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + String.format(plugin.getM().getMessage().get("NO_CREATIVE_PLACE"), mat.toString()));
plugin.message(p, plugin.getM().get("NO_CREATIVE_PLACE", new Arg("material", mat.toString())));
}
return;
}
if (plugin.getConfig().getBoolean("track_creative_place.enabled")) {
Block block = event.getBlock();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
if (plugin.getNoTrackList().contains(mat)) {
return;
}
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc) || !plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
if (!plugin.getCreativeBlocks().containsKey(gmiwc)
|| !plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString()))
{
plugin.getBlock().addBlock(gmiwc, block.getLocation().toString());
}
}
}
}
@@ -3,7 +3,8 @@
*/
package me.eccentric_nz.gamemodeinventories;
import de.diddiz.LogBlock.Actor;
import me.eccentric_nz.gamemodeinventories.GameModeInventoriesMessage.Arg;
import net.kyori.adventure.text.Component;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -16,104 +17,164 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesTrackWhiteListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesTrackWhiteListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!plugin.getConfig().getBoolean("track_creative_place.enabled")) {
return;
}
Player p = event.getPlayer();
Block block = event.getBlock();
if (block.getType().isAir()) {
return;
}
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
if (plugin.getNoTrackList().contains(block.getType())) {
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)) {
return;
}
if (plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
if (p.getGameMode().equals(GameMode.CREATIVE)) {
plugin.getBlock().removeBlock(gmiwc, block.getLocation().toString());
} else {
String message;
Component message;
if (plugin.getConfig().getBoolean("track_creative_place.break_no_drop")) {
// remove the location from the creative blocks list because we're removing the block!
// remove the location from the creative blocks list because we're removing the
// block
plugin.getBlock().removeBlock(gmiwc, block.getLocation().toString());
if (plugin.getBlockLogger().isLogging()) {
Location loc = block.getLocation();
String pname = p.getName();
switch (plugin.getBlockLogger().getWhichLogger()) {
case CORE_PROTECT: // log the block removal
Material type = block.getType();
BlockData data = block.getBlockData();
plugin.getBlockLogger().getCoreProtectAPI().logRemoval(pname, loc, type, data);
break;
case LOG_BLOCK:
plugin.getBlockLogger().getLogBlockConsumer().queueBlockBreak(Actor.actorFromEntity(p), block.getState());
break;
default:
break;
}
Material type = block.getType();
BlockData data = block.getBlockData();
plugin.getBlockLogger().getCoreProtectAPI().logRemoval(pname, loc, type, data);
}
block.setType(Material.AIR);
block.getDrops().clear();
message = plugin.getM().getMessage().get("NO_CREATIVE_DROPS");
message = plugin.getM().get("NO_CREATIVE_DROPS");
} else {
event.setCancelled(true);
message = plugin.getM().getMessage().get("NO_CREATIVE_BREAK");
message = plugin.getM().get("NO_CREATIVE_BREAK");
}
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + message);
plugin.message(p, message);
}
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Player p = event.getPlayer();
if (!p.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
Material mat = event.getBlock().getType();
if ((mat.equals(Material.WITHER_SKELETON_SKULL) || mat.equals(Material.WITHER_SKELETON_WALL_SKULL)) && plugin.getConfig().getBoolean("no_wither_spawn") && GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock())) {
if ((mat.equals(Material.WITHER_SKELETON_SKULL) || mat.equals(Material.WITHER_SKELETON_WALL_SKULL))
&& plugin.getConfig().getBoolean("no_wither_spawn")
&& GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock()))
{
event.setCancelled(true);
} else if ((mat.equals(Material.CARVED_PUMPKIN) || mat.equals(Material.JACK_O_LANTERN)) && plugin.getConfig().getBoolean("no_golem_spawn") && GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock())) {
} else if ((mat.equals(Material.CARVED_PUMPKIN) || mat.equals(Material.JACK_O_LANTERN))
&& plugin.getConfig().getBoolean("no_golem_spawn")
&& GameModeInventoriesConstructedMob.checkBlocks(mat, event.getBlock()))
{
event.setCancelled(true);
}
if (plugin.getConfig().getBoolean("creative_blacklist") && plugin.getBlackList().contains(mat) && !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin)) {
if (plugin.getConfig().getBoolean("creative_blacklist") && plugin.getBlackList().contains(mat)
&& !GameModeInventoriesBypass.canBypass(p, "blacklist", plugin))
{
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
p.sendMessage(plugin.MY_PLUGIN_NAME + String.format(plugin.getM().getMessage().get("NO_CREATIVE_PLACE"), mat.toString()));
plugin.message(p, plugin.getM().get("NO_CREATIVE_PLACE", new Arg("material", mat.toString())));
}
return;
}
if (plugin.getConfig().getBoolean("track_creative_place.enabled")) {
Block block = event.getBlock();
if (!plugin.getConfig().getStringList("track_creative_place.worlds").contains(block.getWorld().getName())) {
return;
}
if (plugin.getNoTrackList().contains(mat)) {
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + "," + block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc) || !plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString())) {
String gmiwc = block.getWorld().getName() + "," + block.getChunk().getX() + ","
+ block.getChunk().getZ();
if (!plugin.getCreativeBlocks().containsKey(gmiwc)
|| !plugin.getCreativeBlocks().get(gmiwc).contains(block.getLocation().toString()))
{
plugin.getBlock().addBlock(gmiwc, block.getLocation().toString());
}
}
}
}
}
@@ -11,23 +11,38 @@ public class GameModeInventoriesVillagerListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesVillagerListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void onVillagerInteract(PlayerInteractEntityEvent event) {
if (!plugin.getConfig().getBoolean("no_villager_trade")) {
return;
}
Player player = event.getPlayer();
if (!player.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
if (!GameModeInventoriesBypass.canBypass(player, "trades", plugin)) {
event.setCancelled(true);
if (!plugin.getConfig().getBoolean("dont_spam_chat")) {
player.sendMessage(plugin.MY_PLUGIN_NAME + plugin.getM().getMessage().get("NO_TRADE"));
plugin.message(player, plugin.getM().get("NO_TRADE"));
}
}
}
}
@@ -3,164 +3,177 @@
*/
package me.eccentric_nz.gamemodeinventories;
import me.eccentric_nz.gamemodeinventories.database.GameModeInventoriesConnectionPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.kyori.adventure.text.Component;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesWorldListener implements Listener {
private final GameModeInventories plugin;
public GameModeInventoriesWorldListener(GameModeInventories plugin) {
this.plugin = plugin;
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent event) {
// if (plugin.getConfig().getBoolean("creative_world.switch_to")) {
// String uuid = p.getUniqueId().toString();
// // player changed worlds, record last location
// Connection connection = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try {
// connection = GameModeInventoriesConnectionPool.dbc();
// if (connection != null && !connection.isClosed()) {
// // check if the player has a record for this world
// statement = connection.prepareStatement("SELECT * FROM worlds WHERE uuid = ? AND world = ?");
// statement.setString(1, uuid);
// statement.setString(2, to.getName());
// rs = statement.executeQuery();
// if (rs.next()) {
// World w = plugin.getServer().getWorld(rs.getString("world"));
// if (w != null) {
// double x = rs.getDouble("x");
// double y = rs.getDouble("y");
// double z = rs.getDouble("z");
// float yaw = rs.getFloat("yaw");
// float pitch = rs.getFloat("pitch");
// Location loc = new Location(w, x, y, z, yaw, pitch);
// p.teleport(loc);
// }
// }
// }
// } catch (SQLException e) {
// plugin.debug("Could not get creative world location, " + e);
// } finally {
// try {
// if (rs != null) {
// rs.close();
// }
// if (statement != null) {
// statement.close();
// }
// if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
// connection.close();
// }
// } catch (SQLException e) {
// System.err.println("Could not close resultsets, statements or connection, " + e);
// }
// }
// }
// Disabled feature: with creative_world.switch_to set, look up the player's
// saved location for this world and teleport them back to it.
if (!plugin.getConfig().getBoolean("survival_on_world_change")) {
return;
}
Player p = event.getPlayer();
if (GameModeInventoriesBypass.canBypass(p, "survival", plugin)) {
return;
}
World from = event.getFrom();
World to = p.getWorld();
if (from != to) {
p.setGameMode(GameMode.SURVIVAL);
if (from == to) {
return;
}
if (plugin.getBundles().usesMyWorlds()) {
// MyWorlds loads the profile at MONITOR, so the swap waits a tick
plugin.getServer().getScheduler().runTask(plugin, () -> {
if (p.isOnline()) {
plugin.internalGameModeChange(p, GameMode.SURVIVAL);
}
});
} else {
plugin.internalGameModeChange(p, GameMode.SURVIVAL);
}
}
// Without MyWorlds, survival must be in hand before the next world's save
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCrossWorldTeleport(PlayerTeleportEvent event) {
Player p = event.getPlayer();
if (plugin.getBundles().usesMyWorlds() || event.getTo() == null
|| event.getFrom().getWorld().equals(event.getTo().getWorld()))
{
return;
}
if (p.getGameMode().equals(GameMode.SURVIVAL) || !p.hasPermission("gamemodeinventories.use")) {
return;
}
plugin.internalGameModeChange(p, GameMode.SURVIVAL);
plugin.message(p, Component.text("Switched to survival before changing worlds"));
}
@EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event) {
if (plugin.getConfig().getBoolean("creative_world.switch_to")) {
// remember last location in from world
Location from = event.getFrom();
Location to = event.getTo();
if (!from.getWorld().equals(to.getWorld())) {
String uuid = event.getPlayer().getUniqueId().toString();
// player changed worlds, record last location
Connection connection = null;
PreparedStatement statement = null;
PreparedStatement update = null;
PreparedStatement insert = null;
ResultSet rs = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
if (connection != null && !connection.isClosed()) {
try (Connection connection = plugin.getDatabaseConnection();
// check if the player has a record for this world
statement = connection.prepareStatement("SELECT world FROM " + plugin.getPrefix() + "worlds WHERE uuid = ? AND world = ?");
statement.setString(1, uuid);
statement.setString(2, from.getWorld().getName());
rs = statement.executeQuery();
PreparedStatement statement = connection.prepareStatement(
"SELECT world FROM " + plugin.getPrefix() + "worlds WHERE uuid = ? AND world = ?");)
{
statement.setString(1, uuid);
statement.setString(2, from.getWorld().getName());
try (ResultSet rs = statement.executeQuery();) {
if (rs.isBeforeFirst()) {
rs.next();
// update the record
update = connection.prepareStatement("UPDATE " + plugin.getPrefix() + "worlds set x = ?, y = ?, z = ?, pitch = ?, yaw = ? WHERE uuid = ? AND world = ?");
update.setDouble(1, from.getX());
update.setDouble(2, from.getY());
update.setDouble(3, from.getZ());
update.setDouble(4, from.getPitch());
update.setDouble(5, from.getYaw());
update.setString(6, uuid);
update.setString(7, from.getWorld().getName());
update.executeUpdate();
try (PreparedStatement update = connection.prepareStatement("UPDATE " + plugin.getPrefix()
+ "worlds set x = ?, y = ?, z = ?, pitch = ?, yaw = ? WHERE uuid = ? AND world = ?");)
{
update.setDouble(1, from.getX());
update.setDouble(2, from.getY());
update.setDouble(3, from.getZ());
update.setDouble(4, from.getPitch());
update.setDouble(5, from.getYaw());
update.setString(6, uuid);
update.setString(7, from.getWorld().getName());
update.executeUpdate();
}
} else {
// add a new record
insert = connection.prepareStatement("INSERT INTO " + plugin.getPrefix() + "worlds (uuid, world, x, y, z, pitch, yaw) VALUES (?, ?, ?, ?, ?, ?, ?)");
insert.setString(1, uuid);
insert.setString(2, from.getWorld().getName());
insert.setDouble(3, from.getX());
insert.setDouble(4, from.getY());
insert.setDouble(5, from.getZ());
insert.setDouble(6, from.getPitch());
insert.setDouble(7, from.getYaw());
insert.executeUpdate();
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO "
+ plugin.getPrefix()
+ "worlds (uuid, world, x, y, z, pitch, yaw) VALUES (?, ?, ?, ?, ?, ?, ?)");)
{
insert.setString(1, uuid);
insert.setString(2, from.getWorld().getName());
insert.setDouble(3, from.getX());
insert.setDouble(4, from.getY());
insert.setDouble(5, from.getZ());
insert.setDouble(6, from.getPitch());
insert.setDouble(7, from.getYaw());
insert.executeUpdate();
}
}
}
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not save world on teleport, " + e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (update != null) {
update.close();
}
if (insert != null) {
insert.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not close resultsets, statements or connection, " + e);
}
}
}
}
}
}
@@ -1,22 +1,12 @@
package me.eccentric_nz.gamemodeinventories;
import org.apache.commons.lang.Validate;
import org.bukkit.entity.Player;
import com.google.common.base.Preconditions;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import org.bukkit.entity.Player;
/**
* @author desht
* <p>
* Adapted from ExperienceUtils code originally in ScrollingMenuSign.
* <p>
* Credit to nisovin (http://forums.bukkit.org/threads/experienceutils-make-giving-taking-exp-a-bit-more-intuitive.54450/#post-1067480)
* for an implementation that avoids the problems of getTotalExperience(), which doesn't work properly after a player
* has enchanted something.
* <p>
* Credit to comphenix for further contributions: See http://forums.bukkit.org/threads/experiencemanager-was-experienceutils-make-giving-taking-exp-a-bit-more-intuitive.54450/page-3#post-1273622
*/
// By desht, adapted from ExperienceUtils (ScrollingMenuSign); credit to nisovin and comphenix
// for an approach that avoids getTotalExperience(), which breaks after a player enchants.
public class GameModeInventoriesXPCalculator {
// this is to stop the lookup table growing without control
@@ -25,243 +15,212 @@ public class GameModeInventoriesXPCalculator {
private static int xpTotalToReachLevel[];
static {
// 25 is an arbitrary value for the initial table size - the actual
// value isn't critically important since the table is resized as needed.
initLookupTables(25);
}
private final WeakReference<Player> player;
private final String playerName;
/**
* Create a new GameModeInventoriesXPCalculator for the given player.
*
* @param player the player for this GameModeInventoriesXPCalculator object
* @throws IllegalArgumentException if the player is null
*/
public GameModeInventoriesXPCalculator(Player player) {
Validate.notNull(player, "Player cannot be null");
GameModeInventoriesXPCalculator(Player player) {
Preconditions.checkNotNull(player, "Player cannot be null");
this.player = new WeakReference<>(player);
playerName = player.getName();
}
/**
* Get the current hard max level for which calculations will be done.
*
* @return the current hard max level
*/
public static int getHardMaxLevel() {
return hardMaxLevel;
}
/**
* Set the current hard max level for which calculations will be done.
*
* @param hardMaxLevel the new hard max level
*/
public static void setHardMaxLevel(int hardMaxLevel) {
GameModeInventoriesXPCalculator.hardMaxLevel = hardMaxLevel;
}
/**
* Initialize the XP lookup table. See http://minecraft.gamepedia.com/Experience
*
* @param maxLevel The highest level handled by the lookup tables
*/
// XP formulas from http://minecraft.gamepedia.com/Experience
private static void initLookupTables(int maxLevel) {
xpTotalToReachLevel = new int[maxLevel];
for (int i = 0; i < xpTotalToReachLevel.length; i++) {
xpTotalToReachLevel[i]
= i >= 30 ? (int) (3.5 * i * i - 151.5 * i + 2220)
: i >= 16 ? (int) (1.5 * i * i - 29.5 * i + 360)
: 17 * i;
xpTotalToReachLevel[i] = i >= 30 ? (int) (3.5 * i * i - 151.5 * i + 2220)
: i >= 16 ? (int) (1.5 * i * i - 29.5 * i + 360) : 17 * i;
}
}
/**
* Calculate the level that the given XP quantity corresponds to, without using the lookup tables. This is needed if
* getLevelForExp() is called with an XP quantity beyond the range of the existing lookup tables.
*
* @param exp
* @return
*/
// Calculates the level for an XP quantity without the lookup tables, for
// getLevelForExp() calls with XP beyond the range of the existing tables.
private static int calculateLevelForExp(int exp) {
int level = 0;
int curExp = 7; // level 1
int incr = 10;
while (curExp <= exp) {
curExp += incr;
level++;
incr += (level % 2 == 0) ? 3 : 4;
}
return level;
}
/**
* Get the Player associated with this GameModeInventoriesXPCalculator.
*
* @return the Player object
* @throws IllegalStateException if the player is no longer online
*/
// Throws IllegalStateException if the player is no longer online.
public Player getPlayer() {
Player p = player.get();
if (p == null) {
throw new IllegalStateException("Player " + playerName + " is not online");
}
return p;
}
/**
* Adjust the player's XP by the given amount in an intelligent fashion. Works around some of the non-intuitive
* behaviour of the basic Bukkit player.giveExp() method.
*
* @param amt Amount of XP, may be negative
*/
// Adjusts the player's XP by the given amount (may be negative); works around
// non-intuitive behaviour of the basic Bukkit player.giveExp() method.
public void changeExp(int amt) {
changeExp((double) amt);
}
/**
* Adjust the player's XP by the given amount in an intelligent fashion. Works around some of the non-intuitive
* behaviour of the basic Bukkit player.giveExp() method.
*
* @param amt Amount of XP, may be negative
*/
public void changeExp(double amt) {
// As changeExp(int), for fractional amounts.
private void changeExp(double amt) {
setExp(getCurrentFractionalXP(), amt);
}
/**
* Set the player's experience
*
* @param amt Amount of XP, should not be negative
*/
public void setExp(int amt) {
// Sets the player's experience; amount should not be negative.
void setExp(int amt) {
setExp(0, amt);
}
/**
* Set the player's fractional experience.
*
* @param amt Amount of XP, should not be negative
*/
// Sets the player's fractional experience; amount should not be negative.
public void setExp(double amt) {
setExp(0, amt);
}
private void setExp(double base, double amt) {
int xp = (int) Math.max(base + amt, 0);
Player p = getPlayer();
int curLvl = p.getLevel();
int newLvl = getLevelForExp(xp);
// Increment level
if (curLvl != newLvl) {
p.setLevel(newLvl);
}
// Increment total experience - this should force the server to send an update packet
if (xp > base) {
p.setTotalExperience(p.getTotalExperience() + xp - (int) base);
}
// Keep the vanilla counter equal to the absolute total being applied
p.setTotalExperience(xp);
double pct = (base - getXpForLevel(newLvl) + amt) / (double) (getXpNeededToLevelUp(newLvl));
p.setExp((float) pct);
}
/**
* Get the player's current XP total.
*
* @return the player's total XP
*/
public int getCurrentExp() {
int getCurrentExp() {
Player p = getPlayer();
int lvl = p.getLevel();
int cur = getXpForLevel(lvl) + Math.round(getXpNeededToLevelUp(lvl) * p.getExp());
return cur;
}
/**
* Get the player's current fractional XP.
*
* @return The player's total XP with fractions.
*/
private double getCurrentFractionalXP() {
Player p = getPlayer();
int lvl = p.getLevel();
double cur = getXpForLevel(lvl) + (double) (getXpNeededToLevelUp(lvl) * p.getExp());
return cur;
}
/**
* Checks if the player has the given amount of XP.
*
* @param amt The amount to check for.
* @return true if the player has enough XP, false otherwise
*/
public boolean hasExp(int amt) {
return getCurrentExp() >= amt;
}
/**
* Checks if the player has the given amount of fractional XP.
*
* @param amt The amount to check for.
* @return true if the player has enough XP, false otherwise
*/
public boolean hasExp(double amt) {
return getCurrentFractionalXP() >= amt;
}
/**
* Get the level that the given amount of XP falls within.
*
* @param exp the amount to check for
* @return the level that a player with this amount total XP would be
* @throws IllegalArgumentException if the given XP is less than 0
*/
public int getLevelForExp(int exp) {
// Returns the level that a player with this amount of total XP would be.
private int getLevelForExp(int exp) {
if (exp <= 0) {
return 0;
}
if (exp > xpTotalToReachLevel[xpTotalToReachLevel.length - 1]) {
// need to extend the lookup tables
int newMax = calculateLevelForExp(exp) * 2;
Validate.isTrue(newMax <= hardMaxLevel, "Level for exp " + exp + " > hard max level " + hardMaxLevel);
Preconditions.checkArgument(newMax <= hardMaxLevel,
"Level for exp " + exp + " > hard max level " + hardMaxLevel);
initLookupTables(newMax);
}
int pos = Arrays.binarySearch(xpTotalToReachLevel, exp);
return pos < 0 ? -pos - 2 : pos;
}
/**
* Retrieves the amount of experience the experience bar can hold at the given level.
*
* @param level the level to check
* @return the amount of experience at this level in the level bar
* @throws IllegalArgumentException if the level is less than 0
*/
public int getXpNeededToLevelUp(int level) {
Validate.isTrue(level >= 0, "Level may not be negative.");
// Amount of experience the XP bar can hold at the given level.
private int getXpNeededToLevelUp(int level) {
Preconditions.checkArgument(level >= 0, "Level may not be negative.");
return level > 30 ? 62 + (level - 30) * 7 : level >= 16 ? 17 + (level - 15) * 3 : 17;
}
/**
* Return the total XP needed to be the given level.
*
* @param level The level to check for.
* @return The amount of XP needed for the level.
* @throws IllegalArgumentException if the level is less than 0 or greater than the current hard maximum
*/
public int getXpForLevel(int level) {
Validate.isTrue(level >= 0 && level <= hardMaxLevel, "Invalid level " + level + "(must be in range 0.." + hardMaxLevel + ")");
// Total XP needed to reach the given level.
private int getXpForLevel(int level) {
Preconditions.checkArgument(level >= 0 && level <= hardMaxLevel,
"Invalid level " + level + "(must be in range 0.." + hardMaxLevel + ")");
if (level >= xpTotalToReachLevel.length) {
initLookupTables(level * 2);
}
return xpTotalToReachLevel[level];
}
}
File diff suppressed because it is too large. Load diff
@@ -1,42 +1,31 @@
package me.eccentric_nz.gamemodeinventories.JSON;
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
* @author JSON.org
* @version 2013-02-10
*/
// Thrown by the JSON.org classes when things are amiss.
public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
*
* @param message Detail about the reason for the exception.
*/
public JSONException(String message) {
super(message);
}
/**
* Constructs a new JSONException with the specified cause.
*
* @param cause
*/
public JSONException(Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
/**
* Returns the cause of this exception or null if the cause is nonexistent or unknown.
*
* @return the cause of this exception or null if the cause is nonexistent or unknown.
*/
// Returns the cause of this exception, or null if the cause is nonexistent or
// unknown.
@Override
public Throwable getCause() {
return this.cause;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,24 +1,10 @@
package me.eccentric_nz.gamemodeinventories.JSON;
/**
* The
* <code>JSONString</code> interface allows a
* <code>toJSONString()</code> method so that a class can change the behavior of
* <code>JSONObject.toString()</code>,
* <code>JSONArray.toString()</code>, and
* <code>JSONWriter.value(</code>Object<code>)</code>. The
* <code>toJSONString</code> method will be used instead of the default behavior
* of using the Object's
* <code>toString()</code> method and quoting the result.
*/
// Lets a class supply its own JSON serialization: toJSONString() is used by JSONObject.toString(),
// JSONArray.toString(), and JSONWriter.value(Object) instead of quoting the Object's toString().
public interface JSONString {
/**
* The
* <code>toJSONString</code> method allows a class to produce its own JSON
* serialization.
*
* @return A strictly syntactically correct JSON text.
*/
// Returns a strictly syntactically correct JSON text representing this object.
public String toJSONString();
}
@@ -3,36 +3,31 @@ package me.eccentric_nz.gamemodeinventories.JSON;
import java.io.*;
/*
Copyright (c) 2002 JSON.org
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and
* JSONArray constructors to parse JSON source strings.
*
* @author JSON.org
* @version 2012-02-16
*/
// Extracts characters and tokens from a source string. Used by the JSONObject
// and JSONArray constructors to parse JSON source strings.
public class JSONTokener {
private final Reader reader;
@@ -43,200 +38,219 @@ public class JSONTokener {
private char previous;
private boolean usePrevious;
/**
* Construct a JSONTokener from a Reader.
*
* @param reader A reader.
*/
public JSONTokener(Reader reader) {
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
eof = false;
usePrevious = false;
previous = 0;
index = 0;
character = 1;
line = 1;
}
/**
* Construct a JSONTokener from an InputStream.
*
* @param inputStream
*/
public JSONTokener(InputStream inputStream) throws JSONException {
this(new InputStreamReader(inputStream));
}
/**
* Construct a JSONTokener from a string.
*
* @param s A source string.
*/
public JSONTokener(String s) {
this(new StringReader(s));
}
/**
* Get the hex value of a character (base16).
*
* @param c A character between '0' and '9' or between 'A' and 'F' or between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
// Get the hex value of a character (base16), or -1 if c is not a hex digit.
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
/**
* Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter
* before attempting to parse the next number or identifier.
*/
// Back up one character to provide lookahead; stepping back twice is not
// supported.
public void back() throws JSONException {
if (usePrevious || index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
index -= 1;
character -= 1;
usePrevious = true;
eof = false;
}
public boolean end() {
return eof && !usePrevious;
}
/**
* Determine if the source string still contains characters that next() can consume.
*
* @return true if not yet at the end of the source.
*/
// Returns true if the source string still contains characters that next() can
// consume.
public boolean more() throws JSONException {
next();
if (end()) {
return false;
}
back();
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
*/
// Get the next character in the source string, or 0 if past the end.
public char next() throws JSONException {
int c;
if (usePrevious) {
usePrevious = false;
c = previous;
} else {
try {
c = reader.read();
} catch (IOException exception) {
throw new JSONException(exception);
}
if (c <= 0) { // End of stream
eof = true;
c = 0;
}
}
index += 1;
if (previous == '\r') {
line += 1;
character = c == '\n' ? 0 : 1;
} else if (c == '\n') {
line += 1;
character = 0;
} else {
character += 1;
}
previous = (char) c;
return previous;
}
/**
* Consume the next character, and check that it matches a specified character.
*
* @param c The character to match.
* @return The character.
* @throws JSONException if the character does not match.
*/
// Consume the next character and check that it matches c; throws if it does
// not.
public char next(char c) throws JSONException {
char n = next();
if (n != c) {
throw syntaxError("Expected '" + c + "' and instead saw '"
+ n + "'");
throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
}
return n;
}
/**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @throws JSONException Substring bounds error if there are not n characters remaining in the source string.
*/
// Get the next n characters; throws if fewer than n characters remain in the
// source.
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = next();
if (end()) {
throw syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
*
* @return A character, or 0 if there are no more characters.
* @throws JSONException
*/
// Get the next character, skipping whitespace; 0 if there are no more
// characters.
public char nextClean() throws JSONException {
for (; ; ) {
for (;;) {
char c = next();
if (c == 0 || c > ' ') {
return c;
}
}
}
/**
* Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format
* does not allow strings in single quotes, but an implementation is allowed to accept them.
*
* @param quote The quoting character, either
* <code>"</code>&nbsp;<small>(double quote)</small> or
* <code>'</code>&nbsp;<small>(single quote)</small>.
* @return A String.
* @throws JSONException Unterminated string.
*/
// Return the characters up to the next close quote, processing backslash
// escapes. Single quotes are accepted even though formal JSON forbids them.
public String nextString(char quote) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (; ; ) {
for (;;) {
c = next();
switch (c) {
case 0:
case '\n':
case '\r':
@@ -244,6 +258,7 @@ public class JSONTokener {
case '\\':
c = next();
switch (c) {
case 'b':
sb.append('\b');
break;
@@ -270,71 +285,83 @@ public class JSONTokener {
break;
default:
throw syntaxError("Illegal escape.");
}
break;
default:
if (c == quote) {
return sb.toString();
}
sb.append(c);
}
}
}
/**
* Get the text up but not including the specified character or the end of line, whichever comes first.
*
* @param delimiter A delimiter character.
* @return A string.
*/
// Get the text up to but not including the delimiter or end of line, trimmed.
public String nextTo(char delimiter) throws JSONException {
StringBuilder sb = new StringBuilder();
for (; ; ) {
for (;;) {
char c = next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) {
back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes
* first.
*
* @param delimiters A set of delimiter characters.
* @return A string, trimmed.
*/
// Get the text up to but not including one of the delimiter characters
// or the end of line, trimmed.
public String nextTo(String delimiters) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (; ; ) {
for (;;) {
c = next();
if (delimiters.indexOf(c) >= 0 || c == 0
|| c == '\n' || c == '\r') {
if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') {
if (c != 0) {
back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
*
* @return An object.
* @throws JSONException If syntax error.
*/
// Get the next value: a Boolean, Double, Integer, JSONArray, JSONObject, Long,
// or String, or the JSONObject.NULL object. Throws on syntax error.
public Object nextValue() throws JSONException {
char c = nextClean();
String string;
switch (c) {
case '"':
case '\'':
return nextString(c);
@@ -344,70 +371,80 @@ public class JSONTokener {
case '[':
back();
return new JSONArray(this);
}
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
string = sb.toString().trim();
if ("".equals(string)) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
/**
* Skip characters until the next character is the requested character. If the requested character is not found, no
* characters are skipped.
*
* @param to A character to skip to.
* @return The requested character, or zero if the requested character is not found.
*/
// Skip characters until the next character is the requested character. Returns
// that character, or 0 (with no characters skipped) if it is not found.
public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = index;
long startCharacter = character;
long startLine = line;
reader.mark(1000000);
do {
c = next();
if (c == 0) {
reader.reset();
index = startIndex;
character = startCharacter;
line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
back();
return c;
}
/**
* Make a JSONException to signal a syntax error.
*
* @param message The error message.
* @return A JSONException object, suitable for throwing
*/
// Make a JSONException to signal a syntax error, with the current position
// appended.
public JSONException syntaxError(String message) {
return new JSONException(message + toString());
}
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
// Returns " at {index} [character {character} line {line}]".
@Override
public String toString() {
return " at " + index + " [character " + character + " line "
+ line + "]";
return " at " + index + " [character " + character + " line " + line + "]";
}
}
@@ -0,0 +1,50 @@
/*
* Copyright 2014 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories;
import com.bergerkiller.bukkit.mw.WorldConfig;
import com.bergerkiller.bukkit.mw.WorldInventory;
import org.bukkit.World;
// The only class referencing MyWorlds, loaded once MyWorlds is known present
final class MyWorldsBundles {
private MyWorldsBundles() {
}
static boolean available() {
try {
Class.forName("com.bergerkiller.bukkit.mw.WorldInventory");
return true;
} catch (Throwable t) {
return false;
}
}
// Storage world of the inventory group, null when MyWorlds has none
static String of(World world) {
try {
WorldInventory group = WorldConfig.get(world).inventory;
return group == null ? null : group.getSharedWorldName();
} catch (Throwable t) {
GameModeInventories.plugin
.debug("Could not resolve the MyWorlds inventory group of " + world.getName() + ", " + t);
return null;
}
}
}
@@ -16,69 +16,101 @@
*/
package me.eccentric_nz.gamemodeinventories;
/**
* Class to compare version strings. Borrowed from StackOverflow.
*
* @author alex http://stackoverflow.com/users/1445568/alex
*/
// Compares dotted version strings numerically.
// Borrowed from StackOverflow user alex (http://stackoverflow.com/users/1445568/alex).
public class Version implements Comparable<Version> {
private final String version;
public Version(String version) {
if (version == null) {
throw new IllegalArgumentException("Version can not be null");
}
if (!version.matches("[0-9]+(\\.[0-9]+)*")) {
throw new IllegalArgumentException("Invalid version format");
}
this.version = version;
}
public String get() {
return version;
}
@Override
public int compareTo(Version that) {
if (that == null) {
return 1;
}
String[] thisParts = get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length
? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length
? Integer.parseInt(thatParts[i]) : 0;
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if (thisPart < thatPart) {
return -1;
}
if (thisPart > thatPart) {
return 1;
}
}
return 0;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
return compareTo((Version) that) == 0;
}
}
@@ -0,0 +1,118 @@
package me.eccentric_nz.gamemodeinventories.api;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
// The single authority on which gamemodes GameModeInventories-OG sanctions and where; published so other
// plugins enforce the same rule. Obtain via the Bukkit services manager or GameModeInventories#getGameModePolicy().
public final class GameModePolicy {
public static final String ANYWHERE_PERMISSION = "gamemodeinventories.anywhere";
public static final String TOGGLE_PERMISSION = "gamemodeinventories.toggle";
public static final String SPECTATOR_PERMISSION = "gamemodeinventories.spectator";
public static final String NOCLIP_PERMISSION = "noclip.use";
private static final List<String> DEFAULT_CREATIVE_REGIONS = List.of("spawn");
private final GameModeInventories plugin;
private final RegionContainer regionContainer;
private final Set<String> creativeRegions = new HashSet<>();
public GameModePolicy(GameModeInventories plugin) {
this.plugin = plugin;
this.regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer();
List<String> configured = plugin.getConfig().getStringList("creative_regions");
if (configured.isEmpty()) {
configured = DEFAULT_CREATIVE_REGIONS;
}
configured.stream().map(region -> region.toLowerCase(Locale.ROOT)).forEach(creativeRegions::add);
}
// Whether this plugin's rules permit the player to hold the gamemode at the
// location. Survival is always permitted; the rest follow the rules below.
public boolean mayUse(Player player, GameMode gameMode, Location location) {
return switch (gameMode) {
case SURVIVAL -> true;
case CREATIVE -> mayUseCreativeAt(player, location);
case SPECTATOR -> mayUseSpectator(player);
case ADVENTURE -> mayUseAdventureAt(location);
};
}
// Minigames put players in adventure legitimately, so it is refused only in
// worlds meant to stay survival; minigame worlds must be left off that list.
public boolean mayUseAdventureAt(Location location) {
if (location == null || location.getWorld() == null)
return true;
String world = location.getWorld().getName();
return plugin.getConfig().getStringList("restrict_adventure_worlds").stream()
.noneMatch(restricted -> restricted.equalsIgnoreCase(world));
}
// Creative is staff only. The permission says who, the region says where,
// and both are required: a region alone licenses no ordinary player.
public boolean mayUseCreativeAt(Player player, Location location) {
if (player.hasPermission(ANYWHERE_PERMISSION))
return true;
if (!player.hasPermission(TOGGLE_PERMISSION))
return false;
if (location == null || location.getWorld() == null)
return false;
return regionContainer.createQuery().getApplicableRegions(BukkitAdapter.adapt(location)).getRegions().stream()
.anyMatch(region -> creativeRegions.contains(region.getId().toLowerCase(Locale.ROOT)));
}
// Spectator is permission gated rather than region gated, and only while
// restrict_spectator is on.
public boolean mayUseSpectator(Player player) {
return !plugin.getConfig().getBoolean("restrict_spectator") || player.hasPermission(SPECTATOR_PERMISSION)
|| player.hasPermission(NOCLIP_PERMISSION);
}
// Lower-case ids of the regions creative is allowed in.
public Set<String> getCreativeRegions() {
return Set.copyOf(creativeRegions);
}
// The sanctioned programmatic switch: policy-validated, then flagged internal
// so the listener trusts it. False: refused here or cancelled elsewhere.
public boolean changeGameMode(Player player, GameMode gameMode) {
if (!mayUse(player, gameMode, player.getLocation()))
return false;
plugin.internalGameModeChange(player, gameMode);
return player.getGameMode() == gameMode;
}
}
@@ -3,65 +3,63 @@
*/
package me.eccentric_nz.gamemodeinventories.database;
import me.eccentric_nz.gamemodeinventories.GMIDebug;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import org.bukkit.scheduler.BukkitRunnable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import me.eccentric_nz.gamemodeinventories.GMIDebug;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import org.bukkit.scheduler.BukkitRunnable;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBlockLoader extends BukkitRunnable {
private final GameModeInventories plugin;
private final String gmiwc;
public GameModeInventoriesBlockLoader(GameModeInventories plugin, String gmiwc) {
this.plugin = plugin;
this.gmiwc = gmiwc;
}
@Override
public void run() {
Connection connection = null;
PreparedStatement psb = null;
ResultSet rb = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
String blocksQuery = "SELECT location FROM " + plugin.getPrefix() + "blocks WHERE worldchunk = ?";
psb = connection.prepareStatement(blocksQuery);
String blocksQuery = "SELECT location FROM " + plugin.getPrefix() + "blocks WHERE worldchunk = ?";
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement psb = connection.prepareStatement(blocksQuery);)
{
psb.setString(1, gmiwc);
rb = psb.executeQuery();
List<String> l = new ArrayList<>();
if (rb.isBeforeFirst()) {
while (rb.next()) {
l.add(rb.getString("location"));
try (ResultSet rb = psb.executeQuery();) {
if (rb.isBeforeFirst()) {
List<String> l = new ArrayList<>();
while (rb.next()) {
l.add(rb.getString("location"));
}
plugin.getCreativeBlocks().put(gmiwc, l);
}
plugin.debug("Protecting blocks for chunk: " + gmiwc, GMIDebug.ALL);
}
plugin.getCreativeBlocks().put(gmiwc, l);
plugin.debug("Protecting blocks for chunk: " + gmiwc, GMIDebug.ALL);
} catch (SQLException e) {
System.err.println("Could not load blocks, " + e);
} finally {
try {
if (rb != null) {
rb.close();
}
if (psb != null) {
psb.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Could not load blocks, " + e);
}
plugin.getLogger().log(Level.WARNING, "Could not load blocks, " + e);
}
}
}
@@ -3,111 +3,107 @@
*/
package me.eccentric_nz.gamemodeinventories.database;
import java.sql.*;
import me.eccentric_nz.gamemodeinventories.GMIDebug;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import java.sql.*;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesBlocksConverter {
private final GameModeInventories plugin;
public GameModeInventoriesBlocksConverter(GameModeInventories plugin) {
this.plugin = plugin;
}
public static void processUpdateCounts(int[] updateCounts) {
for (int i = 0; i < updateCounts.length; i++) {
if (updateCounts[i] >= 0) {
// Successfully executed; the number represents number of affected rows
} else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
// Successfully executed; number of affected rows not available
} else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
// Failed to execute
}
}
}
public void convertBlocksTable() {
Connection connection = null;
PreparedStatement statement = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.prepareStatement("SELECT id, location FROM " + plugin.getPrefix() + "blocks");
rs = statement.executeQuery();
try (Connection connection = plugin.getDatabaseConnection();
PreparedStatement statement = connection
.prepareStatement("SELECT id, location FROM " + plugin.getPrefix() + "blocks");
ResultSet rs = statement.executeQuery();)
{
if (rs.isBeforeFirst()) {
ps = connection.prepareStatement("UPDATE " + plugin.getPrefix() + "blocks SET worldchunk = ? WHERE id = ?");
connection.setAutoCommit(false);
long count = 0;
while (rs.next()) {
String l = rs.getString("location");
// Location{world=CraftWorld{name=world},x=-87.0,y=61.0,z=237.0,pitch=0.0,yaw=0.0}
String[] first = l.split(",");
String[] wStr = first[0].split("=");
String[] xStr = first[1].split("=");
String[] zStr = first[3].split("=");
String w = wStr[2].substring(0, (wStr[2].length() - 1));
int x = Integer.parseInt(xStr[1].substring(0, (xStr[1].length() - 2))) >> 4;
int z = Integer.parseInt(zStr[1].substring(0, (zStr[1].length() - 2))) >> 4;
ps.setString(1, w + "," + x + "," + z);
ps.setInt(2, rs.getInt("id"));
ps.addBatch();
count++;
if (count == 1000) {
// Execute the batch
int[] updateCounts = ps.executeBatch();
// All statements were successfully executed.
// updateCounts contains one element for each batched statement.
// updateCounts[i] contains the number of rows affected by that statement.
processUpdateCounts(updateCounts);
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE " + plugin.getPrefix() + "blocks SET worldchunk = ? WHERE id = ?");)
{
connection.setAutoCommit(false);
long count = 0;
while (rs.next()) {
String l = rs.getString("location");
// Location{world=CraftWorld{name=world},x=-87.0,y=61.0,z=237.0,pitch=0.0,yaw=0.0}
String[] first = l.split(",");
String[] wStr = first[0].split("=");
String[] xStr = first[1].split("=");
String[] zStr = first[3].split("=");
String w = wStr[2].substring(0, (wStr[2].length() - 1));
int x = Integer.parseInt(xStr[1].substring(0, (xStr[1].length() - 2))) >> 4;
int z = Integer.parseInt(zStr[1].substring(0, (zStr[1].length() - 2))) >> 4;
ps.setString(1, w + "," + x + "," + z);
ps.setInt(2, rs.getInt("id"));
ps.addBatch();
count++;
if (count == 1000) {
// Execute the batch
int[] updateCounts = ps.executeBatch();
// All statements executed: updateCounts holds one
// element (rows affected) per batched statement.
processUpdateCounts(updateCounts);
// Since there were no errors, commit
connection.commit();
count = 0;
}
// Since there were no errors, commit
connection.commit();
count = 0;
}
}
}
} catch (BatchUpdateException ex) {
// Not all of the statements were successfully executed
int[] updateCounts = ex.getUpdateCounts();
// Some databases will continue to execute after one fails.
// If so, updateCounts.length will equal the number of batched statements.
// If not, updateCounts.length will equal the number of successfully executed statements
// Some databases continue past a failure: updateCounts.length is then
// the batched count, otherwise the successfully executed count.
processUpdateCounts(updateCounts);
if (connection != null) {
// Either commit the successfully executed statements or rollback the entire batch
connection.rollback();
}
}
} catch (SQLException ex) {
plugin.debug("Blocks updater error: " + ex.getMessage(), GMIDebug.ERROR);
} finally {
try {
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.setAutoCommit(true);
connection.close();
}
} catch (SQLException ex) {
plugin.debug("Blocks closing error: " + ex.getMessage(), GMIDebug.ERROR);
}
}
}
}
@@ -1,79 +0,0 @@
/*
* Copyright 2015 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesConnectionPool {
private static HikariDataSource hikari;
private static boolean isMySQL = false;
private static GameModeInventoriesSQLiteConnection service;
public GameModeInventoriesConnectionPool(String path) {
try {
service = GameModeInventoriesSQLiteConnection.getINSTANCE();
service.setConnection(path);
} catch (Exception e) {
GameModeInventories.plugin.debug("Database connection failed. " + e.getMessage());
}
}
public GameModeInventoriesConnectionPool() throws ClassNotFoundException {
isMySQL = true;
Class.forName("com.mysql.jdbc.Driver");
String host = GameModeInventories.plugin.getConfig().getString("storage.mysql.server");
String port = GameModeInventories.plugin.getConfig().getString("storage.mysql.port");
String databaseName = GameModeInventories.plugin.getConfig().getString("storage.mysql.database");
String user = GameModeInventories.plugin.getConfig().getString("storage.mysql.user");
String password = GameModeInventories.plugin.getConfig().getString("storage.mysql.password");
int pool_size = GameModeInventories.plugin.getConfig().getInt("storage.mysql.pool_size");
String url = String.format("jdbc:mysql://%s:%s/%s", host, port, databaseName);
if (!GameModeInventories.plugin.getConfig().getBoolean("storage.mysql.useSSL")) {
url += "?useSSL=false";
}
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(pool_size);
config.setJdbcUrl(url);
config.setUsername(user);
config.setPassword(password);
config.setDriverClassName("com.mysql.jdbc.Driver");
config.addDataSourceProperty("databaseName", databaseName);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "1024");
if (GameModeInventories.plugin.getConfig().getBoolean("storage.mysql.test_connection")) {
config.setConnectionTestQuery("SELECT 1");
}
hikari = new HikariDataSource(config);
}
public static Connection dbc() {
Connection con = null;
if (isMySQL) {
try {
con = hikari.getConnection();
} catch (SQLException e) {
GameModeInventories.plugin.debug("Could not get database connection: " + e.getMessage());
}
} else {
service = GameModeInventoriesSQLiteConnection.getINSTANCE();
con = service.getConnection();
}
return con;
}
public static boolean isIsMySQL() {
return isMySQL;
}
}
@@ -3,85 +3,114 @@
*/
package me.eccentric_nz.gamemodeinventories.database;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesMySQL {
private final GameModeInventories plugin;
public GameModeInventoriesMySQL(GameModeInventories plugin) {
this.plugin = plugin;
}
public void createTables() {
Connection connection = null;
Statement statement = null;
ResultSet rsAttr = null;
ResultSet rsWorld = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.createStatement();
try (Connection connection = plugin.getDatabaseConnection();
Statement statement = connection.createStatement();)
{
// add inventories table
String queryInventories = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "inventories (id int(11) NOT NULL AUTO_INCREMENT, uuid varchar(48) DEFAULT '', player varchar(24) DEFAULT '', gamemode varchar(24) DEFAULT '', inventory text, xp double, armour text, enderchest text, attributes text, armour_attributes text, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
String queryInventories = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "inventories (id int(11) NOT NULL AUTO_INCREMENT, uuid varchar(48) DEFAULT '', player varchar(24) DEFAULT '', gamemode varchar(24) DEFAULT '', inventory text, xp double, armour text, enderchest text, attributes text, armour_attributes text, bundle varchar(64), PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
statement.executeUpdate(queryInventories);
// deaths table, parked until the player is back in the death world
String queryDeaths = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "deaths (id int(11) NOT NULL AUTO_INCREMENT, uuid varchar(48) DEFAULT '', player varchar(24) DEFAULT '', gamemode varchar(24) DEFAULT '', world varchar(64), inventory text, armour text, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
statement.executeUpdate(queryDeaths);
// add the bundle column, the inventory group a slot belongs to
String queryBundle = "SHOW COLUMNS FROM " + plugin.getPrefix() + "inventories LIKE 'bundle'";
try (ResultSet rsBundle = statement.executeQuery(queryBundle);) {
if (!rsBundle.next()) {
statement.executeUpdate("ALTER TABLE " + plugin.getPrefix() + "inventories ADD bundle varchar(64)");
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding bundle to database!");
}
}
// One slot per (uuid, gamemode, bundle); stops a failed legacy assignment
// leaving conflicting rows
String queryUnique = "SHOW INDEX FROM " + plugin.getPrefix() + "inventories WHERE Key_name = 'uq_gmi_slot'";
try (ResultSet rsUnique = statement.executeQuery(queryUnique);) {
if (!rsUnique.next()) {
statement.executeUpdate("ALTER TABLE " + plugin.getPrefix()
+ "inventories ADD UNIQUE KEY uq_gmi_slot (uuid, gamemode, bundle)");
}
}
// update inventories if there is no attributes column
String queryAttr = "SHOW COLUMNS FROM " + plugin.getPrefix() + "inventories LIKE 'attributes'";
rsAttr = statement.executeQuery(queryAttr);
if (!rsAttr.next()) {
String queryAlter4 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD attributes text";
statement.executeUpdate(queryAlter4);
String queryAlter5 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour_attributes text";
statement.executeUpdate(queryAlter5);
System.out.println("[GameModeInventories] Adding attributes to database!");
try (ResultSet rsAttr = statement.executeQuery(queryAttr);) {
if (!rsAttr.next()) {
String queryAlter4 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD attributes text";
statement.executeUpdate(queryAlter4);
String queryAlter5 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour_attributes text";
statement.executeUpdate(queryAlter5);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding attributes to database!");
}
}
// add blocks table
String queryBlocks = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "blocks (id int(11) NOT NULL AUTO_INCREMENT, worldchunk varchar(128), location text, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
String queryBlocks = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "blocks (id int(11) NOT NULL AUTO_INCREMENT, worldchunk varchar(128), location text, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
statement.executeUpdate(queryBlocks);
// update blocks if there is no world column
String queryWorld = "SHOW COLUMNS FROM " + plugin.getPrefix() + "blocks LIKE 'worldchunk'";
rsWorld = statement.executeQuery(queryWorld);
if (!rsWorld.next()) {
String queryAlter6 = "ALTER TABLE " + plugin.getPrefix() + "blocks ADD worldchunk varchar(128)";
statement.executeUpdate(queryAlter6);
System.out.println("[GameModeInventories] Adding new fields to database!");
try (ResultSet rsWorld = statement.executeQuery(queryWorld);) {
if (!rsWorld.next()) {
String queryAlter6 = "ALTER TABLE " + plugin.getPrefix() + "blocks ADD worldchunk varchar(128)";
statement.executeUpdate(queryAlter6);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding new fields to database!");
}
}
// add stands table
String queryStands = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "stands (uuid varchar(48) NOT NULL, PRIMARY KEY (uuid)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
String queryStands = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "stands (uuid varchar(48) NOT NULL, PRIMARY KEY (uuid)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
statement.executeUpdate(queryStands);
// add worlds table
String queryWorlds = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "worlds (id int(11) NOT NULL AUTO_INCREMENT, uuid varchar(48) DEFAULT '', world varchar(24) DEFAULT '', x double, y double, z double, yaw float, pitch float, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
String queryWorlds = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "worlds (id int(11) NOT NULL AUTO_INCREMENT, uuid varchar(48) DEFAULT '', world varchar(24) DEFAULT '', x double, y double, z double, yaw float, pitch float, PRIMARY KEY (id)) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
statement.executeUpdate(queryWorlds);
} catch (SQLException e) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "MySQL create table error: " + e);
} finally {
try {
if (rsWorld != null) {
rsWorld.close();
}
if (rsAttr != null) {
rsAttr.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "MySQL close statement error: " + e);
}
plugin.getLogger().log(Level.WARNING, "MySQL create table error: " + e);
}
}
}
@@ -0,0 +1,65 @@
/*
* Copyright 2015 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
public class GameModeInventoriesMySQLConnectionPool {
private static boolean isMySQL = false;
private final HikariDataSource hikari;
public GameModeInventoriesMySQLConnectionPool(GameModeInventories plugin) throws ClassNotFoundException {
isMySQL = true;
Class.forName("com.mysql.jdbc.Driver");
String host = plugin.getConfig().getString("storage.mysql.server");
String port = plugin.getConfig().getString("storage.mysql.port");
String databaseName = plugin.getConfig().getString("storage.mysql.database");
String user = plugin.getConfig().getString("storage.mysql.user");
String password = plugin.getConfig().getString("storage.mysql.password");
int pool_size = plugin.getConfig().getInt("storage.mysql.pool_size");
String url = String.format("jdbc:mysql://%s:%s/%s", host, port, databaseName);
if (!plugin.getConfig().getBoolean("storage.mysql.useSSL")) {
url += "?useSSL=false";
}
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(pool_size);
config.setJdbcUrl(url);
config.setUsername(user);
config.setPassword(password);
config.setDriverClassName("com.mysql.jdbc.Driver");
config.addDataSourceProperty("databaseName", databaseName);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "1024");
if (plugin.getConfig().getBoolean("storage.mysql.test_connection")) {
config.setConnectionTestQuery("SELECT 1");
}
hikari = new HikariDataSource(config);
}
public static boolean isIsMySQL() {
return isMySQL;
}
public HikariDataSource getHikari() {
return hikari;
}
}
@@ -3,24 +3,28 @@
*/
package me.eccentric_nz.gamemodeinventories.database;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesQueueData {
private final String worldchunk;
private final String location;
public GameModeInventoriesQueueData(String worldchunk, String location) {
this.worldchunk = worldchunk;
this.location = location;
}
public String getWorldChunk() {
return worldchunk;
}
public String getLocation() {
return location;
}
}
@@ -5,21 +5,14 @@ import me.eccentric_nz.gamemodeinventories.GameModeInventories;
public class GameModeInventoriesQueueDrain {
/**
*
*/
private final GameModeInventories plugin;
/**
* @param plugin
*/
public GameModeInventoriesQueueDrain(GameModeInventories plugin) {
this.plugin = plugin;
}
/**
*
*/
public void forceDrainQueue() {
plugin.debug("Forcing recorder queue to run a new batch before shutdown...", GMIDebug.INFO);
@@ -34,16 +27,27 @@ public class GameModeInventoriesQueueDrain {
// run insert
try {
recorderTask.insertIntoDatabase();
} catch (final Exception e) {
// e.printStackTrace();
plugin.debug("Stopping queue drain due to caught exception. Queue items lost: " + GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
// e.printStackTrace();
plugin.debug("Stopping queue drain due to caught exception. Queue items lost: "
+ GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
break;
}
if (GameModeInventoriesRecordingManager.failedDbConnectionCount > 0) {
plugin.debug("Stopping queue drain due to detected database error. Queue items lost: " + GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
plugin.debug("Stopping queue drain due to detected database error. Queue items lost: "
+ GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
}
}
}
}
@@ -2,9 +2,8 @@ package me.eccentric_nz.gamemodeinventories.database;
public class GameModeInventoriesRecordingManager {
/**
* If the recorder skips running we need to count because if this happens x times in a row, the recorder will delay
* itself so we don't kill the server
*/
// Counts skipped recorder runs: after x skips in a row the recorder delays
// itself so it does not kill the server.
public static int failedDbConnectionCount = 0;
}
@@ -6,27 +6,28 @@ public class GameModeInventoriesRecordingQueue {
private static final LinkedBlockingQueue<GameModeInventoriesQueueData> QUEUE = new LinkedBlockingQueue<GameModeInventoriesQueueData>();
/**
* @return the size of the QUEUE
*/
public static int getQueueSize() {
return QUEUE.size();
}
/**
* @param data
*/
public static void addToQueue(final GameModeInventoriesQueueData data) {
if (data == null) {
return;
}
QUEUE.add(data);
}
/**
* @return the QUEUE
*/
public static LinkedBlockingQueue<GameModeInventoriesQueueData> getQUEUE() {
return QUEUE;
}
}
@@ -1,117 +1,190 @@
package me.eccentric_nz.gamemodeinventories.database;
import me.eccentric_nz.gamemodeinventories.GMIDebug;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import me.eccentric_nz.gamemodeinventories.GMIDebug;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
public class GameModeInventoriesRecordingTask implements Runnable {
private final GameModeInventories plugin;
public GameModeInventoriesRecordingTask(GameModeInventories plugin) {
this.plugin = plugin;
}
public void save() {
if (!GameModeInventoriesRecordingQueue.getQUEUE().isEmpty()) {
insertIntoDatabase();
}
}
public void insertIntoDatabase() {
PreparedStatement s = null;
Connection conn = null;
try {
int perBatch = 1000;
if (!GameModeInventoriesRecordingQueue.getQUEUE().isEmpty()) {
plugin.debug("Beginning batch insert from queue. " + System.currentTimeMillis(), GMIDebug.INFO);
conn = GameModeInventoriesConnectionPool.dbc();
conn = plugin.getDatabaseConnection();
// Handle dead connections
if (conn == null || conn.isClosed()) {
if (GameModeInventoriesRecordingManager.failedDbConnectionCount == 0) {
plugin.debug("GMI database error. Connection should be there but it's not. Leaving actions to log in queue.", GMIDebug.INFO);
plugin.debug(
"GMI database error. Connection should be there but it's not. Leaving actions to log in queue.",
GMIDebug.INFO);
}
GameModeInventoriesRecordingManager.failedDbConnectionCount++;
if (GameModeInventoriesRecordingManager.failedDbConnectionCount > 5) {
plugin.debug("Too many problems connecting. Giving up for a bit.", GMIDebug.INFO);
scheduleNextRecording();
}
plugin.debug("Database connection still missing, incrementing count.", GMIDebug.INFO);
return;
} else {
GameModeInventoriesRecordingManager.failedDbConnectionCount = 0;
}
// Connection valid, proceed
conn.setAutoCommit(false);
s = conn.prepareStatement("INSERT INTO " + plugin.getPrefix() + "blocks (worldchunk,location) VALUES (?,?)");
s = conn.prepareStatement(
"INSERT INTO " + plugin.getPrefix() + "blocks (worldchunk,location) VALUES (?,?)");
int i = 0;
while (!GameModeInventoriesRecordingQueue.getQUEUE().isEmpty()) {
if (conn.isClosed()) {
plugin.debug("GMI database error. We have to bail in the middle of building primary bulk insert query.", GMIDebug.ERROR);
plugin.debug(
"GMI database error. We have to bail in the middle of building primary bulk insert query.",
GMIDebug.ERROR);
break;
}
GameModeInventoriesQueueData a = GameModeInventoriesRecordingQueue.getQUEUE().poll();
// poll() returns null if queue is empty
if (a == null) {
break;
}
s.setString(1, a.getWorldChunk());
s.setString(2, a.getLocation());
s.addBatch();
// Break out of the loop and just commit what we have
if (i >= perBatch) {
plugin.debug("Recorder: Batch max exceeded, running insert. Queue remaining: " + GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
plugin.debug("Recorder: Batch max exceeded, running insert. Queue remaining: "
+ GameModeInventoriesRecordingQueue.getQUEUE().size(), GMIDebug.INFO);
break;
}
i++;
}
s.executeBatch();
if (conn.isClosed()) {
plugin.debug("GMI database error. We have to bail in the middle of building primary bulk insert query.", GMIDebug.ERROR);
plugin.debug(
"GMI database error. We have to bail in the middle of building primary bulk insert query.",
GMIDebug.ERROR);
} else {
conn.commit();
conn.setAutoCommit(true);
plugin.debug("Batch insert was committed: " + System.currentTimeMillis(), GMIDebug.INFO);
}
}
} catch (SQLException e) {
plugin.debug("SQL error: " + e.getMessage(), GMIDebug.ERROR);
} finally {
try {
if (s != null) {
s.close();
}
if (conn != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
if (conn != null && GameModeInventoriesMySQLConnectionPool.isIsMySQL()) {
conn.close();
}
} catch (SQLException ignored) {
}
}
}
@Override
public void run() {
save();
scheduleNextRecording();
}
protected int getTickDelayForNextBatch() {
// If we have too many rejected connections, increase the schedule
if (GameModeInventoriesRecordingManager.failedDbConnectionCount > 5) {
return GameModeInventoriesRecordingManager.failedDbConnectionCount * 20;
}
return 3;
}
protected void scheduleNextRecording() {
if (!plugin.isEnabled()) {
plugin.debug("Can't schedule new recording tasks as plugin is now disabled. If you're shutting down the server, ignore me.", GMIDebug.INFO);
plugin.debug(
"Can't schedule new recording tasks as plugin is now disabled. If you're shutting down the server, ignore me.",
GMIDebug.INFO);
return;
}
plugin.recordingTask = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new GameModeInventoriesRecordingTask(plugin), getTickDelayForNextBatch());
plugin.recordingTask = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin,
new GameModeInventoriesRecordingTask(plugin), getTickDelayForNextBatch());
}
}
@@ -3,130 +3,169 @@
*/
package me.eccentric_nz.gamemodeinventories.database;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesSQLite {
private final GameModeInventories plugin;
public GameModeInventoriesSQLite(GameModeInventories plugin) {
this.plugin = plugin;
}
public void createTables() {
Connection connection = null;
Statement statement = null;
ResultSet rsUUID = null;
ResultSet rsXP = null;
ResultSet rsArmour = null;
ResultSet rsEnder = null;
ResultSet rsAttr = null;
ResultSet rsWorld = null;
try {
connection = GameModeInventoriesConnectionPool.dbc();
statement = connection.createStatement();
String queryInventories = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "inventories (id INTEGER PRIMARY KEY NOT NULL, uuid TEXT, player TEXT, gamemode TEXT, inventory TEXT, xp REAL, armour TEXT, enderchest TEXT, attributes TEXT, armour_attributes TEXT)";
try (Connection connection = plugin.getDatabaseConnection();
Statement statement = connection.createStatement();)
{
String queryInventories = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "inventories (id INTEGER PRIMARY KEY NOT NULL, uuid TEXT, player TEXT, gamemode TEXT, inventory TEXT, xp REAL, armour TEXT, enderchest TEXT, attributes TEXT, armour_attributes TEXT, bundle TEXT)";
statement.executeUpdate(queryInventories);
// deaths table, parked until the player is back in the death world
String queryDeaths = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "deaths (id INTEGER PRIMARY KEY NOT NULL, uuid TEXT, player TEXT, gamemode TEXT, world TEXT, inventory TEXT, armour TEXT)";
statement.executeUpdate(queryDeaths);
// add the bundle column, the inventory group a slot belongs to
String queryBundle = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%bundle TEXT%'";
try (ResultSet rsBundle = statement.executeQuery(queryBundle);) {
if (!rsBundle.next()) {
statement.executeUpdate("ALTER TABLE " + plugin.getPrefix() + "inventories ADD bundle TEXT");
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding bundle to database!");
}
}
// One slot per (uuid, gamemode, bundle); stops a failed legacy assignment
// leaving conflicting rows
statement.executeUpdate("CREATE UNIQUE INDEX IF NOT EXISTS uq_gmi_slot ON " + plugin.getPrefix()
+ "inventories (uuid, gamemode, bundle)");
// update inventories if there is no uuid column
String queryUUID = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "inventories' AND sql LIKE '%uuid TEXT%'";
rsUUID = statement.executeQuery(queryUUID);
if (!rsUUID.next()) {
String queryAlterU = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD uuid TEXT";
statement.executeUpdate(queryAlterU);
System.out.println("[GameModeInventories] Adding UUID to database!");
String queryUUID = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%uuid TEXT%'";
try (ResultSet rsUUID = statement.executeQuery(queryUUID);) {
if (!rsUUID.next()) {
String queryAlterU = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD uuid TEXT";
statement.executeUpdate(queryAlterU);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding UUID to database!");
}
}
// update inventories if there is no xp column
String queryXP = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "inventories' AND sql LIKE '%xp REAL%'";
rsXP = statement.executeQuery(queryXP);
if (!rsXP.next()) {
String queryAlter = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD xp REAL";
statement.executeUpdate(queryAlter);
System.out.println("[GameModeInventories] Adding xp to database!");
String queryXP = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%xp REAL%'";
try (ResultSet rsXP = statement.executeQuery(queryXP);) {
if (!rsXP.next()) {
String queryAlter = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD xp REAL";
statement.executeUpdate(queryAlter);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding xp to database!");
}
}
// update inventories if there is no armour column
String queryArmour = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "inventories' AND sql LIKE '%armour TEXT%'";
rsArmour = statement.executeQuery(queryArmour);
if (!rsArmour.next()) {
String queryAlter2 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour TEXT";
statement.executeUpdate(queryAlter2);
System.out.println("[GameModeInventories] Adding armour to database!");
String queryArmour = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%armour TEXT%'";
try (ResultSet rsArmour = statement.executeQuery(queryArmour);) {
if (!rsArmour.next()) {
String queryAlter2 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour TEXT";
statement.executeUpdate(queryAlter2);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding armour to database!");
}
}
// update inventories if there is no enderchest column
String queryEnder = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "inventories' AND sql LIKE '%enderchest TEXT%'";
rsEnder = statement.executeQuery(queryEnder);
if (!rsEnder.next()) {
String queryAlter3 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD enderchest TEXT";
statement.executeUpdate(queryAlter3);
System.out.println("[GameModeInventories] Adding enderchest to database!");
String queryEnder = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%enderchest TEXT%'";
try (ResultSet rsEnder = statement.executeQuery(queryEnder);) {
if (!rsEnder.next()) {
String queryAlter3 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD enderchest TEXT";
statement.executeUpdate(queryAlter3);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding enderchest to database!");
}
}
// update inventories if there is no attributes column
String queryAttr = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "inventories' AND sql LIKE '%attributes TEXT%'";
rsAttr = statement.executeQuery(queryAttr);
if (!rsAttr.next()) {
String queryAlter4 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD attributes TEXT";
statement.executeUpdate(queryAlter4);
String queryAlter5 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour_attributes TEXT";
statement.executeUpdate(queryAlter5);
System.out.println("[GameModeInventories] Adding attributes to database!");
String queryAttr = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "inventories' AND sql LIKE '%attributes TEXT%'";
try (ResultSet rsAttr = statement.executeQuery(queryAttr);) {
if (!rsAttr.next()) {
String queryAlter4 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD attributes TEXT";
statement.executeUpdate(queryAlter4);
String queryAlter5 = "ALTER TABLE " + plugin.getPrefix() + "inventories ADD armour_attributes TEXT";
statement.executeUpdate(queryAlter5);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding attributes to database!");
}
}
// add blocks table
String queryBlocks = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "blocks (id INTEGER PRIMARY KEY NOT NULL, worldchunk TEXT, location TEXT)";
String queryBlocks = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "blocks (id INTEGER PRIMARY KEY NOT NULL, worldchunk TEXT, location TEXT)";
statement.executeUpdate(queryBlocks);
// update inventories if there is no attributes column
String queryWorld = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix() + "blocks' AND sql LIKE '%worldchunk TEXT%'";
rsWorld = statement.executeQuery(queryWorld);
if (!rsWorld.next()) {
String queryAlter6 = "ALTER TABLE " + plugin.getPrefix() + "blocks ADD worldchunk TEXT";
statement.executeUpdate(queryAlter6);
System.out.println("[GameModeInventories] Adding new fields to database!");
String queryWorld = "SELECT sql FROM sqlite_master WHERE tbl_name = '" + plugin.getPrefix()
+ "blocks' AND sql LIKE '%worldchunk TEXT%'";
try (ResultSet rsWorld = statement.executeQuery(queryWorld);) {
if (!rsWorld.next()) {
String queryAlter6 = "ALTER TABLE " + plugin.getPrefix() + "blocks ADD worldchunk TEXT";
statement.executeUpdate(queryAlter6);
plugin.getLogger().log(Level.INFO, "[GameModeInventories] Adding new fields to database!");
}
}
// add stands table
String queryStands = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "stands (uuid TEXT PRIMARY KEY NOT NULL)";
String queryStands = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "stands (uuid TEXT PRIMARY KEY NOT NULL)";
statement.executeUpdate(queryStands);
// add worlds table
String queryWorlds = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix() + "worlds (id INTEGER PRIMARY KEY NOT NULL, uuid TEXT, world TEXT, x REAL, y REAL, z REAL, yaw REAL, pitch REAL)";
String queryWorlds = "CREATE TABLE IF NOT EXISTS " + plugin.getPrefix()
+ "worlds (id INTEGER PRIMARY KEY NOT NULL, uuid TEXT, world TEXT, x REAL, y REAL, z REAL, yaw REAL, pitch REAL)";
statement.executeUpdate(queryWorlds);
// close
statement.close();
} catch (SQLException e) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "SQLite create table error: " + e);
} finally {
try {
if (rsUUID != null) {
rsUUID.close();
}
if (rsXP != null) {
rsXP.close();
}
if (rsArmour != null) {
rsArmour.close();
}
if (rsEnder != null) {
rsEnder.close();
}
if (rsAttr != null) {
rsAttr.close();
}
if (rsWorld != null) {
rsWorld.close();
}
if (statement != null) {
statement.close();
}
if (connection != null && GameModeInventoriesConnectionPool.isIsMySQL()) {
connection.close();
}
} catch (SQLException e) {
plugin.getServer().getConsoleSender().sendMessage(plugin.MY_PLUGIN_NAME + "SQLite close statement error: " + e);
}
plugin.getLogger().log(Level.WARNING, "SQLite create table error: " + e);
}
}
}
@@ -1,38 +0,0 @@
/*
* Copyright 2014 eccentric_nz.
*/
package me.eccentric_nz.gamemodeinventories.database;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* @author eccentric_nz
*/
public class GameModeInventoriesSQLiteConnection {
private static final GameModeInventoriesSQLiteConnection INSTANCE = new GameModeInventoriesSQLiteConnection();
public Connection connection = null;
public static synchronized GameModeInventoriesSQLiteConnection getINSTANCE() {
return INSTANCE;
}
public Connection getConnection() {
return connection;
}
public void setConnection(String path) throws Exception {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + path);
}
/**
* @return an exception
* @throws CloneNotSupportedException
*/
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not allowed.");
}
}
@@ -0,0 +1,39 @@
package me.eccentric_nz.gamemodeinventories.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.File;
import me.eccentric_nz.gamemodeinventories.GameModeInventories;
public class GameModeInventoriesSQLiteConnectionPool {
private final HikariDataSource hikari;
public GameModeInventoriesSQLiteConnectionPool(GameModeInventories plugin) throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
HikariConfig config = new HikariConfig();
config.setPoolName("GMISQLitePool");
config.setDriverClassName("org.sqlite.JDBC");
config.setJdbcUrl("jdbc:sqlite:" + plugin.getDataFolder() + File.separator + "GMI.db");
config.setConnectionTestQuery("SELECT 1");
config.setMinimumIdle(1);
int pool_size = plugin.getConfig().getInt("storage.mysql.pool_size");
config.setMaximumPoolSize(pool_size);
config.setMaxLifetime(60000); // 60 Sec
config.setIdleTimeout(45000); // 45 Sec
config.addDataSourceProperty("databaseName", "GMI");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "1024");
hikari = new HikariDataSource(config);
}
public HikariDataSource getHikari() {
return hikari;
}
}
+111 -69
View File
@@ -1,64 +1,74 @@
armor: true
debug: false
debug_level: ERROR
dont_spam_chat: false
dont_spam_chat: true
enderchest: true
no_creative_pvp: false
no_drops: false
no_falling_drops: false
no_pickups: false
no_drops: true
no_falling_drops: true
no_pickups: true
no_villager_trade: false
no_wither_spawn: false
no_golem_spawn: false
remove_potions: true
restrict_creative: false
no_wither_spawn: true
no_golem_spawn: true
remove_potions: false
restrict_creative: true
# Where creative is allowed for holders of gamemodeinventories.toggle; both are
# required, so an ordinary player standing here cannot hold creative. gamemodeinventories.anywhere ignores this list.
creative_regions:
- spawn
# Worlds where adventure is refused, so it cannot stick where survival rules apply.
# Leave minigame worlds off: their plugins put players in adventure legitimately and those changes must not be cancelled.
restrict_adventure_worlds:
- world
- world_nether
- world_the_end
containers:
- ANVIL
- BARREL
- BEACON
- BEE_NEST
- BEEHIVE
- BLACK_SHULKER_BOX
- BLAST_FURNACE
- BLUE_SHULKER_BOX
- BREWING_STAND
- BROWN_SHULKER_BOX
- CAMPFIRE
- CARTOGRAPHY_TABLE
- CHEST
- CHIPPED_ANVIL
- COMPOSTER
- CYAN_SHULKER_BOX
- DAMAGED_ANVIL
- DISPENSER
- DROPPER
- ENCHANTING_TABLE
- ENDER_CHEST
- FLETCHING_TABLE
- FURNACE
- GRAY_SHULKER_BOX
- GREEN_SHULKER_BOX
- GRINDSTONE
- HOPPER
- JUKEBOX
- LECTERN
- LIGHT_BLUE_SHULKER_BOX
- LIGHT_GRAY_SHULKER_BOX
- LIME_SHULKER_BOX
- LOOM
- MAGENTA_SHULKER_BOX
- ORANGE_SHULKER_BOX
- PINK_SHULKER_BOX
- PURPLE_SHULKER_BOX
- RED_SHULKER_BOX
- SHULKER_BOX
- SMITHING_TABLE
- SMOKER
- SOUL_CAMPFIRE
- STONECUTTER
- TRAPPED_CHEST
- WHITE_SHULKER_BOX
- YELLOW_SHULKER_BOX
- ANVIL
- BARREL
- BEACON
- BEE_NEST
- BEEHIVE
- BLACK_SHULKER_BOX
- BLAST_FURNACE
- BLUE_SHULKER_BOX
- BREWING_STAND
- BROWN_SHULKER_BOX
- CAMPFIRE
- CARTOGRAPHY_TABLE
- CHEST
- CHIPPED_ANVIL
- COMPOSTER
- CYAN_SHULKER_BOX
- DAMAGED_ANVIL
- DISPENSER
- DROPPER
- ENCHANTING_TABLE
- ENDER_CHEST
- FLETCHING_TABLE
- FURNACE
- GRAY_SHULKER_BOX
- GREEN_SHULKER_BOX
- GRINDSTONE
- HOPPER
- JUKEBOX
- LECTERN
- LIGHT_BLUE_SHULKER_BOX
- LIGHT_GRAY_SHULKER_BOX
- LIME_SHULKER_BOX
- LOOM
- MAGENTA_SHULKER_BOX
- ORANGE_SHULKER_BOX
- PINK_SHULKER_BOX
- PURPLE_SHULKER_BOX
- RED_SHULKER_BOX
- SHULKER_BOX
- SMITHING_TABLE
- SMOKER
- SOUL_CAMPFIRE
- STONECUTTER
- TRAPPED_CHEST
- WHITE_SHULKER_BOX
- YELLOW_SHULKER_BOX
save_on_death: true
survival_on_world_change: false
xp: true
@@ -69,25 +79,57 @@ track_creative_place:
attached_block: false
no_seeds_from_pumpkin: false
worlds:
- world
- world
dont_track:
- STONE
- DIRT
- STONE
- DIRT
dont_track_is_whitelist: false
creative_blacklist: false
creative_blacklist: true
blacklist:
- TNT
- BEDROCK
- LAVA_BUCKET
- ARMOR_STAND
- BEDROCK
- DEEPSLATE_DIAMOND_ORE
- DIAMOND
- DIAMOND_AXE
- DIAMOND_BLOCK
- DIAMOND_BOOTS
- DIAMOND_CHESTPLATE
- DIAMOND_HELMET
- DIAMOND_HOE
- DIAMOND_HORSE_ARMOR
- DIAMOND_LEGGINGS
- DIAMOND_ORE
- DIAMOND_PICKAXE
- DIAMOND_SHOVEL
- DIAMOND_SWORD
- LAVA_BUCKET
- NETHER_STAR
- PRISMARINE_SHARD
- TNT
break_bedrock: false
command_blacklist: false
command_blacklist: true
commands:
- areashop
- bounty
- buy
- deposit
- ec
- echest
- enderchest
- ebal
- ebalance
- ebalancetop
- ebaltop
- eco
- give
- i
- buy
- item
- money
- pay
- qs
- quickshop
- sell
restrict_spectator: false
- withdraw
restrict_spectator: true
bypass:
inventories: true
items: true
@@ -101,13 +143,13 @@ storage:
mysql:
server: localhost
port: 3306
database: GMI
user: bukkit
password: mysecurepassword
database: gamemodeinventories
user: ^{MARIADB_USER}
password: ^{MARIADB_PASSWORD}
pool_size: 10
test_connection: false
useSSL: true
database: sqlite
database: mysql
prefix: ''
creative_world:
location: last_known
+21 -17
View File
@@ -1,17 +1,21 @@
# Do NOT change the '%s' - they must be left in, though the position may change
CONFIG_SET: '%s was set to: %s'
HELP: 'There is no help! Just switch game modes, and your inventory/armor/xp will change.'
INVALID_MATERIAL: 'Invalid material in blacklist'
INVALID_MATERIAL_TRACK: 'Invalid material in dont_track list'
NO_CREATIVE_BREAK: 'You cannot break blocks that were placed in CREATIVE gamemode!'
NO_CREATIVE_COMMAND: 'You are not allowed to use %s in CREATIVE!'
NO_CREATIVE_DROPS: 'Blocks that were placed in CREATIVE gamemode, do not give drops!'
NO_CREATIVE_HORSE: 'You are not allowed to access horse inventories in CREATIVE!'
NO_CREATIVE_INVENTORY: 'You are not allowed to access inventories in CREATIVE!'
NO_CREATIVE_PICKUP: 'You are not allowed to pick up items in CREATIVE!'
NO_CREATIVE_PLACE: '%s placement is disabled in CREATIVE gamemode!'
NO_PERMISSION: 'You do not have permission to run that command!'
NO_PLAYER_DROPS: 'You are not allowed to drop items in CREATIVE!'
NO_WORKBENCH_DROPS: 'Workbenches do not drop items in CREATIVE!'
NO_SPECTATOR: 'You are not allowed to be a SPECTATOR!'
NO_TRADE: 'You are not allowed to trade with villagers in CREATIVE!'
# Colours use MiniMessage tags - see https://docs.advntr.dev/minimessage/format.html
# Do NOT remove the placeholders (<command>, <material>, <option>, <value>) - though their position may change
CONFIG_SET: '<green><option> was set to: <value>'
FORCED_SURVIVAL: '<red>Notice: <gold>You were switched to Survival mode because you do not have permission for Creative mode here.'
HELP: '<gold>Simply switch game modes, and your inventory, armor and xp will change with you.'
INVALID_MATERIAL: '<red>Error: <gold>Invalid material in blacklist'
INVALID_MATERIAL_TRACK: '<red>Error: <gold>Invalid material in dont_track list'
NO_CREATIVE_BREAK: '<red>Error: <gold>You cannot break blocks that were placed in Creative mode!'
NO_CREATIVE_COMMAND: '<red>Error: <gold>You are not allowed to use <green><command></green> in Creative mode!'
NO_CREATIVE_DROPS: '<red>Error: <gold>Blocks that were placed in Creative mode do not give drops!'
NO_CREATIVE_HORSE: '<red>Error: <gold>You are not allowed to access horse inventories in Creative mode!'
NO_CREATIVE_INVENTORY: '<red>Error: <gold>You are not allowed to access inventories in Creative mode!'
NO_CREATIVE_PICKUP: '<red>Error: <gold>You are not allowed to pick up items in Creative mode!'
NO_CREATIVE_PLACE: '<red>Error: <gold><material> placement is disabled in Creative mode!'
NO_CREATIVE_REGION: '<red>Error: <gold>You do not have permission to enter Creative mode in this region!'
NO_PERMISSION: '<red>Error: <gold>You do not have permission to run that command!'
NO_PLAYER_DROPS: '<red>Error: <gold>You are not allowed to drop items in Creative mode!'
NO_WORKBENCH_DROPS: '<red>Error: <gold>Workbenches do not drop items in Creative mode!'
NO_SPECTATOR: '<red>Error: <gold>You are not allowed to be a Spectator!'
NO_ADVENTURE: '<red>Error: <gold>Adventure mode is not allowed in this world!'
NO_TRADE: '<red>Error: <gold>You are not allowed to trade with villagers in Creative mode!'
+15 -6
View File
@@ -1,11 +1,14 @@
author: eccentric_nz
description: Allow players to have separate inventories for each game mode (Creative and Survival).
main: me.eccentric_nz.gamemodeinventories.GameModeInventories
name: GameModeInventories
name: GameModeInventories-OG
load: POSTWORLD
softdepend: [ Multiverse-Core,MultiWorld,CoreProtect,LogBlock ]
version: 3.4.0
api-version: 1.18
depend: [ WorldGuard ]
softdepend: [ Multiverse-Core,MultiWorld,CoreProtect,MyWorlds ]
version: 3.5.0
api-version: 1.19
libraries:
- com.zaxxer:HikariCP:5.0.1
permissions:
gamemodeinventories.use:
default: true
@@ -22,8 +25,14 @@ permissions:
gamemodeinventories.admin:
default: op
description: Allow players to change config options.
gamemodeinventories.toggle:
default: op
description: Allow players to toggle between CREATIVE and SURVIVAL with /gmic.
gamemodeinventories.anywhere:
default: op
description: Allow players to use CREATIVE mode outside configured WorldGuard regions.
commands:
gmi:
permissions: gamemodeinventories.admin
description: Allow players to change config options.
aliases: [ gmic ]
description: Allow players to change config options or toggle CREATIVE mode.
usage: /<command> [config option]