Add license file and headers

This commit is contained in:
filoghost 2018-10-10 13:05:31 +02:00
parent dbaf2cc151
commit c41689fee2
61 changed files with 6129 additions and 4615 deletions

674
LICENSE.txt Normal file
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>.

View File

@ -1,319 +1,333 @@
package com.gmail.filoghost.chestcommands; /*
* This program is free software: you can redistribute it and/or modify
import java.io.File; * it under the terms of the GNU General Public License as published by
import java.io.IOException; * the Free Software Foundation, either version 3 of the License, or
import java.util.List; * (at your option) any later version.
import java.util.Map; *
import java.util.Set; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import org.bstats.bukkit.MetricsLite; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import org.bukkit.Bukkit; * GNU General Public License for more details.
import org.bukkit.ChatColor; *
import org.bukkit.configuration.InvalidConfigurationException; * You should have received a copy of the GNU General Public License
import org.bukkit.entity.Player; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import org.bukkit.plugin.java.JavaPlugin; */
package com.gmail.filoghost.chestcommands;
import com.gmail.filoghost.chestcommands.SimpleUpdater.ResponseHandler;
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge; import java.io.File;
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge; import java.io.IOException;
import com.gmail.filoghost.chestcommands.command.CommandFramework; import java.util.List;
import com.gmail.filoghost.chestcommands.command.CommandHandler; import java.util.Map;
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders; import java.util.Set;
import com.gmail.filoghost.chestcommands.config.Lang;
import com.gmail.filoghost.chestcommands.config.Settings; import org.bstats.bukkit.MetricsLite;
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig; import org.bukkit.Bukkit;
import com.gmail.filoghost.chestcommands.internal.BoundItem; import org.bukkit.ChatColor;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; import org.bukkit.configuration.InvalidConfigurationException;
import com.gmail.filoghost.chestcommands.internal.MenuData; import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder; import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.filoghost.chestcommands.listener.CommandListener;
import com.gmail.filoghost.chestcommands.listener.InventoryListener; import com.gmail.filoghost.chestcommands.SimpleUpdater.ResponseHandler;
import com.gmail.filoghost.chestcommands.listener.JoinListener; import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge;
import com.gmail.filoghost.chestcommands.listener.SignListener; import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import com.gmail.filoghost.chestcommands.nms.AttributeRemover; import com.gmail.filoghost.chestcommands.command.CommandFramework;
import com.gmail.filoghost.chestcommands.serializer.CommandSerializer; import com.gmail.filoghost.chestcommands.command.CommandHandler;
import com.gmail.filoghost.chestcommands.serializer.MenuSerializer; import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask; import com.gmail.filoghost.chestcommands.config.Lang;
import com.gmail.filoghost.chestcommands.task.RefreshMenusTask; import com.gmail.filoghost.chestcommands.config.Settings;
import com.gmail.filoghost.chestcommands.util.CaseInsensitiveMap; import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
import com.gmail.filoghost.chestcommands.util.ErrorLogger; import com.gmail.filoghost.chestcommands.internal.BoundItem;
import com.gmail.filoghost.chestcommands.util.Utils; import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.util.VersionUtils; import com.gmail.filoghost.chestcommands.internal.MenuData;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
public class ChestCommands extends JavaPlugin { import com.gmail.filoghost.chestcommands.listener.CommandListener;
import com.gmail.filoghost.chestcommands.listener.InventoryListener;
public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN; import com.gmail.filoghost.chestcommands.listener.JoinListener;
import com.gmail.filoghost.chestcommands.listener.SignListener;
private static ChestCommands instance; import com.gmail.filoghost.chestcommands.nms.AttributeRemover;
private static Settings settings; import com.gmail.filoghost.chestcommands.serializer.CommandSerializer;
private static Lang lang; import com.gmail.filoghost.chestcommands.serializer.MenuSerializer;
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask;
private static Map<String, ExtendedIconMenu> fileNameToMenuMap; import com.gmail.filoghost.chestcommands.task.RefreshMenusTask;
private static Map<String, ExtendedIconMenu> commandsToMenuMap; import com.gmail.filoghost.chestcommands.util.CaseInsensitiveMap;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
private static Set<BoundItem> boundItems; import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.VersionUtils;
private static int lastReloadErrors;
private static String newVersion; public class ChestCommands extends JavaPlugin {
private static AttributeRemover attributeRemover; public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN;
@Override private static ChestCommands instance;
public void onEnable() { private static Settings settings;
if (instance != null) { private static Lang lang;
getLogger().warning("Please do not use /reload or plugin reloaders. Do \"/cc reload\" instead.");
return; private static Map<String, ExtendedIconMenu> fileNameToMenuMap;
} private static Map<String, ExtendedIconMenu> commandsToMenuMap;
instance = this; private static Set<BoundItem> boundItems;
fileNameToMenuMap = CaseInsensitiveMap.create();
commandsToMenuMap = CaseInsensitiveMap.create(); private static int lastReloadErrors;
boundItems = Utils.newHashSet(); private static String newVersion;
settings = new Settings(new PluginConfig(this, "config.yml")); private static AttributeRemover attributeRemover;
lang = new Lang(new PluginConfig(this, "lang.yml"));
@Override
if (!EconomyBridge.setupEconomy()) { public void onEnable() {
getLogger().warning("Vault with a compatible economy plugin was not found! Icons with a PRICE or commands that give money will not work."); if (instance != null) {
} getLogger().warning("Please do not use /reload or plugin reloaders. Do \"/cc reload\" instead.");
return;
if (BarAPIBridge.setupPlugin()) { }
getLogger().info("Hooked BarAPI");
} instance = this;
fileNameToMenuMap = CaseInsensitiveMap.create();
AttributeRemover.setup(); commandsToMenuMap = CaseInsensitiveMap.create();
boundItems = Utils.newHashSet();
if (settings.update_notifications) {
new SimpleUpdater(this, 56919).checkForUpdates(new ResponseHandler() { settings = new Settings(new PluginConfig(this, "config.yml"));
lang = new Lang(new PluginConfig(this, "lang.yml"));
@Override
public void onUpdateFound(String newVersion) { if (!EconomyBridge.setupEconomy()) {
ChestCommands.newVersion = newVersion; getLogger().warning("Vault with a compatible economy plugin was not found! Icons with a PRICE or commands that give money will not work.");
}
if (settings.use_console_colors) {
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + "Found a new version: " + newVersion + ChatColor.WHITE + " (yours: v" + getDescription().getVersion() + ")"); if (BarAPIBridge.setupPlugin()) {
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "Download it on Bukkit Dev:"); getLogger().info("Hooked BarAPI");
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "dev.bukkit.org/bukkit-plugins/chest-commands"); }
} else {
getLogger().info("Found a new version available: " + newVersion); AttributeRemover.setup();
getLogger().info("Download it on Bukkit Dev:");
getLogger().info("dev.bukkit.org/bukkit-plugins/chest-commands"); if (settings.update_notifications) {
} new SimpleUpdater(this, 56919).checkForUpdates(new ResponseHandler() {
}
}); @Override
} public void onUpdateFound(String newVersion) {
ChestCommands.newVersion = newVersion;
// Start bStats metrics
new MetricsLite(this); if (settings.use_console_colors) {
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + "Found a new version: " + newVersion + ChatColor.WHITE + " (yours: v" + getDescription().getVersion() + ")");
Bukkit.getPluginManager().registerEvents(new CommandListener(), this); Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "Download it on Bukkit Dev:");
Bukkit.getPluginManager().registerEvents(new InventoryListener(), this); Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "dev.bukkit.org/bukkit-plugins/chest-commands");
Bukkit.getPluginManager().registerEvents(new JoinListener(), this); } else {
Bukkit.getPluginManager().registerEvents(new SignListener(), this); getLogger().info("Found a new version available: " + newVersion);
getLogger().info("Download it on Bukkit Dev:");
CommandFramework.register(this, new CommandHandler("chestcommands")); getLogger().info("dev.bukkit.org/bukkit-plugins/chest-commands");
}
ErrorLogger errorLogger = new ErrorLogger(); }
load(errorLogger); });
}
lastReloadErrors = errorLogger.getSize();
if (errorLogger.hasErrors()) { // Start bStats metrics
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new ErrorLoggerTask(errorLogger), 10L); new MetricsLite(this);
}
Bukkit.getPluginManager().registerEvents(new CommandListener(), this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new RefreshMenusTask(), 2L, 2L); Bukkit.getPluginManager().registerEvents(new InventoryListener(), this);
} Bukkit.getPluginManager().registerEvents(new JoinListener(), this);
Bukkit.getPluginManager().registerEvents(new SignListener(), this);
CommandFramework.register(this, new CommandHandler("chestcommands"));
@Override
public void onDisable() { ErrorLogger errorLogger = new ErrorLogger();
closeAllMenus(); load(errorLogger);
}
lastReloadErrors = errorLogger.getSize();
if (errorLogger.hasErrors()) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new ErrorLoggerTask(errorLogger), 10L);
public void load(ErrorLogger errorLogger) { }
fileNameToMenuMap.clear();
commandsToMenuMap.clear(); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new RefreshMenusTask(), 2L, 2L);
boundItems.clear(); }
CommandSerializer.checkClassConstructors(errorLogger);
try { @Override
settings.load(); public void onDisable() {
} catch (IOException e) { closeAllMenus();
e.printStackTrace(); }
getLogger().warning("I/O error while using the configuration. Default values will be used.");
} catch (InvalidConfigurationException e) {
e.printStackTrace();
getLogger().warning("The config.yml was not a valid YAML, please look at the error above. Default values will be used."); public void load(ErrorLogger errorLogger) {
} catch (Exception e) { fileNameToMenuMap.clear();
e.printStackTrace(); commandsToMenuMap.clear();
getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer."); boundItems.clear();
}
CommandSerializer.checkClassConstructors(errorLogger);
try {
lang.load(); try {
} catch (IOException e) { settings.load();
e.printStackTrace(); } catch (IOException e) {
getLogger().warning("I/O error while using the language file. Default values will be used."); e.printStackTrace();
} catch (InvalidConfigurationException e) { getLogger().warning("I/O error while using the configuration. Default values will be used.");
e.printStackTrace(); } catch (InvalidConfigurationException e) {
getLogger().warning("The lang.yml was not a valid YAML, please look at the error above. Default values will be used."); e.printStackTrace();
} catch (Exception e) { getLogger().warning("The config.yml was not a valid YAML, please look at the error above. Default values will be used.");
e.printStackTrace(); } catch (Exception e) {
getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer."); e.printStackTrace();
} getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer.");
}
try {
AsciiPlaceholders.load(errorLogger); try {
} catch (IOException e) { lang.load();
e.printStackTrace(); } catch (IOException e) {
getLogger().warning("I/O error while reading the placeholders. They will not work."); e.printStackTrace();
} catch (Exception e) { getLogger().warning("I/O error while using the language file. Default values will be used.");
e.printStackTrace(); } catch (InvalidConfigurationException e) {
getLogger().warning("Unhandled error while reading the placeholders! Please inform the developer."); e.printStackTrace();
} getLogger().warning("The lang.yml was not a valid YAML, please look at the error above. Default values will be used.");
} catch (Exception e) {
// Load the menus. e.printStackTrace();
File menusFolder = new File(getDataFolder(), "menu"); getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer.");
}
if (!menusFolder.isDirectory()) {
// Create the directory with the default menu. try {
menusFolder.mkdirs(); AsciiPlaceholders.load(errorLogger);
Utils.saveResourceSafe(this, "menu" + File.separator + "example.yml"); } catch (IOException e) {
} e.printStackTrace();
getLogger().warning("I/O error while reading the placeholders. They will not work.");
List<PluginConfig> menusList = loadMenus(menusFolder); } catch (Exception e) {
for (PluginConfig menuConfig : menusList) { e.printStackTrace();
try { getLogger().warning("Unhandled error while reading the placeholders! Please inform the developer.");
menuConfig.load(); }
} catch (IOException e) {
e.printStackTrace(); // Load the menus.
errorLogger.addError("I/O error while loading the menu \"" + menuConfig.getFileName() + "\". Is the file in use?"); File menusFolder = new File(getDataFolder(), "menu");
continue;
} catch (InvalidConfigurationException e) { if (!menusFolder.isDirectory()) {
e.printStackTrace(); // Create the directory with the default menu.
errorLogger.addError("Invalid YAML configuration for the menu \"" + menuConfig.getFileName() + "\". Please look at the error above, or use an online YAML parser (google is your friend)."); menusFolder.mkdirs();
continue; Utils.saveResourceSafe(this, "menu" + File.separator + "example.yml");
} }
MenuData data = MenuSerializer.loadMenuData(menuConfig, errorLogger); List<PluginConfig> menusList = loadMenus(menusFolder);
ExtendedIconMenu iconMenu = MenuSerializer.loadMenu(menuConfig, data.getTitle(), data.getRows(), errorLogger); for (PluginConfig menuConfig : menusList) {
try {
if (fileNameToMenuMap.containsKey(menuConfig.getFileName())) { menuConfig.load();
errorLogger.addError("Two menus have the same file name \"" + menuConfig.getFileName() + "\" with different cases. There will be problems opening one of these two menus."); } catch (IOException e) {
} e.printStackTrace();
fileNameToMenuMap.put(menuConfig.getFileName(), iconMenu); errorLogger.addError("I/O error while loading the menu \"" + menuConfig.getFileName() + "\". Is the file in use?");
continue;
if (data.hasCommands()) { } catch (InvalidConfigurationException e) {
for (String command : data.getCommands()) { e.printStackTrace();
if (!command.isEmpty()) { errorLogger.addError("Invalid YAML configuration for the menu \"" + menuConfig.getFileName() + "\". Please look at the error above, or use an online YAML parser (google is your friend).");
if (commandsToMenuMap.containsKey(command)) { continue;
errorLogger.addError("The menus \"" + commandsToMenuMap.get(command).getFileName() + "\" and \"" + menuConfig.getFileName() + "\" have the same command \"" + command + "\". Only one will be opened."); }
}
commandsToMenuMap.put(command, iconMenu); MenuData data = MenuSerializer.loadMenuData(menuConfig, errorLogger);
} ExtendedIconMenu iconMenu = MenuSerializer.loadMenu(menuConfig, data.getTitle(), data.getRows(), errorLogger);
}
} if (fileNameToMenuMap.containsKey(menuConfig.getFileName())) {
errorLogger.addError("Two menus have the same file name \"" + menuConfig.getFileName() + "\" with different cases. There will be problems opening one of these two menus.");
iconMenu.setRefreshTicks(data.getRefreshTenths()); }
fileNameToMenuMap.put(menuConfig.getFileName(), iconMenu);
if (data.getOpenActions() != null) {
iconMenu.setOpenActions(data.getOpenActions()); if (data.hasCommands()) {
} for (String command : data.getCommands()) {
if (!command.isEmpty()) {
if (data.hasBoundMaterial() && data.getClickType() != null) { if (commandsToMenuMap.containsKey(command)) {
BoundItem boundItem = new BoundItem(iconMenu, data.getBoundMaterial(), data.getClickType()); errorLogger.addError("The menus \"" + commandsToMenuMap.get(command).getFileName() + "\" and \"" + menuConfig.getFileName() + "\" have the same command \"" + command + "\". Only one will be opened.");
if (data.hasBoundDataValue()) { }
boundItem.setRestrictiveData(data.getBoundDataValue()); commandsToMenuMap.put(command, iconMenu);
} }
boundItems.add(boundItem); }
} }
}
iconMenu.setRefreshTicks(data.getRefreshTenths());
// Register the BungeeCord plugin channel.
if (!Bukkit.getMessenger().isOutgoingChannelRegistered(this, "BungeeCord")) { if (data.getOpenActions() != null) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); iconMenu.setOpenActions(data.getOpenActions());
} }
}
if (data.hasBoundMaterial() && data.getClickType() != null) {
BoundItem boundItem = new BoundItem(iconMenu, data.getBoundMaterial(), data.getClickType());
if (data.hasBoundDataValue()) {
/** boundItem.setRestrictiveData(data.getBoundDataValue());
* Loads all the configuration files recursively into a list. }
*/ boundItems.add(boundItem);
private List<PluginConfig> loadMenus(File file) { }
List<PluginConfig> list = Utils.newArrayList(); }
if (file.isDirectory()) {
for (File subFile : file.listFiles()) { // Register the BungeeCord plugin channel.
list.addAll(loadMenus(subFile)); if (!Bukkit.getMessenger().isOutgoingChannelRegistered(this, "BungeeCord")) {
} Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
} else if (file.isFile()) { }
if (file.getName().endsWith(".yml")) { }
list.add(new PluginConfig(this, file));
}
}
return list; /**
} * Loads all the configuration files recursively into a list.
*/
private List<PluginConfig> loadMenus(File file) {
List<PluginConfig> list = Utils.newArrayList();
public static void closeAllMenus() { if (file.isDirectory()) {
for (Player player : VersionUtils.getOnlinePlayers()) { for (File subFile : file.listFiles()) {
if (player.getOpenInventory() != null) { list.addAll(loadMenus(subFile));
if (player.getOpenInventory().getTopInventory().getHolder() instanceof MenuInventoryHolder || player.getOpenInventory().getBottomInventory().getHolder() instanceof MenuInventoryHolder) { }
player.closeInventory(); } else if (file.isFile()) {
} if (file.getName().endsWith(".yml")) {
} list.add(new PluginConfig(this, file));
} }
} }
return list;
}
public static ChestCommands getInstance() {
return instance;
} public static void closeAllMenus() {
for (Player player : VersionUtils.getOnlinePlayers()) {
public static Settings getSettings() { if (player.getOpenInventory() != null) {
return settings; if (player.getOpenInventory().getTopInventory().getHolder() instanceof MenuInventoryHolder || player.getOpenInventory().getBottomInventory().getHolder() instanceof MenuInventoryHolder) {
} player.closeInventory();
}
public static Lang getLang() { }
return lang; }
} }
public static boolean hasNewVersion() {
return newVersion != null;
} public static ChestCommands getInstance() {
return instance;
public static String getNewVersion() { }
return newVersion;
} public static Settings getSettings() {
return settings;
public static Map<String, ExtendedIconMenu> getFileNameToMenuMap() { }
return fileNameToMenuMap;
} public static Lang getLang() {
return lang;
public static Map<String, ExtendedIconMenu> getCommandToMenuMap() { }
return commandsToMenuMap;
} public static boolean hasNewVersion() {
return newVersion != null;
public static Set<BoundItem> getBoundItems() { }
return boundItems;
} public static String getNewVersion() {
return newVersion;
public static int getLastReloadErrors() { }
return lastReloadErrors;
} public static Map<String, ExtendedIconMenu> getFileNameToMenuMap() {
return fileNameToMenuMap;
public static void setLastReloadErrors(int lastReloadErrors) { }
ChestCommands.lastReloadErrors = lastReloadErrors;
} public static Map<String, ExtendedIconMenu> getCommandToMenuMap() {
return commandsToMenuMap;
public static AttributeRemover getAttributeRemover() { }
return attributeRemover;
} public static Set<BoundItem> getBoundItems() {
return boundItems;
} }
public static int getLastReloadErrors() {
return lastReloadErrors;
}
public static void setLastReloadErrors(int lastReloadErrors) {
ChestCommands.lastReloadErrors = lastReloadErrors;
}
public static AttributeRemover getAttributeRemover() {
return attributeRemover;
}
}

View File

@ -1,14 +1,28 @@
package com.gmail.filoghost.chestcommands; /*
* This program is free software: you can redistribute it and/or modify
public class Permissions { * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public static final String * (at your option) any later version.
*
UPDATE_NOTIFICATIONS = "chestcommands.update", * This program is distributed in the hope that it will be useful,
SEE_ERRORS = "chestcommands.errors", * but WITHOUT ANY WARRANTY; without even the implied warranty of
SIGN_CREATE = "chestcommands.sign", * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
COMMAND_BASE = "chestcommands.command.", *
OPEN_MENU_BASE = "chestcommands.open."; * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
} */
package com.gmail.filoghost.chestcommands;
public class Permissions {
public static final String
UPDATE_NOTIFICATIONS = "chestcommands.update",
SEE_ERRORS = "chestcommands.errors",
SIGN_CREATE = "chestcommands.sign",
COMMAND_BASE = "chestcommands.command.",
OPEN_MENU_BASE = "chestcommands.open.";
}

View File

@ -1,166 +1,180 @@
package com.gmail.filoghost.chestcommands; /*
* This program is free software: you can redistribute it and/or modify
import java.io.BufferedReader; * it under the terms of the GNU General Public License as published by
import java.io.IOException; * the Free Software Foundation, either version 3 of the License, or
import java.io.InputStreamReader; * (at your option) any later version.
import java.net.MalformedURLException; *
import java.net.URL; * This program is distributed in the hope that it will be useful,
import java.net.URLConnection; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import java.util.regex.Matcher; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import java.util.regex.Pattern; * GNU General Public License for more details.
*
import org.bukkit.Bukkit; * You should have received a copy of the GNU General Public License
import org.bukkit.plugin.Plugin; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import org.json.simple.JSONArray; */
import org.json.simple.JSONObject; package com.gmail.filoghost.chestcommands;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
/** import java.io.IOException;
* A very simple and lightweight updater. import java.io.InputStreamReader;
*/ import java.net.MalformedURLException;
public final class SimpleUpdater { import java.net.URL;
import java.net.URLConnection;
public interface ResponseHandler { import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Called when the updater finds a new version. import org.bukkit.Bukkit;
* @param newVersion - the new version import org.bukkit.plugin.Plugin;
*/ import org.json.simple.JSONArray;
public void onUpdateFound(final String newVersion); import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
}
/**
private Plugin plugin; * A very simple and lightweight updater.
private int projectId; */
public final class SimpleUpdater {
public SimpleUpdater(Plugin plugin, int projectId) {
if (plugin == null) { public interface ResponseHandler {
throw new NullPointerException("Plugin cannot be null");
} /**
* Called when the updater finds a new version.
this.plugin = plugin; * @param newVersion - the new version
this.projectId = projectId; */
} public void onUpdateFound(final String newVersion);
/** }
* This method creates a new async thread to check for updates.
*/ private Plugin plugin;
public void checkForUpdates(final ResponseHandler responseHandler) { private int projectId;
Thread updaterThread = new Thread(new Runnable() {
@Override public SimpleUpdater(Plugin plugin, int projectId) {
public void run() { if (plugin == null) {
throw new NullPointerException("Plugin cannot be null");
try { }
JSONArray filesArray = (JSONArray) readJson("https://api.curseforge.com/servermods/files?projectIds=" + projectId);
this.plugin = plugin;
if (filesArray.size() == 0) { this.projectId = projectId;
// The array cannot be empty, there must be at least one file. The project ID is not valid. }
plugin.getLogger().warning("The project ID (" + projectId + ") provided for updating is invalid or curse had a problem.");
plugin.getLogger().warning("If the error persists, please inform the author."); /**
return; * This method creates a new async thread to check for updates.
} */
public void checkForUpdates(final ResponseHandler responseHandler) {
String updateName = (String) ((JSONObject) filesArray.get(filesArray.size() - 1)).get("name"); Thread updaterThread = new Thread(new Runnable() {
final String newVersion = extractVersion(updateName); @Override
public void run() {
if (newVersion == null) {
throw new NumberFormatException(); try {
} JSONArray filesArray = (JSONArray) readJson("https://api.curseforge.com/servermods/files?projectIds=" + projectId);
if (isNewerVersion(newVersion)) { if (filesArray.size() == 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { // The array cannot be empty, there must be at least one file. The project ID is not valid.
plugin.getLogger().warning("The project ID (" + projectId + ") provided for updating is invalid or curse had a problem.");
public void run() { plugin.getLogger().warning("If the error persists, please inform the author.");
responseHandler.onUpdateFound(newVersion); return;
} }
});
} String updateName = (String) ((JSONObject) filesArray.get(filesArray.size() - 1)).get("name");
final String newVersion = extractVersion(updateName);
} catch (IOException e) {
plugin.getLogger().warning("Could not contact BukkitDev to check for updates."); if (newVersion == null) {
} catch (NumberFormatException e) { throw new NumberFormatException();
plugin.getLogger().warning("The author of this plugin has misconfigured the Updater system."); }
plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
plugin.getLogger().warning("Please notify the author of this error."); if (isNewerVersion(newVersion)) {
} catch (Exception e) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
e.printStackTrace();
plugin.getLogger().warning("Unable to check for updates: unhandled exception."); public void run() {
} responseHandler.onUpdateFound(newVersion);
}
} });
}); }
updaterThread.start();
} } catch (IOException e) {
plugin.getLogger().warning("Could not contact BukkitDev to check for updates.");
private Object readJson(String url) throws MalformedURLException, IOException { } catch (NumberFormatException e) {
plugin.getLogger().warning("The author of this plugin has misconfigured the Updater system.");
URLConnection conn = new URL(url).openConnection(); plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
conn.setConnectTimeout(5000); plugin.getLogger().warning("Please notify the author of this error.");
conn.setReadTimeout(8000); } catch (Exception e) {
conn.addRequestProperty("User-Agent", "Updater (by filoghost)"); e.printStackTrace();
conn.setDoOutput(true); plugin.getLogger().warning("Unable to check for updates: unhandled exception.");
}
return JSONValue.parse(new BufferedReader(new InputStreamReader(conn.getInputStream())));
} }
});
/** updaterThread.start();
* Compare the version found with the plugin's version, from an array of integer separated by full stops. }
* Examples:
* v1.2 > v1.12 private Object readJson(String url) throws MalformedURLException, IOException {
* v2.1 = v2.01
*/ URLConnection conn = new URL(url).openConnection();
private boolean isNewerVersion(String remoteVersion) { conn.setConnectTimeout(5000);
String pluginVersion = plugin.getDescription().getVersion(); conn.setReadTimeout(8000);
conn.addRequestProperty("User-Agent", "Updater (by filoghost)");
if (pluginVersion == null) { conn.setDoOutput(true);
// Do not throw exceptions, just consider it as v0.
pluginVersion = "0"; return JSONValue.parse(new BufferedReader(new InputStreamReader(conn.getInputStream())));
} }
if (!remoteVersion.matches("v?[0-9\\.]+")) { /**
// Should always be checked before by this class. * Compare the version found with the plugin's version, from an array of integer separated by full stops.
throw new IllegalArgumentException("fetched version's format is incorrect"); * Examples:
} * v1.2 > v1.12
* v2.1 = v2.01
// Remove all the "v" from the versions, replace multiple full stops with a single full stop, and split them. */
String[] pluginVersionSplit = pluginVersion.replace("v", "").replaceAll("[\\.]{2,}", ".").split("\\."); private boolean isNewerVersion(String remoteVersion) {
String[] remoteVersionSplit = remoteVersion.replace("v", "").replaceAll("[\\.]{2,}", ".").split("\\."); String pluginVersion = plugin.getDescription().getVersion();
int longest = Math.max(pluginVersionSplit.length, remoteVersionSplit.length); if (pluginVersion == null) {
// Do not throw exceptions, just consider it as v0.
int[] pluginVersionArray = new int[longest]; pluginVersion = "0";
int[] remoteVersionArray = new int[longest]; }
for (int i = 0; i < pluginVersionSplit.length; i++) { if (!remoteVersion.matches("v?[0-9\\.]+")) {
pluginVersionArray[i] = Integer.parseInt(pluginVersionSplit[i]); // Should always be checked before by this class.
} throw new IllegalArgumentException("fetched version's format is incorrect");
}
for (int i = 0; i < remoteVersionSplit.length; i++) {
remoteVersionArray[i] = Integer.parseInt(remoteVersionSplit[i]); // Remove all the "v" from the versions, replace multiple full stops with a single full stop, and split them.
} String[] pluginVersionSplit = pluginVersion.replace("v", "").replaceAll("[\\.]{2,}", ".").split("\\.");
String[] remoteVersionSplit = remoteVersion.replace("v", "").replaceAll("[\\.]{2,}", ".").split("\\.");
for (int i = 0; i < longest; i++) {
int diff = remoteVersionArray[i] - pluginVersionArray[i]; int longest = Math.max(pluginVersionSplit.length, remoteVersionSplit.length);
if (diff > 0) {
return true; int[] pluginVersionArray = new int[longest];
} else if (diff < 0) { int[] remoteVersionArray = new int[longest];
return false;
} for (int i = 0; i < pluginVersionSplit.length; i++) {
pluginVersionArray[i] = Integer.parseInt(pluginVersionSplit[i]);
// Continue the loop. }
}
for (int i = 0; i < remoteVersionSplit.length; i++) {
return false; remoteVersionArray[i] = Integer.parseInt(remoteVersionSplit[i]);
} }
private String extractVersion(String input) { for (int i = 0; i < longest; i++) {
Matcher matcher = Pattern.compile("v[0-9\\.]+").matcher(input); int diff = remoteVersionArray[i] - pluginVersionArray[i];
if (diff > 0) {
String result = null; return true;
if (matcher.find()) { } else if (diff < 0) {
result = matcher.group(); return false;
} }
return result; // Continue the loop.
} }
}
return false;
}
private String extractVersion(String input) {
Matcher matcher = Pattern.compile("v[0-9\\.]+").matcher(input);
String result = null;
if (matcher.find()) {
result = matcher.group();
}
return result;
}
}

View File

@ -1,36 +1,50 @@
package com.gmail.filoghost.chestcommands.api; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.ChestCommands; * (at your option) any later version.
*
public class ChestCommandsAPI { * 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
* Checks if a menu with a given file name was loaded by the plugin. * GNU General Public License for more details.
* *
* @return true - if the menu was found. * You should have received a copy of the GNU General Public License
*/ * along with this program. If not, see <https://www.gnu.org/licenses/>.
public static boolean isPluginMenu(String yamlFile) { */
return ChestCommands.getFileNameToMenuMap().containsKey(yamlFile); package com.gmail.filoghost.chestcommands.api;
}
import org.bukkit.entity.Player;
/**
* Opens a menu loaded by ChestCommands to a player. import com.gmail.filoghost.chestcommands.ChestCommands;
* NOTE: this method ignores permissions.
* public class ChestCommandsAPI {
* @param player - the player that will see the GUI.
* @param yamlFile - the file name of the menu to open. The .yml extension CANNOT be omitted. /**
* @return true - if the menu was found and opened, false if not. * Checks if a menu with a given file name was loaded by the plugin.
*/ *
public static boolean openPluginMenu(Player player, String yamlFile) { * @return true - if the menu was found.
IconMenu menu = ChestCommands.getFileNameToMenuMap().get(yamlFile); */
public static boolean isPluginMenu(String yamlFile) {
if (menu != null) { return ChestCommands.getFileNameToMenuMap().containsKey(yamlFile);
menu.open(player); }
return true;
} else { /**
return false; * Opens a menu loaded by ChestCommands to a player.
} * NOTE: this method ignores permissions.
} *
} * @param player - the player that will see the GUI.
* @param yamlFile - the file name of the menu to open. The .yml extension CANNOT be omitted.
* @return true - if the menu was found and opened, false if not.
*/
public static boolean openPluginMenu(Player player, String yamlFile) {
IconMenu menu = ChestCommands.getFileNameToMenuMap().get(yamlFile);
if (menu != null) {
menu.open(player);
return true;
} else {
return false;
}
}
}

View File

@ -1,14 +1,28 @@
package com.gmail.filoghost.chestcommands.api; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public interface ClickHandler { * (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
* @param player - the player that clicked on the icon. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* @return true if the menu should be closed, false otherwise. * GNU General Public License for more details.
*/ *
public boolean onClick(Player player); * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
} */
package com.gmail.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
public interface ClickHandler {
/**
*
* @param player - the player that clicked on the icon.
* @return true if the menu should be closed, false otherwise.
*/
public boolean onClick(Player player);
}

View File

@ -1,312 +1,326 @@
package com.gmail.filoghost.chestcommands.api; /*
* This program is free software: you can redistribute it and/or modify
import java.util.Arrays; * it under the terms of the GNU General Public License as published by
import java.util.HashMap; * the Free Software Foundation, either version 3 of the License, or
import java.util.HashSet; * (at your option) any later version.
import java.util.List; *
import java.util.Map; * This program is distributed in the hope that it will be useful,
import java.util.Map.Entry; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import java.util.Set; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
import org.bukkit.ChatColor; *
import org.bukkit.Color; * You should have received a copy of the GNU General Public License
import org.bukkit.Material; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import org.bukkit.enchantments.Enchantment; */
import org.bukkit.entity.Player; package com.gmail.filoghost.chestcommands.api;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import java.util.Arrays;
import org.bukkit.inventory.meta.LeatherArmorMeta; import java.util.HashMap;
import org.bukkit.inventory.meta.SkullMeta; import java.util.HashSet;
import java.util.List;
import com.gmail.filoghost.chestcommands.internal.Variable; import java.util.Map;
import com.gmail.filoghost.chestcommands.util.Utils; import java.util.Map.Entry;
import java.util.Set;
public class Icon {
import org.bukkit.ChatColor;
private Material material; import org.bukkit.Color;
private int amount; import org.bukkit.Material;
private short dataValue; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
private String name; import org.bukkit.inventory.ItemStack;
private List<String> lore; import org.bukkit.inventory.meta.ItemMeta;
private Map<Enchantment, Integer> enchantments; import org.bukkit.inventory.meta.LeatherArmorMeta;
private Color color; import org.bukkit.inventory.meta.SkullMeta;
private String skullOwner;
import com.gmail.filoghost.chestcommands.internal.Variable;
protected boolean closeOnClick; import com.gmail.filoghost.chestcommands.util.Utils;
private ClickHandler clickHandler;
public class Icon {
private Set<Variable> nameVariables;
private Map<Integer, Set<Variable>> loreVariables; private Material material;
private ItemStack cachedItem; // When there are no variables, we don't recreate the item. private int amount;
private short dataValue;
public Icon() {
enchantments = new HashMap<Enchantment, Integer>(); private String name;
closeOnClick = true; private List<String> lore;
} private Map<Enchantment, Integer> enchantments;
private Color color;
public boolean hasVariables() { private String skullOwner;
return nameVariables != null || loreVariables != null;
} protected boolean closeOnClick;
private ClickHandler clickHandler;
public void setMaterial(Material material) {
if (material == Material.AIR) material = null; private Set<Variable> nameVariables;
this.material = material; private Map<Integer, Set<Variable>> loreVariables;
} private ItemStack cachedItem; // When there are no variables, we don't recreate the item.
public Material getMaterial() { public Icon() {
return material; enchantments = new HashMap<Enchantment, Integer>();
} closeOnClick = true;
}
public void setAmount(int amount) {
if (amount < 1) amount = 1; public boolean hasVariables() {
else if (amount > 127) amount = 127; return nameVariables != null || loreVariables != null;
}
this.amount = amount;
} public void setMaterial(Material material) {
if (material == Material.AIR) material = null;
public int getAmount() { this.material = material;
return amount; }
}
public Material getMaterial() {
public void setDataValue(short dataValue) { return material;
if (dataValue < 0) dataValue = 0; }
this.dataValue = dataValue; public void setAmount(int amount) {
} if (amount < 1) amount = 1;
else if (amount > 127) amount = 127;
public short getDataValue() {
return dataValue; this.amount = amount;
} }
public void setName(String name) { public int getAmount() {
this.name = name; return amount;
this.nameVariables = null; // Reset the variables }
if (name != null) { public void setDataValue(short dataValue) {
for (Variable variable : Variable.values()) { if (dataValue < 0) dataValue = 0;
if (name.contains(variable.getText())) {
this.dataValue = dataValue;
if (nameVariables == null) { }
nameVariables = new HashSet<Variable>();
} public short getDataValue() {
return dataValue;
nameVariables.add(variable); }
}
} public void setName(String name) {
} this.name = name;
} this.nameVariables = null; // Reset the variables
public boolean hasName() { if (name != null) {
return name != null; for (Variable variable : Variable.values()) {
} if (name.contains(variable.getText())) {
public void setLore(String... lore) { if (nameVariables == null) {
if (lore != null) { nameVariables = new HashSet<Variable>();
setLore(Arrays.asList(lore)); }
}
} nameVariables.add(variable);
}
public void setLore(List<String> lore) { }
this.lore = lore; }
this.loreVariables = null; // Reset the variables }
if (lore != null) { public boolean hasName() {
for (int i = 0; i < lore.size(); i++) { return name != null;
for (Variable variable : Variable.values()) { }
if (lore.get(i).contains(variable.getText())) {
public void setLore(String... lore) {
if (loreVariables == null) { if (lore != null) {
loreVariables = new HashMap<Integer, Set<Variable>>(); setLore(Arrays.asList(lore));
} }
}
Set<Variable> lineVariables = loreVariables.get(i);
public void setLore(List<String> lore) {
if (lineVariables == null) { this.lore = lore;
lineVariables = new HashSet<Variable>(); this.loreVariables = null; // Reset the variables
loreVariables.put(i, lineVariables);
} if (lore != null) {
for (int i = 0; i < lore.size(); i++) {
lineVariables.add(variable); for (Variable variable : Variable.values()) {
} if (lore.get(i).contains(variable.getText())) {
}
} if (loreVariables == null) {
} loreVariables = new HashMap<Integer, Set<Variable>>();
} }
public boolean hasLore() { Set<Variable> lineVariables = loreVariables.get(i);
return lore != null && lore.size() > 0;
} if (lineVariables == null) {
lineVariables = new HashSet<Variable>();
public List<String> getLore() { loreVariables.put(i, lineVariables);
return lore; }
}
lineVariables.add(variable);
public void setEnchantments(Map<Enchantment, Integer> enchantments) { }
if (enchantments == null) { }
this.enchantments.clear(); }
return; }
} }
this.enchantments = enchantments;
} public boolean hasLore() {
return lore != null && lore.size() > 0;
public Map<Enchantment, Integer> getEnchantments() { }
return new HashMap<Enchantment, Integer>(enchantments);
} public List<String> getLore() {
return lore;
public void addEnchantment(Enchantment ench) { }
addEnchantment(ench, 1);
} public void setEnchantments(Map<Enchantment, Integer> enchantments) {
if (enchantments == null) {
public void addEnchantment(Enchantment ench, Integer level) { this.enchantments.clear();
enchantments.put(ench, level); return;
} }
this.enchantments = enchantments;
public void removeEnchantment(Enchantment ench) { }
enchantments.remove(ench);
} public Map<Enchantment, Integer> getEnchantments() {
return new HashMap<Enchantment, Integer>(enchantments);
public void clearEnchantments() { }
enchantments.clear();
} public void addEnchantment(Enchantment ench) {
addEnchantment(ench, 1);
public Color getColor() { }
return color;
} public void addEnchantment(Enchantment ench, Integer level) {
enchantments.put(ench, level);
public void setColor(Color color) { }
this.color = color;
} public void removeEnchantment(Enchantment ench) {
enchantments.remove(ench);
public String getSkullOwner() { }
return skullOwner;
} public void clearEnchantments() {
enchantments.clear();
public void setSkullOwner(String skullOwner) { }
this.skullOwner = skullOwner;
} public Color getColor() {
return color;
public void setCloseOnClick(boolean closeOnClick) { }
this.closeOnClick = closeOnClick;
} public void setColor(Color color) {
this.color = color;
public void setClickHandler(ClickHandler clickHandler) { }
this.clickHandler = clickHandler;
} public String getSkullOwner() {
return skullOwner;
public ClickHandler getClickHandler() { }
return clickHandler;
} public void setSkullOwner(String skullOwner) {
this.skullOwner = skullOwner;
protected String calculateName(Player pov) { }
if (hasName()) {
public void setCloseOnClick(boolean closeOnClick) {
String name = this.name; this.closeOnClick = closeOnClick;
}
if (pov != null && nameVariables != null) {
for (Variable nameVariable : nameVariables) { public void setClickHandler(ClickHandler clickHandler) {
name = name.replace(nameVariable.getText(), nameVariable.getReplacement(pov)); this.clickHandler = clickHandler;
} }
}
public ClickHandler getClickHandler() {
if (name.isEmpty()) { return clickHandler;
// Add a color to display the name empty. }
return ChatColor.WHITE.toString();
} else { protected String calculateName(Player pov) {
return name; if (hasName()) {
}
} String name = this.name;
return null; if (pov != null && nameVariables != null) {
} for (Variable nameVariable : nameVariables) {
name = name.replace(nameVariable.getText(), nameVariable.getReplacement(pov));
protected List<String> calculateLore(Player pov) { }
}
List<String> output = null;
if (name.isEmpty()) {
if (hasLore()) { // Add a color to display the name empty.
return ChatColor.WHITE.toString();
output = Utils.newArrayList(); } else {
return name;
if (pov != null && loreVariables != null) { }
for (int i = 0; i < lore.size(); i++) { }
String line = lore.get(i); return null;
}
Set<Variable> lineVariables = loreVariables.get(i);
if (lineVariables != null) { protected List<String> calculateLore(Player pov) {
for (Variable lineVariable : lineVariables) {
line = line.replace(lineVariable.getText(), lineVariable.getReplacement(pov)); List<String> output = null;
}
} if (hasLore()) {
output.add(line); output = Utils.newArrayList();
}
} else { if (pov != null && loreVariables != null) {
// Otherwise just copy the lines. for (int i = 0; i < lore.size(); i++) {
output.addAll(lore);
} String line = lore.get(i);
}
Set<Variable> lineVariables = loreVariables.get(i);
if (material == null) { if (lineVariables != null) {
for (Variable lineVariable : lineVariables) {
if (output == null) { line = line.replace(lineVariable.getText(), lineVariable.getReplacement(pov));
output = Utils.newArrayList(); }
} }
// Add an error message. output.add(line);
output.add(ChatColor.RED + "(Invalid material)"); }
} } else {
// Otherwise just copy the lines.
return output; output.addAll(lore);
} }
}
public ItemStack createItemstack(Player pov) {
if (material == null) {
if (!this.hasVariables() && cachedItem != null) {
// Performance. if (output == null) {
return cachedItem; output = Utils.newArrayList();
} }
// If the material is not set, display BEDROCK. // Add an error message.
ItemStack itemStack = (material != null) ? new ItemStack(material, amount, dataValue) : new ItemStack(Material.BEDROCK, amount); output.add(ChatColor.RED + "(Invalid material)");
}
// Apply name, lore and color.
ItemMeta itemMeta = itemStack.getItemMeta(); return output;
}
itemMeta.setDisplayName(calculateName(pov));
itemMeta.setLore(calculateLore(pov)); public ItemStack createItemstack(Player pov) {
if (color != null && itemMeta instanceof LeatherArmorMeta) { if (!this.hasVariables() && cachedItem != null) {
((LeatherArmorMeta) itemMeta).setColor(color); // Performance.
} return cachedItem;
}
if (skullOwner != null && itemMeta instanceof SkullMeta) {
((SkullMeta) itemMeta).setOwner(skullOwner); // If the material is not set, display BEDROCK.
} ItemStack itemStack = (material != null) ? new ItemStack(material, amount, dataValue) : new ItemStack(Material.BEDROCK, amount);
itemStack.setItemMeta(itemMeta); // Apply name, lore and color.
ItemMeta itemMeta = itemStack.getItemMeta();
// Apply enchants.
if (enchantments.size() > 0) { itemMeta.setDisplayName(calculateName(pov));
for (Entry<Enchantment, Integer> entry : enchantments.entrySet()) { itemMeta.setLore(calculateLore(pov));
itemStack.addUnsafeEnchantment(entry.getKey(), entry.getValue());
} if (color != null && itemMeta instanceof LeatherArmorMeta) {
} ((LeatherArmorMeta) itemMeta).setColor(color);
}
if (!this.hasVariables()) {
// If there are no variables, cache the item. if (skullOwner != null && itemMeta instanceof SkullMeta) {
cachedItem = itemStack; ((SkullMeta) itemMeta).setOwner(skullOwner);
} }
return itemStack; itemStack.setItemMeta(itemMeta);
}
// Apply enchants.
public boolean onClick(Player whoClicked) { if (enchantments.size() > 0) {
if (clickHandler != null) { for (Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
return clickHandler.onClick(whoClicked); itemStack.addUnsafeEnchantment(entry.getKey(), entry.getValue());
} }
}
return closeOnClick;
} if (!this.hasVariables()) {
} // If there are no variables, cache the item.
cachedItem = itemStack;
}
return itemStack;
}
public boolean onClick(Player whoClicked) {
if (clickHandler != null) {
return clickHandler.onClick(whoClicked);
}
return closeOnClick;
}
}

View File

@ -1,93 +1,107 @@
package com.gmail.filoghost.chestcommands.api; /*
* This program is free software: you can redistribute it and/or modify
import java.util.Arrays; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Bukkit; * (at your option) any later version.
import org.bukkit.entity.Player; *
import org.bukkit.inventory.Inventory; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.nms.AttributeRemover; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.util.Utils; *
import com.gmail.filoghost.chestcommands.util.Validate; * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
/* */
* MEMO: Raw slot numbers package com.gmail.filoghost.chestcommands.api;
*
* | 0| 1| 2| 3| 4| 5| 6| 7| 8| import java.util.Arrays;
* | 9|10|11|12|13|14|15|16|17|
* ... import org.bukkit.Bukkit;
* import org.bukkit.entity.Player;
*/ import org.bukkit.inventory.Inventory;
public class IconMenu {
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
protected final String title; import com.gmail.filoghost.chestcommands.nms.AttributeRemover;
protected final Icon[] icons; import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.Validate;
public IconMenu(String title, int rows) { /*
this.title = title; * MEMO: Raw slot numbers
icons = new Icon[rows * 9]; *
} * | 0| 1| 2| 3| 4| 5| 6| 7| 8|
* | 9|10|11|12|13|14|15|16|17|
public void setIcon(int x, int y, Icon icon) { * ...
int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1); *
if (slot >= 0 && slot < icons.length) { */
icons[slot] = icon; public class IconMenu {
}
} protected final String title;
protected final Icon[] icons;
public void setIconRaw(int slot, Icon icon) {
if (slot >= 0 && slot < icons.length) {
icons[slot] = icon; public IconMenu(String title, int rows) {
} this.title = title;
} icons = new Icon[rows * 9];
}
public Icon getIcon(int x, int y) {
int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1); public void setIcon(int x, int y, Icon icon) {
if (slot >= 0 && slot < icons.length) { int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1);
return icons[slot]; if (slot >= 0 && slot < icons.length) {
} icons[slot] = icon;
}
return null; }
}
public void setIconRaw(int slot, Icon icon) {
public Icon getIconRaw(int slot) { if (slot >= 0 && slot < icons.length) {
if (slot >= 0 && slot < icons.length) { icons[slot] = icon;
return icons[slot]; }
} }
return null; public Icon getIcon(int x, int y) {
} int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1);
if (slot >= 0 && slot < icons.length) {
public int getRows() { return icons[slot];
return icons.length / 9; }
}
return null;
public int getSize() { }
return icons.length;
} public Icon getIconRaw(int slot) {
if (slot >= 0 && slot < icons.length) {
public String getTitle() { return icons[slot];
return title; }
}
return null;
public void open(Player player) { }
Validate.notNull(player, "Player cannot be null");
public int getRows() {
Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title); return icons.length / 9;
}
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) { public int getSize() {
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player))); return icons.length;
} }
}
public String getTitle() {
player.openInventory(inventory); return title;
} }
@Override public void open(Player player) {
public String toString() { Validate.notNull(player, "Player cannot be null");
return "IconMenu [title=" + title + ", icons=" + Arrays.toString(icons) + "]";
} Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
}
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) {
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player)));
}
}
player.openInventory(inventory);
}
@Override
public String toString() {
return "IconMenu [title=" + title + ", icons=" + Arrays.toString(icons) + "]";
}
}

View File

@ -1,34 +1,48 @@
package com.gmail.filoghost.chestcommands.bridge; /*
* This program is free software: you can redistribute it and/or modify
import me.confuser.barapi.BarAPI; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Bukkit; * (at your option) any later version.
import org.bukkit.entity.Player; *
import org.bukkit.plugin.Plugin; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public class BarAPIBridge { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
private static BarAPI barAPI; *
* You should have received a copy of the GNU General Public License
public static boolean setupPlugin() { * along with this program. If not, see <https://www.gnu.org/licenses/>.
Plugin barPlugin = Bukkit.getPluginManager().getPlugin("BarAPI"); */
package com.gmail.filoghost.chestcommands.bridge;
if (barPlugin == null) {
return false; import me.confuser.barapi.BarAPI;
}
import org.bukkit.Bukkit;
barAPI = (BarAPI) barPlugin; import org.bukkit.entity.Player;
return true; import org.bukkit.plugin.Plugin;
}
public class BarAPIBridge {
public static boolean hasValidPlugin() {
return barAPI != null; private static BarAPI barAPI;
}
public static boolean setupPlugin() {
public static void setMessage(Player player, String message, int seconds) { Plugin barPlugin = Bukkit.getPluginManager().getPlugin("BarAPI");
if (!hasValidPlugin()) throw new IllegalStateException("BarAPI plugin was not found!");
if (barPlugin == null) {
BarAPI.setMessage(player, message, seconds); return false;
} }
} barAPI = (BarAPI) barPlugin;
return true;
}
public static boolean hasValidPlugin() {
return barAPI != null;
}
public static void setMessage(Player player, String message, int seconds) {
if (!hasValidPlugin()) throw new IllegalStateException("BarAPI plugin was not found!");
BarAPI.setMessage(player, message, seconds);
}
}

View File

@ -1,89 +1,103 @@
package com.gmail.filoghost.chestcommands.bridge; /*
* This program is free software: you can redistribute it and/or modify
import net.milkbowl.vault.economy.Economy; * it under the terms of the GNU General Public License as published by
import net.milkbowl.vault.economy.EconomyResponse; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.Bukkit; *
import org.bukkit.entity.Player; * This program is distributed in the hope that it will be useful,
import org.bukkit.plugin.RegisteredServiceProvider; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.util.Utils; * GNU General Public License for more details.
*
public class EconomyBridge { * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
private static Economy economy; */
package com.gmail.filoghost.chestcommands.bridge;
public static boolean setupEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") == null) { import net.milkbowl.vault.economy.Economy;
return false; import net.milkbowl.vault.economy.EconomyResponse;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); import org.bukkit.Bukkit;
if (rsp == null) { import org.bukkit.entity.Player;
return false; import org.bukkit.plugin.RegisteredServiceProvider;
}
economy = rsp.getProvider(); import com.gmail.filoghost.chestcommands.util.Utils;
return economy != null;
} public class EconomyBridge {
public static boolean hasValidEconomy() { private static Economy economy;
return economy != null;
} public static boolean setupEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
public static Economy getEconomy() { return false;
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!"); }
return economy; RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class);
} if (rsp == null) {
return false;
public static double getMoney(Player player) { }
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!"); economy = rsp.getProvider();
return economy.getBalance(player.getName(), player.getWorld().getName()); return economy != null;
} }
public static boolean hasMoney(Player player, double minimum) { public static boolean hasValidEconomy() {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!"); return economy != null;
if (minimum < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + minimum); }
double balance = economy.getBalance(player.getName(), player.getWorld().getName()); public static Economy getEconomy() {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
if (balance < minimum) { return economy;
return false; }
} else {
return true; public static double getMoney(Player player) {
} if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
} return economy.getBalance(player.getName(), player.getWorld().getName());
}
/**
* @return true if the operation was successful. public static boolean hasMoney(Player player, double minimum) {
*/ if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
public static boolean takeMoney(Player player, double amount) { if (minimum < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + minimum);
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount); double balance = economy.getBalance(player.getName(), player.getWorld().getName());
EconomyResponse response = economy.withdrawPlayer(player.getName(), player.getWorld().getName(), amount); if (balance < minimum) {
boolean result = response.transactionSuccess(); return false;
} else {
Utils.refreshMenu(player); return true;
}
return result; }
}
/**
public static boolean giveMoney(Player player, double amount) { * @return true if the operation was successful.
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!"); */
if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount); public static boolean takeMoney(Player player, double amount) {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
EconomyResponse response = economy.depositPlayer(player.getName(), player.getWorld().getName(), amount); if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount);
boolean result = response.transactionSuccess();
EconomyResponse response = economy.withdrawPlayer(player.getName(), player.getWorld().getName(), amount);
Utils.refreshMenu(player); boolean result = response.transactionSuccess();
return result; Utils.refreshMenu(player);
}
return result;
public static String formatMoney(double amount) { }
if (hasValidEconomy()) {
return economy.format(amount); public static boolean giveMoney(Player player, double amount) {
} else { if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
return Double.toString(amount); if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount);
}
} EconomyResponse response = economy.depositPlayer(player.getName(), player.getWorld().getName(), amount);
} boolean result = response.transactionSuccess();
Utils.refreshMenu(player);
return result;
}
public static String formatMoney(double amount) {
if (hasValidEconomy()) {
return economy.format(amount);
} else {
return Double.toString(amount);
}
}
}

View File

@ -1,39 +1,53 @@
package com.gmail.filoghost.chestcommands.bridge.bungee; /*
* This program is free software: you can redistribute it and/or modify
import java.io.ByteArrayOutputStream; * it under the terms of the GNU General Public License as published by
import java.io.DataOutputStream; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.ChatColor; *
import org.bukkit.entity.Player; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.ChestCommands; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public class BungeeCordUtils { * GNU General Public License for more details.
*
public static boolean connect(Player player, String server) { * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
try { */
package com.gmail.filoghost.chestcommands.bridge.bungee;
if (server.length() == 0) {
player.sendMessage("§cTarget server was \"\" (empty string) cannot connect to it."); import java.io.ByteArrayOutputStream;
return false; import java.io.DataOutputStream;
}
import org.bukkit.ChatColor;
ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); import org.bukkit.entity.Player;
DataOutputStream out = new DataOutputStream(byteArray); import com.gmail.filoghost.chestcommands.ChestCommands;
out.writeUTF("Connect"); public class BungeeCordUtils {
out.writeUTF(server); // Target Server.
public static boolean connect(Player player, String server) {
player.sendPluginMessage(ChestCommands.getInstance(), "BungeeCord", byteArray.toByteArray());
try {
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "An unexpected exception has occurred. Please notify the server's staff about this. (They should look at the console)."); if (server.length() == 0) {
ex.printStackTrace(); player.sendMessage("§cTarget server was \"\" (empty string) cannot connect to it.");
ChestCommands.getInstance().getLogger().warning("Could not connect \"" + player.getName() + "\" to the server \"" + server + "\"."); return false;
return false; }
}
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
return true; DataOutputStream out = new DataOutputStream(byteArray);
}
out.writeUTF("Connect");
} out.writeUTF(server); // Target Server.
player.sendPluginMessage(ChestCommands.getInstance(), "BungeeCord", byteArray.toByteArray());
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "An unexpected exception has occurred. Please notify the server's staff about this. (They should look at the console).");
ex.printStackTrace();
ChestCommands.getInstance().getLogger().warning("Could not connect \"" + player.getName() + "\" to the server \"" + server + "\".");
return false;
}
return true;
}
}

View File

@ -1,151 +1,165 @@
package com.gmail.filoghost.chestcommands.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.command.Command; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.command.CommandExecutor; * (at your option) any later version.
import org.bukkit.command.CommandSender; *
import org.bukkit.command.PluginCommand; * This program is distributed in the hope that it will be useful,
import org.bukkit.plugin.java.JavaPlugin; * 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.
* Wrapper for the default command executor. *
*/ * You should have received a copy of the GNU General Public License
public abstract class CommandFramework implements CommandExecutor { * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/*************************************************** package com.gmail.filoghost.chestcommands.command;
*
* STATIC REGISTER METHOD import org.bukkit.ChatColor;
* import org.bukkit.command.Command;
***************************************************/ import org.bukkit.command.CommandExecutor;
public static boolean register(JavaPlugin plugin, CommandFramework command) { import org.bukkit.command.CommandSender;
PluginCommand pluginCommand = plugin.getCommand(command.label); import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
if (pluginCommand == null) {
return false; /**
} * Wrapper for the default command executor.
*/
pluginCommand.setExecutor(command); public abstract class CommandFramework implements CommandExecutor {
return true;
} /***************************************************
*
/*************************************************** * STATIC REGISTER METHOD
* *
* COMMAND FRAMEWORK CLASS ***************************************************/
* public static boolean register(JavaPlugin plugin, CommandFramework command) {
***************************************************/ PluginCommand pluginCommand = plugin.getCommand(command.label);
private String label;
if (pluginCommand == null) {
public CommandFramework(String label) { return false;
this.label = label; }
}
pluginCommand.setExecutor(command);
@Override return true;
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { }
try {
/***************************************************
execute(sender, label, args); *
* COMMAND FRAMEWORK CLASS
} catch (CommandException ex) { *
***************************************************/
if (ex.getMessage() != null && !ex.getMessage().isEmpty()) { private String label;
// Use RED by default.
sender.sendMessage(ChatColor.RED + ex.getMessage()); public CommandFramework(String label) {
} this.label = label;
} }
return true; @Override
} public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
public abstract void execute(CommandSender sender, String label, String[] args);
execute(sender, label, args);
/*************************************************** } catch (CommandException ex) {
*
* COMMAND EXCEPTION if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
* // Use RED by default.
***************************************************/ sender.sendMessage(ChatColor.RED + ex.getMessage());
public static class CommandException extends RuntimeException { }
}
private static final long serialVersionUID = 1L;
return true;
public CommandException(String msg) { }
super(msg);
} public abstract void execute(CommandSender sender, String label, String[] args);
}
/***************************************************
*
/*************************************************** * COMMAND EXCEPTION
* *
* VALIDATE CLASS ***************************************************/
* public static class CommandException extends RuntimeException {
***************************************************/
public static class CommandValidate { private static final long serialVersionUID = 1L;
public static void notNull(Object o, String msg) { public CommandException(String msg) {
if (o == null) { super(msg);
throw new CommandException(msg); }
}
} }
public static void isTrue(boolean b, String msg) {
if (!b) { /***************************************************
throw new CommandException(msg); *
} * VALIDATE CLASS
} *
***************************************************/
public static int getPositiveInteger(String input) { public static class CommandValidate {
try {
int i = Integer.parseInt(input); public static void notNull(Object o, String msg) {
if (i < 0) { if (o == null) {
throw new CommandException("The number must be 0 or positive."); throw new CommandException(msg);
} }
return i; }
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\"."); public static void isTrue(boolean b, String msg) {
} if (!b) {
} throw new CommandException(msg);
}
public static int getPositiveIntegerNotZero(String input) { }
try {
int i = Integer.parseInt(input); public static int getPositiveInteger(String input) {
if (i <= 0) { try {
throw new CommandException("The number must be positive."); int i = Integer.parseInt(input);
} if (i < 0) {
return i; throw new CommandException("The number must be 0 or positive.");
} catch (NumberFormatException e) { }
throw new CommandException("Invalid number \"" + input + "\"."); return i;
} } catch (NumberFormatException e) {
} throw new CommandException("Invalid number \"" + input + "\".");
}
public static double getPositiveDouble(String input) { }
try {
double d = Double.parseDouble(input); public static int getPositiveIntegerNotZero(String input) {
if (d < 0) { try {
throw new CommandException("The number must be 0 or positive."); int i = Integer.parseInt(input);
} if (i <= 0) {
return d; throw new CommandException("The number must be positive.");
} catch (NumberFormatException e) { }
throw new CommandException("Invalid number \"" + input + "\"."); return i;
} } catch (NumberFormatException e) {
} throw new CommandException("Invalid number \"" + input + "\".");
}
public static double getPositiveDoubleNotZero(String input) { }
try {
double d = Integer.parseInt(input); public static double getPositiveDouble(String input) {
if (d <= 0) { try {
throw new CommandException("The number must be positive."); double d = Double.parseDouble(input);
} if (d < 0) {
return d; throw new CommandException("The number must be 0 or positive.");
} catch (NumberFormatException e) { }
throw new CommandException("Invalid number \"" + input + "\"."); return d;
} } catch (NumberFormatException e) {
} throw new CommandException("Invalid number \"" + input + "\".");
}
public static void minLength(Object[] array, int minLength, String msg) { }
if (array.length < minLength) {
throw new CommandException(msg); public static double getPositiveDoubleNotZero(String input) {
} try {
} double d = Integer.parseInt(input);
} if (d <= 0) {
} throw new CommandException("The number must be positive.");
}
return d;
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\".");
}
}
public static void minLength(Object[] array, int minLength, String msg) {
if (array.length < minLength) {
throw new CommandException(msg);
}
}
}
}

View File

@ -1,128 +1,142 @@
package com.gmail.filoghost.chestcommands.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.ChatColor; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.command.CommandSender; * (at your option) any later version.
import org.bukkit.command.ConsoleCommandSender; *
import org.bukkit.entity.Player; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.ChestCommands; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.Permissions; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; *
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.util.ErrorLogger; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
public class CommandHandler extends CommandFramework { package com.gmail.filoghost.chestcommands.command;
public CommandHandler(String label) { import org.bukkit.Bukkit;
super(label); import org.bukkit.ChatColor;
} import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
@Override import org.bukkit.entity.Player;
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 0) { import com.gmail.filoghost.chestcommands.ChestCommands;
// This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for FREE. import com.gmail.filoghost.chestcommands.Permissions;
sender.sendMessage(ChestCommands.CHAT_PREFIX); import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getInstance().getDescription().getVersion()); import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask;
sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost"); import com.gmail.filoghost.chestcommands.util.ErrorLogger;
sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help");
return; public class CommandHandler extends CommandFramework {
}
public CommandHandler(String label) {
super(label);
}
if (args[0].equalsIgnoreCase("help")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "help"), "You don't have permission."); @Override
sender.sendMessage(ChestCommands.CHAT_PREFIX + " Commands:"); public void execute(CommandSender sender, String label, String[] args) {
sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin."); if (args.length == 0) {
sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus."); // This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for FREE.
sender.sendMessage(ChatColor.WHITE + "/" + label + " open <menu> [player]" + ChatColor.GRAY + " - Opens a menu for a player."); sender.sendMessage(ChestCommands.CHAT_PREFIX);
return; sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getInstance().getDescription().getVersion());
} sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost");
sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help");
return;
}
if (args[0].equalsIgnoreCase("reload")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "reload"), "You don't have permission.");
ChestCommands.closeAllMenus(); if (args[0].equalsIgnoreCase("help")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "help"), "You don't have permission.");
ErrorLogger errorLogger = new ErrorLogger(); sender.sendMessage(ChestCommands.CHAT_PREFIX + " Commands:");
ChestCommands.getInstance().load(errorLogger); sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus.");
ChestCommands.setLastReloadErrors(errorLogger.getSize()); sender.sendMessage(ChatColor.WHITE + "/" + label + " open <menu> [player]" + ChatColor.GRAY + " - Opens a menu for a player.");
return;
if (!errorLogger.hasErrors()) { }
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded.");
} else {
new ErrorLoggerTask(errorLogger).run();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorLogger.getSize() + " error(s)."); if (args[0].equalsIgnoreCase("reload")) {
if (!(sender instanceof ConsoleCommandSender)) { CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "reload"), "You don't have permission.");
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console.");
} ChestCommands.closeAllMenus();
}
return; ErrorLogger errorLogger = new ErrorLogger();
} ChestCommands.getInstance().load(errorLogger);
ChestCommands.setLastReloadErrors(errorLogger.getSize());
if (args[0].equalsIgnoreCase("open")) { if (!errorLogger.hasErrors()) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open"), "You don't have permission."); sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded.");
CommandValidate.minLength(args, 2, "Usage: /" + label + " open <menu> [player]"); } else {
new ErrorLoggerTask(errorLogger).run();
Player target = null; sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorLogger.getSize() + " error(s).");
if (!(sender instanceof ConsoleCommandSender)) {
if (!(sender instanceof Player)) { sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console.");
CommandValidate.minLength(args, 3, "You must specify a player from the console."); }
target = Bukkit.getPlayerExact(args[2]); }
} else { return;
if (args.length > 2) { }
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open.others"), "You don't have permission to open menus for others.");
target = Bukkit.getPlayerExact(args[2]);
} else {
target = (Player) sender; if (args[0].equalsIgnoreCase("open")) {
} CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open"), "You don't have permission.");
CommandValidate.minLength(args, 2, "Usage: /" + label + " open <menu> [player]");
}
Player target = null;
CommandValidate.notNull(target, "That player is not online.");
if (!(sender instanceof Player)) {
String menuName = args[1].toLowerCase().endsWith(".yml") ? args[1] : args[1] + ".yml"; CommandValidate.minLength(args, 3, "You must specify a player from the console.");
ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(menuName); target = Bukkit.getPlayerExact(args[2]);
CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found."); } else {
if (args.length > 2) {
if (!sender.hasPermission(menu.getPermission())) { CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open.others"), "You don't have permission to open menus for others.");
menu.sendNoPermissionMessage(sender); target = Bukkit.getPlayerExact(args[2]);
return; } else {
} target = (Player) sender;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
if (!ChestCommands.getLang().open_menu.isEmpty()) { }
sender.sendMessage(ChestCommands.getLang().open_menu.replace("{menu}", menuName));
} CommandValidate.notNull(target, "That player is not online.");
} else {
if (!ChestCommands.getLang().open_menu_others.isEmpty()) { String menuName = args[1].toLowerCase().endsWith(".yml") ? args[1] : args[1] + ".yml";
sender.sendMessage(ChestCommands.getLang().open_menu_others.replace("{menu}", menuName).replace("{player}", target.getName())); ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(menuName);
} CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found.");
}
if (!sender.hasPermission(menu.getPermission())) {
menu.open(target); menu.sendNoPermissionMessage(sender);
return; return;
} }
if (sender.getName().equalsIgnoreCase(target.getName())) {
if (!ChestCommands.getLang().open_menu.isEmpty()) {
if (args[0].equalsIgnoreCase("list")) { sender.sendMessage(ChestCommands.getLang().open_menu.replace("{menu}", menuName));
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "list"), "You don't have permission."); }
sender.sendMessage(ChestCommands.CHAT_PREFIX + " Loaded menus:"); } else {
for (String file : ChestCommands.getFileNameToMenuMap().keySet()) { if (!ChestCommands.getLang().open_menu_others.isEmpty()) {
sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file); sender.sendMessage(ChestCommands.getLang().open_menu_others.replace("{menu}", menuName).replace("{player}", target.getName()));
} }
}
return;
} menu.open(target);
return;
sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\"."); }
}
}
if (args[0].equalsIgnoreCase("list")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "list"), "You don't have permission.");
sender.sendMessage(ChestCommands.CHAT_PREFIX + " Loaded menus:");
for (String file : ChestCommands.getFileNameToMenuMap().keySet()) {
sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file);
}
return;
}
sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\".");
}
}

View File

@ -1,100 +1,114 @@
package com.gmail.filoghost.chestcommands.config; /*
* This program is free software: you can redistribute it and/or modify
import java.io.File; * it under the terms of the GNU General Public License as published by
import java.io.IOException; * the Free Software Foundation, either version 3 of the License, or
import java.util.List; * (at your option) any later version.
import java.util.Map; *
import java.util.Map.Entry; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import org.apache.commons.lang.StringEscapeUtils; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.ChestCommands; *
import com.gmail.filoghost.chestcommands.util.ErrorLogger; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.util.Utils; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** package com.gmail.filoghost.chestcommands.config;
* This is not a real YAML file ;)
*/ import java.io.File;
public class AsciiPlaceholders { import java.io.IOException;
import java.util.List;
private static Map<String, String> placeholders = Utils.newHashMap(); import java.util.Map;
import java.util.Map.Entry;
public static void load(ErrorLogger errorLogger) throws IOException, Exception { import org.apache.commons.lang.StringEscapeUtils;
placeholders.clear(); import com.gmail.filoghost.chestcommands.ChestCommands;
File file = new File(ChestCommands.getInstance().getDataFolder(), "placeholders.yml"); import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils;
if (!file.exists()) {
Utils.saveResourceSafe(ChestCommands.getInstance(), "placeholders.yml"); /**
} * This is not a real YAML file ;)
*/
List<String> lines = Utils.readLines(file); public class AsciiPlaceholders {
for (String line : lines) {
private static Map<String, String> placeholders = Utils.newHashMap();
// Comment or empty line.
if (line.isEmpty() || line.startsWith("#")) {
continue; public static void load(ErrorLogger errorLogger) throws IOException, Exception {
}
placeholders.clear();
if (!line.contains(":")) { File file = new File(ChestCommands.getInstance().getDataFolder(), "placeholders.yml");
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: it must contain ':' to separate the placeholder and the replacement.");
continue; if (!file.exists()) {
} Utils.saveResourceSafe(ChestCommands.getInstance(), "placeholders.yml");
}
int indexOf = line.indexOf(':');
String placeholder = unquote(line.substring(0, indexOf).trim()); List<String> lines = Utils.readLines(file);
String replacement = Utils.addColors(StringEscapeUtils.unescapeJava(unquote(line.substring(indexOf + 1, line.length()).trim()))); for (String line : lines) {
if (placeholder.length() == 0 || replacement.length() == 0) { // Comment or empty line.
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder and the replacement must have both at least 1 character."); if (line.isEmpty() || line.startsWith("#")) {
continue; continue;
} }
if (placeholder.length() > 100) { if (!line.contains(":")) {
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder cannot be longer than 100 characters."); errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: it must contain ':' to separate the placeholder and the replacement.");
continue; continue;
} }
placeholders.put(placeholder, replacement); int indexOf = line.indexOf(':');
} String placeholder = unquote(line.substring(0, indexOf).trim());
} String replacement = Utils.addColors(StringEscapeUtils.unescapeJava(unquote(line.substring(indexOf + 1, line.length()).trim())));
public static List<String> placeholdersToSymbols(List<String> input) { if (placeholder.length() == 0 || replacement.length() == 0) {
if (input == null) return null; errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder and the replacement must have both at least 1 character.");
for (int i = 0; i < input.size(); i++) { continue;
input.set(i, placeholdersToSymbols(input.get(i))); }
}
return input; if (placeholder.length() > 100) {
} errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder cannot be longer than 100 characters.");
continue;
public static String placeholdersToSymbols(String input) { }
if (input == null) return null;
for (Entry<String, String> entry : placeholders.entrySet()) { placeholders.put(placeholder, replacement);
input = input.replace(entry.getKey(), entry.getValue()); }
} }
return input;
} public static List<String> placeholdersToSymbols(List<String> input) {
if (input == null) return null;
public static String symbolsToPlaceholders(String input) { for (int i = 0; i < input.size(); i++) {
if (input == null) return null; input.set(i, placeholdersToSymbols(input.get(i)));
for (Entry<String, String> entry : placeholders.entrySet()) { }
input = input.replace(entry.getValue(), entry.getKey()); return input;
} }
return input;
} public static String placeholdersToSymbols(String input) {
if (input == null) return null;
private static String unquote(String input) { for (Entry<String, String> entry : placeholders.entrySet()) {
if (input.length() < 2) { input = input.replace(entry.getKey(), entry.getValue());
// Cannot be quoted. }
return input; return input;
} }
if (input.startsWith("'") && input.endsWith("'")) {
return input.substring(1, input.length() - 1); public static String symbolsToPlaceholders(String input) {
} else if (input.startsWith("\"") && input.endsWith("\"")) { if (input == null) return null;
return input.substring(1, input.length() - 1); for (Entry<String, String> entry : placeholders.entrySet()) {
} input = input.replace(entry.getValue(), entry.getKey());
}
return input; return input;
} }
}
private static String unquote(String input) {
if (input.length() < 2) {
// Cannot be quoted.
return input;
}
if (input.startsWith("'") && input.endsWith("'")) {
return input.substring(1, input.length() - 1);
} else if (input.startsWith("\"") && input.endsWith("\"")) {
return input.substring(1, input.length() - 1);
}
return input;
}
}

View File

@ -1,21 +1,35 @@
package com.gmail.filoghost.chestcommands.config; /*
* This program is free software: you can redistribute it and/or modify
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig; * it under the terms of the GNU General Public License as published by
import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
public class Lang extends SpecialConfig { *
* This program is distributed in the hope that it will be useful,
public String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu."; * but WITHOUT ANY WARRANTY; without even the implied warranty of
public String default_no_icon_permission = "&cYou don't have permission for this icon."; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public String no_required_item = "&cYou must have &e{amount}x {material} &c(ID: {id}, data value: {datavalue}) for this."; * GNU General Public License for more details.
public String no_money = "&cYou need {money}$ for this."; *
public String no_exp = "&cYou need {levels} XP levels for this."; * You should have received a copy of the GNU General Public License
public String menu_not_found = "&cMenu not found! Please inform the staff."; * along with this program. If not, see <https://www.gnu.org/licenses/>.
public String open_menu = "&aOpening the menu \"{menu}\"."; */
public String open_menu_others = "&aOpening the menu \"{menu}\" to {player}."; package com.gmail.filoghost.chestcommands.config;
public String any = "any"; // Used in no_required_item when data value is not restrictive.
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
public Lang(PluginConfig config) { import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig;
super(config);
} public class Lang extends SpecialConfig {
}
public String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu.";
public String default_no_icon_permission = "&cYou don't have permission for this icon.";
public String no_required_item = "&cYou must have &e{amount}x {material} &c(ID: {id}, data value: {datavalue}) for this.";
public String no_money = "&cYou need {money}$ for this.";
public String no_exp = "&cYou need {levels} XP levels for this.";
public String menu_not_found = "&cMenu not found! Please inform the staff.";
public String open_menu = "&aOpening the menu \"{menu}\".";
public String open_menu_others = "&aOpening the menu \"{menu}\" to {player}.";
public String any = "any"; // Used in no_required_item when data value is not restrictive.
public Lang(PluginConfig config) {
super(config);
}
}

View File

@ -1,21 +1,35 @@
package com.gmail.filoghost.chestcommands.config; /*
* This program is free software: you can redistribute it and/or modify
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig; * it under the terms of the GNU General Public License as published by
import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
public class Settings extends SpecialConfig { *
* This program is distributed in the hope that it will be useful,
public boolean use_console_colors = true; * but WITHOUT ANY WARRANTY; without even the implied warranty of
public String default_color__name = "&f"; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public String default_color__lore = "&7"; * GNU General Public License for more details.
public String multiple_commands_separator = ";"; *
public boolean update_notifications = true; * You should have received a copy of the GNU General Public License
public int anti_click_spam_delay = 200; * along with this program. If not, see <https://www.gnu.org/licenses/>.
public boolean use_only_commands_without_args = true; */
package com.gmail.filoghost.chestcommands.config;
public Settings(PluginConfig config) {
super(config); import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
setHeader("ChestCommands configuration file.\nTutorial: http://dev.bukkit.org/bukkit-plugins/chest-commands\n"); import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig;
}
public class Settings extends SpecialConfig {
}
public boolean use_console_colors = true;
public String default_color__name = "&f";
public String default_color__lore = "&7";
public String multiple_commands_separator = ";";
public boolean update_notifications = true;
public int anti_click_spam_delay = 200;
public boolean use_only_commands_without_args = true;
public Settings(PluginConfig config) {
super(config);
setHeader("ChestCommands configuration file.\nTutorial: http://dev.bukkit.org/bukkit-plugins/chest-commands\n");
}
}

View File

@ -1,59 +1,73 @@
package com.gmail.filoghost.chestcommands.config.yaml; /*
* This program is free software: you can redistribute it and/or modify
import java.io.File; * it under the terms of the GNU General Public License as published by
import java.io.IOException; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.configuration.InvalidConfigurationException; *
import org.bukkit.configuration.file.YamlConfiguration; * This program is distributed in the hope that it will be useful,
import org.bukkit.plugin.Plugin; * 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.
* A simple utility class to manage configurations with a file associated to them. *
*/ * You should have received a copy of the GNU General Public License
public class PluginConfig extends YamlConfiguration { * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
private File file; package com.gmail.filoghost.chestcommands.config.yaml;
private Plugin plugin;
import java.io.File;
public PluginConfig(Plugin plugin, File file) { import java.io.IOException;
super();
this.file = file; import org.bukkit.configuration.InvalidConfigurationException;
this.plugin = plugin; import org.bukkit.configuration.file.YamlConfiguration;
} import org.bukkit.plugin.Plugin;
public PluginConfig(Plugin plugin, String name) { /**
this(plugin, new File(plugin.getDataFolder(), name)); * A simple utility class to manage configurations with a file associated to them.
} */
public class PluginConfig extends YamlConfiguration {
public void load() throws IOException, InvalidConfigurationException {
private File file;
if (!file.isFile()) { private Plugin plugin;
if (plugin.getResource(file.getName()) != null) {
plugin.saveResource(file.getName(), false); public PluginConfig(Plugin plugin, File file) {
} else { super();
if (file.getParentFile() != null) { this.file = file;
file.getParentFile().mkdirs(); this.plugin = plugin;
} }
file.createNewFile();
} public PluginConfig(Plugin plugin, String name) {
} this(plugin, new File(plugin.getDataFolder(), name));
}
// To reset all the values when loading.
for (String section : this.getKeys(false)) { public void load() throws IOException, InvalidConfigurationException {
set(section, null);
} if (!file.isFile()) {
load(file); if (plugin.getResource(file.getName()) != null) {
} plugin.saveResource(file.getName(), false);
} else {
public void save() throws IOException { if (file.getParentFile() != null) {
this.save(file); file.getParentFile().mkdirs();
} }
file.createNewFile();
public Plugin getPlugin() { }
return plugin; }
}
// To reset all the values when loading.
public String getFileName() { for (String section : this.getKeys(false)) {
return file.getName(); set(section, null);
} }
} load(file);
}
public void save() throws IOException {
this.save(file);
}
public Plugin getPlugin() {
return plugin;
}
public String getFileName() {
return file.getName();
}
}

View File

@ -1,121 +1,135 @@
package com.gmail.filoghost.chestcommands.config.yaml; /*
* This program is free software: you can redistribute it and/or modify
import java.io.IOException; * it under the terms of the GNU General Public License as published by
import java.lang.reflect.Field; * the Free Software Foundation, either version 3 of the License, or
import java.lang.reflect.Modifier; * (at your option) any later version.
import java.util.HashMap; *
import java.util.Map; * This program is distributed in the hope that it will be useful,
import java.util.Map.Entry; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import org.bukkit.configuration.InvalidConfigurationException; * GNU General Public License for more details.
*
import com.gmail.filoghost.chestcommands.util.Utils; * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
/** */
* A special configuration wrapper that reads the values using reflection. package com.gmail.filoghost.chestcommands.config.yaml;
* It will also save default values if not set.
*/ import java.io.IOException;
public class SpecialConfig { import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
private transient PluginConfig config; import java.util.HashMap;
private transient String header; import java.util.Map;
private transient Map<String, Object> defaultValuesMap; import java.util.Map.Entry;
public SpecialConfig(PluginConfig config) { import org.bukkit.configuration.InvalidConfigurationException;
this.config = config;
} import com.gmail.filoghost.chestcommands.util.Utils;
public void setHeader(String header) { /**
this.header = header; * A special configuration wrapper that reads the values using reflection.
} * It will also save default values if not set.
*/
public void load() throws IOException, InvalidConfigurationException, Exception { public class SpecialConfig {
// Check if the configuration was initialized. private transient PluginConfig config;
if (defaultValuesMap == null) { private transient String header;
defaultValuesMap = new HashMap<String, Object>(); private transient Map<String, Object> defaultValuesMap;
// Put the values in the default values map. public SpecialConfig(PluginConfig config) {
for (Field field : getClass().getDeclaredFields()) { this.config = config;
if (!isValidField(field)) continue; }
field.setAccessible(true); public void setHeader(String header) {
String configKey = formatFieldName(field); this.header = header;
}
try {
Object defaultValue = field.get(this); public void load() throws IOException, InvalidConfigurationException, Exception {
if (defaultValue != null) {
defaultValuesMap.put(configKey, defaultValue); // Check if the configuration was initialized.
} else { if (defaultValuesMap == null) {
config.getPlugin().getLogger().warning("The field " + field.getName() + " was not provided with a default value, please inform the developer."); defaultValuesMap = new HashMap<String, Object>();
}
// Put the values in the default values map.
} catch (Exception ex) { for (Field field : getClass().getDeclaredFields()) {
ex.printStackTrace(); if (!isValidField(field)) continue;
}
} field.setAccessible(true);
} String configKey = formatFieldName(field);
// First of all, try to load the yaml file. try {
config.load(); Object defaultValue = field.get(this);
if (defaultValue != null) {
// Save default values not set. defaultValuesMap.put(configKey, defaultValue);
boolean needsSave = false; } else {
for (Entry<String, Object> entry : defaultValuesMap.entrySet()) { config.getPlugin().getLogger().warning("The field " + field.getName() + " was not provided with a default value, please inform the developer.");
if (!config.isSet(entry.getKey())) { }
needsSave = true;
config.set(entry.getKey(), entry.getValue()); } catch (Exception ex) {
} ex.printStackTrace();
} }
}
if (needsSave) { }
config.options().header(header);
config.save(); // First of all, try to load the yaml file.
} config.load();
// Now read change the fields. // Save default values not set.
for (Field field : getClass().getDeclaredFields()) { boolean needsSave = false;
for (Entry<String, Object> entry : defaultValuesMap.entrySet()) {
if (!isValidField(field)) continue; if (!config.isSet(entry.getKey())) {
needsSave = true;
field.setAccessible(true); config.set(entry.getKey(), entry.getValue());
String configKey = formatFieldName(field); }
}
if (config.isSet(configKey)) { if (needsSave) {
config.options().header(header);
Class<?> type = field.getType(); config.save();
}
if (type == boolean.class || type == Boolean.class) {
field.set(this, config.getBoolean(configKey)); // Now read change the fields.
for (Field field : getClass().getDeclaredFields()) {
} else if (type == int.class || type == Integer.class) {
field.set(this, config.getInt(configKey)); if (!isValidField(field)) continue;
} else if (type == double.class || type == Double.class) { field.setAccessible(true);
field.set(this, config.getDouble(configKey)); String configKey = formatFieldName(field);
} else if (type == String.class) {
field.set(this, Utils.addColors(config.getString(configKey))); // Always add colors. if (config.isSet(configKey)) {
} else { Class<?> type = field.getType();
config.getPlugin().getLogger().warning("Unknown field type: " + field.getType().getName() + " (" + field.getName() + "). Please inform the developer.");
} if (type == boolean.class || type == Boolean.class) {
field.set(this, config.getBoolean(configKey));
} else {
field.set(this, defaultValuesMap.get(configKey)); } else if (type == int.class || type == Integer.class) {
} field.set(this, config.getInt(configKey));
}
} } else if (type == double.class || type == Double.class) {
field.set(this, config.getDouble(configKey));
private boolean isValidField(Field field) { } else if (type == String.class) {
int modifiers = field.getModifiers(); field.set(this, Utils.addColors(config.getString(configKey))); // Always add colors.
return !Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers);
} } else {
config.getPlugin().getLogger().warning("Unknown field type: " + field.getType().getName() + " (" + field.getName() + "). Please inform the developer.");
private String formatFieldName(Field field) { }
return field.getName().replace("__", ".").replace("_", "-");
} } else {
field.set(this, defaultValuesMap.get(configKey));
} }
}
}
private boolean isValidField(Field field) {
int modifiers = field.getModifiers();
return !Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers);
}
private String formatFieldName(Field field) {
return field.getName().replace("__", ".").replace("_", "-");
}
}

View File

@ -1,10 +1,24 @@
package com.gmail.filoghost.chestcommands.exception; /*
* This program is free software: you can redistribute it and/or modify
public class FormatException extends Exception { * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
private static final long serialVersionUID = 1L; * (at your option) any later version.
*
public FormatException(String message) { * This program is distributed in the hope that it will be useful,
super(message); * 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/>.
*/
package com.gmail.filoghost.chestcommands.exception;
public class FormatException extends Exception {
private static final long serialVersionUID = 1L;
public FormatException(String message) {
super(message);
}
}

View File

@ -1,53 +1,67 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Material; * it under the terms of the GNU General Public License as published by
import org.bukkit.event.block.Action; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.ItemStack; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.util.ClickType; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.Validate; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public class BoundItem { * GNU General Public License for more details.
*
private ExtendedIconMenu menu; * You should have received a copy of the GNU General Public License
private Material material; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private short data; */
private ClickType clickType; package com.gmail.filoghost.chestcommands.internal;
public BoundItem(ExtendedIconMenu menu, Material material, ClickType clickType) { import org.bukkit.Material;
Validate.notNull(material, "Material cannot be null"); import org.bukkit.event.block.Action;
Validate.notNull(material, "ClickType cannot be null"); import org.bukkit.inventory.ItemStack;
Validate.isTrue(material != Material.AIR, "Material cannot be AIR");
import com.gmail.filoghost.chestcommands.util.ClickType;
this.menu = menu; import com.gmail.filoghost.chestcommands.util.Validate;
this.material = material;
this.clickType = clickType; public class BoundItem {
data = -1; // -1 = any.
} private ExtendedIconMenu menu;
private Material material;
public void setRestrictiveData(short data) { private short data;
this.data = data; private ClickType clickType;
}
public BoundItem(ExtendedIconMenu menu, Material material, ClickType clickType) {
public ExtendedIconMenu getMenu() { Validate.notNull(material, "Material cannot be null");
return menu; Validate.notNull(material, "ClickType cannot be null");
} Validate.isTrue(material != Material.AIR, "Material cannot be AIR");
public boolean isValidTrigger(ItemStack item, Action action) { this.menu = menu;
if (item == null) { this.material = material;
return false; this.clickType = clickType;
} data = -1; // -1 = any.
}
// First, they must have the same material.
if (this.material != item.getType()) { public void setRestrictiveData(short data) {
return false; this.data = data;
} }
// Check if the data value is valid (-1 = any data value).
if (this.data != -1 && this.data != item.getDurability()) { public ExtendedIconMenu getMenu() {
return false; return menu;
} }
// Finally checks the action. public boolean isValidTrigger(ItemStack item, Action action) {
return clickType.isValidInteract(action); if (item == null) {
} return false;
} }
// First, they must have the same material.
if (this.material != item.getType()) {
return false;
}
// Check if the data value is valid (-1 = any data value).
if (this.data != -1 && this.data != item.getDurability()) {
return false;
}
// Finally checks the action.
return clickType.isValidInteract(action);
}
}

View File

@ -1,22 +1,36 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import com.gmail.filoghost.chestcommands.util.VersionUtils; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public class CachedGetters { * (at your option) any later version.
*
private static long lastOnlinePlayersRefresh; * This program is distributed in the hope that it will be useful,
private static int onlinePlayers; * 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.
public static int getOnlinePlayers() { *
long now = System.currentTimeMillis(); * You should have received a copy of the GNU General Public License
if (lastOnlinePlayersRefresh == 0 || now - lastOnlinePlayersRefresh > 1000) { * along with this program. If not, see <https://www.gnu.org/licenses/>.
// getOnlinePlayers() could be expensive if called frequently */
lastOnlinePlayersRefresh = now; package com.gmail.filoghost.chestcommands.internal;
onlinePlayers = VersionUtils.getOnlinePlayers().size();
} import com.gmail.filoghost.chestcommands.util.VersionUtils;
return onlinePlayers; public class CachedGetters {
}
private static long lastOnlinePlayersRefresh;
} private static int onlinePlayers;
public static int getOnlinePlayers() {
long now = System.currentTimeMillis();
if (lastOnlinePlayersRefresh == 0 || now - lastOnlinePlayersRefresh > 1000) {
// getOnlinePlayers() could be expensive if called frequently
lastOnlinePlayersRefresh = now;
onlinePlayers = VersionUtils.getOnlinePlayers().size();
}
return onlinePlayers;
}
}

View File

@ -1,43 +1,57 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.entity.Player; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.api.ClickHandler; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.icon.command.OpenIconCommand; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class CommandsClickHandler implements ClickHandler { *
* You should have received a copy of the GNU General Public License
private List<IconCommand> commands; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private boolean closeOnClick; */
package com.gmail.filoghost.chestcommands.internal;
public CommandsClickHandler(List<IconCommand> commands, boolean closeOnClick) {
this.commands = commands; import java.util.List;
this.closeOnClick = closeOnClick;
import org.bukkit.entity.Player;
if (commands != null && commands.size() > 0) {
for (IconCommand command : commands) { import com.gmail.filoghost.chestcommands.api.ClickHandler;
if (command instanceof OpenIconCommand) { import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
// Fix GUI closing if KEEP-OPEN is not set, and a command should open another GUI. import com.gmail.filoghost.chestcommands.internal.icon.command.OpenIconCommand;
this.closeOnClick = false;
} public class CommandsClickHandler implements ClickHandler {
}
} private List<IconCommand> commands;
} private boolean closeOnClick;
@Override public CommandsClickHandler(List<IconCommand> commands, boolean closeOnClick) {
public boolean onClick(Player player) { this.commands = commands;
if (commands != null && commands.size() > 0) { this.closeOnClick = closeOnClick;
for (IconCommand command : commands) {
command.execute(player); if (commands != null && commands.size() > 0) {
} for (IconCommand command : commands) {
} if (command instanceof OpenIconCommand) {
// Fix GUI closing if KEEP-OPEN is not set, and a command should open another GUI.
return closeOnClick; this.closeOnClick = false;
} }
}
}
}
}
@Override
public boolean onClick(Player player) {
if (commands != null && commands.size() > 0) {
for (IconCommand command : commands) {
command.execute(player);
}
}
return closeOnClick;
}
}

View File

@ -1,129 +1,143 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Bukkit; * (at your option) any later version.
import org.bukkit.ChatColor; *
import org.bukkit.command.CommandSender; * This program is distributed in the hope that it will be useful,
import org.bukkit.entity.Player; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import org.bukkit.inventory.Inventory; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import org.bukkit.inventory.ItemStack; * GNU General Public License for more details.
import org.bukkit.inventory.meta.ItemMeta; *
* You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.ChestCommands; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.Permissions; */
import com.gmail.filoghost.chestcommands.api.IconMenu; package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; import java.util.List;
import com.gmail.filoghost.chestcommands.nms.AttributeRemover;
import org.bukkit.Bukkit;
public class ExtendedIconMenu extends IconMenu { import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
private String fileName; import org.bukkit.entity.Player;
private String permission; import org.bukkit.inventory.Inventory;
private List<IconCommand> openActions; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
private int refreshTicks;
import com.gmail.filoghost.chestcommands.ChestCommands;
public ExtendedIconMenu(String title, int rows, String fileName) { import com.gmail.filoghost.chestcommands.Permissions;
super(title, rows); import com.gmail.filoghost.chestcommands.api.IconMenu;
this.fileName = fileName; import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon;
this.permission = Permissions.OPEN_MENU_BASE + fileName; import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
} import com.gmail.filoghost.chestcommands.nms.AttributeRemover;
public List<IconCommand> getOpenActions() { public class ExtendedIconMenu extends IconMenu {
return openActions;
} private String fileName;
private String permission;
public void setOpenActions(List<IconCommand> openAction) { private List<IconCommand> openActions;
this.openActions = openAction;
} private int refreshTicks;
public String getPermission() { public ExtendedIconMenu(String title, int rows, String fileName) {
return permission; super(title, rows);
} this.fileName = fileName;
this.permission = Permissions.OPEN_MENU_BASE + fileName;
public String getFileName() { }
return fileName;
} public List<IconCommand> getOpenActions() {
return openActions;
public int getRefreshTicks() { }
return refreshTicks;
} public void setOpenActions(List<IconCommand> openAction) {
this.openActions = openAction;
public void setRefreshTicks(int refreshTicks) { }
this.refreshTicks = refreshTicks;
} public String getPermission() {
return permission;
@Override }
public void open(Player player) {
try { public String getFileName() {
if (openActions != null) { return fileName;
for (IconCommand openAction : openActions) { }
openAction.execute(player);
} public int getRefreshTicks() {
} return refreshTicks;
}
Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
public void setRefreshTicks(int refreshTicks) {
for (int i = 0; i < icons.length; i++) { this.refreshTicks = refreshTicks;
if (icons[i] != null) { }
if (icons[i] instanceof ExtendedIcon && !((ExtendedIcon) icons[i]).canViewIcon(player)) { @Override
continue; public void open(Player player) {
} try {
if (openActions != null) {
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player))); for (IconCommand openAction : openActions) {
} openAction.execute(player);
} }
}
player.openInventory(inventory);
} catch (Exception e) { Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
e.printStackTrace();
player.sendMessage(ChatColor.RED + "An internal error occurred while opening the menu. The staff should check the console for errors."); for (int i = 0; i < icons.length; i++) {
} if (icons[i] != null) {
}
if (icons[i] instanceof ExtendedIcon && !((ExtendedIcon) icons[i]).canViewIcon(player)) {
public void refresh(Player player, Inventory inventory) { continue;
try { }
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null && icons[i] instanceof ExtendedIcon) { inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player)));
ExtendedIcon extIcon = (ExtendedIcon) icons[i]; }
}
if (extIcon.hasViewPermission() || extIcon.hasVariables()) {
// Then we have to refresh it player.openInventory(inventory);
if (extIcon.canViewIcon(player)) { } catch (Exception e) {
e.printStackTrace();
if (inventory.getItem(i) == null) { player.sendMessage(ChatColor.RED + "An internal error occurred while opening the menu. The staff should check the console for errors.");
ItemStack newItem = AttributeRemover.hideAttributes(extIcon.createItemstack(player)); }
inventory.setItem(i, newItem); }
} else {
// Performance, only update name and lore. public void refresh(Player player, Inventory inventory) {
ItemStack oldItem = AttributeRemover.hideAttributes(inventory.getItem(i)); try {
ItemMeta meta = oldItem.getItemMeta(); for (int i = 0; i < icons.length; i++) {
meta.setDisplayName(extIcon.calculateName(player)); if (icons[i] != null && icons[i] instanceof ExtendedIcon) {
meta.setLore(extIcon.calculateLore(player)); ExtendedIcon extIcon = (ExtendedIcon) icons[i];
oldItem.setItemMeta(meta);
} if (extIcon.hasViewPermission() || extIcon.hasVariables()) {
// Then we have to refresh it
} else { if (extIcon.canViewIcon(player)) {
inventory.setItem(i, null);
} if (inventory.getItem(i) == null) {
} ItemStack newItem = AttributeRemover.hideAttributes(extIcon.createItemstack(player));
} inventory.setItem(i, newItem);
} } else {
} catch (Exception e) { // Performance, only update name and lore.
e.printStackTrace(); ItemStack oldItem = AttributeRemover.hideAttributes(inventory.getItem(i));
player.sendMessage(ChatColor.RED + "An internal error occurred while refreshing the menu. The staff should check the console for errors."); ItemMeta meta = oldItem.getItemMeta();
} meta.setDisplayName(extIcon.calculateName(player));
} meta.setLore(extIcon.calculateLore(player));
oldItem.setItemMeta(meta);
}
public void sendNoPermissionMessage(CommandSender sender) {
String noPermMessage = ChestCommands.getLang().no_open_permission; } else {
if (noPermMessage != null && !noPermMessage.isEmpty()) { inventory.setItem(i, null);
sender.sendMessage(noPermMessage.replace("{permission}", this.permission)); }
} }
} }
}
} } catch (Exception e) {
e.printStackTrace();
player.sendMessage(ChatColor.RED + "An internal error occurred while refreshing the menu. The staff should check the console for errors.");
}
}
public void sendNoPermissionMessage(CommandSender sender) {
String noPermMessage = ChestCommands.getLang().no_open_permission;
if (noPermMessage != null && !noPermMessage.isEmpty()) {
sender.sendMessage(noPermMessage.replace("{permission}", this.permission));
}
}
}

View File

@ -1,97 +1,111 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Material; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.ClickType; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public class MenuData { * GNU General Public License for more details.
*
// Required data. * You should have received a copy of the GNU General Public License
private String title; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private int rows; */
package com.gmail.filoghost.chestcommands.internal;
// Optional data.
private String[] commands; import java.util.List;
private Material boundMaterial;
private short boundDataValue; import org.bukkit.Material;
private ClickType clickType;
private List<IconCommand> openActions; import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
private int refreshTenths; import com.gmail.filoghost.chestcommands.util.ClickType;
public MenuData(String title, int rows) { public class MenuData {
this.title = title;
this.rows = rows; // Required data.
boundDataValue = -1; // -1 = any. private String title;
} private int rows;
public String getTitle() { // Optional data.
return title; private String[] commands;
} private Material boundMaterial;
private short boundDataValue;
public int getRows() { private ClickType clickType;
return rows; private List<IconCommand> openActions;
} private int refreshTenths;
public boolean hasCommands() { public MenuData(String title, int rows) {
return commands != null && commands.length > 0; this.title = title;
} this.rows = rows;
boundDataValue = -1; // -1 = any.
public void setCommands(String[] commands) { }
this.commands = commands;
} public String getTitle() {
return title;
public String[] getCommands() { }
return commands;
} public int getRows() {
return rows;
public boolean hasBoundMaterial() { }
return boundMaterial != null;
} public boolean hasCommands() {
return commands != null && commands.length > 0;
public Material getBoundMaterial() { }
return boundMaterial;
} public void setCommands(String[] commands) {
this.commands = commands;
public void setBoundMaterial(Material boundMaterial) { }
this.boundMaterial = boundMaterial;
} public String[] getCommands() {
return commands;
public boolean hasBoundDataValue() { }
return boundDataValue > -1;
} public boolean hasBoundMaterial() {
return boundMaterial != null;
public short getBoundDataValue() { }
return boundDataValue;
} public Material getBoundMaterial() {
return boundMaterial;
public void setBoundDataValue(short boundDataValue) { }
this.boundDataValue = boundDataValue;
} public void setBoundMaterial(Material boundMaterial) {
this.boundMaterial = boundMaterial;
public ClickType getClickType() { }
return clickType;
} public boolean hasBoundDataValue() {
return boundDataValue > -1;
public void setClickType(ClickType clickType) { }
this.clickType = clickType;
} public short getBoundDataValue() {
return boundDataValue;
public List<IconCommand> getOpenActions() { }
return openActions;
} public void setBoundDataValue(short boundDataValue) {
this.boundDataValue = boundDataValue;
public void setOpenActions(List<IconCommand> openAction) { }
this.openActions = openAction;
} public ClickType getClickType() {
return clickType;
public int getRefreshTenths() { }
return refreshTenths;
} public void setClickType(ClickType clickType) {
this.clickType = clickType;
public void setRefreshTenths(int refreshTenths) { }
this.refreshTenths = refreshTenths;
} public List<IconCommand> getOpenActions() {
} return openActions;
}
public void setOpenActions(List<IconCommand> openAction) {
this.openActions = openAction;
}
public int getRefreshTenths() {
return refreshTenths;
}
public void setRefreshTenths(int refreshTenths) {
this.refreshTenths = refreshTenths;
}
}

View File

@ -1,39 +1,53 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.inventory.Inventory; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.InventoryHolder; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.api.IconMenu; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.Validate; * 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.
* This class links an IconMenu with an Inventory, via InventoryHolder. *
*/ * You should have received a copy of the GNU General Public License
public class MenuInventoryHolder implements InventoryHolder { * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
private IconMenu iconMenu; package com.gmail.filoghost.chestcommands.internal;
public MenuInventoryHolder(IconMenu iconMenu) { import org.bukkit.Bukkit;
this.iconMenu = iconMenu; import org.bukkit.inventory.Inventory;
} import org.bukkit.inventory.InventoryHolder;
@Override import com.gmail.filoghost.chestcommands.api.IconMenu;
public Inventory getInventory() { import com.gmail.filoghost.chestcommands.util.Validate;
// This inventory will not do anything.
// I'm 90% sure that it doesn't break any other plugin, /**
// because the only way you can get here is using InventoryClickEvent, * This class links an IconMenu with an Inventory, via InventoryHolder.
// that is cancelled by ChestCommands, or using InventoryOpenEvent. */
return Bukkit.createInventory(null, iconMenu.getSize()); public class MenuInventoryHolder implements InventoryHolder {
}
private IconMenu iconMenu;
public IconMenu getIconMenu() {
return iconMenu; public MenuInventoryHolder(IconMenu iconMenu) {
} this.iconMenu = iconMenu;
}
public void setIconMenu(IconMenu iconMenu) {
Validate.notNull(iconMenu, "IconMenu cannot be null"); @Override
this.iconMenu = iconMenu; public Inventory getInventory() {
} // This inventory will not do anything.
// I'm 90% sure that it doesn't break any other plugin,
} // because the only way you can get here is using InventoryClickEvent,
// that is cancelled by ChestCommands, or using InventoryOpenEvent.
return Bukkit.createInventory(null, iconMenu.getSize());
}
public IconMenu getIconMenu() {
return iconMenu;
}
public void setIconMenu(IconMenu iconMenu) {
Validate.notNull(iconMenu, "IconMenu cannot be null");
this.iconMenu = iconMenu;
}
}

View File

@ -1,99 +1,113 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Material; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.ItemStack; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.util.Validate; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public class RequiredItem { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
private Material material; *
private int amount; * You should have received a copy of the GNU General Public License
private short dataValue; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private boolean isDurabilityRestrictive = false; */
package com.gmail.filoghost.chestcommands.internal;
public RequiredItem(Material material, int amount) {
Validate.notNull(material, "Material cannot be null"); import org.bukkit.Material;
Validate.isTrue(material != Material.AIR, "Material cannot be air"); import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
this.material = material;
this.amount = amount; import com.gmail.filoghost.chestcommands.util.Validate;
}
public class RequiredItem {
public ItemStack createItemStack() {
return new ItemStack(material, amount, dataValue); private Material material;
} private int amount;
private short dataValue;
public Material getMaterial() { private boolean isDurabilityRestrictive = false;
return material;
} public RequiredItem(Material material, int amount) {
Validate.notNull(material, "Material cannot be null");
public int getAmount() { Validate.isTrue(material != Material.AIR, "Material cannot be air");
return amount;
} this.material = material;
this.amount = amount;
public short getDataValue() { }
return dataValue;
} public ItemStack createItemStack() {
return new ItemStack(material, amount, dataValue);
public void setRestrictiveDataValue(short data) { }
Validate.isTrue(data >= 0, "Data value cannot be negative");
public Material getMaterial() {
this.dataValue = data; return material;
isDurabilityRestrictive = true; }
}
public int getAmount() {
public boolean hasRestrictiveDataValue() { return amount;
return isDurabilityRestrictive; }
}
public short getDataValue() {
public boolean isValidDataValue(short data) { return dataValue;
if (!isDurabilityRestrictive) return true; }
return data == this.dataValue;
} public void setRestrictiveDataValue(short data) {
Validate.isTrue(data >= 0, "Data value cannot be negative");
public boolean hasItem(Player player) {
int amountFound = 0; this.dataValue = data;
isDurabilityRestrictive = true;
for (ItemStack item : player.getInventory().getContents()) { }
if (item != null && item.getType() == material && isValidDataValue(item.getDurability())) {
amountFound += item.getAmount(); public boolean hasRestrictiveDataValue() {
} return isDurabilityRestrictive;
} }
return amountFound >= amount; public boolean isValidDataValue(short data) {
} if (!isDurabilityRestrictive) return true;
return data == this.dataValue;
public boolean takeItem(Player player) { }
if (amount <= 0) {
return true; public boolean hasItem(Player player) {
} int amountFound = 0;
int itemsToTake = amount; //start from amount and decrease for (ItemStack item : player.getInventory().getContents()) {
if (item != null && item.getType() == material && isValidDataValue(item.getDurability())) {
ItemStack[] contents = player.getInventory().getContents(); amountFound += item.getAmount();
ItemStack current = null; }
}
for (int i = 0; i < contents.length; i++) { return amountFound >= amount;
}
current = contents[i];
public boolean takeItem(Player player) {
if (current != null && current.getType() == material && isValidDataValue(current.getDurability())) { if (amount <= 0) {
if (current.getAmount() > itemsToTake) { return true;
current.setAmount(current.getAmount() - itemsToTake); }
return true;
} else { int itemsToTake = amount; //start from amount and decrease
itemsToTake -= current.getAmount();
player.getInventory().setItem(i, new ItemStack(Material.AIR)); ItemStack[] contents = player.getInventory().getContents();
} ItemStack current = null;
}
// The end for (int i = 0; i < contents.length; i++) {
if (itemsToTake <= 0) return true;
} current = contents[i];
return false; if (current != null && current.getType() == material && isValidDataValue(current.getDurability())) {
} if (current.getAmount() > itemsToTake) {
} current.setAmount(current.getAmount() - itemsToTake);
return true;
} else {
itemsToTake -= current.getAmount();
player.getInventory().setItem(i, new ItemStack(Material.AIR));
}
}
// The end
if (itemsToTake <= 0) return true;
}
return false;
}
}

View File

@ -1,55 +1,69 @@
package com.gmail.filoghost.chestcommands.internal; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge; *
* This program is distributed in the hope that it will be useful,
public enum Variable { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
PLAYER("{player}") { * GNU General Public License for more details.
public String getReplacement(Player executor) { *
return executor.getName(); * You should have received a copy of the GNU General Public License
} * along with this program. If not, see <https://www.gnu.org/licenses/>.
}, */
package com.gmail.filoghost.chestcommands.internal;
ONLINE("{online}") {
public String getReplacement(Player executor) { import org.bukkit.Bukkit;
return String.valueOf(CachedGetters.getOnlinePlayers()); import org.bukkit.entity.Player;
}
}, import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
MAX_PLAYERS("{max_players}") { public enum Variable {
public String getReplacement(Player executor) {
return String.valueOf(Bukkit.getMaxPlayers()); PLAYER("{player}") {
} public String getReplacement(Player executor) {
}, return executor.getName();
}
MONEY("{money}") { },
public String getReplacement(Player executor) {
if (EconomyBridge.hasValidEconomy()) { ONLINE("{online}") {
return EconomyBridge.formatMoney(EconomyBridge.getMoney(executor)); public String getReplacement(Player executor) {
} else { return String.valueOf(CachedGetters.getOnlinePlayers());
return "[ECONOMY PLUGIN NOT FOUND]"; }
} },
}
}, MAX_PLAYERS("{max_players}") {
public String getReplacement(Player executor) {
WORLD("{world}") { return String.valueOf(Bukkit.getMaxPlayers());
public String getReplacement(Player executor) { }
return executor.getWorld().getName(); },
}
}; MONEY("{money}") {
public String getReplacement(Player executor) {
private String text; if (EconomyBridge.hasValidEconomy()) {
return EconomyBridge.formatMoney(EconomyBridge.getMoney(executor));
private Variable(String text) { } else {
this.text = text; return "[ECONOMY PLUGIN NOT FOUND]";
} }
}
public String getText() { },
return text;
} WORLD("{world}") {
public String getReplacement(Player executor) {
public abstract String getReplacement(Player executor); return executor.getWorld().getName();
} }
};
private String text;
private Variable(String text) {
this.text = text;
}
public String getText() {
return text;
}
public abstract String getReplacement(Player executor);
}

View File

@ -1,217 +1,231 @@
package com.gmail.filoghost.chestcommands.internal.icon; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.ChatColor; * (at your option) any later version.
import org.bukkit.entity.Player; *
import org.bukkit.inventory.Inventory; * This program is distributed in the hope that it will be useful,
import org.bukkit.inventory.InventoryView; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.ChestCommands; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.api.Icon; *
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder; */
import com.gmail.filoghost.chestcommands.internal.RequiredItem; package com.gmail.filoghost.chestcommands.internal.icon;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import com.gmail.filoghost.chestcommands.util.Utils; import java.util.List;
public class ExtendedIcon extends Icon { import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
private String permission; import org.bukkit.inventory.Inventory;
private String permissionMessage; import org.bukkit.inventory.InventoryView;
private String viewPermission;
import com.gmail.filoghost.chestcommands.ChestCommands;
private boolean permissionNegated; import com.gmail.filoghost.chestcommands.api.Icon;
private boolean viewPermissionNegated; import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
private double moneyPrice; import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
private int expLevelsPrice; import com.gmail.filoghost.chestcommands.internal.RequiredItem;
private RequiredItem requiredItem; import com.gmail.filoghost.chestcommands.util.StringUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
public ExtendedIcon() {
super(); public class ExtendedIcon extends Icon {
}
private String permission;
public boolean canClickIcon(Player player) { private String permissionMessage;
if (permission == null) { private String viewPermission;
return true;
} private boolean permissionNegated;
private boolean viewPermissionNegated;
if (permissionNegated) {
return !player.hasPermission(permission); private double moneyPrice;
} else { private int expLevelsPrice;
return player.hasPermission(permission); private RequiredItem requiredItem;
}
} public ExtendedIcon() {
super();
public void setPermission(String permission) { }
if (StringUtils.isNullOrEmpty(permission)) {
permission = null; public boolean canClickIcon(Player player) {
} if (permission == null) {
return true;
if (permission != null) { }
if (permission.startsWith("-")) {
permissionNegated = true; if (permissionNegated) {
permission = permission.substring(1, permission.length()).trim(); return !player.hasPermission(permission);
} } else {
} return player.hasPermission(permission);
this.permission = permission; }
} }
public String getPermissionMessage() { public void setPermission(String permission) {
return permissionMessage; if (StringUtils.isNullOrEmpty(permission)) {
} permission = null;
}
public void setPermissionMessage(String permissionMessage) {
this.permissionMessage = permissionMessage; if (permission != null) {
} if (permission.startsWith("-")) {
permissionNegated = true;
public boolean hasViewPermission() { permission = permission.substring(1, permission.length()).trim();
return viewPermission != null; }
} }
this.permission = permission;
public boolean canViewIcon(Player player) { }
if (viewPermission == null) {
return true; public String getPermissionMessage() {
} return permissionMessage;
}
if (viewPermissionNegated) {
return !player.hasPermission(viewPermission); public void setPermissionMessage(String permissionMessage) {
} else { this.permissionMessage = permissionMessage;
return player.hasPermission(viewPermission); }
}
} public boolean hasViewPermission() {
return viewPermission != null;
public void setViewPermission(String viewPermission) { }
if (StringUtils.isNullOrEmpty(viewPermission)) {
viewPermission = null; public boolean canViewIcon(Player player) {
} if (viewPermission == null) {
return true;
if (viewPermission != null) { }
if (viewPermission.startsWith("-")) {
viewPermissionNegated = true; if (viewPermissionNegated) {
viewPermission = viewPermission.substring(1, viewPermission.length()).trim(); return !player.hasPermission(viewPermission);
} } else {
} return player.hasPermission(viewPermission);
this.viewPermission = viewPermission; }
} }
public double getMoneyPrice() { public void setViewPermission(String viewPermission) {
return moneyPrice; if (StringUtils.isNullOrEmpty(viewPermission)) {
} viewPermission = null;
}
public void setMoneyPrice(double moneyPrice) {
this.moneyPrice = moneyPrice; if (viewPermission != null) {
} if (viewPermission.startsWith("-")) {
viewPermissionNegated = true;
public int getExpLevelsPrice() { viewPermission = viewPermission.substring(1, viewPermission.length()).trim();
return expLevelsPrice; }
} }
this.viewPermission = viewPermission;
public void setExpLevelsPrice(int expLevelsPrice) { }
this.expLevelsPrice = expLevelsPrice;
} public double getMoneyPrice() {
return moneyPrice;
public RequiredItem getRequiredItem() { }
return requiredItem;
} public void setMoneyPrice(double moneyPrice) {
this.moneyPrice = moneyPrice;
public void setRequiredItem(RequiredItem requiredItem) { }
this.requiredItem = requiredItem;
} public int getExpLevelsPrice() {
return expLevelsPrice;
public String calculateName(Player pov) { }
return super.calculateName(pov);
} public void setExpLevelsPrice(int expLevelsPrice) {
this.expLevelsPrice = expLevelsPrice;
public List<String> calculateLore(Player pov) { }
return super.calculateLore(pov);
} public RequiredItem getRequiredItem() {
return requiredItem;
@SuppressWarnings("deprecation") }
@Override
public boolean onClick(Player player) { public void setRequiredItem(RequiredItem requiredItem) {
this.requiredItem = requiredItem;
// Check all the requirements. }
if (!canClickIcon(player)) { public String calculateName(Player pov) {
if (permissionMessage != null) { return super.calculateName(pov);
player.sendMessage(permissionMessage); }
} else {
player.sendMessage(ChestCommands.getLang().default_no_icon_permission); public List<String> calculateLore(Player pov) {
} return super.calculateLore(pov);
return closeOnClick; }
}
@SuppressWarnings("deprecation")
if (moneyPrice > 0) { @Override
if (!EconomyBridge.hasValidEconomy()) { public boolean onClick(Player player) {
player.sendMessage(ChatColor.RED + "This command has a price, but Vault with a compatible economy plugin was not found. For security, the command has been blocked. Please inform the staff.");
return closeOnClick; // Check all the requirements.
}
if (!canClickIcon(player)) {
if (!EconomyBridge.hasMoney(player, moneyPrice)) { if (permissionMessage != null) {
player.sendMessage(ChestCommands.getLang().no_money.replace("{money}", EconomyBridge.formatMoney(moneyPrice))); player.sendMessage(permissionMessage);
return closeOnClick; } else {
} player.sendMessage(ChestCommands.getLang().default_no_icon_permission);
} }
return closeOnClick;
if (expLevelsPrice > 0) { }
if (player.getLevel() < expLevelsPrice) {
player.sendMessage(ChestCommands.getLang().no_exp.replace("{levels}", Integer.toString(expLevelsPrice))); if (moneyPrice > 0) {
return closeOnClick; if (!EconomyBridge.hasValidEconomy()) {
} player.sendMessage(ChatColor.RED + "This command has a price, but Vault with a compatible economy plugin was not found. For security, the command has been blocked. Please inform the staff.");
} return closeOnClick;
}
if (requiredItem != null) {
if (!EconomyBridge.hasMoney(player, moneyPrice)) {
if (!requiredItem.hasItem(player)) { player.sendMessage(ChestCommands.getLang().no_money.replace("{money}", EconomyBridge.formatMoney(moneyPrice)));
player.sendMessage(ChestCommands.getLang().no_required_item return closeOnClick;
.replace("{material}", Utils.formatMaterial(requiredItem.getMaterial())) }
.replace("{id}", Integer.toString(requiredItem.getMaterial().getId())) }
.replace("{amount}", Integer.toString(requiredItem.getAmount()))
.replace("{datavalue}", requiredItem.hasRestrictiveDataValue() ? Short.toString(requiredItem.getDataValue()) : ChestCommands.getLang().any) if (expLevelsPrice > 0) {
); if (player.getLevel() < expLevelsPrice) {
return closeOnClick; player.sendMessage(ChestCommands.getLang().no_exp.replace("{levels}", Integer.toString(expLevelsPrice)));
} return closeOnClick;
} }
}
// Take the money and the required item.
if (requiredItem != null) {
boolean changedVariables = false; // To update the placeholders.
if (!requiredItem.hasItem(player)) {
if (moneyPrice > 0) { player.sendMessage(ChestCommands.getLang().no_required_item
if (!EconomyBridge.takeMoney(player, moneyPrice)) { .replace("{material}", Utils.formatMaterial(requiredItem.getMaterial()))
player.sendMessage(ChatColor.RED + "Error: the transaction couldn't be executed. Please inform the staff."); .replace("{id}", Integer.toString(requiredItem.getMaterial().getId()))
return closeOnClick; .replace("{amount}", Integer.toString(requiredItem.getAmount()))
} .replace("{datavalue}", requiredItem.hasRestrictiveDataValue() ? Short.toString(requiredItem.getDataValue()) : ChestCommands.getLang().any)
changedVariables = true; );
} return closeOnClick;
}
if (expLevelsPrice > 0) { }
player.setLevel(player.getLevel() - expLevelsPrice);
} // Take the money and the required item.
if (requiredItem != null) { boolean changedVariables = false; // To update the placeholders.
requiredItem.takeItem(player);
} if (moneyPrice > 0) {
if (!EconomyBridge.takeMoney(player, moneyPrice)) {
if (changedVariables) { player.sendMessage(ChatColor.RED + "Error: the transaction couldn't be executed. Please inform the staff.");
InventoryView view = player.getOpenInventory(); return closeOnClick;
if (view != null) { }
Inventory topInventory = view.getTopInventory(); changedVariables = true;
if (topInventory.getHolder() instanceof MenuInventoryHolder) { }
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (expLevelsPrice > 0) {
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) { player.setLevel(player.getLevel() - expLevelsPrice);
((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory); }
}
} if (requiredItem != null) {
} requiredItem.takeItem(player);
} }
return super.onClick(player); if (changedVariables) {
} InventoryView view = player.getOpenInventory();
if (view != null) {
Inventory topInventory = view.getTopInventory();
} if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory);
}
}
}
}
return super.onClick(player);
}
}

View File

@ -1,41 +1,55 @@
package com.gmail.filoghost.chestcommands.internal.icon; /*
* This program is free software: you can redistribute it and/or modify
import java.util.ArrayList; * it under the terms of the GNU General Public License as published by
import java.util.List; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.entity.Player; *
* This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.Variable; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public abstract class IconCommand { *
* You should have received a copy of the GNU General Public License
protected String command; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private List<Variable> containedVariables; */
package com.gmail.filoghost.chestcommands.internal.icon;
public IconCommand(String command) {
this.command = AsciiPlaceholders.placeholdersToSymbols(command).trim(); import java.util.ArrayList;
this.containedVariables = new ArrayList<Variable>(); import java.util.List;
for (Variable variable : Variable.values()) { import org.bukkit.entity.Player;
if (command.contains(variable.getText())) {
containedVariables.add(variable); import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
} import com.gmail.filoghost.chestcommands.internal.Variable;
}
} public abstract class IconCommand {
public String getParsedCommand(Player executor) { protected String command;
if (containedVariables.isEmpty()) { private List<Variable> containedVariables;
return command;
} public IconCommand(String command) {
this.command = AsciiPlaceholders.placeholdersToSymbols(command).trim();
String commandCopy = command; this.containedVariables = new ArrayList<Variable>();
for (Variable variable : containedVariables) {
commandCopy = commandCopy.replace(variable.getText(), variable.getReplacement(executor)); for (Variable variable : Variable.values()) {
} if (command.contains(variable.getText())) {
return commandCopy; containedVariables.add(variable);
} }
}
public abstract void execute(Player player); }
} public String getParsedCommand(Player executor) {
if (containedVariables.isEmpty()) {
return command;
}
String commandCopy = command;
for (Variable variable : containedVariables) {
commandCopy = commandCopy.replace(variable.getText(), variable.getReplacement(executor));
}
return commandCopy;
}
public abstract void execute(Player player);
}

View File

@ -1,21 +1,35 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; *
import com.gmail.filoghost.chestcommands.util.Utils; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public class BroadcastIconCommand extends IconCommand { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public BroadcastIconCommand(String command) { *
super(Utils.addColors(command)); * You should have received a copy of the GNU General Public License
} * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
@Override package com.gmail.filoghost.chestcommands.internal.icon.command;
public void execute(Player player) {
Bukkit.broadcastMessage(getParsedCommand(player)); import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
}
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
} import com.gmail.filoghost.chestcommands.util.Utils;
public class BroadcastIconCommand extends IconCommand {
public BroadcastIconCommand(String command) {
super(Utils.addColors(command));
}
@Override
public void execute(Player player) {
Bukkit.broadcastMessage(getParsedCommand(player));
}
}

View File

@ -1,19 +1,33 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; *
* This program is distributed in the hope that it will be useful,
public class ConsoleIconCommand extends IconCommand { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public ConsoleIconCommand(String command) { * GNU General Public License for more details.
super(command); *
} * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
@Override */
public void execute(Player player) { package com.gmail.filoghost.chestcommands.internal.icon.command;
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), getParsedCommand(player));
} import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
}
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
public class ConsoleIconCommand extends IconCommand {
public ConsoleIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), getParsedCommand(player));
}
}

View File

@ -1,36 +1,50 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge; * (at your option) any later version.
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; *
import com.gmail.filoghost.chestcommands.util.Utils; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public class DragonBarIconCommand extends IconCommand { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
private String message; *
private int seconds; * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
public DragonBarIconCommand(String command) { */
super(command); package com.gmail.filoghost.chestcommands.internal.icon.command;
seconds = 1; import org.bukkit.entity.Player;
message = command;
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge;
String[] split = command.split("\\|", 2); // Max of 2 pieces. import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
if (split.length > 1 && Utils.isValidPositiveInteger(split[0].trim())) { import com.gmail.filoghost.chestcommands.util.Utils;
seconds = Integer.parseInt(split[0].trim());
message = split[1].trim(); public class DragonBarIconCommand extends IconCommand {
}
private String message;
message = Utils.addColors(message); private int seconds;
}
public DragonBarIconCommand(String command) {
@Override super(command);
public void execute(Player player) {
if (BarAPIBridge.hasValidPlugin()) { seconds = 1;
BarAPIBridge.setMessage(player, message, seconds); message = command;
}
} String[] split = command.split("\\|", 2); // Max of 2 pieces.
if (split.length > 1 && Utils.isValidPositiveInteger(split[0].trim())) {
} seconds = Integer.parseInt(split[0].trim());
message = split[1].trim();
}
message = Utils.addColors(message);
}
@Override
public void execute(Player player) {
if (BarAPIBridge.hasValidPlugin()) {
BarAPIBridge.setMessage(player, message, seconds);
}
}
}

View File

@ -1,38 +1,52 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.ItemStack; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.exception.FormatException; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.util.ItemStackReader; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class GiveIconCommand extends IconCommand { *
* You should have received a copy of the GNU General Public License
private ItemStack itemToGive; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private String errorMessage; */
package com.gmail.filoghost.chestcommands.internal.icon.command;
public GiveIconCommand(String command) {
super(command); import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
try { import org.bukkit.inventory.ItemStack;
ItemStackReader reader = new ItemStackReader(command, true);
itemToGive = reader.createStack(); import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
} catch (FormatException e) { import com.gmail.filoghost.chestcommands.util.ItemStackReader;
errorMessage = ChatColor.RED + "Invalid item to give: " + e.getMessage();
} public class GiveIconCommand extends IconCommand {
}
private ItemStack itemToGive;
@Override private String errorMessage;
public void execute(Player player) {
if (errorMessage != null) { public GiveIconCommand(String command) {
player.sendMessage(errorMessage); super(command);
return;
} try {
ItemStackReader reader = new ItemStackReader(command, true);
player.getInventory().addItem(itemToGive.clone()); itemToGive = reader.createStack();
}
} catch (FormatException e) {
} errorMessage = ChatColor.RED + "Invalid item to give: " + e.getMessage();
}
}
@Override
public void execute(Player player) {
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
player.getInventory().addItem(itemToGive.clone());
}
}

View File

@ -1,40 +1,54 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge; *
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.Utils; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public class GiveMoneyIconCommand extends IconCommand { * GNU General Public License for more details.
*
private double moneyToGive; * You should have received a copy of the GNU General Public License
private String errorMessage; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
public GiveMoneyIconCommand(String command) { package com.gmail.filoghost.chestcommands.internal.icon.command;
super(command);
import org.bukkit.ChatColor;
if (!Utils.isValidPositiveDouble(command)) { import org.bukkit.entity.Player;
errorMessage = ChatColor.RED + "Invalid money amount: " + command;
return; import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
} import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
moneyToGive = Double.parseDouble(command);
} public class GiveMoneyIconCommand extends IconCommand {
@Override private double moneyToGive;
public void execute(Player player) { private String errorMessage;
if (errorMessage != null) {
player.sendMessage(errorMessage); public GiveMoneyIconCommand(String command) {
return; super(command);
}
if (!Utils.isValidPositiveDouble(command)) {
if (EconomyBridge.hasValidEconomy()) { errorMessage = ChatColor.RED + "Invalid money amount: " + command;
EconomyBridge.giveMoney(player, moneyToGive); return;
} else { }
player.sendMessage(ChatColor.RED + "Vault with a compatible economy plugin not found. Please inform the staff.");
} moneyToGive = Double.parseDouble(command);
} }
} @Override
public void execute(Player player) {
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
if (EconomyBridge.hasValidEconomy()) {
EconomyBridge.giveMoney(player, moneyToGive);
} else {
player.sendMessage(ChatColor.RED + "Vault with a compatible economy plugin not found. Please inform the staff.");
}
}
}

View File

@ -1,26 +1,40 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * (at your option) any later version.
*
public class OpIconCommand extends IconCommand { * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public OpIconCommand(String command) { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
super(command); * GNU General Public License for more details.
} *
* You should have received a copy of the GNU General Public License
@Override * along with this program. If not, see <https://www.gnu.org/licenses/>.
public void execute(Player player) { */
package com.gmail.filoghost.chestcommands.internal.icon.command;
if (player.isOp()) {
player.chat("/" + getParsedCommand(player)); import org.bukkit.entity.Player;
} else { import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
player.setOp(true);
player.chat("/" + getParsedCommand(player)); public class OpIconCommand extends IconCommand {
player.setOp(false);
} public OpIconCommand(String command) {
} super(command);
}
}
@Override
public void execute(Player player) {
if (player.isOp()) {
player.chat("/" + getParsedCommand(player));
} else {
player.setOp(true);
player.chat("/" + getParsedCommand(player));
player.setOp(false);
}
}
}

View File

@ -1,39 +1,53 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Bukkit; * it under the terms of the GNU General Public License as published by
import org.bukkit.ChatColor; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.entity.Player; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.ChestCommands; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class OpenIconCommand extends IconCommand { *
* You should have received a copy of the GNU General Public License
public OpenIconCommand(String command) { * along with this program. If not, see <https://www.gnu.org/licenses/>.
super(command); */
} package com.gmail.filoghost.chestcommands.internal.icon.command;
@Override import org.bukkit.Bukkit;
public void execute(final Player player) { import org.bukkit.ChatColor;
final ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(command.toLowerCase()); import org.bukkit.entity.Player;
if (menu != null) {
import com.gmail.filoghost.chestcommands.ChestCommands;
// Delay the task, since this command is executed in ClickInventoryEvent import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
// and opening another inventory in the same moment is not a good idea. import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new Runnable() {
public void run() { public class OpenIconCommand extends IconCommand {
if (player.hasPermission(menu.getPermission())) {
menu.open(player); public OpenIconCommand(String command) {
} else { super(command);
menu.sendNoPermissionMessage(player); }
}
} @Override
}); public void execute(final Player player) {
final ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(command.toLowerCase());
} else { if (menu != null) {
player.sendMessage(ChatColor.RED + "Menu not found! Please inform the staff.");
} // Delay the task, since this command is executed in ClickInventoryEvent
} // and opening another inventory in the same moment is not a good idea.
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new Runnable() {
} public void run() {
if (player.hasPermission(menu.getPermission())) {
menu.open(player);
} else {
menu.sendNoPermissionMessage(player);
}
}
});
} else {
player.sendMessage(ChatColor.RED + "Menu not found! Please inform the staff.");
}
}
}

View File

@ -1,18 +1,32 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * (at your option) any later version.
*
public class PlayerIconCommand extends IconCommand { * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
public PlayerIconCommand(String command) { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
super(command); * GNU General Public License for more details.
} *
* You should have received a copy of the GNU General Public License
@Override * along with this program. If not, see <https://www.gnu.org/licenses/>.
public void execute(Player player) { */
player.chat('/' + getParsedCommand(player)); package com.gmail.filoghost.chestcommands.internal.icon.command;
}
import org.bukkit.entity.Player;
}
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
public class PlayerIconCommand extends IconCommand {
public PlayerIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
player.chat('/' + getParsedCommand(player));
}
}

View File

@ -1,19 +1,33 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.bridge.bungee.BungeeCordUtils; * (at your option) any later version.
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; *
* This program is distributed in the hope that it will be useful,
public class ServerIconCommand extends IconCommand { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public ServerIconCommand(String command) { * GNU General Public License for more details.
super(command); *
} * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
@Override */
public void execute(Player player) { package com.gmail.filoghost.chestcommands.internal.icon.command;
BungeeCordUtils.connect(player, command);
} import org.bukkit.entity.Player;
} import com.gmail.filoghost.chestcommands.bridge.bungee.BungeeCordUtils;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
public class ServerIconCommand extends IconCommand {
public ServerIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
BungeeCordUtils.connect(player, command);
}
}

View File

@ -1,54 +1,68 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.Sound; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.entity.Player; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.Utils; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public class SoundIconCommand extends IconCommand { * GNU General Public License for more details.
*
private Sound sound; * You should have received a copy of the GNU General Public License
private float pitch; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private float volume; */
private String errorMessage; package com.gmail.filoghost.chestcommands.internal.icon.command;
public SoundIconCommand(String command) { import org.bukkit.ChatColor;
super(command); import org.bukkit.Sound;
import org.bukkit.entity.Player;
pitch = 1.0f;
volume = 1.0f; import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
String[] split = command.split(",");
public class SoundIconCommand extends IconCommand {
sound = Utils.matchSound(split[0]);
if (sound == null) { private Sound sound;
errorMessage = ChatColor.RED + "Invalid sound \"" + split[0].trim() + "\"."; private float pitch;
return; private float volume;
} private String errorMessage;
if (split.length > 1) { public SoundIconCommand(String command) {
try { super(command);
pitch = Float.parseFloat(split[1].trim());
} catch (NumberFormatException e) { } pitch = 1.0f;
} volume = 1.0f;
if (split.length > 2) { String[] split = command.split(",");
try {
volume = Float.parseFloat(split[2].trim()); sound = Utils.matchSound(split[0]);
} catch (NumberFormatException e) { } if (sound == null) {
} errorMessage = ChatColor.RED + "Invalid sound \"" + split[0].trim() + "\".";
} return;
}
@Override
public void execute(Player player) { if (split.length > 1) {
if (errorMessage != null) { try {
player.sendMessage(errorMessage); pitch = Float.parseFloat(split[1].trim());
return; } catch (NumberFormatException e) { }
} }
player.playSound(player.getLocation(), sound, volume, pitch); if (split.length > 2) {
} try {
volume = Float.parseFloat(split[2].trim());
} } catch (NumberFormatException e) { }
}
}
@Override
public void execute(Player player) {
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
player.playSound(player.getLocation(), sound, volume, pitch);
}
}

View File

@ -1,19 +1,33 @@
package com.gmail.filoghost.chestcommands.internal.icon.command; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * (at your option) any later version.
import com.gmail.filoghost.chestcommands.util.Utils; *
* This program is distributed in the hope that it will be useful,
public class TellIconCommand extends IconCommand { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public TellIconCommand(String command) { * GNU General Public License for more details.
super(Utils.addColors(command)); *
} * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
@Override */
public void execute(Player player) { package com.gmail.filoghost.chestcommands.internal.icon.command;
player.sendMessage(getParsedCommand(player));
} import org.bukkit.entity.Player;
} import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
public class TellIconCommand extends IconCommand {
public TellIconCommand(String command) {
super(Utils.addColors(command));
}
@Override
public void execute(Player player) {
player.sendMessage(getParsedCommand(player));
}
}

View File

@ -1,41 +1,55 @@
package com.gmail.filoghost.chestcommands.listener; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.event.EventHandler; * it under the terms of the GNU General Public License as published by
import org.bukkit.event.EventPriority; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.event.Listener; * (at your option) any later version.
import org.bukkit.event.player.PlayerCommandPreprocessEvent; *
* This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.ChestCommands; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.util.StringUtils; * GNU General Public License for more details.
*
public class CommandListener implements Listener { * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
@EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) */
public void onCommand(PlayerCommandPreprocessEvent event) { package com.gmail.filoghost.chestcommands.listener;
if (ChestCommands.getSettings().use_only_commands_without_args && event.getMessage().contains(" ")) { import org.bukkit.event.EventHandler;
return; import org.bukkit.event.EventPriority;
} import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
// Very fast method compared to split & substring.
String command = StringUtils.getCleanCommand(event.getMessage()); import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
if (command.isEmpty()) { import com.gmail.filoghost.chestcommands.util.StringUtils;
return;
} public class CommandListener implements Listener {
ExtendedIconMenu menu = ChestCommands.getCommandToMenuMap().get(command); @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
if (menu != null) {
event.setCancelled(true); if (ChestCommands.getSettings().use_only_commands_without_args && event.getMessage().contains(" ")) {
return;
if (event.getPlayer().hasPermission(menu.getPermission())) { }
menu.open(event.getPlayer());
} else { // Very fast method compared to split & substring.
menu.sendNoPermissionMessage(event.getPlayer()); String command = StringUtils.getCleanCommand(event.getMessage());
}
} if (command.isEmpty()) {
} return;
}
}
ExtendedIconMenu menu = ChestCommands.getCommandToMenuMap().get(command);
if (menu != null) {
event.setCancelled(true);
if (event.getPlayer().hasPermission(menu.getPermission())) {
menu.open(event.getPlayer());
} else {
menu.sendNoPermissionMessage(event.getPlayer());
}
}
}
}

View File

@ -1,82 +1,96 @@
package com.gmail.filoghost.chestcommands.listener; /*
* This program is free software: you can redistribute it and/or modify
import java.util.Map; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Bukkit; * (at your option) any later version.
import org.bukkit.entity.Player; *
import org.bukkit.event.EventHandler; * This program is distributed in the hope that it will be useful,
import org.bukkit.event.EventPriority; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import org.bukkit.event.Listener; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import org.bukkit.event.block.Action; * GNU General Public License for more details.
import org.bukkit.event.inventory.InventoryClickEvent; *
import org.bukkit.event.player.PlayerInteractEvent; * You should have received a copy of the GNU General Public License
import org.bukkit.event.player.PlayerQuitEvent; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import com.gmail.filoghost.chestcommands.ChestCommands; package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.api.IconMenu; import java.util.Map;
import com.gmail.filoghost.chestcommands.internal.BoundItem;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder; import org.bukkit.Bukkit;
import com.gmail.filoghost.chestcommands.task.ExecuteCommandsTask; import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.util.Utils; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
public class InventoryListener implements Listener { import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
private static Map<Player, Long> antiClickSpam = Utils.newHashMap(); import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
@EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = false) import org.bukkit.event.player.PlayerQuitEvent;
public void onInteract(PlayerInteractEvent event) {
if (event.hasItem() && event.getAction() != Action.PHYSICAL) { import com.gmail.filoghost.chestcommands.ChestCommands;
for (BoundItem boundItem : ChestCommands.getBoundItems()) { import com.gmail.filoghost.chestcommands.api.Icon;
if (boundItem.isValidTrigger(event.getItem(), event.getAction())) { import com.gmail.filoghost.chestcommands.api.IconMenu;
if (event.getPlayer().hasPermission(boundItem.getMenu().getPermission())) { import com.gmail.filoghost.chestcommands.internal.BoundItem;
boundItem.getMenu().open(event.getPlayer()); import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
} else { import com.gmail.filoghost.chestcommands.task.ExecuteCommandsTask;
boundItem.getMenu().sendNoPermissionMessage(event.getPlayer()); import com.gmail.filoghost.chestcommands.util.Utils;
}
} public class InventoryListener implements Listener {
}
} private static Map<Player, Long> antiClickSpam = Utils.newHashMap();
}
@EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = false)
@EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = false) public void onInteract(PlayerInteractEvent event) {
public void onInventoryClick(InventoryClickEvent event) { if (event.hasItem() && event.getAction() != Action.PHYSICAL) {
if (event.getInventory().getHolder() instanceof MenuInventoryHolder) { for (BoundItem boundItem : ChestCommands.getBoundItems()) {
if (boundItem.isValidTrigger(event.getItem(), event.getAction())) {
event.setCancelled(true); // First thing to do, if an exception is thrown at least the player doesn't take the item. if (event.getPlayer().hasPermission(boundItem.getMenu().getPermission())) {
boundItem.getMenu().open(event.getPlayer());
IconMenu menu = ((MenuInventoryHolder) event.getInventory().getHolder()).getIconMenu(); } else {
int slot = event.getRawSlot(); boundItem.getMenu().sendNoPermissionMessage(event.getPlayer());
}
if (slot >= 0 && slot < menu.getSize()) { }
}
Icon icon = menu.getIconRaw(slot); }
}
if (icon != null && event.getInventory().getItem(slot) != null) {
Player clicker = (Player) event.getWhoClicked(); @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onInventoryClick(InventoryClickEvent event) {
Long cooldownUntil = antiClickSpam.get(clicker); if (event.getInventory().getHolder() instanceof MenuInventoryHolder) {
long now = System.currentTimeMillis();
int minDelay = ChestCommands.getSettings().anti_click_spam_delay; event.setCancelled(true); // First thing to do, if an exception is thrown at least the player doesn't take the item.
if (minDelay > 0) { IconMenu menu = ((MenuInventoryHolder) event.getInventory().getHolder()).getIconMenu();
if (cooldownUntil != null && cooldownUntil > now) { int slot = event.getRawSlot();
return;
} else { if (slot >= 0 && slot < menu.getSize()) {
antiClickSpam.put(clicker, now + minDelay);
} Icon icon = menu.getIconRaw(slot);
}
if (icon != null && event.getInventory().getItem(slot) != null) {
// Closes the inventory and executes commands AFTER the event. Player clicker = (Player) event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new ExecuteCommandsTask(clicker, icon));
} Long cooldownUntil = antiClickSpam.get(clicker);
} long now = System.currentTimeMillis();
} int minDelay = ChestCommands.getSettings().anti_click_spam_delay;
}
if (minDelay > 0) {
@EventHandler if (cooldownUntil != null && cooldownUntil > now) {
public void onQuit(PlayerQuitEvent event) { return;
antiClickSpam.remove(event.getPlayer()); } else {
} antiClickSpam.put(clicker, now + minDelay);
}
} }
// Closes the inventory and executes commands AFTER the event.
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new ExecuteCommandsTask(clicker, icon));
}
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
antiClickSpam.remove(event.getPlayer());
}
}

View File

@ -1,26 +1,40 @@
package com.gmail.filoghost.chestcommands.listener; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.event.EventHandler; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.event.Listener; * (at your option) any later version.
import org.bukkit.event.player.PlayerJoinEvent; *
* This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.ChestCommands; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.Permissions; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class JoinListener implements Listener { *
* You should have received a copy of the GNU General Public License
@EventHandler * along with this program. If not, see <https://www.gnu.org/licenses/>.
public void onJoin(PlayerJoinEvent event) { */
package com.gmail.filoghost.chestcommands.listener;
if (ChestCommands.getLastReloadErrors() > 0 && event.getPlayer().hasPermission(Permissions.SEE_ERRORS)) {
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastReloadErrors() + " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console."); import org.bukkit.ChatColor;
} import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
if (ChestCommands.hasNewVersion() && ChestCommands.getSettings().update_notifications && event.getPlayer().hasPermission(Permissions.UPDATE_NOTIFICATIONS)) { import org.bukkit.event.player.PlayerJoinEvent;
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:");
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands"); import com.gmail.filoghost.chestcommands.ChestCommands;
} import com.gmail.filoghost.chestcommands.Permissions;
}
public class JoinListener implements Listener {
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
if (ChestCommands.getLastReloadErrors() > 0 && event.getPlayer().hasPermission(Permissions.SEE_ERRORS)) {
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastReloadErrors() + " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console.");
}
if (ChestCommands.hasNewVersion() && ChestCommands.getSettings().update_notifications && event.getPlayer().hasPermission(Permissions.UPDATE_NOTIFICATIONS)) {
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:");
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands");
}
}
}

View File

@ -1,81 +1,95 @@
package com.gmail.filoghost.chestcommands.listener; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.Material; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.block.Sign; * (at your option) any later version.
import org.bukkit.event.EventHandler; *
import org.bukkit.event.EventPriority; * This program is distributed in the hope that it will be useful,
import org.bukkit.event.Listener; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import org.bukkit.event.block.Action; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import org.bukkit.event.block.SignChangeEvent; * GNU General Public License for more details.
import org.bukkit.event.player.PlayerInteractEvent; *
* You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.ChestCommands; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.Permissions; */
import com.gmail.filoghost.chestcommands.api.IconMenu; package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.util.Utils; import org.bukkit.ChatColor;
import org.bukkit.Material;
public class SignListener implements Listener { import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
@EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true) import org.bukkit.event.EventPriority;
public void onInteract(PlayerInteractEvent event) { import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && isSign(event.getClickedBlock().getType())) { import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
Sign sign = (Sign) event.getClickedBlock().getState();
if (sign.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]")) { import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.Permissions;
sign.getLine(1); import com.gmail.filoghost.chestcommands.api.IconMenu;
ExtendedIconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(sign.getLine(1))); import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
if (iconMenu != null) { import com.gmail.filoghost.chestcommands.util.Utils;
if (event.getPlayer().hasPermission(iconMenu.getPermission())) { public class SignListener implements Listener {
iconMenu.open(event.getPlayer());
} else { @EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true)
iconMenu.sendNoPermissionMessage(event.getPlayer()); public void onInteract(PlayerInteractEvent event) {
}
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && isSign(event.getClickedBlock().getType())) {
} else {
sign.setLine(0, ChatColor.RED + ChatColor.stripColor(sign.getLine(0))); Sign sign = (Sign) event.getClickedBlock().getState();
event.getPlayer().sendMessage(ChestCommands.getLang().menu_not_found); if (sign.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]")) {
}
} sign.getLine(1);
} ExtendedIconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(sign.getLine(1)));
} if (iconMenu != null) {
@EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true) if (event.getPlayer().hasPermission(iconMenu.getPermission())) {
public void onSignChange(SignChangeEvent event) { iconMenu.open(event.getPlayer());
if (event.getLine(0).equalsIgnoreCase("[menu]") && event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) { } else {
iconMenu.sendNoPermissionMessage(event.getPlayer());
if (event.getLine(1).isEmpty()) { }
event.setLine(0, ChatColor.RED + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.RED + "You must set a valid menu name in the second line."); } else {
return; sign.setLine(0, ChatColor.RED + ChatColor.stripColor(sign.getLine(0)));
} event.getPlayer().sendMessage(ChestCommands.getLang().menu_not_found);
}
IconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(event.getLine(1))); }
if (iconMenu == null) { }
event.setLine(0, ChatColor.RED + event.getLine(0)); }
event.getPlayer().sendMessage(ChatColor.RED + "That menu was not found.");
return; @EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true)
} public void onSignChange(SignChangeEvent event) {
if (event.getLine(0).equalsIgnoreCase("[menu]") && event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) {
event.setLine(0, ChatColor.DARK_BLUE + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + Utils.addYamlExtension(event.getLine(1)) + "."); if (event.getLine(1).isEmpty()) {
} event.setLine(0, ChatColor.RED + event.getLine(0));
} event.getPlayer().sendMessage(ChatColor.RED + "You must set a valid menu name in the second line.");
return;
@EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) }
public void onSignChangeMonitor(SignChangeEvent event) {
// Prevent players with permissions for creating colored signs from creating menu signs. IconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(event.getLine(1)));
if (event.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]") && !event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) { if (iconMenu == null) {
event.setLine(0, ChatColor.stripColor(event.getLine(0))); event.setLine(0, ChatColor.RED + event.getLine(0));
} event.getPlayer().sendMessage(ChatColor.RED + "That menu was not found.");
} return;
}
private boolean isSign(Material material) {
return material == Material.WALL_SIGN || material == Material.SIGN_POST; event.setLine(0, ChatColor.DARK_BLUE + event.getLine(0));
} event.getPlayer().sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + Utils.addYamlExtension(event.getLine(1)) + ".");
}
} }
@EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChangeMonitor(SignChangeEvent event) {
// Prevent players with permissions for creating colored signs from creating menu signs.
if (event.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]") && !event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) {
event.setLine(0, ChatColor.stripColor(event.getLine(0)));
}
}
private boolean isSign(Material material) {
return material == Material.WALL_SIGN || material == Material.SIGN_POST;
}
}

View File

@ -1,121 +1,135 @@
package com.gmail.filoghost.chestcommands.nms; /*
* This program is free software: you can redistribute it and/or modify
import java.lang.reflect.Method; * it under the terms of the GNU General Public License as published by
import java.util.Collection; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.inventory.ItemFlag; *
import org.bukkit.inventory.ItemStack; * This program is distributed in the hope that it will be useful,
import org.bukkit.inventory.meta.ItemMeta; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.ChestCommands; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.util.Utils; *
* You should have received a copy of the GNU General Public License
public class AttributeRemover { * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
private static boolean useItemFlags; package com.gmail.filoghost.chestcommands.nms;
private static boolean useReflection;
import java.lang.reflect.Method;
// Reflection stuff import java.util.Collection;
private static Class<?> nbtTagCompoundClass;
private static Class<?> nbtTagListClass; import org.bukkit.inventory.ItemFlag;
private static Class<?> nmsItemstackClass; import org.bukkit.inventory.ItemStack;
private static Method asNmsCopyMethod; // static import org.bukkit.inventory.meta.ItemMeta;
private static Method asCraftMirrorMethod; // static
private static Method hasTagMethod; import com.gmail.filoghost.chestcommands.ChestCommands;
private static Method getTagMethod; import com.gmail.filoghost.chestcommands.util.Utils;
private static Method setTagMethod;
private static Method nbtSetMethod; public class AttributeRemover {
private static boolean useItemFlags;
public static boolean setup() { private static boolean useReflection;
if (Utils.isClassLoaded("org.bukkit.inventory.ItemFlag")) { // Reflection stuff
// We can use the new Bukkit API (1.8.3+) private static Class<?> nbtTagCompoundClass;
useItemFlags = true; private static Class<?> nbtTagListClass;
private static Class<?> nmsItemstackClass;
} else { private static Method asNmsCopyMethod; // static
private static Method asCraftMirrorMethod; // static
try { private static Method hasTagMethod;
// Try to get the NMS methods and classes private static Method getTagMethod;
nbtTagCompoundClass = getNmsClass("NBTTagCompound"); private static Method setTagMethod;
nbtTagListClass = getNmsClass("NBTTagList"); private static Method nbtSetMethod;
nmsItemstackClass = getNmsClass("ItemStack");
asNmsCopyMethod = getObcClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack.class); public static boolean setup() {
asCraftMirrorMethod = getObcClass("inventory.CraftItemStack").getMethod("asCraftMirror", nmsItemstackClass);
if (Utils.isClassLoaded("org.bukkit.inventory.ItemFlag")) {
hasTagMethod = nmsItemstackClass.getMethod("hasTag"); // We can use the new Bukkit API (1.8.3+)
getTagMethod = nmsItemstackClass.getMethod("getTag"); useItemFlags = true;
setTagMethod = nmsItemstackClass.getMethod("setTag", nbtTagCompoundClass);
} else {
nbtSetMethod = nbtTagCompoundClass.getMethod("set", String.class, getNmsClass("NBTBase"));
try {
useReflection = true; // Try to get the NMS methods and classes
nbtTagCompoundClass = getNmsClass("NBTTagCompound");
} catch (Exception e) { nbtTagListClass = getNmsClass("NBTTagList");
ChestCommands.getInstance().getLogger().info("Could not enable the attribute remover for this version (" + e + "). Attributes will show up on items."); nmsItemstackClass = getNmsClass("ItemStack");
}
} asNmsCopyMethod = getObcClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack.class);
asCraftMirrorMethod = getObcClass("inventory.CraftItemStack").getMethod("asCraftMirror", nmsItemstackClass);
return true;
} hasTagMethod = nmsItemstackClass.getMethod("hasTag");
getTagMethod = nmsItemstackClass.getMethod("getTag");
setTagMethod = nmsItemstackClass.getMethod("setTag", nbtTagCompoundClass);
private static Class<?> getNmsClass(String name) throws ClassNotFoundException {
return Class.forName("net.minecraft.server." + Utils.getBukkitVersion() + "." + name); nbtSetMethod = nbtTagCompoundClass.getMethod("set", String.class, getNmsClass("NBTBase"));
}
useReflection = true;
private static Class<?> getObcClass(String name) throws ClassNotFoundException {
return Class.forName("org.bukkit.craftbukkit." + Utils.getBukkitVersion() + "." + name); } catch (Exception e) {
} ChestCommands.getInstance().getLogger().info("Could not enable the attribute remover for this version (" + e + "). Attributes will show up on items.");
}
public static ItemStack hideAttributes(ItemStack item) { }
if (item == null) {
return null; return true;
} }
if (useItemFlags) {
ItemMeta meta = item.getItemMeta(); private static Class<?> getNmsClass(String name) throws ClassNotFoundException {
if (isNullOrEmpty(meta.getItemFlags())) { return Class.forName("net.minecraft.server." + Utils.getBukkitVersion() + "." + name);
// Add them only if necessary }
meta.addItemFlags(ItemFlag.values());
item.setItemMeta(meta); private static Class<?> getObcClass(String name) throws ClassNotFoundException {
} return Class.forName("org.bukkit.craftbukkit." + Utils.getBukkitVersion() + "." + name);
return item; }
} else if (useReflection) { public static ItemStack hideAttributes(ItemStack item) {
try { if (item == null) {
return null;
Object nmsItemstack = asNmsCopyMethod.invoke(null, item); }
if (nmsItemstack == null) {
return item; if (useItemFlags) {
} ItemMeta meta = item.getItemMeta();
if (isNullOrEmpty(meta.getItemFlags())) {
Object nbtCompound; // Add them only if necessary
if ((Boolean) hasTagMethod.invoke(nmsItemstack)) { meta.addItemFlags(ItemFlag.values());
nbtCompound = getTagMethod.invoke(nmsItemstack); item.setItemMeta(meta);
} else { }
nbtCompound = nbtTagCompoundClass.newInstance(); return item;
setTagMethod.invoke(nmsItemstack, nbtCompound);
} } else if (useReflection) {
try {
if (nbtCompound == null) {
return item; Object nmsItemstack = asNmsCopyMethod.invoke(null, item);
} if (nmsItemstack == null) {
return item;
Object nbtList = nbtTagListClass.newInstance(); }
nbtSetMethod.invoke(nbtCompound, "AttributeModifiers", nbtList);
return (ItemStack) asCraftMirrorMethod.invoke(null, nmsItemstack); Object nbtCompound;
if ((Boolean) hasTagMethod.invoke(nmsItemstack)) {
} catch (Exception e) { } nbtCompound = getTagMethod.invoke(nmsItemstack);
} } else {
nbtCompound = nbtTagCompoundClass.newInstance();
// On failure setTagMethod.invoke(nmsItemstack, nbtCompound);
return item; }
}
if (nbtCompound == null) {
private static boolean isNullOrEmpty(Collection<?> coll) { return item;
return coll == null || coll.isEmpty(); }
}
Object nbtList = nbtTagListClass.newInstance();
} nbtSetMethod.invoke(nbtCompound, "AttributeModifiers", nbtList);
return (ItemStack) asCraftMirrorMethod.invoke(null, nmsItemstack);
} catch (Exception e) { }
}
// On failure
return item;
}
private static boolean isNullOrEmpty(Collection<?> coll) {
return coll == null || coll.isEmpty();
}
}

View File

@ -1,96 +1,110 @@
package com.gmail.filoghost.chestcommands.serializer; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
import java.util.Map; * the Free Software Foundation, either version 3 of the License, or
import java.util.Map.Entry; * (at your option) any later version.
import java.util.regex.Matcher; *
import java.util.regex.Pattern; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.ChestCommands; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.internal.icon.command.BroadcastIconCommand; *
import com.gmail.filoghost.chestcommands.internal.icon.command.ConsoleIconCommand; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.internal.icon.command.DragonBarIconCommand; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.internal.icon.command.GiveIconCommand; */
import com.gmail.filoghost.chestcommands.internal.icon.command.GiveMoneyIconCommand; package com.gmail.filoghost.chestcommands.serializer;
import com.gmail.filoghost.chestcommands.internal.icon.command.OpIconCommand;
import com.gmail.filoghost.chestcommands.internal.icon.command.OpenIconCommand; import java.util.List;
import com.gmail.filoghost.chestcommands.internal.icon.command.PlayerIconCommand; import java.util.Map;
import com.gmail.filoghost.chestcommands.internal.icon.command.ServerIconCommand; import java.util.Map.Entry;
import com.gmail.filoghost.chestcommands.internal.icon.command.SoundIconCommand; import java.util.regex.Matcher;
import com.gmail.filoghost.chestcommands.internal.icon.command.TellIconCommand; import java.util.regex.Pattern;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils; import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
public class CommandSerializer { import com.gmail.filoghost.chestcommands.internal.icon.command.BroadcastIconCommand;
import com.gmail.filoghost.chestcommands.internal.icon.command.ConsoleIconCommand;
private static Map<Pattern, Class<? extends IconCommand>> commandTypesMap = Utils.newHashMap(); import com.gmail.filoghost.chestcommands.internal.icon.command.DragonBarIconCommand;
static { import com.gmail.filoghost.chestcommands.internal.icon.command.GiveIconCommand;
commandTypesMap.put(commandPattern("console:"), ConsoleIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.GiveMoneyIconCommand;
commandTypesMap.put(commandPattern("op:"), OpIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.OpIconCommand;
commandTypesMap.put(commandPattern("(open|menu):"), OpenIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.OpenIconCommand;
commandTypesMap.put(commandPattern("server:?"), ServerIconCommand.class); // The colon is optional. import com.gmail.filoghost.chestcommands.internal.icon.command.PlayerIconCommand;
commandTypesMap.put(commandPattern("tell:"), TellIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.ServerIconCommand;
commandTypesMap.put(commandPattern("broadcast:"), BroadcastIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.SoundIconCommand;
commandTypesMap.put(commandPattern("give:"), GiveIconCommand.class); import com.gmail.filoghost.chestcommands.internal.icon.command.TellIconCommand;
commandTypesMap.put(commandPattern("give-?money:"), GiveMoneyIconCommand.class); import com.gmail.filoghost.chestcommands.util.ErrorLogger;
commandTypesMap.put(commandPattern("sound:"), SoundIconCommand.class); import com.gmail.filoghost.chestcommands.util.Utils;
commandTypesMap.put(commandPattern("dragon-?bar:"), DragonBarIconCommand.class);
} public class CommandSerializer {
private static Pattern commandPattern(String regex) { private static Map<Pattern, Class<? extends IconCommand>> commandTypesMap = Utils.newHashMap();
return Pattern.compile("^(?i)" + regex); // Case insensitive and only at the beginning. static {
} commandTypesMap.put(commandPattern("console:"), ConsoleIconCommand.class);
commandTypesMap.put(commandPattern("op:"), OpIconCommand.class);
public static void checkClassConstructors(ErrorLogger errorLogger) { commandTypesMap.put(commandPattern("(open|menu):"), OpenIconCommand.class);
for (Class<? extends IconCommand> clazz : commandTypesMap.values()) { commandTypesMap.put(commandPattern("server:?"), ServerIconCommand.class); // The colon is optional.
try { commandTypesMap.put(commandPattern("tell:"), TellIconCommand.class);
clazz.getDeclaredConstructor(String.class).newInstance(""); commandTypesMap.put(commandPattern("broadcast:"), BroadcastIconCommand.class);
} catch (Exception ex) { commandTypesMap.put(commandPattern("give:"), GiveIconCommand.class);
String className = clazz.getName().replace("Command", ""); commandTypesMap.put(commandPattern("give-?money:"), GiveMoneyIconCommand.class);
className = className.substring(className.lastIndexOf('.') + 1, className.length()); commandTypesMap.put(commandPattern("sound:"), SoundIconCommand.class);
errorLogger.addError("Unable to register the \"" + className + "\" command type(" + ex.getClass().getName() + "), please inform the developer (filoghost). The plugin will still work, but all the \"" + className + "\" commands will be treated as normal commands."); commandTypesMap.put(commandPattern("dragon-?bar:"), DragonBarIconCommand.class);
} }
}
} private static Pattern commandPattern(String regex) {
return Pattern.compile("^(?i)" + regex); // Case insensitive and only at the beginning.
public static List<IconCommand> readCommands(String input) { }
String separator = ChestCommands.getSettings().multiple_commands_separator;
if (separator == null || separator.length() == 0) { public static void checkClassConstructors(ErrorLogger errorLogger) {
separator = ";"; for (Class<? extends IconCommand> clazz : commandTypesMap.values()) {
} try {
clazz.getDeclaredConstructor(String.class).newInstance("");
String[] split = input.split(Pattern.quote(separator)); } catch (Exception ex) {
List<IconCommand> iconCommands = Utils.newArrayList(); String className = clazz.getName().replace("Command", "");
className = className.substring(className.lastIndexOf('.') + 1, className.length());
for (String command : split) { errorLogger.addError("Unable to register the \"" + className + "\" command type(" + ex.getClass().getName() + "), please inform the developer (filoghost). The plugin will still work, but all the \"" + className + "\" commands will be treated as normal commands.");
String trim = command.trim(); }
}
if (trim.length() > 0) { }
iconCommands.add(matchCommand(trim));
} public static List<IconCommand> readCommands(String input) {
} String separator = ChestCommands.getSettings().multiple_commands_separator;
if (separator == null || separator.length() == 0) {
return iconCommands; separator = ";";
} }
public static IconCommand matchCommand(String input) { String[] split = input.split(Pattern.quote(separator));
List<IconCommand> iconCommands = Utils.newArrayList();
for (Entry<Pattern, Class<? extends IconCommand>> entry : commandTypesMap.entrySet()) {
Matcher matcher = entry.getKey().matcher(input); for (String command : split) {
if (matcher.find()) { String trim = command.trim();
// Remove the command prefix and trim the spaces.
String cleanCommand = matcher.replaceFirst("").trim(); if (trim.length() > 0) {
iconCommands.add(matchCommand(trim));
try { }
return entry.getValue().getDeclaredConstructor(String.class).newInstance(cleanCommand); }
} catch (Exception e) {
// Checked at startup. return iconCommands;
} }
}
} public static IconCommand matchCommand(String input) {
return new PlayerIconCommand(input); // Normal command, no match found. for (Entry<Pattern, Class<? extends IconCommand>> entry : commandTypesMap.entrySet()) {
} Matcher matcher = entry.getKey().matcher(input);
if (matcher.find()) {
} // Remove the command prefix and trim the spaces.
String cleanCommand = matcher.replaceFirst("").trim();
try {
return entry.getValue().getDeclaredConstructor(String.class).newInstance(cleanCommand);
} catch (Exception e) {
// Checked at startup.
}
}
}
return new PlayerIconCommand(input); // Normal command, no match found.
}
}

View File

@ -1,94 +1,108 @@
package com.gmail.filoghost.chestcommands.serializer; /*
* This program is free software: you can redistribute it and/or modify
import java.util.HashMap; * it under the terms of the GNU General Public License as published by
import java.util.Map; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import org.bukkit.enchantments.Enchantment; *
* This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.util.ErrorLogger; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.util.StringUtils; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class EnchantmentSerializer { *
* You should have received a copy of the GNU General Public License
private static Map<String, Enchantment> enchantmentsMap = new HashMap<String, Enchantment>(); * along with this program. If not, see <https://www.gnu.org/licenses/>.
static { */
enchantmentsMap.put(formatLowercase("Protection"), Enchantment.PROTECTION_ENVIRONMENTAL); package com.gmail.filoghost.chestcommands.serializer;
enchantmentsMap.put(formatLowercase("Fire Protection"), Enchantment.PROTECTION_FIRE);
enchantmentsMap.put(formatLowercase("Feather Falling"), Enchantment.PROTECTION_FALL); import java.util.HashMap;
enchantmentsMap.put(formatLowercase("Blast Protection"), Enchantment.PROTECTION_EXPLOSIONS); import java.util.Map;
enchantmentsMap.put(formatLowercase("Projectile Protection"), Enchantment.PROTECTION_PROJECTILE);
enchantmentsMap.put(formatLowercase("Respiration"), Enchantment.OXYGEN); import org.bukkit.enchantments.Enchantment;
enchantmentsMap.put(formatLowercase("Aqua Affinity"), Enchantment.WATER_WORKER);
enchantmentsMap.put(formatLowercase("Thorns"), Enchantment.THORNS); import com.gmail.filoghost.chestcommands.util.ErrorLogger;
enchantmentsMap.put(formatLowercase("Sharpness"), Enchantment.DAMAGE_ALL); import com.gmail.filoghost.chestcommands.util.StringUtils;
enchantmentsMap.put(formatLowercase("Smite"), Enchantment.DAMAGE_UNDEAD);
enchantmentsMap.put(formatLowercase("Bane Of Arthropods"), Enchantment.DAMAGE_ARTHROPODS); public class EnchantmentSerializer {
enchantmentsMap.put(formatLowercase("Knockback"), Enchantment.KNOCKBACK);
enchantmentsMap.put(formatLowercase("Fire Aspect"), Enchantment.FIRE_ASPECT); private static Map<String, Enchantment> enchantmentsMap = new HashMap<String, Enchantment>();
enchantmentsMap.put(formatLowercase("Looting"), Enchantment.LOOT_BONUS_MOBS); static {
enchantmentsMap.put(formatLowercase("Efficiency"), Enchantment.DIG_SPEED); enchantmentsMap.put(formatLowercase("Protection"), Enchantment.PROTECTION_ENVIRONMENTAL);
enchantmentsMap.put(formatLowercase("Silk Touch"), Enchantment.SILK_TOUCH); enchantmentsMap.put(formatLowercase("Fire Protection"), Enchantment.PROTECTION_FIRE);
enchantmentsMap.put(formatLowercase("Unbreaking"), Enchantment.DURABILITY); enchantmentsMap.put(formatLowercase("Feather Falling"), Enchantment.PROTECTION_FALL);
enchantmentsMap.put(formatLowercase("Fortune"), Enchantment.LOOT_BONUS_BLOCKS); enchantmentsMap.put(formatLowercase("Blast Protection"), Enchantment.PROTECTION_EXPLOSIONS);
enchantmentsMap.put(formatLowercase("Power"), Enchantment.ARROW_DAMAGE); enchantmentsMap.put(formatLowercase("Projectile Protection"), Enchantment.PROTECTION_PROJECTILE);
enchantmentsMap.put(formatLowercase("Punch"), Enchantment.ARROW_KNOCKBACK); enchantmentsMap.put(formatLowercase("Respiration"), Enchantment.OXYGEN);
enchantmentsMap.put(formatLowercase("Flame"), Enchantment.ARROW_FIRE); enchantmentsMap.put(formatLowercase("Aqua Affinity"), Enchantment.WATER_WORKER);
enchantmentsMap.put(formatLowercase("Infinity"), Enchantment.ARROW_INFINITE); enchantmentsMap.put(formatLowercase("Thorns"), Enchantment.THORNS);
enchantmentsMap.put(formatLowercase("Lure"), Enchantment.LURE); enchantmentsMap.put(formatLowercase("Sharpness"), Enchantment.DAMAGE_ALL);
enchantmentsMap.put(formatLowercase("Luck Of The Sea"), Enchantment.LUCK); enchantmentsMap.put(formatLowercase("Smite"), Enchantment.DAMAGE_UNDEAD);
enchantmentsMap.put(formatLowercase("Bane Of Arthropods"), Enchantment.DAMAGE_ARTHROPODS);
for (Enchantment enchant : Enchantment.values()) { enchantmentsMap.put(formatLowercase("Knockback"), Enchantment.KNOCKBACK);
if (enchant != null) { enchantmentsMap.put(formatLowercase("Fire Aspect"), Enchantment.FIRE_ASPECT);
// Accepts the ugly default names too. enchantmentsMap.put(formatLowercase("Looting"), Enchantment.LOOT_BONUS_MOBS);
enchantmentsMap.put(formatLowercase(enchant.getName()), enchant); enchantmentsMap.put(formatLowercase("Efficiency"), Enchantment.DIG_SPEED);
} enchantmentsMap.put(formatLowercase("Silk Touch"), Enchantment.SILK_TOUCH);
} enchantmentsMap.put(formatLowercase("Unbreaking"), Enchantment.DURABILITY);
} enchantmentsMap.put(formatLowercase("Fortune"), Enchantment.LOOT_BONUS_BLOCKS);
enchantmentsMap.put(formatLowercase("Power"), Enchantment.ARROW_DAMAGE);
private static String formatLowercase(String string) { enchantmentsMap.put(formatLowercase("Punch"), Enchantment.ARROW_KNOCKBACK);
return StringUtils.stripChars(string, " _-").toLowerCase(); enchantmentsMap.put(formatLowercase("Flame"), Enchantment.ARROW_FIRE);
} enchantmentsMap.put(formatLowercase("Infinity"), Enchantment.ARROW_INFINITE);
enchantmentsMap.put(formatLowercase("Lure"), Enchantment.LURE);
public static Map<Enchantment, Integer> loadEnchantments(String input, String iconName, String menuFileName, ErrorLogger errorLogger) { enchantmentsMap.put(formatLowercase("Luck Of The Sea"), Enchantment.LUCK);
Map<Enchantment, Integer> output = new HashMap<Enchantment, Integer>();
for (Enchantment enchant : Enchantment.values()) {
if (input == null || input.isEmpty()) { if (enchant != null) {
return output; // Accepts the ugly default names too.
} enchantmentsMap.put(formatLowercase(enchant.getName()), enchant);
}
for (String singleEnchant : input.split(";")) { }
}
int level = 1;
private static String formatLowercase(String string) {
if (singleEnchant.contains(",")) { return StringUtils.stripChars(string, " _-").toLowerCase();
String[] levelSplit = singleEnchant.split(","); }
try { public static Map<Enchantment, Integer> loadEnchantments(String input, String iconName, String menuFileName, ErrorLogger errorLogger) {
level = Integer.parseInt(levelSplit[1].trim()); Map<Enchantment, Integer> output = new HashMap<Enchantment, Integer>();
} catch (NumberFormatException ex) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment level: " + levelSplit[1]); if (input == null || input.isEmpty()) {
} return output;
singleEnchant = levelSplit[0]; }
}
for (String singleEnchant : input.split(";")) {
Enchantment ench = matchEnchantment(singleEnchant);
int level = 1;
if (ench == null) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment: " + singleEnchant); if (singleEnchant.contains(",")) {
} else { String[] levelSplit = singleEnchant.split(",");
output.put(ench, level);
} try {
} level = Integer.parseInt(levelSplit[1].trim());
} catch (NumberFormatException ex) {
return output; errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment level: " + levelSplit[1]);
} }
singleEnchant = levelSplit[0];
public static Enchantment matchEnchantment(String input) { }
if (input == null) {
return null; Enchantment ench = matchEnchantment(singleEnchant);
}
if (ench == null) {
return enchantmentsMap.get(formatLowercase(input)); errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment: " + singleEnchant);
} } else {
output.put(ench, level);
} }
}
return output;
}
public static Enchantment matchEnchantment(String input) {
if (input == null) {
return null;
}
return enchantmentsMap.get(formatLowercase(input));
}
}

View File

@ -1,234 +1,248 @@
package com.gmail.filoghost.chestcommands.serializer; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.configuration.ConfigurationSection; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.api.Icon; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.exception.FormatException; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.internal.CommandsClickHandler; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.internal.RequiredItem; *
import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.util.ErrorLogger; */
import com.gmail.filoghost.chestcommands.util.ItemStackReader; package com.gmail.filoghost.chestcommands.serializer;
import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.Validate; import java.util.List;
public class IconSerializer { import org.bukkit.configuration.ConfigurationSection;
private static class Nodes { import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
public static final import com.gmail.filoghost.chestcommands.exception.FormatException;
String ID = "ID", import com.gmail.filoghost.chestcommands.internal.CommandsClickHandler;
DATA_VALUE = "DATA-VALUE", import com.gmail.filoghost.chestcommands.internal.RequiredItem;
AMOUNT = "AMOUNT", import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon;
NAME = "NAME", import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
LORE = "LORE", import com.gmail.filoghost.chestcommands.util.ErrorLogger;
ENCHANT = "ENCHANTMENT", import com.gmail.filoghost.chestcommands.util.ItemStackReader;
COLOR = "COLOR", import com.gmail.filoghost.chestcommands.util.Utils;
SKULL_OWNER = "SKULL-OWNER", import com.gmail.filoghost.chestcommands.util.Validate;
COMMAND = "COMMAND",
PRICE = "PRICE", public class IconSerializer {
EXP_LEVELS = "LEVELS",
REQUIRED_ITEM = "REQUIRED-ITEM", private static class Nodes {
PERMISSION = "PERMISSION",
PERMISSION_MESSAGE = "PERMISSION-MESSAGE", public static final
VIEW_PERMISSION = "VIEW-PERMISSION", String ID = "ID",
KEEP_OPEN = "KEEP-OPEN", DATA_VALUE = "DATA-VALUE",
POSITION_X = "POSITION-X", AMOUNT = "AMOUNT",
POSITION_Y = "POSITION-Y"; NAME = "NAME",
} LORE = "LORE",
ENCHANT = "ENCHANTMENT",
public static class Coords { COLOR = "COLOR",
SKULL_OWNER = "SKULL-OWNER",
private Integer x, y; COMMAND = "COMMAND",
PRICE = "PRICE",
protected Coords(Integer x, Integer y) { EXP_LEVELS = "LEVELS",
this.x = x; REQUIRED_ITEM = "REQUIRED-ITEM",
this.y = y; PERMISSION = "PERMISSION",
} PERMISSION_MESSAGE = "PERMISSION-MESSAGE",
VIEW_PERMISSION = "VIEW-PERMISSION",
public boolean isSetX() { KEEP_OPEN = "KEEP-OPEN",
return x != null; POSITION_X = "POSITION-X",
} POSITION_Y = "POSITION-Y";
}
public boolean isSetY() {
return y != null; public static class Coords {
}
private Integer x, y;
public Integer getX() {
return x; protected Coords(Integer x, Integer y) {
} this.x = x;
this.y = y;
public Integer getY() { }
return y;
} public boolean isSetX() {
} return x != null;
}
public static Icon loadIconFromSection(ConfigurationSection section, String iconName, String menuFileName, ErrorLogger errorLogger) {
Validate.notNull(section, "ConfigurationSection cannot be null"); public boolean isSetY() {
return y != null;
// The icon is valid even without a Material. }
ExtendedIcon icon = new ExtendedIcon();
public Integer getX() {
if (section.isSet(Nodes.ID)) { return x;
try { }
ItemStackReader itemReader = new ItemStackReader(section.getString(Nodes.ID), true);
icon.setMaterial(itemReader.getMaterial()); public Integer getY() {
icon.setDataValue(itemReader.getDataValue()); return y;
icon.setAmount(itemReader.getAmount()); }
} catch (FormatException e) { }
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid ID: " + e.getMessage());
} public static Icon loadIconFromSection(ConfigurationSection section, String iconName, String menuFileName, ErrorLogger errorLogger) {
} Validate.notNull(section, "ConfigurationSection cannot be null");
if (section.isSet(Nodes.DATA_VALUE)) { // The icon is valid even without a Material.
icon.setDataValue((short) section.getInt(Nodes.DATA_VALUE)); ExtendedIcon icon = new ExtendedIcon();
}
if (section.isSet(Nodes.ID)) {
if (section.isSet(Nodes.AMOUNT)) { try {
icon.setAmount(section.getInt(Nodes.AMOUNT)); ItemStackReader itemReader = new ItemStackReader(section.getString(Nodes.ID), true);
} icon.setMaterial(itemReader.getMaterial());
icon.setDataValue(itemReader.getDataValue());
icon.setName(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeName(section.getString(Nodes.NAME)))); icon.setAmount(itemReader.getAmount());
icon.setLore(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeLore(section.getStringList(Nodes.LORE)))); } catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid ID: " + e.getMessage());
if (section.isSet(Nodes.ENCHANT)) { }
icon.setEnchantments(EnchantmentSerializer.loadEnchantments(section.getString(Nodes.ENCHANT), iconName, menuFileName, errorLogger)); }
}
if (section.isSet(Nodes.DATA_VALUE)) {
if (section.isSet(Nodes.COLOR)) { icon.setDataValue((short) section.getInt(Nodes.DATA_VALUE));
try { }
icon.setColor(Utils.parseColor(section.getString(Nodes.COLOR)));
} catch (FormatException e) { if (section.isSet(Nodes.AMOUNT)) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid COLOR: " + e.getMessage()); icon.setAmount(section.getInt(Nodes.AMOUNT));
} }
}
icon.setName(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeName(section.getString(Nodes.NAME))));
icon.setSkullOwner(section.getString(Nodes.SKULL_OWNER)); icon.setLore(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeLore(section.getStringList(Nodes.LORE))));
icon.setPermission(section.getString(Nodes.PERMISSION)); if (section.isSet(Nodes.ENCHANT)) {
icon.setPermissionMessage(Utils.addColors(section.getString(Nodes.PERMISSION_MESSAGE))); icon.setEnchantments(EnchantmentSerializer.loadEnchantments(section.getString(Nodes.ENCHANT), iconName, menuFileName, errorLogger));
icon.setViewPermission(section.getString(Nodes.VIEW_PERMISSION)); }
boolean closeOnClick = !section.getBoolean(Nodes.KEEP_OPEN); if (section.isSet(Nodes.COLOR)) {
icon.setCloseOnClick(closeOnClick); try {
icon.setColor(Utils.parseColor(section.getString(Nodes.COLOR)));
if (section.isSet(Nodes.COMMAND)) { } catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid COLOR: " + e.getMessage());
List<IconCommand> commands; }
}
if (section.isList(Nodes.COMMAND)) {
commands = Utils.newArrayList(); icon.setSkullOwner(section.getString(Nodes.SKULL_OWNER));
for (String commandString : section.getStringList(Nodes.COMMAND)) { icon.setPermission(section.getString(Nodes.PERMISSION));
if (commandString.isEmpty()) { icon.setPermissionMessage(Utils.addColors(section.getString(Nodes.PERMISSION_MESSAGE)));
continue; icon.setViewPermission(section.getString(Nodes.VIEW_PERMISSION));
}
commands.add(CommandSerializer.matchCommand(commandString)); boolean closeOnClick = !section.getBoolean(Nodes.KEEP_OPEN);
} icon.setCloseOnClick(closeOnClick);
} else { if (section.isSet(Nodes.COMMAND)) {
commands = CommandSerializer.readCommands(section.getString(Nodes.COMMAND));
} List<IconCommand> commands;
icon.setClickHandler(new CommandsClickHandler(commands, closeOnClick)); if (section.isList(Nodes.COMMAND)) {
} commands = Utils.newArrayList();
double price = section.getDouble(Nodes.PRICE); for (String commandString : section.getStringList(Nodes.COMMAND)) {
if (price > 0.0) { if (commandString.isEmpty()) {
icon.setMoneyPrice(price); continue;
} else if (price < 0.0) { }
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has a negative PRICE: " + price); commands.add(CommandSerializer.matchCommand(commandString));
} }
int levels = section.getInt(Nodes.EXP_LEVELS); } else {
if (levels > 0) { commands = CommandSerializer.readCommands(section.getString(Nodes.COMMAND));
icon.setExpLevelsPrice(levels); }
} else if (levels < 0) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has negative LEVELS: " + levels); icon.setClickHandler(new CommandsClickHandler(commands, closeOnClick));
} }
if (section.isSet(Nodes.REQUIRED_ITEM)) { double price = section.getDouble(Nodes.PRICE);
try { if (price > 0.0) {
ItemStackReader itemReader = new ItemStackReader(section.getString(Nodes.REQUIRED_ITEM), true); icon.setMoneyPrice(price);
RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount()); } else if (price < 0.0) {
if (itemReader.hasExplicitDataValue()) { errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has a negative PRICE: " + price);
requiredItem.setRestrictiveDataValue(itemReader.getDataValue()); }
}
icon.setRequiredItem(requiredItem); int levels = section.getInt(Nodes.EXP_LEVELS);
} catch (FormatException e) { if (levels > 0) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid REQUIRED-ITEM: " + e.getMessage()); icon.setExpLevelsPrice(levels);
} } else if (levels < 0) {
} errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has negative LEVELS: " + levels);
}
return icon;
} if (section.isSet(Nodes.REQUIRED_ITEM)) {
try {
public static Coords loadCoordsFromSection(ConfigurationSection section) { ItemStackReader itemReader = new ItemStackReader(section.getString(Nodes.REQUIRED_ITEM), true);
Validate.notNull(section, "ConfigurationSection cannot be null"); RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount());
if (itemReader.hasExplicitDataValue()) {
Integer x = null; requiredItem.setRestrictiveDataValue(itemReader.getDataValue());
Integer y = null; }
icon.setRequiredItem(requiredItem);
if (section.isInt(Nodes.POSITION_X)) { } catch (FormatException e) {
x = section.getInt(Nodes.POSITION_X); errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid REQUIRED-ITEM: " + e.getMessage());
} }
}
if (section.isInt(Nodes.POSITION_Y)) {
y = section.getInt(Nodes.POSITION_Y); return icon;
} }
return new Coords(x, y); public static Coords loadCoordsFromSection(ConfigurationSection section) {
} Validate.notNull(section, "ConfigurationSection cannot be null");
// /** Integer x = null;
// * Reads a list of strings or a single String as list. Integer y = null;
// */
// private static List<String> readAsList(ConfigurationSection section, String node) { if (section.isInt(Nodes.POSITION_X)) {
// if (section.isList(node)) { x = section.getInt(Nodes.POSITION_X);
// return section.getStringList(node); }
// } else if (section.isString(node)) {
// return Arrays.asList(section.getString(node)); if (section.isInt(Nodes.POSITION_Y)) {
// } else { y = section.getInt(Nodes.POSITION_Y);
// return null; }
// }
// } return new Coords(x, y);
}
public static void saveToSection(Icon icon, ConfigurationSection section) {
Validate.notNull(icon, "Icon cannot be null"); // /**
Validate.notNull(section, "ConfigurationSection cannot be null"); // * Reads a list of strings or a single String as list.
// */
section.set(Nodes.ID, serializeIconID(icon)); // private static List<String> readAsList(ConfigurationSection section, String node) {
// if (section.isList(node)) {
if (icon.getEnchantments().size() > 0) { // return section.getStringList(node);
section.set(Nodes.ENCHANT, 1); // } else if (section.isString(node)) {
} // return Arrays.asList(section.getString(node));
// } else {
//TODO not finished // return null;
} // }
// }
public static String serializeIconID(Icon icon) {
if (icon.getMaterial() == null) { public static void saveToSection(Icon icon, ConfigurationSection section) {
return "Not set"; Validate.notNull(icon, "Icon cannot be null");
} Validate.notNull(section, "ConfigurationSection cannot be null");
StringBuilder output = new StringBuilder(); section.set(Nodes.ID, serializeIconID(icon));
output.append(Utils.formatMaterial(icon.getMaterial()));
if (icon.getEnchantments().size() > 0) {
if (icon.getDataValue() > 0) { section.set(Nodes.ENCHANT, 1);
output.append(":"); }
output.append(icon.getDataValue());
} //TODO not finished
}
if (icon.getAmount() != 1) {
output.append(", "); public static String serializeIconID(Icon icon) {
output.append(icon.getAmount()); if (icon.getMaterial() == null) {
} return "Not set";
}
return output.toString();
} StringBuilder output = new StringBuilder();
output.append(Utils.formatMaterial(icon.getMaterial()));
}
if (icon.getDataValue() > 0) {
output.append(":");
output.append(icon.getDataValue());
}
if (icon.getAmount() != 1) {
output.append(", ");
output.append(icon.getAmount());
}
return output.toString();
}
}

View File

@ -1,133 +1,147 @@
package com.gmail.filoghost.chestcommands.serializer; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.ChatColor; * it under the terms of the GNU General Public License as published by
import org.bukkit.configuration.ConfigurationSection; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.api.Icon; *
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.exception.FormatException; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.internal.MenuData; * GNU General Public License for more details.
import com.gmail.filoghost.chestcommands.serializer.IconSerializer.Coords; *
import com.gmail.filoghost.chestcommands.util.ClickType; * You should have received a copy of the GNU General Public License
import com.gmail.filoghost.chestcommands.util.ErrorLogger; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import com.gmail.filoghost.chestcommands.util.ItemStackReader; */
import com.gmail.filoghost.chestcommands.util.Utils; package com.gmail.filoghost.chestcommands.serializer;
public class MenuSerializer { import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
private static class Nodes {
import com.gmail.filoghost.chestcommands.api.Icon;
public static final String MENU_NAME = "menu-settings.name"; import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
public static final String MENU_ROWS = "menu-settings.rows"; import com.gmail.filoghost.chestcommands.exception.FormatException;
public static final String MENU_COMMAND = "menu-settings.command"; import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuData;
public static final String OPEN_ACTION = "menu-settings.open-action"; import com.gmail.filoghost.chestcommands.serializer.IconSerializer.Coords;
import com.gmail.filoghost.chestcommands.util.ClickType;
public static final String OPEN_ITEM_MATERIAL = "menu-settings.open-with-item.id"; import com.gmail.filoghost.chestcommands.util.ErrorLogger;
public static final String OPEN_ITEM_LEFT_CLICK = "menu-settings.open-with-item.left-click"; import com.gmail.filoghost.chestcommands.util.ItemStackReader;
public static final String OPEN_ITEM_RIGHT_CLICK = "menu-settings.open-with-item.right-click"; import com.gmail.filoghost.chestcommands.util.Utils;
public static final String AUTO_REFRESH = "menu-settings.auto-refresh"; public class MenuSerializer {
} private static class Nodes {
public static ExtendedIconMenu loadMenu(PluginConfig config, String title, int rows, ErrorLogger errorLogger) { public static final String MENU_NAME = "menu-settings.name";
ExtendedIconMenu iconMenu = new ExtendedIconMenu(title, rows, config.getFileName()); public static final String MENU_ROWS = "menu-settings.rows";
public static final String MENU_COMMAND = "menu-settings.command";
for (String subSectionName : config.getKeys(false)) {
if (subSectionName.equals("menu-settings")) { public static final String OPEN_ACTION = "menu-settings.open-action";
continue;
} public static final String OPEN_ITEM_MATERIAL = "menu-settings.open-with-item.id";
public static final String OPEN_ITEM_LEFT_CLICK = "menu-settings.open-with-item.left-click";
ConfigurationSection iconSection = config.getConfigurationSection(subSectionName); public static final String OPEN_ITEM_RIGHT_CLICK = "menu-settings.open-with-item.right-click";
Icon icon = IconSerializer.loadIconFromSection(iconSection, subSectionName, config.getFileName(), errorLogger); public static final String AUTO_REFRESH = "menu-settings.auto-refresh";
Coords coords = IconSerializer.loadCoordsFromSection(iconSection);
}
if (!coords.isSetX() || !coords.isSetY()) {
errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is missing POSITION-X and/or POSITION-Y."); public static ExtendedIconMenu loadMenu(PluginConfig config, String title, int rows, ErrorLogger errorLogger) {
continue; ExtendedIconMenu iconMenu = new ExtendedIconMenu(title, rows, config.getFileName());
}
for (String subSectionName : config.getKeys(false)) {
if (iconMenu.getIcon(coords.getX(), coords.getY()) != null) { if (subSectionName.equals("menu-settings")) {
errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is overriding another icon with the same position."); continue;
} }
iconMenu.setIcon(coords.getX(), coords.getY(), icon); ConfigurationSection iconSection = config.getConfigurationSection(subSectionName);
}
Icon icon = IconSerializer.loadIconFromSection(iconSection, subSectionName, config.getFileName(), errorLogger);
return iconMenu; Coords coords = IconSerializer.loadCoordsFromSection(iconSection);
}
if (!coords.isSetX() || !coords.isSetY()) {
/** errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is missing POSITION-X and/or POSITION-Y.");
* Reads all the settings of a menu. It will never return a null title, even if not set. continue;
*/ }
public static MenuData loadMenuData(PluginConfig config, ErrorLogger errorLogger) {
if (iconMenu.getIcon(coords.getX(), coords.getY()) != null) {
String title = Utils.addColors(config.getString(Nodes.MENU_NAME)); errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is overriding another icon with the same position.");
int rows; }
if (title == null) { iconMenu.setIcon(coords.getX(), coords.getY(), icon);
errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a name set."); }
title = ChatColor.DARK_RED + "No title set";
} return iconMenu;
}
if (title.length() > 32) {
title = title.substring(0, 32); /**
} * Reads all the settings of a menu. It will never return a null title, even if not set.
*/
if (config.isInt(Nodes.MENU_ROWS)) { public static MenuData loadMenuData(PluginConfig config, ErrorLogger errorLogger) {
rows = config.getInt(Nodes.MENU_ROWS);
String title = Utils.addColors(config.getString(Nodes.MENU_NAME));
if (rows <= 0) { int rows;
rows = 1;
} if (title == null) {
errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a name set.");
} else { title = ChatColor.DARK_RED + "No title set";
rows = 6; // Defaults to 6 rows. }
errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a the number of rows set, it will have 6 rows by default.");
} if (title.length() > 32) {
title = title.substring(0, 32);
MenuData menuData = new MenuData(title, rows); }
if (config.isSet(Nodes.MENU_COMMAND)) { if (config.isInt(Nodes.MENU_ROWS)) {
menuData.setCommands(config.getString(Nodes.MENU_COMMAND).replace(" ", "").split(";")); rows = config.getInt(Nodes.MENU_ROWS);
}
if (rows <= 0) {
if (config.isSet(Nodes.OPEN_ACTION)) { rows = 1;
menuData.setOpenActions(CommandSerializer.readCommands(config.getString(Nodes.OPEN_ACTION))); }
}
} else {
if (config.isSet(Nodes.OPEN_ITEM_MATERIAL)) { rows = 6; // Defaults to 6 rows.
try { errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a the number of rows set, it will have 6 rows by default.");
ItemStackReader itemReader = new ItemStackReader(config.getString(Nodes.OPEN_ITEM_MATERIAL), false); }
menuData.setBoundMaterial(itemReader.getMaterial());
MenuData menuData = new MenuData(title, rows);
if (itemReader.hasExplicitDataValue()) {
menuData.setBoundDataValue(itemReader.getDataValue()); if (config.isSet(Nodes.MENU_COMMAND)) {
} menuData.setCommands(config.getString(Nodes.MENU_COMMAND).replace(" ", "").split(";"));
} catch (FormatException e) { }
errorLogger.addError("The item \""+ config.getString(Nodes.OPEN_ITEM_MATERIAL) + "\" used to open the menu \"" + config.getFileName() + "\" is invalid: " + e.getMessage());
} if (config.isSet(Nodes.OPEN_ACTION)) {
menuData.setOpenActions(CommandSerializer.readCommands(config.getString(Nodes.OPEN_ACTION)));
boolean leftClick = config.getBoolean(Nodes.OPEN_ITEM_LEFT_CLICK); }
boolean rightClick = config.getBoolean(Nodes.OPEN_ITEM_RIGHT_CLICK);
if (config.isSet(Nodes.OPEN_ITEM_MATERIAL)) {
if (leftClick || rightClick) { try {
menuData.setClickType(ClickType.fromOptions(leftClick, rightClick)); ItemStackReader itemReader = new ItemStackReader(config.getString(Nodes.OPEN_ITEM_MATERIAL), false);
} menuData.setBoundMaterial(itemReader.getMaterial());
}
if (itemReader.hasExplicitDataValue()) {
if (config.isSet(Nodes.AUTO_REFRESH)) { menuData.setBoundDataValue(itemReader.getDataValue());
int tenthsToRefresh = (int) (config.getDouble(Nodes.AUTO_REFRESH) * 10.0); }
if (tenthsToRefresh < 1) { } catch (FormatException e) {
tenthsToRefresh = 1; errorLogger.addError("The item \""+ config.getString(Nodes.OPEN_ITEM_MATERIAL) + "\" used to open the menu \"" + config.getFileName() + "\" is invalid: " + e.getMessage());
} }
menuData.setRefreshTenths(tenthsToRefresh);
} boolean leftClick = config.getBoolean(Nodes.OPEN_ITEM_LEFT_CLICK);
boolean rightClick = config.getBoolean(Nodes.OPEN_ITEM_RIGHT_CLICK);
return menuData;
} if (leftClick || rightClick) {
menuData.setClickType(ClickType.fromOptions(leftClick, rightClick));
} }
}
if (config.isSet(Nodes.AUTO_REFRESH)) {
int tenthsToRefresh = (int) (config.getDouble(Nodes.AUTO_REFRESH) * 10.0);
if (tenthsToRefresh < 1) {
tenthsToRefresh = 1;
}
menuData.setRefreshTenths(tenthsToRefresh);
}
return menuData;
}
}

View File

@ -1,42 +1,56 @@
package com.gmail.filoghost.chestcommands.task; /*
* This program is free software: you can redistribute it and/or modify
import java.util.List; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import org.bukkit.Bukkit; * (at your option) any later version.
import org.bukkit.ChatColor; *
* This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.ChestCommands; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.util.ErrorLogger; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import com.gmail.filoghost.chestcommands.util.Utils; * GNU General Public License for more details.
*
public class ErrorLoggerTask implements Runnable { * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
private ErrorLogger errorLogger; */
package com.gmail.filoghost.chestcommands.task;
public ErrorLoggerTask(ErrorLogger errorLogger) {
this.errorLogger = errorLogger; import java.util.List;
}
import org.bukkit.Bukkit;
@Override import org.bukkit.ChatColor;
public void run() {
import com.gmail.filoghost.chestcommands.ChestCommands;
List<String> lines = Utils.newArrayList(); import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils;
lines.add(" ");
lines.add(ChatColor.RED + "#------------------- Chest Commands Errors -------------------#"); public class ErrorLoggerTask implements Runnable {
int count = 1;
for (String error : errorLogger.getErrors()) { private ErrorLogger errorLogger;
lines.add(ChatColor.GRAY + "" + (count++) + ") " + ChatColor.WHITE + error);
} public ErrorLoggerTask(ErrorLogger errorLogger) {
lines.add(ChatColor.RED + "#-------------------------------------------------------------#"); this.errorLogger = errorLogger;
}
String output = Utils.join(lines, "\n");
@Override
if (ChestCommands.getSettings().use_console_colors) { public void run() {
Bukkit.getConsoleSender().sendMessage(output);
} else { List<String> lines = Utils.newArrayList();
System.out.println(ChatColor.stripColor(output));
} lines.add(" ");
} lines.add(ChatColor.RED + "#------------------- Chest Commands Errors -------------------#");
int count = 1;
} for (String error : errorLogger.getErrors()) {
lines.add(ChatColor.GRAY + "" + (count++) + ") " + ChatColor.WHITE + error);
}
lines.add(ChatColor.RED + "#-------------------------------------------------------------#");
String output = Utils.join(lines, "\n");
if (ChestCommands.getSettings().use_console_colors) {
Bukkit.getConsoleSender().sendMessage(output);
} else {
System.out.println(ChatColor.stripColor(output));
}
}
}

View File

@ -1,29 +1,43 @@
package com.gmail.filoghost.chestcommands.task; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
import com.gmail.filoghost.chestcommands.api.Icon; * (at your option) any later version.
*
public class ExecuteCommandsTask implements Runnable { * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
private Player player; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
private Icon icon; * GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
public ExecuteCommandsTask(Player player, Icon icon) { * along with this program. If not, see <https://www.gnu.org/licenses/>.
this.player = player; */
this.icon = icon; package com.gmail.filoghost.chestcommands.task;
}
import org.bukkit.entity.Player;
@Override import com.gmail.filoghost.chestcommands.api.Icon;
public void run() {
boolean close = icon.onClick(player); public class ExecuteCommandsTask implements Runnable {
if (close) { private Player player;
player.closeInventory(); private Icon icon;
}
}
public ExecuteCommandsTask(Player player, Icon icon) {
this.player = player;
} this.icon = icon;
}
@Override
public void run() {
boolean close = icon.onClick(player);
if (close) {
player.closeInventory();
}
}
}

View File

@ -1,44 +1,58 @@
package com.gmail.filoghost.chestcommands.task; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.entity.Player; * it under the terms of the GNU General Public License as published by
import org.bukkit.inventory.Inventory; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.InventoryView; * (at your option) any later version.
*
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; * This program is distributed in the hope that it will be useful,
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.gmail.filoghost.chestcommands.util.VersionUtils; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class RefreshMenusTask implements Runnable { *
* You should have received a copy of the GNU General Public License
private long elapsedTenths; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
@Override package com.gmail.filoghost.chestcommands.task;
public void run() {
import org.bukkit.entity.Player;
for (Player player : VersionUtils.getOnlinePlayers()) { import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
InventoryView view = player.getOpenInventory();
if (view == null) { import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
return; import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
} import com.gmail.filoghost.chestcommands.util.VersionUtils;
Inventory topInventory = view.getTopInventory(); public class RefreshMenusTask implements Runnable {
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder(); private long elapsedTenths;
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) { @Override
ExtendedIconMenu extMenu = (ExtendedIconMenu) menuHolder.getIconMenu(); public void run() {
if (extMenu.getRefreshTicks() > 0) { for (Player player : VersionUtils.getOnlinePlayers()) {
if (elapsedTenths % extMenu.getRefreshTicks() == 0) {
extMenu.refresh(player, topInventory); InventoryView view = player.getOpenInventory();
} if (view == null) {
} return;
} }
}
} Inventory topInventory = view.getTopInventory();
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
elapsedTenths++; MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
}
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
} ExtendedIconMenu extMenu = (ExtendedIconMenu) menuHolder.getIconMenu();
if (extMenu.getRefreshTicks() > 0) {
if (elapsedTenths % extMenu.getRefreshTicks() == 0) {
extMenu.refresh(player, topInventory);
}
}
}
}
}
elapsedTenths++;
}
}

View File

@ -1,49 +1,63 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import java.util.HashMap; * it under the terms of the GNU General Public License as published by
import java.util.Map; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
public class CaseInsensitiveMap<V> extends HashMap<String, V> { *
* This program is distributed in the hope that it will be useful,
private static final long serialVersionUID = 4712822893326841081L; * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public static <K> CaseInsensitiveMap<K> create() { * GNU General Public License for more details.
return new CaseInsensitiveMap<K>(); *
} * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
@Override */
public V put(String key, V value) { package com.gmail.filoghost.chestcommands.util;
return super.put(key.toLowerCase(), value);
} import java.util.HashMap;
import java.util.Map;
@Override
public V get(Object key) { public class CaseInsensitiveMap<V> extends HashMap<String, V> {
return super.get(key.getClass() == String.class ? key.toString().toLowerCase() : key);
} private static final long serialVersionUID = 4712822893326841081L;
public String getKey(V value) { public static <K> CaseInsensitiveMap<K> create() {
for (java.util.Map.Entry<String, V> entry : entrySet()) { return new CaseInsensitiveMap<K>();
if (entry.getValue().equals(value)) { }
return entry.getKey();
} @Override
} public V put(String key, V value) {
return super.put(key.toLowerCase(), value);
return null; }
}
@Override
@Override public V get(Object key) {
public boolean containsKey(Object key) { return super.get(key.getClass() == String.class ? key.toString().toLowerCase() : key);
return super.containsKey(key.getClass() == String.class ? key.toString().toLowerCase() : key); }
}
public String getKey(V value) {
@Override for (java.util.Map.Entry<String, V> entry : entrySet()) {
public V remove(Object key) { if (entry.getValue().equals(value)) {
return super.remove(key.getClass() == String.class ? key.toString().toLowerCase() : key); return entry.getKey();
} }
}
@Override
public void putAll(Map<? extends String, ? extends V> m) { return null;
throw new UnsupportedOperationException("putAll not supported"); }
}
@Override
} public boolean containsKey(Object key) {
return super.containsKey(key.getClass() == String.class ? key.toString().toLowerCase() : key);
}
@Override
public V remove(Object key) {
return super.remove(key.getClass() == String.class ? key.toString().toLowerCase() : key);
}
@Override
public void putAll(Map<? extends String, ? extends V> m) {
throw new UnsupportedOperationException("putAll not supported");
}
}

View File

@ -1,33 +1,47 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.event.block.Action; * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public enum ClickType { * (at your option) any later version.
*
LEFT, * This program is distributed in the hope that it will be useful,
RIGHT, * but WITHOUT ANY WARRANTY; without even the implied warranty of
BOTH; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public static ClickType fromOptions(boolean left, boolean right) { *
if (left && right) { * You should have received a copy of the GNU General Public License
return BOTH; * along with this program. If not, see <https://www.gnu.org/licenses/>.
} else if (left && !right) { */
return LEFT; package com.gmail.filoghost.chestcommands.util;
} else if (!left && right) {
return RIGHT; import org.bukkit.event.block.Action;
} else {
return null; public enum ClickType {
}
} LEFT,
RIGHT,
public boolean isValidInteract(Action action) { BOTH;
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
return this == LEFT || this == BOTH; public static ClickType fromOptions(boolean left, boolean right) {
} else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { if (left && right) {
return this == RIGHT || this == BOTH; return BOTH;
} else { } else if (left && !right) {
return false; return LEFT;
} } else if (!left && right) {
} return RIGHT;
} else {
} return null;
}
}
public boolean isValidInteract(Action action) {
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
return this == LEFT || this == BOTH;
} else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
return this == RIGHT || this == BOTH;
} else {
return false;
}
}
}

View File

@ -1,29 +1,43 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import java.util.ArrayList; * it under the terms of the GNU General Public License as published by
import java.util.List; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
/** *
* This is a class to collect all the errors found while loading the plugin. * This program is distributed in the hope that it will be useful,
*/ * but WITHOUT ANY WARRANTY; without even the implied warranty of
public class ErrorLogger { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
private List<String> errors = new ArrayList<String>(); *
* You should have received a copy of the GNU General Public License
public void addError(String error) { * along with this program. If not, see <https://www.gnu.org/licenses/>.
errors.add(error); */
} package com.gmail.filoghost.chestcommands.util;
public List<String> getErrors() { import java.util.ArrayList;
return new ArrayList<String>(errors); import java.util.List;
}
/**
public boolean hasErrors() { * This is a class to collect all the errors found while loading the plugin.
return errors.size() > 0; */
} public class ErrorLogger {
public int getSize() { private List<String> errors = new ArrayList<String>();
return errors.size();
} public void addError(String error) {
errors.add(error);
} }
public List<String> getErrors() {
return new ArrayList<String>(errors);
}
public boolean hasErrors() {
return errors.size() > 0;
}
public int getSize() {
return errors.size();
}
}

View File

@ -1,38 +1,52 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Material; * it under the terms of the GNU General Public License as published by
import org.bukkit.entity.Player; * the Free Software Foundation, either version 3 of the License, or
import org.bukkit.inventory.Inventory; * (at your option) any later version.
import org.bukkit.inventory.ItemStack; *
* This program is distributed in the hope that it will be useful,
public class InventoryUtils { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
public static boolean hasInventoryFull(Player player) { * GNU General Public License for more details.
return player.getInventory().firstEmpty() == -1; *
} * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount) { */
int contained = 0; package com.gmail.filoghost.chestcommands.util;
for (ItemStack item : inv.getContents()) { import org.bukkit.Material;
if (item != null && item.getType() == material) { import org.bukkit.entity.Player;
contained += item.getAmount(); import org.bukkit.inventory.Inventory;
} import org.bukkit.inventory.ItemStack;
}
public class InventoryUtils {
return contained >= minAmount;
} public static boolean hasInventoryFull(Player player) {
return player.getInventory().firstEmpty() == -1;
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount, short data) { }
int contained = 0;
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount) {
for (ItemStack item : inv.getContents()) { int contained = 0;
if (item != null && item.getType() == material && item.getDurability() == data) {
contained += item.getAmount(); for (ItemStack item : inv.getContents()) {
} if (item != null && item.getType() == material) {
} contained += item.getAmount();
}
return contained >= minAmount; }
}
return contained >= minAmount;
} }
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount, short data) {
int contained = 0;
for (ItemStack item : inv.getContents()) {
if (item != null && item.getType() == material && item.getDurability() == data) {
contained += item.getAmount();
}
}
return contained >= minAmount;
}
}

View File

@ -1,95 +1,109 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import org.bukkit.Material; * it under the terms of the GNU General Public License as published by
import org.bukkit.inventory.ItemStack; * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
import com.gmail.filoghost.chestcommands.exception.FormatException; *
* This program is distributed in the hope that it will be useful,
public class ItemStackReader { * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
private Material material = Material.STONE; // In the worst case (bad exception handling) we just get stone. * GNU General Public License for more details.
private int amount = 1; *
private short dataValue = 0; * You should have received a copy of the GNU General Public License
private boolean explicitDataValue = false; * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** package com.gmail.filoghost.chestcommands.util;
* Reads item in the format "id:data, amount"
* id can be either the id of the material or its name. import org.bukkit.Material;
* for example wool:5, 3 is a valid input. import org.bukkit.inventory.ItemStack;
*/
public ItemStackReader(String input, boolean parseAmount) throws FormatException { import com.gmail.filoghost.chestcommands.exception.FormatException;
Validate.notNull(input, "input cannot be null");
public class ItemStackReader {
// Remove spaces, they're not needed.
input = StringUtils.stripChars(input, " _-"); private Material material = Material.STONE; // In the worst case (bad exception handling) we just get stone.
private int amount = 1;
if (parseAmount) { private short dataValue = 0;
// Read the optional amount. private boolean explicitDataValue = false;
String[] splitAmount = input.split(",");
/**
if (splitAmount.length > 1) { * Reads item in the format "id:data, amount"
* id can be either the id of the material or its name.
if (!Utils.isValidInteger(splitAmount[1])) { * for example wool:5, 3 is a valid input.
throw new FormatException("invalid amount \"" + splitAmount[1] + "\""); */
} public ItemStackReader(String input, boolean parseAmount) throws FormatException {
Validate.notNull(input, "input cannot be null");
int amount = Integer.parseInt(splitAmount[1]);
if (amount <= 0) throw new FormatException("invalid amount \"" + splitAmount[1] + "\""); // Remove spaces, they're not needed.
this.amount = amount; input = StringUtils.stripChars(input, " _-");
// Only keep the first part as input. if (parseAmount) {
input = splitAmount[0]; // Read the optional amount.
} String[] splitAmount = input.split(",");
}
if (splitAmount.length > 1) {
// Read the optional data value. if (!Utils.isValidInteger(splitAmount[1])) {
String[] splitByColons = input.split(":"); throw new FormatException("invalid amount \"" + splitAmount[1] + "\"");
}
if (splitByColons.length > 1) {
int amount = Integer.parseInt(splitAmount[1]);
if (!Utils.isValidShort(splitByColons[1])) { if (amount <= 0) throw new FormatException("invalid amount \"" + splitAmount[1] + "\"");
throw new FormatException("invalid data value \"" + splitByColons[1] + "\""); this.amount = amount;
}
// Only keep the first part as input.
short dataValue = Short.parseShort(splitByColons[1]); input = splitAmount[0];
if (dataValue < 0) { }
throw new FormatException("invalid data value \"" + splitByColons[1] + "\""); }
}
this.explicitDataValue = true; // Read the optional data value.
this.dataValue = dataValue; String[] splitByColons = input.split(":");
// Only keep the first part as input. if (splitByColons.length > 1) {
input = splitByColons[0];
} if (!Utils.isValidShort(splitByColons[1])) {
throw new FormatException("invalid data value \"" + splitByColons[1] + "\"");
Material material = Utils.matchMaterial(input); }
if (material == null || material == Material.AIR) { short dataValue = Short.parseShort(splitByColons[1]);
throw new FormatException("invalid material \"" + input + "\""); if (dataValue < 0) {
} throw new FormatException("invalid data value \"" + splitByColons[1] + "\"");
this.material = material; }
}
this.explicitDataValue = true;
public Material getMaterial() { this.dataValue = dataValue;
return material;
} // Only keep the first part as input.
input = splitByColons[0];
public int getAmount() { }
return amount;
} Material material = Utils.matchMaterial(input);
public short getDataValue() { if (material == null || material == Material.AIR) {
return dataValue; throw new FormatException("invalid material \"" + input + "\"");
} }
this.material = material;
public boolean hasExplicitDataValue() { }
return explicitDataValue;
} public Material getMaterial() {
return material;
public ItemStack createStack() { }
return new ItemStack(material, amount, dataValue);
} public int getAmount() {
return amount;
} }
public short getDataValue() {
return dataValue;
}
public boolean hasExplicitDataValue() {
return explicitDataValue;
}
public ItemStack createStack() {
return new ItemStack(material, amount, dataValue);
}
}

View File

@ -1,88 +1,102 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
public class StringUtils { * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public static String stripChars(String input, String removed) { * (at your option) any later version.
if (removed == null || removed.isEmpty()) { *
return input; * 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
return stripChars(input, removed.toCharArray()); * GNU General Public License for more details.
} *
* You should have received a copy of the GNU General Public License
// Removes the first slash, and returns the all the chars until a space is encontered. * along with this program. If not, see <https://www.gnu.org/licenses/>.
public static String getCleanCommand(String message) { */
char[] chars = message.toCharArray(); package com.gmail.filoghost.chestcommands.util;
if (chars.length <= 1) { public class StringUtils {
return "";
} public static String stripChars(String input, String removed) {
if (removed == null || removed.isEmpty()) {
int pos = 0; return input;
for (int i = 1; i < chars.length; i++) { }
if (chars[i] == ' ') {
break; return stripChars(input, removed.toCharArray());
} }
chars[(pos++)] = chars[i]; // Removes the first slash, and returns the all the chars until a space is encontered.
} public static String getCleanCommand(String message) {
char[] chars = message.toCharArray();
return new String(chars, 0, pos);
} if (chars.length <= 1) {
return "";
public static String stripChars(String input, char... removed) { }
if (input == null || input.isEmpty() || removed.length == 0) {
return input; int pos = 0;
} for (int i = 1; i < chars.length; i++) {
if (chars[i] == ' ') {
char[] chars = input.toCharArray(); break;
}
int pos = 0;
for (int i = 0; i < chars.length; i++) { chars[(pos++)] = chars[i];
if (!arrayContains(removed, chars[i])) { }
chars[(pos++)] = chars[i];
} return new String(chars, 0, pos);
} }
return new String(chars, 0, pos); public static String stripChars(String input, char... removed) {
} if (input == null || input.isEmpty() || removed.length == 0) {
return input;
private static boolean arrayContains(char[] arr, char match) { }
for (char c : arr) {
if (c == match) { char[] chars = input.toCharArray();
return true;
} int pos = 0;
} for (int i = 0; i < chars.length; i++) {
if (!arrayContains(removed, chars[i])) {
return false; chars[(pos++)] = chars[i];
} }
}
public static String capitalizeFully(String input) {
if (input == null) return null; return new String(chars, 0, pos);
}
String s = input.toLowerCase();
private static boolean arrayContains(char[] arr, char match) {
int strLen = s.length(); for (char c : arr) {
StringBuffer buffer = new StringBuffer(strLen); if (c == match) {
boolean capitalizeNext = true; return true;
for (int i = 0; i < strLen; i++) { }
char ch = s.charAt(i); }
if (Character.isWhitespace(ch)) { return false;
buffer.append(ch); }
capitalizeNext = true;
} else if (capitalizeNext) { public static String capitalizeFully(String input) {
buffer.append(Character.toTitleCase(ch)); if (input == null) return null;
capitalizeNext = false;
} else { String s = input.toLowerCase();
buffer.append(ch);
} int strLen = s.length();
} StringBuffer buffer = new StringBuffer(strLen);
return buffer.toString(); boolean capitalizeNext = true;
} for (int i = 0; i < strLen; i++) {
char ch = s.charAt(i);
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty(); if (Character.isWhitespace(ch)) {
} buffer.append(ch);
capitalizeNext = true;
} } else if (capitalizeNext) {
buffer.append(Character.toTitleCase(ch));
capitalizeNext = false;
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
}

View File

@ -1,345 +1,359 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import java.io.BufferedReader; * it under the terms of the GNU General Public License as published by
import java.io.File; * the Free Software Foundation, either version 3 of the License, or
import java.io.FileNotFoundException; * (at your option) any later version.
import java.io.FileReader; *
import java.io.IOException; * This program is distributed in the hope that it will be useful,
import java.text.DecimalFormat; * but WITHOUT ANY WARRANTY; without even the implied warranty of
import java.util.ArrayList; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import java.util.HashMap; * GNU General Public License for more details.
import java.util.HashSet; *
import java.util.Iterator; * You should have received a copy of the GNU General Public License
import java.util.List; * along with this program. If not, see <https://www.gnu.org/licenses/>.
import java.util.Map; */
import java.util.Map.Entry; package com.gmail.filoghost.chestcommands.util;
import java.util.Set;
import java.io.BufferedReader;
import org.bukkit.Bukkit; import java.io.File;
import org.bukkit.ChatColor; import java.io.FileNotFoundException;
import org.bukkit.Color; import java.io.FileReader;
import org.bukkit.Material; import java.io.IOException;
import org.bukkit.Sound; import java.text.DecimalFormat;
import org.bukkit.entity.Player; import java.util.ArrayList;
import org.bukkit.inventory.Inventory; import java.util.HashMap;
import org.bukkit.inventory.InventoryView; import java.util.HashSet;
import org.bukkit.plugin.Plugin; import java.util.Iterator;
import java.util.List;
import com.gmail.filoghost.chestcommands.ChestCommands; import java.util.Map;
import com.gmail.filoghost.chestcommands.exception.FormatException; import java.util.Map.Entry;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu; import java.util.Set;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import org.bukkit.Bukkit;
public class Utils { import org.bukkit.ChatColor;
import org.bukkit.Color;
// Default material names are ugly. import org.bukkit.Material;
private static Map<String, Material> materialMap = newHashMap(); import org.bukkit.Sound;
import org.bukkit.entity.Player;
static { import org.bukkit.inventory.Inventory;
for (Material mat : Material.values()) { import org.bukkit.inventory.InventoryView;
materialMap.put(StringUtils.stripChars(mat.toString(), "_").toLowerCase(), mat); import org.bukkit.plugin.Plugin;
}
import com.gmail.filoghost.chestcommands.ChestCommands;
Map<String, Material> tempMap = newHashMap(); import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
tempMap.put("iron bar", Material.IRON_FENCE); import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
tempMap.put("iron bars", Material.IRON_FENCE);
tempMap.put("glass pane", Material.THIN_GLASS); public class Utils {
tempMap.put("nether wart", Material.NETHER_STALK);
tempMap.put("nether warts", Material.NETHER_STALK); // Default material names are ugly.
tempMap.put("slab", Material.STEP); private static Map<String, Material> materialMap = newHashMap();
tempMap.put("double slab", Material.DOUBLE_STEP);
tempMap.put("stone brick", Material.SMOOTH_BRICK); static {
tempMap.put("stone bricks", Material.SMOOTH_BRICK); for (Material mat : Material.values()) {
tempMap.put("stone stair", Material.SMOOTH_STAIRS); materialMap.put(StringUtils.stripChars(mat.toString(), "_").toLowerCase(), mat);
tempMap.put("stone stairs", Material.SMOOTH_STAIRS); }
tempMap.put("potato", Material.POTATO_ITEM);
tempMap.put("carrot", Material.CARROT_ITEM); Map<String, Material> tempMap = newHashMap();
tempMap.put("brewing stand", Material.BREWING_STAND_ITEM);
tempMap.put("cauldron", Material.CAULDRON_ITEM); tempMap.put("iron bar", Material.IRON_FENCE);
tempMap.put("carrot on stick", Material.CARROT_STICK); tempMap.put("iron bars", Material.IRON_FENCE);
tempMap.put("carrot on a stick", Material.CARROT_STICK); tempMap.put("glass pane", Material.THIN_GLASS);
tempMap.put("cobblestone wall", Material.COBBLE_WALL); tempMap.put("nether wart", Material.NETHER_STALK);
// tempMap.put("acacia wood stairs", Material.ACACIA_STAIRS); tempMap.put("nether warts", Material.NETHER_STALK);
// tempMap.put("dark oak wood stairs", Material.DARK_OAK_STAIRS); tempMap.put("slab", Material.STEP);
tempMap.put("wood slab", Material.WOOD_STEP); tempMap.put("double slab", Material.DOUBLE_STEP);
tempMap.put("double wood slab", Material.WOOD_DOUBLE_STEP); tempMap.put("stone brick", Material.SMOOTH_BRICK);
tempMap.put("repeater", Material.DIODE); tempMap.put("stone bricks", Material.SMOOTH_BRICK);
tempMap.put("piston", Material.PISTON_BASE); tempMap.put("stone stair", Material.SMOOTH_STAIRS);
tempMap.put("sticky piston", Material.PISTON_STICKY_BASE); tempMap.put("stone stairs", Material.SMOOTH_STAIRS);
tempMap.put("flower pot", Material.FLOWER_POT_ITEM); tempMap.put("potato", Material.POTATO_ITEM);
tempMap.put("wood showel", Material.WOOD_SPADE); tempMap.put("carrot", Material.CARROT_ITEM);
tempMap.put("stone showel", Material.STONE_SPADE); tempMap.put("brewing stand", Material.BREWING_STAND_ITEM);
tempMap.put("gold showel", Material.GOLD_SPADE); tempMap.put("cauldron", Material.CAULDRON_ITEM);
tempMap.put("iron showel", Material.IRON_SPADE); tempMap.put("carrot on stick", Material.CARROT_STICK);
tempMap.put("diamond showel", Material.DIAMOND_SPADE); tempMap.put("carrot on a stick", Material.CARROT_STICK);
tempMap.put("steak", Material.COOKED_BEEF); tempMap.put("cobblestone wall", Material.COBBLE_WALL);
tempMap.put("cooked porkchop", Material.GRILLED_PORK); // tempMap.put("acacia wood stairs", Material.ACACIA_STAIRS);
tempMap.put("raw porkchop", Material.PORK); // tempMap.put("dark oak wood stairs", Material.DARK_OAK_STAIRS);
tempMap.put("hardened clay", Material.HARD_CLAY); tempMap.put("wood slab", Material.WOOD_STEP);
tempMap.put("huge brown mushroom", Material.HUGE_MUSHROOM_1); tempMap.put("double wood slab", Material.WOOD_DOUBLE_STEP);
tempMap.put("huge red mushroom", Material.HUGE_MUSHROOM_2); tempMap.put("repeater", Material.DIODE);
tempMap.put("mycelium", Material.MYCEL); tempMap.put("piston", Material.PISTON_BASE);
tempMap.put("poppy", Material.RED_ROSE); tempMap.put("sticky piston", Material.PISTON_STICKY_BASE);
tempMap.put("comparator", Material.REDSTONE_COMPARATOR); tempMap.put("flower pot", Material.FLOWER_POT_ITEM);
tempMap.put("skull", Material.SKULL_ITEM); tempMap.put("wood showel", Material.WOOD_SPADE);
tempMap.put("head", Material.SKULL_ITEM); tempMap.put("stone showel", Material.STONE_SPADE);
tempMap.put("redstone torch", Material.REDSTONE_TORCH_ON); tempMap.put("gold showel", Material.GOLD_SPADE);
tempMap.put("redstone lamp", Material.REDSTONE_LAMP_OFF); tempMap.put("iron showel", Material.IRON_SPADE);
tempMap.put("glistering melon", Material.SPECKLED_MELON); tempMap.put("diamond showel", Material.DIAMOND_SPADE);
// tempMap.put("acacia leaves", Material.LEAVES_2); It wouldn't work with 1.6 :/ tempMap.put("steak", Material.COOKED_BEEF);
// tempMap.put("acacia log", Material.LOG_2); tempMap.put("cooked porkchop", Material.GRILLED_PORK);
tempMap.put("gunpowder", Material.SULPHUR); tempMap.put("raw porkchop", Material.PORK);
tempMap.put("lilypad", Material.WATER_LILY); tempMap.put("hardened clay", Material.HARD_CLAY);
tempMap.put("command block", Material.COMMAND); tempMap.put("huge brown mushroom", Material.HUGE_MUSHROOM_1);
tempMap.put("dye", Material.INK_SACK); tempMap.put("huge red mushroom", Material.HUGE_MUSHROOM_2);
tempMap.put("mycelium", Material.MYCEL);
for (Entry<String, Material> tempEntry : tempMap.entrySet()) { tempMap.put("poppy", Material.RED_ROSE);
materialMap.put(StringUtils.stripChars(tempEntry.getKey(), " _-").toLowerCase(), tempEntry.getValue()); tempMap.put("comparator", Material.REDSTONE_COMPARATOR);
} tempMap.put("skull", Material.SKULL_ITEM);
} tempMap.put("head", Material.SKULL_ITEM);
tempMap.put("redstone torch", Material.REDSTONE_TORCH_ON);
private static String bukkitVersion; tempMap.put("redstone lamp", Material.REDSTONE_LAMP_OFF);
tempMap.put("glistering melon", Material.SPECKLED_MELON);
public static String getBukkitVersion() { // tempMap.put("acacia leaves", Material.LEAVES_2); It wouldn't work with 1.6 :/
if (bukkitVersion == null) { // tempMap.put("acacia log", Material.LOG_2);
String packageName = Bukkit.getServer().getClass().getPackage().getName(); tempMap.put("gunpowder", Material.SULPHUR);
bukkitVersion = packageName.substring(packageName.lastIndexOf('.') + 1); tempMap.put("lilypad", Material.WATER_LILY);
} tempMap.put("command block", Material.COMMAND);
tempMap.put("dye", Material.INK_SACK);
return bukkitVersion;
} for (Entry<String, Material> tempEntry : tempMap.entrySet()) {
materialMap.put(StringUtils.stripChars(tempEntry.getKey(), " _-").toLowerCase(), tempEntry.getValue());
public static String colorizeName(String input) { }
if (input == null || input.isEmpty()) return input; }
if (input.charAt(0) != ChatColor.COLOR_CHAR) { private static String bukkitVersion;
return ChestCommands.getSettings().default_color__name + addColors(input);
} else { public static String getBukkitVersion() {
return addColors(input); if (bukkitVersion == null) {
} String packageName = Bukkit.getServer().getClass().getPackage().getName();
} bukkitVersion = packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static List<String> colorizeLore(List<String> input) {
if (input == null || input.isEmpty()) return input; return bukkitVersion;
}
for (int i = 0; i < input.size(); i++) {
public static String colorizeName(String input) {
String line = input.get(i); if (input == null || input.isEmpty()) return input;
if (line.isEmpty()) continue; if (input.charAt(0) != ChatColor.COLOR_CHAR) {
return ChestCommands.getSettings().default_color__name + addColors(input);
if (line.charAt(0) != ChatColor.COLOR_CHAR) { } else {
input.set(i, ChestCommands.getSettings().default_color__lore + addColors(line)); return addColors(input);
} else { }
input.set(i, addColors(line)); }
}
} public static List<String> colorizeLore(List<String> input) {
return input; if (input == null || input.isEmpty()) return input;
}
for (int i = 0; i < input.size(); i++) {
public static void refreshMenu(Player player) {
InventoryView view = player.getOpenInventory(); String line = input.get(i);
if (view != null) {
Inventory topInventory = view.getTopInventory(); if (line.isEmpty()) continue;
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder(); if (line.charAt(0) != ChatColor.COLOR_CHAR) {
input.set(i, ChestCommands.getSettings().default_color__lore + addColors(line));
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) { } else {
((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory); input.set(i, addColors(line));
} }
} }
} return input;
} }
public static String addColors(String input) { public static void refreshMenu(Player player) {
if (input == null || input.isEmpty()) return input; InventoryView view = player.getOpenInventory();
return ChatColor.translateAlternateColorCodes('&', input); if (view != null) {
} Inventory topInventory = view.getTopInventory();
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
public static List<String> addColors(List<String> input) { MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (input == null || input.isEmpty()) return input;
for (int i = 0; i < input.size(); i++) { if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
input.set(i, addColors(input.get(i))); ((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory);
} }
return input; }
} }
}
public static String addYamlExtension(String input) {
if (input == null) return null; public static String addColors(String input) {
return input.toLowerCase().endsWith(".yml") ? input : input + ".yml"; if (input == null || input.isEmpty()) return input;
} return ChatColor.translateAlternateColorCodes('&', input);
}
private static DecimalFormat decimalFormat = new DecimalFormat("0.##");
public static String decimalFormat(double number) { public static List<String> addColors(List<String> input) {
return decimalFormat.format(number); if (input == null || input.isEmpty()) return input;
} for (int i = 0; i < input.size(); i++) {
input.set(i, addColors(input.get(i)));
@SuppressWarnings("deprecation") }
public static Material matchMaterial(String input) { return input;
if (input == null) return null; }
input = StringUtils.stripChars(input.toLowerCase(), " _-"); public static String addYamlExtension(String input) {
if (input == null) return null;
if (isValidInteger(input)) { return input.toLowerCase().endsWith(".yml") ? input : input + ".yml";
return Material.getMaterial(Integer.parseInt(input)); }
}
private static DecimalFormat decimalFormat = new DecimalFormat("0.##");
return materialMap.get(input); public static String decimalFormat(double number) {
} return decimalFormat.format(number);
}
public static Sound matchSound(String input) {
if (input == null) return null; @SuppressWarnings("deprecation")
public static Material matchMaterial(String input) {
input = StringUtils.stripChars(input.toLowerCase(), " _-"); if (input == null) return null;
for (Sound sound : Sound.values()) { input = StringUtils.stripChars(input.toLowerCase(), " _-");
if (StringUtils.stripChars(sound.toString().toLowerCase(), "_").equals(input)) return sound;
} if (isValidInteger(input)) {
return null; return Material.getMaterial(Integer.parseInt(input));
} }
public static String formatMaterial(Material material) { return materialMap.get(input);
return StringUtils.capitalizeFully(material.toString().replace("_", " ")); }
}
public static Sound matchSound(String input) {
public static int makePositive(int i) { if (input == null) return null;
return i < 0 ? 0 : i;
} input = StringUtils.stripChars(input.toLowerCase(), " _-");
public static boolean isValidInteger(String input) { for (Sound sound : Sound.values()) {
try { if (StringUtils.stripChars(sound.toString().toLowerCase(), "_").equals(input)) return sound;
Integer.parseInt(input); }
return true; return null;
} catch (NumberFormatException ex) { }
return false;
} public static String formatMaterial(Material material) {
} return StringUtils.capitalizeFully(material.toString().replace("_", " "));
}
public static boolean isValidPositiveInteger(String input) {
try { public static int makePositive(int i) {
return Integer.parseInt(input) > 0; return i < 0 ? 0 : i;
} catch (NumberFormatException ex) { }
return false;
} public static boolean isValidInteger(String input) {
} try {
Integer.parseInt(input);
public static boolean isValidShort(String input) { return true;
try { } catch (NumberFormatException ex) {
Short.parseShort(input); return false;
return true; }
} catch (NumberFormatException ex) { }
return false;
} public static boolean isValidPositiveInteger(String input) {
} try {
return Integer.parseInt(input) > 0;
public static boolean isValidPositiveDouble(String input) { } catch (NumberFormatException ex) {
try { return false;
return Double.parseDouble(input) > 0.0; }
} catch (NumberFormatException ex) { }
return false;
} public static boolean isValidShort(String input) {
} try {
Short.parseShort(input);
public static List<String> readLines(File file) throws IOException, Exception { return true;
BufferedReader br = null; } catch (NumberFormatException ex) {
return false;
try { }
List<String> lines = newArrayList(); }
if (!file.exists()) { public static boolean isValidPositiveDouble(String input) {
throw new FileNotFoundException(); try {
} return Double.parseDouble(input) > 0.0;
} catch (NumberFormatException ex) {
br = new BufferedReader(new FileReader(file)); return false;
String line = br.readLine(); }
}
while (line != null) {
lines.add(line); public static List<String> readLines(File file) throws IOException, Exception {
line = br.readLine(); BufferedReader br = null;
}
try {
return lines; List<String> lines = newArrayList();
} finally {
if (br != null) { if (!file.exists()) {
try { throw new FileNotFoundException();
br.close(); }
} catch (IOException e) {
} br = new BufferedReader(new FileReader(file));
} String line = br.readLine();
}
} while (line != null) {
lines.add(line);
public static Color parseColor(String input) throws FormatException { line = br.readLine();
String[] split = StringUtils.stripChars(input, " ").split(","); }
if (split.length != 3) { return lines;
throw new FormatException("it must be in the format \"red, green, blue\"."); } finally {
} if (br != null) {
try {
int red, green, blue; br.close();
} catch (IOException e) {
try { }
red = Integer.parseInt(split[0]); }
green = Integer.parseInt(split[1]); }
blue = Integer.parseInt(split[2]); }
} catch (NumberFormatException ex) {
throw new FormatException("it contains invalid numbers."); public static Color parseColor(String input) throws FormatException {
} String[] split = StringUtils.stripChars(input, " ").split(",");
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { if (split.length != 3) {
throw new FormatException("it should only contain numbers between 0 and 255."); throw new FormatException("it must be in the format \"red, green, blue\".");
} }
return Color.fromRGB(red, green, blue); int red, green, blue;
}
try {
red = Integer.parseInt(split[0]);
public static void saveResourceSafe(Plugin plugin, String name) { green = Integer.parseInt(split[1]);
try { blue = Integer.parseInt(split[2]);
plugin.saveResource(name, false); } catch (NumberFormatException ex) {
} catch (Exception ex) { throw new FormatException("it contains invalid numbers.");
// Shhh... }
}
} if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) {
throw new FormatException("it should only contain numbers between 0 and 255.");
public static <T> Set<T> newHashSet() { }
return new HashSet<T>();
} return Color.fromRGB(red, green, blue);
}
public static <T, V> Map<T, V> newHashMap() {
return new HashMap<T, V>();
} public static void saveResourceSafe(Plugin plugin, String name) {
try {
public static <T> List<T> newArrayList() { plugin.saveResource(name, false);
return new ArrayList<T>(); } catch (Exception ex) {
} // Shhh...
}
public static String join(Iterable<?> iterable, String separator) { }
StringBuilder builder = new StringBuilder();
Iterator<?> iter = iterable.iterator(); public static <T> Set<T> newHashSet() {
return new HashSet<T>();
boolean first = true; }
while (iter.hasNext()) { public static <T, V> Map<T, V> newHashMap() {
if (first) { return new HashMap<T, V>();
first = false; }
} else {
builder.append(separator); public static <T> List<T> newArrayList() {
} return new ArrayList<T>();
}
builder.append(iter.next());
} public static String join(Iterable<?> iterable, String separator) {
StringBuilder builder = new StringBuilder();
return builder.toString(); Iterator<?> iter = iterable.iterator();
}
boolean first = true;
public static boolean isClassLoaded(String name) {
try { while (iter.hasNext()) {
Class.forName(name); if (first) {
return true; first = false;
} catch (Exception e) { } else {
return false; builder.append(separator);
} }
}
} builder.append(iter.next());
}
return builder.toString();
}
public static boolean isClassLoaded(String name) {
try {
Class.forName(name);
return true;
} catch (Exception e) {
return false;
}
}
}

View File

@ -1,23 +1,37 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
public class Validate { * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
public static void notNull(Object object, String error) { * (at your option) any later version.
if (object == null) { *
throw new NullPointerException(error); * 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.
public static void isTrue(boolean statement, String error) { *
if (!statement) { * You should have received a copy of the GNU General Public License
throw new IllegalArgumentException(error); * along with this program. If not, see <https://www.gnu.org/licenses/>.
} */
} package com.gmail.filoghost.chestcommands.util;
public static void isFalse(boolean statement, String error) { public class Validate {
if (statement) {
throw new IllegalArgumentException(error); public static void notNull(Object object, String error) {
} if (object == null) {
} throw new NullPointerException(error);
}
} }
public static void isTrue(boolean statement, String error) {
if (!statement) {
throw new IllegalArgumentException(error);
}
}
public static void isFalse(boolean statement, String error) {
if (statement) {
throw new IllegalArgumentException(error);
}
}
}

View File

@ -1,41 +1,55 @@
package com.gmail.filoghost.chestcommands.util; /*
* This program is free software: you can redistribute it and/or modify
import java.lang.reflect.Method; * it under the terms of the GNU General Public License as published by
import java.util.Collection; * the Free Software Foundation, either version 3 of the License, or
import java.util.Collections; * (at your option) any later version.
import org.bukkit.Bukkit; *
import org.bukkit.entity.Player; * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
import com.google.common.collect.ImmutableList; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public class VersionUtils { *
* You should have received a copy of the GNU General Public License
private static boolean setup; * along with this program. If not, see <https://www.gnu.org/licenses/>.
private static Method oldGetOnlinePlayersMethod; */
private static boolean useReflection; package com.gmail.filoghost.chestcommands.util;
public static Collection<? extends Player> getOnlinePlayers() { import java.lang.reflect.Method;
try { import java.util.Collection;
import java.util.Collections;
if (!setup) { import org.bukkit.Bukkit;
oldGetOnlinePlayersMethod = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); import org.bukkit.entity.Player;
if (oldGetOnlinePlayersMethod.getReturnType() == Player[].class) {
useReflection = true; import com.google.common.collect.ImmutableList;
}
public class VersionUtils {
setup = true;
} private static boolean setup;
private static Method oldGetOnlinePlayersMethod;
if (!useReflection) { private static boolean useReflection;
return Bukkit.getOnlinePlayers();
} else { public static Collection<? extends Player> getOnlinePlayers() {
Player[] playersArray = (Player[]) oldGetOnlinePlayersMethod.invoke(null); try {
return ImmutableList.copyOf(playersArray);
} if (!setup) {
oldGetOnlinePlayersMethod = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
} catch (Exception e) { if (oldGetOnlinePlayersMethod.getReturnType() == Player[].class) {
e.printStackTrace(); useReflection = true;
return Collections.emptyList(); }
}
} setup = true;
} }
if (!useReflection) {
return Bukkit.getOnlinePlayers();
} else {
Player[] playersArray = (Player[]) oldGetOnlinePlayersMethod.invoke(null);
return ImmutableList.copyOf(playersArray);
}
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}