Merge pull request #3 from Bkm016/dev

有生之年.jpg
This commit is contained in:
坏黑 2018-05-12 23:37:03 +08:00 committed by GitHub
commit 5ba8e2050d
329 changed files with 21504 additions and 14101 deletions

3
.gitignore vendored
View File

@ -19,3 +19,6 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.gradle/4.3.1/
.idea
target

View File

@ -1,2 +0,0 @@
#Sat Mar 10 18:07:09 CST 2018
gradle.version=4.5

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel>
<module name="TabooLib_main" target="1.8" />
<module name="TabooLib_test" target="1.8" />
</bytecodeTargetLevel>
</component>
</project>

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="C:/gradle-4.3.1" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
<option name="useAutoImport" value="true" />
</GradleProjectSettings>
</option>
</component>
</project>

View File

@ -1,36 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="author,author" />
</inspection_tool>
</profile>
</component>

View File

@ -1,148 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="TabooLib:main" external.linked.project.path="$MODULE_DIR$/../.." external.root.project.path="$MODULE_DIR$/../.." external.system.id="GRADLE" external.system.module.group="" external.system.module.type="sourceSet" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>SPIGOT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/../../out/production/classes" />
<exclude-output />
<content url="file://$MODULE_DIR$/../../src/main">
<sourceFolder url="file://$MODULE_DIR$/../../src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/../../src/main/resources" type="java-resource" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_10_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_11_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_12_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_8_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_9_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/com.sun.tools.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/lombok.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/PlaceholderAPI.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/ProtocolLib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Skript.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/TabooCode5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Vault.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/WorldGuard.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Yum.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@ -1,150 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="TabooLib:test" external.linked.project.path="$MODULE_DIR$/../.." external.root.project.path="$MODULE_DIR$/../.." external.system.id="GRADLE" external.system.module.group="" external.system.module.type="sourceSet" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>SPIGOT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output-test url="file://$MODULE_DIR$/../../out/test/classes" />
<exclude-output />
<content url="file://$MODULE_DIR$/../../src/test">
<sourceFolder url="file://$MODULE_DIR$/../../src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/../../src/test/resources" type="java-test-resource" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="TabooLib_main" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_10_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_11_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_12_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_8_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/1_9_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/com.sun.tools.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/lombok.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/PlaceholderAPI.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/ProtocolLib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Skript.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/TabooCode5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Vault.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/WorldGuard.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../libs/Yum.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
<component name="TestModuleProperties" production-module="TabooLib_main" />
</module>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -1,2 +0,0 @@
#Sat Mar 10 18:07:18 CST 2018
connection.project.dir=

View File

@ -1,3 +0,0 @@
eclipse.preferences.version=1
encoding//src/main/java/me/skymc/taboolib/javashell/JavaShell.java=UTF-8
encoding/<project>=UTF-8

695
LICENSE
View File

@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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) 2018 {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 <http://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:
TabooLib Copyright (C) 2018 坏黑
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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
MIT License
Copyright (c) 2018 Bkm016
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,11 +1,17 @@
# TabooLib
> 开发工具库
[TabooLib 文档](https://bkm016.github.io/TabooLib/#/)
---
**3.56** 版本开始 `com.sun.tools.jar` 不再和插件一起发布。
如果需要启用 *JavaShell* 功能请将 [com.sun.tools.jar](http://skymc.oss-cn-shanghai.aliyuncs.com/plugins/com.sun.tools.jar) 放入 *"TabooLib/JavaShell/lib"* 文件夹中。  
如果需要启用 *JavaShell* 功能请将 [com.sun.tools.jar](http://skymc.oss-cn-shanghai.aliyuncs.com/plugins/com.sun.tools.jar) 放入 *"TabooLib/JavaShell/lib"* 文件夹中。
---
暂时停更,等待 dev 分支测试完成后合并。2018-4-7
感谢海螺(@IzzelAliz大佬的指导和更新。
**3.832** 以后的版本的开源协议更改为 MIT License3.832 及以前的版本维持 GPLv3 协议。
## 构建
```
mvn clean install package
```

115
TabooLib.iml Normal file
View File

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/ProtocolLib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.1.0" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: org.javalite:activejdbc:2.0" level="project" />
<orderEntry type="library" name="Maven: org.javalite:javalite-common:2.0" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-core-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-mapper-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.javalite:app-config:2.0" level="project" />
<orderEntry type="library" name="Maven: com.h2database:h2:1.4.197" level="project" />
<orderEntry type="library" name="Maven: com.ilummc.eagletdl:EagletCore:1.1.2" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:6.1.1" level="project" />
<orderEntry type="library" name="Maven: me.clip:placeholderapi:2.8.4" level="project" />
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_12:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_12_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_8:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_8_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: com.sun.tools:jshell:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/com.sun.tools.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: taboocode:taboocode:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/TabooCode5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: yum:yum:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/Yum.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: plib:plib:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/ProtocolLib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: wg:wg:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/WorldGuard.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: sk:sk:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/Skript.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: vault:vault:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/Vault.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@ -1,39 +0,0 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* user guide available at https://docs.gradle.org/4.5/userguide/java_library_plugin.html
*/
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
sourceCompatibility = targetCompatibility = "1.8" // Need this here so eclipse task generates correctly.
compileJava {
sourceCompatibility = targetCompatibility = "1.8"
}
processResources {
from('resources') {
include '**'
}
}
dependencies {
// Library
compile fileTree(dir:'libs', include:['*.jar'])
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}

View File

@ -1,13 +1,61 @@
# TabooLib
> 开发工具库
> Bukkit 开发工具库
[![](http://ci.pcd.ac.cn/job/TabooLibDev/badge/icon)](http://ci.pcd.ac.cn/job/TabooLibDev)
[![](https://img.shields.io/github/downloads/Bkm016/TabooLib/total.svg)](https://github.com/Bkm016/TabooLib/releases)
[![](https://img.shields.io/github/release/Bkm016/TabooLib.svg)](https://github.com/Bkm016/TabooLib/tags)
[![](https://img.shields.io/github/stars/Bkm016/TabooLib.svg?style=flat-square&label=Stars)](https://github.com/Bkm016/TabooLib)
[![](https://jitpack.io/v/Bkm016/TabooLib.svg)](https://jitpack.io/#Bkm016/TabooLib)
## 目录
* [TLocale](tlocale.md)
## 添加 TabooLib 为库
### Maven
```xml
<build>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependency>
<groupId>com.github.Bkm016</groupId>
<artifactId>TabooLib</artifactId>
<version>JitPack版本</version>
</dependency>
</build>
```
### Gradle
```groovy
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
compile 'com.github.Bkm016:TabooLib:JitPack版本'
}
```
### sbt
```scala
resolvers += "jitpack" at "https://jitpack.io"
libraryDependencies += "com.github.Bkm016" % "TabooLib" % "JitPack版本"
```
在添加依赖后,你还需要在 `plugin.yml` 中添加 `softdepend` 或者 `depend` 才能享受到 TabooLib 的全部功能。
---
**3.56** 版本开始 `com.sun.tools.jar` 不再和插件一起发布。
如果需要启用 *JavaShell* 功能请将 [com.sun.tools.jar](http://skymc.oss-cn-shanghai.aliyuncs.com/plugins/com.sun.tools.jar) 放入 *"TabooLib/JavaShell/lib"* 文件夹中。  
---
暂时停更,等待 dev 分支测试完成后合并。2018-4-7
感谢海螺(@IzzelAliz大佬的指导和更新。
**3.832** 版本后开源协议更改为 `MIT`

View File

@ -4,7 +4,7 @@
* TLocale 语言文本 API
* 自动依赖下载
* 注释 * N
* Annotation Development
[GitHub](https://github.com/Bkm016/TabooLib/)
[开始](#目录)

7
docs/_sidebar.md Normal file
View File

@ -0,0 +1,7 @@
* [TabooLib](README.md)
* [TLocale](tlocale.md)
* [TDependency](dependency.md)
* 实用工具 Utilities
* [Ref](ref.md)

40
docs/dependency.md Normal file
View File

@ -0,0 +1,40 @@
# TDependency
几个简单的注解轻松使用第三方库
## 请求一个第三方库
你只需要在你的主类上加上 `@Dependency` 注解。
比如,假如你要用 Scala 或者 Kotlin那么可以
```java
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.scala-lang:scala-library:2.12.6")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.jetbrains.kotlin:kotlin-stdlib:1.2.31")
public class TestMain extends JavaPlugin {
// ...
}
```
然后这些第三方将在 `onEnable` 调用之前可用。如果需要更早可用,你需要在使用任意第三方库之前调用一次 `TDependencyInjector.inject(instance, instance)`
`instance` 为你的插件主类实例。
## 使用自定义仓库的库
`@Dependency` 里加入 `mavenRepo` 即可,如
```java
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.github.Bkm016:TabooLib:dev-SNAPSHOT", mavenRepo = "https://jitpack.io/")
public class TestMain extends JavaPlugin {
// ...
}
```
## 使用指定的 URL 的 jar 文件作为库
```java
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.sun:tools:1.8.0_151", url = "http://skymc.oss-cn-shanghai.aliyuncs.com/plugins/com.sun.tools.jar")
public class TestMain extends JavaPlugin {
// ...
}
```

View File

@ -1,27 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>TabooLib 文档</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css">
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/dark.css" title="dark" disabled>
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/buble.css" title="buble" disabled>
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/pure.css" title="pure" disabled>
</head>
<body>
<div id="app">Loading ...</div>
<script>
<div id="app">Loading ...</div>
<script>
window.$docsify = {
name: '',
repo: '',
auto2top: true,
coverpage: true,
loadSidebar: true,
subMaxLevel: 4,
executeScript: true,
mergeNavbar: true,
search: {
noData: {
'/zh-cn/': '没有结果!',
@ -37,7 +35,7 @@
plugins: [
function (hook, vm) {
hook.beforeEach(function (html) {
var url = 'https://github.com/Bkm016/TabooLib/blob/master/docs/' + vm.route.file
var url = 'https://github.com/Bkm016/TabooLib/blob/master/docs/' + vm.route.file;
return html
+ '\n\n----\n\n'
+ '<a href="https://github.com/Bkm016/TabooLib/" target="_blank" style="color: inherit; font-weight: normal; text-decoration: none;">TabooLib Document</a>'
@ -45,10 +43,14 @@
}
]
}
</script>
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
<script src="//unpkg.com/docsify/lib/plugins/search.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-markdown.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-java.min.js"></script>
</script>
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
<script src="//unpkg.com/docsify/lib/plugins/search.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-markdown.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-java.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-yaml.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-xml.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-groovy.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-scala.min.js"></script>
</body>
</html>

15
docs/ref.md Normal file
View File

@ -0,0 +1,15 @@
`com.ilummc.tlib.util.Ref`
## getDeclaredFields
众所周知(~~啥你竟然不知道~~ `Class#getDeclaredFields` 方法在获取时,如果该类的某个字段的类不在 classpath 里面,那么就会抛出一个 `NoClassDefFoundError` 异常。
而在 Ref 类中的几个 getDeclaredFields 方法解决了这个问题:返回一个 `List<Field>` 实例,只包含在 classpath 中的类。
## getCallerClass
众所周知(~~啥你竟然不知道~~ Oracle 正在对内部包比如 `sun.misc` 这样的包动手脚,并且这些包可能在未来的版本里被删除(我们的 `Unsafe` 已经没了)。
而某个 Reflection 类就很好用,特别是 `Reflection#getCallerClass(int)` 这个方法。于是 Ref 中的 getCallerClass 方法解决了这个问题:通过分析栈调用来获取 caller class并且在 Reflection 这个类还存在的时候用原来的方法调用。
在某个方法中调用 Ref.getCallerClass(3) 会返回调用这个方法的类。

207
docs/tlocale.md Normal file
View File

@ -0,0 +1,207 @@
# TLocale
通过简单的 yml 文件自定义你的所有信息
## 添加一个语言文件
TLocale 的语言文件是自动加载的,你可以在 TabooLib 初始化你的插件完毕后任意的调用来发送,前提是你在 `plugin.yml` 添加了 TabooLib 为 `depend``softdepend`
语言文件应该放在 `/lang/xx_XX.yml`TabooLib 默认会加载 `zh_CN``en_US` 的语言文件。
在添加了语言文件后,你就应该可以使用 `com.ilummc.tlib.resources.TLocale` 类的所有静态方法了。
`/TaabooLib/config.yml` 中有 `LOCALE` 下的几个选项可以设置加载的语言和是否默认启用 PlaceholderAPI
## 发送一条消息
`/lang/zh_CN.yml`
```yaml
TEST: '{0} 加入服务器'
TITLE_TEST:
==: TITLE
title: '&b{0} 加入了服务器'
subtitle: '&a{0} 太强了以至于他还有 subtitle 显示'
```
代码部分
```java
package com.ilummc.tlib;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.player.PlayerJoinEvent;
import com.ilummc.tlib.resources.TLocale;
public class ExampleMain extends JavaPlugin implements Listener {
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
TLocale.sendTo(event.getPlayer(), "TEST", event.getPlayer().getName());
TLocale.sendTo(event.getPlayer(), "TITLE_TEST", event.getPlayer().getName());
}
}
```
## 语言文本格式
TLocale 的语言文本采用 yml 存储,每一个键对应一个或多个值、
以下的格式都是可以的:
```yaml
normal: '一条普通的测试信息'
multiline: |-
多行的测试信息
这是 YAML 表示带有换行符字符串的方法
typeMessage:
==: TITLE
title: 这是带有类型的语言文本
subtitle: 在下方你可以看到所有可用的类型
combinedTypeMessage:
- ==: TEXT
text:
- '这也是一条普通的测试信息'
- '但是他有很多行'
- '还有可替换的文本 {0}'
- ==: ACTION
text: '一条 ActionBar 消息'
- ==: JSON
text:
- '这条消息仍然可以使用 TLocale.sendTo(sender, "combinedTypeMessage") 来发送'
- '玩家会收到一条聊天栏消息'
- '一条 ActionBar 的消息'
- '和一条 JSON 文本,比如<§a§n点击这里就会执行一条命令@cmd>'
args:
cmd:
hover: |-
命令是 /tp ~ ~50 ~
这一条消息展示了 TLocale 的所有特性
command: '/tp ~ ~50 ~'
- '最后,这个消息也能混着普通字符串用'
```
TLocale 可以发送普通的聊天消息和其他复杂的消息,比如 ActionBar 和 Title 消息。
为了方便起见,我们将如下的配置
```yaml
==: 种类
参数1: xxxx
参数2: yyyy
```
称为一个 `语言对象`
每个语言对象可以有以下几种排列方式:
```yaml
文本1: 语言对象
文本2:
- 语言对象
- 语言对象
节点1:
文本3: 语言对象
```
TLocale 的文本都支持替换,如 `{N}` ,替换的文本是 `TLocale` 的方法调用时传入的对应字符串。
!> 因为写这个功能的人是程序员,所以 **N 从 0 开始**
以下内容列举了所有的语言对象种类
### TEXT
`TEXT` 类型代表一条普通的聊天栏文本,有以下几种表示方法:
```yaml
node1: '文本'
node2:
- '文本'
- '文本'
node3:
==: TEXT
text: '文本'
node4:
==: TEXT
text:
- '文本'
- 'Placeholder API 测试 %vault_eco_balance%'
papi: true
```
你可以在任意一个 `TEXT` 中添加 `papi: true` 来启用对 PlaceholderAPI 的支持,如果不添加,默认值为 `/TaabooLib/config.yml` 中的 `LOCALE.USE_PAPI` 设置的值。
所有的选项都是**可选的** 。
### TITLE
`TITLE` 类型代表一条 title 消息,可以含有淡入淡出的时间选项。所有的选项都是**可选的** 。
```yaml
node:
==: TITLE
title: '显示在屏幕正中的 title 文本'
subtitle: 'subtitle 文本'
fadein: 10
fadeout: 10
stay: 20
papi: false
```
### ACTION
`ACTION` 类型代表一条 ActionBar 消息。所有的选项都是**可选的** 。
```yaml
node:
==: ACTION
text: '&6ActionBar &e文本'
papi: false
```
### JSON
`JSON` 类型代表一条可以点击和可以含有悬浮文字的消息。
消息的文本在 `text` 中指定。
可以点击、鼠标停留的文本需要使用 `<可选的文本@参数名称>` 来表示,然后在 `args` 参数中添加你指定的参数名称并添加点击和悬浮的文本。
全部 JSON 的任何地方都可以启用替换功能,包括内置的替换和 PAPI 。
所有的选项都是**可选的** 。
```yaml
node:
==: JSON
text:
- '<点击建议命令@test1>'
- '<点击执行命令@test2>'
- '<鼠标停留查看悬浮字@test3>'
- '<@test4>'
- '<又可以点击又可以悬浮的信息@combined>'
- '替换测试1 {0}'
- '<@test6>'
papi: true
args:
test1:
suggest: '/say 建议执行的命令'
test2:
command: '/say 点击直接执行的命令'
test3:
hover: |-
&6鼠标悬浮显示的文字
&9可以是单行也可以是多行
test4:
text: '你可以在参数中指定显示的文本,比如这一条'
test5:
command: '/say Hello World.'
hover: '点击说一句 &cHello World'
test6:
text: 'JSON 文本也有参数替换的功能,比如 {1}'
hover: |-
悬浮字中也可以替换 {1}
甚至可以加入 PAPI 变量如 %player_name%
command: '点击文本也可以替换,不做演示'
```

Binary file not shown.

View File

@ -1,6 +0,0 @@
#Sat Mar 24 22:41:19 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip

172
gradlew vendored
View File

@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored
View File

@ -1,84 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

160
pom.xml Normal file
View File

@ -0,0 +1,160 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.skymc</groupId>
<artifactId>TabooLib</artifactId>
<version>4.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<defaultGoal>clean install package</defaultGoal>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>com.ilummc.eagletdl</include>
<include>org.ow2.asm</include>
</includes>
</artifactSet>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>placeholderapi</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>activejdbc</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<dependency>
<groupId>com.ilummc.eagletdl</groupId>
<artifactId>EagletCore</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.1.1</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>bukkit</groupId>
<artifactId>bukkit1_12</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/1_12_R1.jar</systemPath>
</dependency>
<dependency>
<groupId>bukkit</groupId>
<artifactId>bukkit1_8</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/1_8_R3.jar</systemPath>
</dependency>
<dependency>
<groupId>com.sun.tools</groupId>
<artifactId>jshell</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/com.sun.tools.jar</systemPath>
</dependency>
<dependency>
<groupId>taboocode</groupId>
<artifactId>taboocode</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/TabooCode5.jar</systemPath>
</dependency>
<dependency>
<groupId>yum</groupId>
<artifactId>yum</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/Yum.jar</systemPath>
</dependency>
<dependency>
<groupId>plib</groupId>
<artifactId>plib</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/ProtocolLib.jar</systemPath>
</dependency>
<dependency>
<groupId>wg</groupId>
<artifactId>wg</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/WorldGuard.jar</systemPath>
</dependency>
<dependency>
<groupId>sk</groupId>
<artifactId>sk</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/Skript.jar</systemPath>
</dependency>
<dependency>
<groupId>vault</groupId>
<artifactId>vault</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/Vault.jar</systemPath>
</dependency>
</dependencies>
</project>

View File

@ -1,12 +0,0 @@
import org.bukkit.*;
public class testshell {
public void onEnable() {
Bukkit.broadcastMessage("testshell enable!");
}
public void onDisable() {
Bukkit.broadcastMessage("testshell disable!");
}
}

View File

@ -1,10 +0,0 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/4.5/userguide/multi_project_builds.html
*/
rootProject.name = 'TabooLib'

View File

@ -1,2 +0,0 @@
#Sat Mar 10 19:32:51 CST 2018
gradle.version=4.5

View File

@ -0,0 +1,34 @@
package com.ilummc.tlib;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.bean.Property;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
@TConfig(name = "cfg.yml", charset = "GBK")
public class ExampleMain extends JavaPlugin {
private Property<Boolean> update = Property.of(false);
@Override
public void onEnable() {
update.addListener(((oldVal, newVal) -> {
Bukkit.getLogger().info("配置项 enableUpdate 的值由 " + oldVal + " 变为了 " + newVal);
if (newVal) {
Updater.start();
} else {
Updater.stop();
}
}));
}
private static class Updater {
public static void start() {
}
public static void stop() {
}
}
}

View File

@ -0,0 +1,122 @@
package com.ilummc.tlib;
import com.ilummc.tlib.annotations.Dependency;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.config.TLibConfig;
import com.ilummc.tlib.db.Pool;
import com.ilummc.tlib.filter.TLoggerFilter;
import com.ilummc.tlib.inject.TConfigWatcher;
import com.ilummc.tlib.inject.TDependencyInjector;
import com.ilummc.tlib.inject.TPluginManager;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:activejdbc:2.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:javalite-common:2.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:app-config:2.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.codehaus.jackson:jackson-mapper-asl:1.9.13")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.codehaus.jackson:jackson-core-asl:1.9.13")
@Dependency(type = Dependency.Type.LIBRARY, maven = "jaxen:jaxen:1.1.6")
@Dependency(type = Dependency.Type.LIBRARY, maven = "dom4j:dom4j:1.6.1")
@Dependency(type = Dependency.Type.LIBRARY, maven = "xml-apis:xml-apis:1.0.b2")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.ehcache:ehcache:3.5.2")
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.h2database:h2:1.4.197")
public class TLib {
private static TLib tLib;
private static YamlConfiguration internalLanguage;
private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
private TLibConfig config;
private TConfigWatcher configWatcher = new TConfigWatcher();
private File libsFolder;
private TLib() {
libsFolder = new File(Main.getInst().getDataFolder(), "/libs");
if (!libsFolder.exists()) {
libsFolder.mkdirs();
}
try {
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8"));
internalLanguage = new YamlConfiguration();
internalLanguage.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) {
}
}
public static TLib getTLib() {
return tLib;
}
public static YamlConfiguration getInternalLanguage() {
return internalLanguage;
}
public static void init() {
tLib = new TLib();
TLoggerFilter.init();
TLocaleLoader.init();
PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib);
try {
Pool.init();
} catch (Throwable ignored) {
}
}
public static void unload() {
try {
Pool.unload();
} catch (Throwable ignored) {
}
tLib.getConfigWatcher().unregisterAll();
TDependencyInjector.eject(Main.getInst(), tLib);
}
public static void injectPluginManager() {
try {
Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager");
field.setAccessible(true);
field.set(Bukkit.getServer(), new TPluginManager());
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
if (Bukkit.getPluginManager() instanceof TPluginManager) {
TLocale.Logger.info("TLIB.INJECTION-SUCCESS");
} else {
TLocale.Logger.fatal("TLIB.INJECTION-FAILED");
}
}
public TLogger getLogger() {
return logger;
}
public TLibConfig getConfig() {
return config;
}
public TConfigWatcher getConfigWatcher() {
return configWatcher;
}
public File getLibsFolder() {
return libsFolder;
}
}

View File

@ -0,0 +1,14 @@
package com.ilummc.tlib.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Dependencies {
Dependency[] value();
}

View File

@ -0,0 +1,24 @@
package com.ilummc.tlib.annotations;
import com.ilummc.tlib.dependency.TDependency;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Dependencies.class)
public @interface Dependency {
enum Type {PLUGIN, LIBRARY}
Type type();
String plugin() default "";
String maven() default "";
String mavenRepo() default TDependency.MAVEN_REPO;
String url() default "";
}

View File

@ -0,0 +1,16 @@
package com.ilummc.tlib.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Logger {
String value() default "[{0}|{1}] {1}";
int level() default com.ilummc.tlib.logger.TLogger.INFO;
}

View File

@ -0,0 +1,13 @@
package com.ilummc.tlib.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PluginInstance {
String value();
}

View File

@ -0,0 +1,29 @@
package com.ilummc.tlib.annotations;
import com.ilummc.tlib.util.Ref;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Modifier;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TConfig {
String name() default "config.yml";
boolean fromJar() default false;
boolean saveOnExit() default false;
boolean readOnly() default true;
String charset() default "UTF-8";
boolean listenChanges() default false;
int excludeModifiers() default Modifier.STATIC | Modifier.TRANSIENT | Ref.ACC_SYNTHETIC | Ref.ACC_BRIDGE;
}

View File

@ -0,0 +1,11 @@
package com.ilummc.tlib.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TLocalePlugin {
}

View File

@ -0,0 +1,11 @@
package com.ilummc.tlib.annotations.db;
public @interface Database {
boolean sharedPool() default true;
int poolSize() default 8;
Class<?> configClass();
}

View File

@ -0,0 +1,4 @@
package com.ilummc.tlib.annotations.db;
public @interface DatabasePassword {
}

View File

@ -0,0 +1,4 @@
package com.ilummc.tlib.annotations.db;
public @interface DatabaseType {
}

View File

@ -0,0 +1,4 @@
package com.ilummc.tlib.annotations.db;
public @interface DatabaseUrl {
}

View File

@ -0,0 +1,4 @@
package com.ilummc.tlib.annotations.db;
public @interface DatabaseUser {
}

View File

@ -0,0 +1,14 @@
package com.ilummc.tlib.annotations.db;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLTable {
String value();
}

View File

@ -0,0 +1,43 @@
package com.ilummc.tlib.bean;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
public class Property<T> {
private Property(T value) {
this.value = value;
}
private List<BiConsumer<T, T>> consumers;
private T value;
public void set(T value) {
if (value != this.value) {
if (consumers != null) {
for (BiConsumer<T, T> consumer : consumers) {
consumer.accept(this.value, value);
}
}
this.value = value;
}
}
public T get() {
return value;
}
public void addListener(BiConsumer<T, T> consumer) {
if (consumers == null) {
consumers = new ArrayList<>();
}
consumers.add(consumer);
}
public static <T> Property<T> of(T value) {
return new Property<>(value);
}
}

View File

@ -0,0 +1,16 @@
package com.ilummc.tlib.bean;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class PropertyTypeAdaptor implements JsonDeserializer<Property> {
@Override
public Property deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
return null;
}
}

View File

@ -0,0 +1,180 @@
package com.ilummc.tlib.bungee.api;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Simplistic enumeration of all supported color values for chat.
* @author md_5
*/
public enum ChatColor {
/**
* Represents black.
*/
BLACK('0', "black"),
/**
* Represents dark blue.
*/
DARK_BLUE('1', "dark_blue"),
/**
* Represents dark green.
*/
DARK_GREEN('2', "dark_green"),
/**
* Represents dark blue (aqua).
*/
DARK_AQUA('3', "dark_aqua"),
/**
* Represents dark red.
*/
DARK_RED('4', "dark_red"),
/**
* Represents dark purple.
*/
DARK_PURPLE('5', "dark_purple"),
/**
* Represents gold.
*/
GOLD('6', "gold"),
/**
* Represents gray.
*/
GRAY('7', "gray"),
/**
* Represents dark gray.
*/
DARK_GRAY('8', "dark_gray"),
/**
* Represents blue.
*/
BLUE('9', "blue"),
/**
* Represents green.
*/
GREEN('a', "green"),
/**
* Represents aqua.
*/
AQUA('b', "aqua"),
/**
* Represents red.
*/
RED('c', "red"),
/**
* Represents light purple.
*/
LIGHT_PURPLE('d', "light_purple"),
/**
* Represents yellow.
*/
YELLOW('e', "yellow"),
/**
* Represents white.
*/
WHITE('f', "white"),
/**
* Represents magical characters that change around randomly.
*/
MAGIC('k', "obfuscated"),
/**
* Makes the text bold.
*/
BOLD('l', "bold"),
/**
* Makes a line appear through the text.
*/
STRIKETHROUGH('m', "strikethrough"),
/**
* Makes the text appear underlined.
*/
UNDERLINE('n', "underline"),
/**
* Makes the text italic.
*/
ITALIC('o', "italic"),
/**
* Resets all previous chat colors or formats.
*/
RESET('r', "reset");
/**
* The special character which prefixes all chat colour codes. Use this if
* you need to dynamically convert colour codes from your custom format.
*/
public static final char COLOR_CHAR = '\u00A7';
public static final String ALL_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRr";
/**
* Pattern to remove all colour codes.
*/
public static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]");
/**
* Colour instances keyed by their active character.
*/
private static final Map<Character, ChatColor> BY_CHAR = new HashMap<Character, ChatColor>();
/**
* The code appended to {@link #COLOR_CHAR} to make usable colour.
*/
private final char code;
/**
* This colour's colour char prefixed by the {@link #COLOR_CHAR}.
*/
private final String toString;
private final String name;
public String getName() {
return name;
}
static {
for (ChatColor colour : values()) {
BY_CHAR.put(colour.code, colour);
}
}
ChatColor(char code, String name) {
this.code = code;
this.name = name;
this.toString = new String(new char[]{COLOR_CHAR, code});
}
@Override
public String toString() {
return toString;
}
/**
* Strips the given message of all color codes
*
* @param input String to strip of color
* @return A copy of the input string, without any coloring
*/
public static String stripColor(final String input) {
if (input == null) {
return null;
}
return STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
}
public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) {
char[] b = textToTranslate.toCharArray();
for (int i = 0; i < b.length - 1; i++) {
if (b[i] == altColorChar && ALL_CODES.indexOf(b[i + 1]) > -1) {
b[i] = ChatColor.COLOR_CHAR;
b[i + 1] = Character.toLowerCase(b[i + 1]);
}
}
return new String(b);
}
/**
* Get the colour represented by the specified code.
*
* @param code the code to search for
* @return the mapped colour, or null if non exists
*/
public static ChatColor getByChar(char code) {
return BY_CHAR.get(code);
}
}

View File

@ -0,0 +1,12 @@
package com.ilummc.tlib.bungee.api;
/**
* Represents the position on the screen where a message will appear.
* @author md_5
*/
public enum ChatMessageType {
CHAT,
SYSTEM,
ACTION_BAR
}

View File

@ -0,0 +1,493 @@
package com.ilummc.tlib.bungee.api.chat;
import com.ilummc.tlib.bungee.api.ChatColor;
import com.ilummc.tlib.bungee.api.chat.ComponentBuilder.FormatRetention;
import java.util.ArrayList;
import java.util.List;
/**
* @author md_5
*/
public abstract class BaseComponent {
BaseComponent parent;
/**
* The color of this component and any child components (unless overridden)
*/
private ChatColor color;
/**
* Whether this component and any child components (unless overridden) is
* bold
*/
private Boolean bold;
/**
* Whether this component and any child components (unless overridden) is
* italic
*/
private Boolean italic;
/**
* Whether this component and any child components (unless overridden) is
* underlined
*/
private Boolean underlined;
/**
* Whether this component and any child components (unless overridden) is
* strikethrough
*/
private Boolean strikethrough;
/**
* Whether this component and any child components (unless overridden) is
* obfuscated
*/
private Boolean obfuscated;
/**
* The text to insert into the chat when this component (and child
* components) are clicked while pressing the shift key
*/
private String insertion;
/**
* Appended components that inherit this component's formatting and events
*/
private List<BaseComponent> extra;
/**
* The action to perform when this component (and child components) are
* clicked
*/
private ClickEvent clickEvent;
/**
* The action to perform when this component (and child components) are
* hovered over
*/
private HoverEvent hoverEvent;
public String getInsertion() {
return insertion;
}
public List<BaseComponent> getExtra() {
return extra;
}
public ClickEvent getClickEvent() {
return clickEvent;
}
public HoverEvent getHoverEvent() {
return hoverEvent;
}
public void setParent(BaseComponent parent) {
this.parent = parent;
}
public void setColor(ChatColor color) {
this.color = color;
}
public void setBold(Boolean bold) {
this.bold = bold;
}
public void setItalic(Boolean italic) {
this.italic = italic;
}
public void setUnderlined(Boolean underlined) {
this.underlined = underlined;
}
public void setStrikethrough(Boolean strikethrough) {
this.strikethrough = strikethrough;
}
public void setObfuscated(Boolean obfuscated) {
this.obfuscated = obfuscated;
}
public void setInsertion(String insertion) {
this.insertion = insertion;
}
public void setClickEvent(ClickEvent clickEvent) {
this.clickEvent = clickEvent;
}
public void setHoverEvent(HoverEvent hoverEvent) {
this.hoverEvent = hoverEvent;
}
@Override
public String toString() {
return "parent=" + "BaseComponent{" + parent + ", color=" + color + ", bold=" + bold + ", italic=" + italic + ", underlined=" + underlined + ", strikethrough=" + strikethrough + ", obfuscated=" + obfuscated + ", insertion='" + insertion + '\'' + ", extra=" + extra + ", clickEvent=" + clickEvent + ", hoverEvent=" + hoverEvent + '}';
}
BaseComponent() {
}
BaseComponent(BaseComponent old) {
copyFormatting(old, FormatRetention.ALL, true);
if (old.getExtra() != null) {
for (BaseComponent extra : old.getExtra()) {
addExtra(extra.duplicate());
}
}
}
/**
* Copies the events and formatting of a BaseComponent. Already set
* formatting will be replaced.
*
* @param component the component to copy from
*/
public void copyFormatting(BaseComponent component) {
copyFormatting(component, FormatRetention.ALL, true);
}
/**
* Copies the events and formatting of a BaseComponent.
*
* @param component the component to copy from
* @param replace if already set formatting should be replaced by the new
* component
*/
public void copyFormatting(BaseComponent component, boolean replace) {
copyFormatting(component, FormatRetention.ALL, replace);
}
/**
* Copies the specified formatting of a BaseComponent.
*
* @param component the component to copy from
* @param retention the formatting to copy
* @param replace if already set formatting should be replaced by the new
* component
*/
public void copyFormatting(BaseComponent component, FormatRetention retention, boolean replace) {
if (retention == FormatRetention.EVENTS || retention == FormatRetention.ALL) {
if (replace || clickEvent == null) {
setClickEvent(component.getClickEvent());
}
if (replace || hoverEvent == null) {
setHoverEvent(component.getHoverEvent());
}
}
if (retention == FormatRetention.FORMATTING || retention == FormatRetention.ALL) {
if (replace || color == null) {
setColor(component.getColorRaw());
}
if (replace || bold == null) {
setBold(component.isBoldRaw());
}
if (replace || italic == null) {
setItalic(component.isItalicRaw());
}
if (replace || underlined == null) {
setUnderlined(component.isUnderlinedRaw());
}
if (replace || strikethrough == null) {
setStrikethrough(component.isStrikethroughRaw());
}
if (replace || obfuscated == null) {
setObfuscated(component.isObfuscatedRaw());
}
if (replace || insertion == null) {
setInsertion(component.getInsertion());
}
}
}
/**
* Retains only the specified formatting.
*
* @param retention the formatting to retain
*/
public void retain(FormatRetention retention) {
if (retention == FormatRetention.FORMATTING || retention == FormatRetention.NONE) {
setClickEvent(null);
setHoverEvent(null);
}
if (retention == FormatRetention.EVENTS || retention == FormatRetention.NONE) {
setColor(null);
setBold(null);
setItalic(null);
setUnderlined(null);
setStrikethrough(null);
setObfuscated(null);
setInsertion(null);
}
}
/**
* Clones the BaseComponent and returns the clone.
*
* @return The duplicate of this BaseComponent
*/
public abstract BaseComponent duplicate();
/**
* Clones the BaseComponent without formatting and returns the clone.
*
* @return The duplicate of this BaseComponent
* @deprecated API use discouraged, use traditional duplicate
*/
@Deprecated
public BaseComponent duplicateWithoutFormatting() {
BaseComponent component = duplicate();
component.retain(FormatRetention.NONE);
return component;
}
/**
* Converts the components to a string that uses the old formatting codes
* ({@link ChatColor#COLOR_CHAR}
*
* @param components the components to convert
* @return the string in the old format
*/
public static String toLegacyText(BaseComponent... components) {
StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) {
builder.append(msg.toLegacyText());
}
return builder.toString();
}
/**
* Converts the components into a string without any formatting
*
* @param components the components to convert
* @return the string as plain text
*/
public static String toPlainText(BaseComponent... components) {
StringBuilder builder = new StringBuilder();
for (BaseComponent msg : components) {
builder.append(msg.toPlainText());
}
return builder.toString();
}
/**
* Returns the color of this component. This uses the parent's color if this
* component doesn't have one. {@link ChatColor#WHITE}
* is returned if no color is found.
*
* @return the color of this component
*/
public ChatColor getColor() {
if (color == null) {
if (parent == null) {
return ChatColor.WHITE;
}
return parent.getColor();
}
return color;
}
/**
* Returns the color of this component without checking the parents color.
* May return null
*
* @return the color of this component
*/
public ChatColor getColorRaw() {
return color;
}
/**
* Returns whether this component is bold. This uses the parent's setting if
* this component hasn't been set. false is returned if none of the parent
* chain has been set.
*
* @return whether the component is bold
*/
public boolean isBold() {
if (bold == null) {
return parent != null && parent.isBold();
}
return bold;
}
/**
* Returns whether this component is bold without checking the parents
* setting. May return null
*
* @return whether the component is bold
*/
public Boolean isBoldRaw() {
return bold;
}
/**
* Returns whether this component is italic. This uses the parent's setting
* if this component hasn't been set. false is returned if none of the
* parent chain has been set.
*
* @return whether the component is italic
*/
public boolean isItalic() {
if (italic == null) {
return parent != null && parent.isItalic();
}
return italic;
}
/**
* Returns whether this component is italic without checking the parents
* setting. May return null
*
* @return whether the component is italic
*/
public Boolean isItalicRaw() {
return italic;
}
/**
* Returns whether this component is underlined. This uses the parent's
* setting if this component hasn't been set. false is returned if none of
* the parent chain has been set.
*
* @return whether the component is underlined
*/
public boolean isUnderlined() {
if (underlined == null) {
return parent != null && parent.isUnderlined();
}
return underlined;
}
/**
* Returns whether this component is underlined without checking the parents
* setting. May return null
*
* @return whether the component is underlined
*/
public Boolean isUnderlinedRaw() {
return underlined;
}
/**
* Returns whether this component is strikethrough. This uses the parent's
* setting if this component hasn't been set. false is returned if none of
* the parent chain has been set.
*
* @return whether the component is strikethrough
*/
public boolean isStrikethrough() {
if (strikethrough == null) {
return parent != null && parent.isStrikethrough();
}
return strikethrough;
}
/**
* Returns whether this component is strikethrough without checking the
* parents setting. May return null
*
* @return whether the component is strikethrough
*/
public Boolean isStrikethroughRaw() {
return strikethrough;
}
/**
* Returns whether this component is obfuscated. This uses the parent's
* setting if this component hasn't been set. false is returned if none of
* the parent chain has been set.
*
* @return whether the component is obfuscated
*/
public boolean isObfuscated() {
if (obfuscated == null) {
return parent != null && parent.isObfuscated();
}
return obfuscated;
}
/**
* Returns whether this component is obfuscated without checking the parents
* setting. May return null
*
* @return whether the component is obfuscated
*/
public Boolean isObfuscatedRaw() {
return obfuscated;
}
public void setExtra(List<BaseComponent> components) {
components.forEach(component -> component.parent = this);
extra = components;
}
/**
* Appends a text element to the component. The text will inherit this
* component's formatting
*
* @param text the text to append
*/
public void addExtra(String text) {
addExtra(new TextComponent(text));
}
/**
* Appends a component to the component. The text will inherit this
* component's formatting
*
* @param component the component to append
*/
public void addExtra(BaseComponent component) {
if (extra == null) {
extra = new ArrayList<>();
}
component.parent = this;
extra.add(component);
}
/**
* Returns whether the component has any formatting or events applied to it
*
* @return Whether any formatting or events are applied
*/
public boolean hasFormatting() {
return color != null || italic != null || bold != null || underlined != null || strikethrough != null || obfuscated != null || insertion != null || hoverEvent != null || clickEvent != null;
}
/**
* Converts the component into a string without any formatting
*
* @return the string as plain text
*/
public String toPlainText() {
StringBuilder builder = new StringBuilder();
toPlainText(builder);
return builder.toString();
}
void toPlainText(StringBuilder builder) {
if (extra != null) {
extra.forEach(e -> e.toPlainText(builder));
}
}
/**
* Converts the component to a string that uses the old formatting codes
* ({@link ChatColor#COLOR_CHAR}
*
* @return the string in the old format
*/
public String toLegacyText() {
StringBuilder builder = new StringBuilder();
toLegacyText(builder);
return builder.toString();
}
void toLegacyText(StringBuilder builder) {
if (extra != null) {
extra.forEach(e -> e.toLegacyText(builder));
}
}
}

View File

@ -0,0 +1,61 @@
package com.ilummc.tlib.bungee.api.chat;
/**
* @author md_5
*/
public final class ClickEvent {
/**
* The type of action to perform on click
*/
private final Action action;
/**
* Depends on action
*
* @see Action
*/
private final String value;
public ClickEvent(Action action, String value) {
this.action = action;
this.value = value;
}
public Action getAction() {
return action;
}
public String getValue() {
return value;
}
public enum Action {
/**
* Open a url at the path given by
* {@link ClickEvent#value}
*/
OPEN_URL,
/**
* Open a file at the path given by
* {@link ClickEvent#value}
*/
OPEN_FILE,
/**
* Run the command given by
* {@link ClickEvent#value}
*/
RUN_COMMAND,
/**
* Inserts the string given by
* {@link ClickEvent#value} into the players
* text box
*/
SUGGEST_COMMAND,
/**
* Change to the page number given by
* {@link ClickEvent#value} in a book
*/
CHANGE_PAGE
}
}

View File

@ -0,0 +1,311 @@
package com.ilummc.tlib.bungee.api.chat;
import com.google.common.base.Preconditions;
import com.ilummc.tlib.bungee.api.ChatColor;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* ComponentBuilder simplifies creating basic messages by allowing the use of a
* chainable builder.
* </p>
* <pre>
* new ComponentBuilder("Hello ").color(ChatColor.RED).
* append("World").color(ChatColor.BLUE). append("!").bold(true).create();
* </pre>
* <p>
* All methods (excluding {@link #append(String)} and {@link #create()} work on
* the last part appended to the builder, so in the example above "Hello " would
* be {@link ChatColor#RED} and "World" would be
* {@link ChatColor#BLUE} but "!" would be bold and
* {@link ChatColor#BLUE} because append copies the previous
* part's formatting
* </p>
*
* @author md_5
*/
public final class ComponentBuilder {
private BaseComponent current;
private final List<BaseComponent> parts = new ArrayList<>();
/**
* Creates a ComponentBuilder from the other given ComponentBuilder to clone
* it.
*
* @param original the original for the new ComponentBuilder.
*/
public ComponentBuilder(ComponentBuilder original) {
current = original.current.duplicate();
original.parts.stream().map(BaseComponent::duplicate).forEach(parts::add);
}
/**
* Creates a ComponentBuilder with the given text as the first part.
*
* @param text the first text element
*/
public ComponentBuilder(String text) {
current = new TextComponent(text);
}
/**
* Creates a ComponentBuilder with the given component as the first part.
*
* @param component the first component element
*/
public ComponentBuilder(BaseComponent component) {
current = component.duplicate();
}
/**
* Appends a component to the builder and makes it the current target for
* formatting. The component will have all the formatting from previous
* part.
*
* @param component the component to append
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(BaseComponent component) {
return append(component, FormatRetention.ALL);
}
/**
* Appends a component to the builder and makes it the current target for
* formatting. You can specify the amount of formatting retained from
* previous part.
*
* @param component the component to append
* @param retention the formatting to retain
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(BaseComponent component, FormatRetention retention) {
parts.add(current);
BaseComponent previous = current;
current = component.duplicate();
current.copyFormatting(previous, retention, false);
return this;
}
/**
* Appends the components to the builder and makes the last element the
* current target for formatting. The components will have all the
* formatting from previous part.
*
* @param components the components to append
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(BaseComponent[] components) {
return append(components, FormatRetention.ALL);
}
/**
* Appends the components to the builder and makes the last element the
* current target for formatting. You can specify the amount of formatting
* retained from previous part.
*
* @param components the components to append
* @param retention the formatting to retain
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(BaseComponent[] components, FormatRetention retention) {
Preconditions.checkArgument(components.length != 0, "No components to append");
BaseComponent previous = current;
for (BaseComponent component : components) {
parts.add(current);
current = component.duplicate();
current.copyFormatting(previous, retention, false);
}
return this;
}
/**
* Appends the text to the builder and makes it the current target for
* formatting. The text will have all the formatting from previous part.
*
* @param text the text to append
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(String text) {
return append(text, FormatRetention.ALL);
}
/**
* Appends the text to the builder and makes it the current target for
* formatting. You can specify the amount of formatting retained from
* previous part.
*
* @param text the text to append
* @param retention the formatting to retain
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder append(String text, FormatRetention retention) {
parts.add(current);
BaseComponent old = current;
current = new TextComponent(text);
current.copyFormatting(old, retention, false);
return this;
}
/**
* Sets the color of the current part.
*
* @param color the new color
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder color(ChatColor color) {
current.setColor(color);
return this;
}
/**
* Sets whether the current part is bold.
*
* @param bold whether this part is bold
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder bold(boolean bold) {
current.setBold(bold);
return this;
}
/**
* Sets whether the current part is italic.
*
* @param italic whether this part is italic
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder italic(boolean italic) {
current.setItalic(italic);
return this;
}
/**
* Sets whether the current part is underlined.
*
* @param underlined whether this part is underlined
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder underlined(boolean underlined) {
current.setUnderlined(underlined);
return this;
}
/**
* Sets whether the current part is strikethrough.
*
* @param strikethrough whether this part is strikethrough
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder strikethrough(boolean strikethrough) {
current.setStrikethrough(strikethrough);
return this;
}
/**
* Sets whether the current part is obfuscated.
*
* @param obfuscated whether this part is obfuscated
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder obfuscated(boolean obfuscated) {
current.setObfuscated(obfuscated);
return this;
}
/**
* Sets the insertion text for the current part.
*
* @param insertion the insertion text
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder insertion(String insertion) {
current.setInsertion(insertion);
return this;
}
/**
* Sets the click event for the current part.
*
* @param clickEvent the click event
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder event(ClickEvent clickEvent) {
current.setClickEvent(clickEvent);
return this;
}
/**
* Sets the hover event for the current part.
*
* @param hoverEvent the hover event
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder event(HoverEvent hoverEvent) {
current.setHoverEvent(hoverEvent);
return this;
}
/**
* Sets the current part back to normal settings. Only text is kept.
*
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder reset() {
return retain(FormatRetention.NONE);
}
/**
* Retains only the specified formatting. Text is not modified.
*
* @param retention the formatting to retain
* @return this ComponentBuilder for chaining
*/
public ComponentBuilder retain(FormatRetention retention) {
current.retain(retention);
return this;
}
/**
* Returns the components needed to display the message created by this
* builder.
*
* @return the created components
*/
public BaseComponent[] create() {
BaseComponent[] result = parts.toArray(new BaseComponent[parts.size() + 1]);
result[parts.size()] = current;
return result;
}
public enum FormatRetention {
/**
* Specify that we do not want to retain anything from the previous
* component.
*/
NONE,
/**
* Specify that we want the formatting retained from the previous
* component.
*/
FORMATTING,
/**
* Specify that we want the events retained from the previous component.
*/
EVENTS,
/**
* Specify that we want to retain everything from the previous
* component.
*/
ALL
}
}

View File

@ -0,0 +1,38 @@
package com.ilummc.tlib.bungee.api.chat;
import java.util.Arrays;
/**
* @author md_5
*/
public final class HoverEvent {
private final Action action;
private final BaseComponent[] value;
public HoverEvent(Action action, BaseComponent[] value) {
this.action = action;
this.value = value;
}
public Action getAction() {
return action;
}
public BaseComponent[] getValue() {
return value;
}
@Override
public String toString() {
return "action=" + "HoverEvent{" + action + ", value=" + Arrays.toString(value) + '}';
}
public enum Action {
SHOW_TEXT,
SHOW_ACHIEVEMENT,
SHOW_ITEM,
SHOW_ENTITY
}
}

View File

@ -0,0 +1,184 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ilummc.tlib.bungee.api.chat;
import com.ilummc.tlib.bungee.api.ChatColor;
import java.beans.ConstructorProperties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author md_5
*/
public class TextComponent extends BaseComponent {
private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$");
private String text;
public static BaseComponent[] fromLegacyText(String message) {
ArrayList<BaseComponent> components = new ArrayList();
StringBuilder builder = new StringBuilder();
TextComponent component = new TextComponent();
Matcher matcher = url.matcher(message);
for(int i = 0; i < message.length(); ++i) {
char c = message.charAt(i);
TextComponent old;
if (c == 167) {
++i;
c = message.charAt(i);
if (c >= 'A' && c <= 'Z') {
c = (char)(c + 32);
}
ChatColor format = ChatColor.getByChar(c);
if (format != null) {
if (builder.length() > 0) {
old = component;
component = new TextComponent(component);
old.setText(builder.toString());
builder = new StringBuilder();
components.add(old);
}
switch(format) {
case BOLD:
component.setBold(true);
break;
case ITALIC:
component.setItalic(true);
break;
case UNDERLINE:
component.setUnderlined(true);
break;
case STRIKETHROUGH:
component.setStrikethrough(true);
break;
case MAGIC:
component.setObfuscated(true);
break;
case RESET:
format = ChatColor.WHITE;
default:
component = new TextComponent();
component.setColor(format);
break;
}
}
} else {
int pos = message.indexOf(32, i);
if (pos == -1) {
pos = message.length();
}
if (matcher.region(i, pos).find()) {
if (builder.length() > 0) {
old = component;
component = new TextComponent(component);
old.setText(builder.toString());
builder = new StringBuilder();
components.add(old);
}
old = component;
component = new TextComponent(component);
String urlString = message.substring(i, pos);
component.setText(urlString);
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString));
components.add(component);
i += pos - i - 1;
component = old;
} else {
builder.append(c);
}
}
}
if (builder.length() > 0) {
component.setText(builder.toString());
components.add(component);
}
if (components.isEmpty()) {
components.add(new TextComponent(""));
}
return components.toArray(new BaseComponent[0]);
}
public TextComponent() {
this.text = "";
}
public TextComponent(TextComponent textComponent) {
super(textComponent);
this.setText(textComponent.getText());
}
public TextComponent(BaseComponent... extras) {
this.setText("");
this.setExtra(new ArrayList(Arrays.asList(extras)));
}
@Override
public BaseComponent duplicate() {
return new TextComponent(this);
}
@Override
protected void toPlainText(StringBuilder builder) {
builder.append(this.text);
super.toPlainText(builder);
}
@Override
protected void toLegacyText(StringBuilder builder) {
builder.append(this.getColor());
if (this.isBold()) {
builder.append(ChatColor.BOLD);
}
if (this.isItalic()) {
builder.append(ChatColor.ITALIC);
}
if (this.isUnderlined()) {
builder.append(ChatColor.UNDERLINE);
}
if (this.isStrikethrough()) {
builder.append(ChatColor.STRIKETHROUGH);
}
if (this.isObfuscated()) {
builder.append(ChatColor.MAGIC);
}
builder.append(this.text);
super.toLegacyText(builder);
}
@Override
public String toString() {
return String.format("TextComponent{text=%s, %s}", this.text, super.toString());
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
@ConstructorProperties({"text"})
public TextComponent(String text) {
this.text = text;
}
}

View File

@ -0,0 +1,242 @@
package com.ilummc.tlib.bungee.api.chat;
import com.ilummc.tlib.bungee.api.ChatColor;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @author md_5
*/
public final class TranslatableComponent extends BaseComponent {
private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US");
private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)");
/**
* The key into the Minecraft locale files to use for the translation. The
* text depends on the client's locale setting. The console is always en_US
*/
private String translate;
/**
* The components to substitute into the translation
*/
private List<BaseComponent> with;
public ResourceBundle getLocales() {
return locales;
}
public Pattern getFormat() {
return format;
}
public String getTranslate() {
return translate;
}
public void setTranslate(String translate) {
this.translate = translate;
}
public List<BaseComponent> getWith() {
return with;
}
public TranslatableComponent() {
}
/**
* Creates a translatable component from the original to clone it.
*
* @param original the original for the new translatable component.
*/
public TranslatableComponent(TranslatableComponent original) {
super(original);
setTranslate(original.getTranslate());
if (original.getWith() != null) {
setWith(original.getWith().stream().map(BaseComponent::duplicate).collect(Collectors.toList()));
}
}
/**
* Creates a translatable component with the passed substitutions
*
* @param translate the translation key
* @param with the {@link java.lang.String}s and
* {@link BaseComponent}s to use into the
* translation
* @see #translate
* @see #setWith(java.util.List)
*/
public TranslatableComponent(String translate, Object... with) {
setTranslate(translate);
if (with != null && with.length != 0) {
List<BaseComponent> temp = new ArrayList<>();
for (Object w : with) {
if (w instanceof String) {
temp.add(new TextComponent((String) w));
} else {
temp.add((BaseComponent) w);
}
}
setWith(temp);
}
}
/**
* Creates a duplicate of this TranslatableComponent.
*
* @return the duplicate of this TranslatableComponent.
*/
@Override
public BaseComponent duplicate() {
return new TranslatableComponent(this);
}
@Override
public String toString() {
return "locales=" + "TranslatableComponent{" + locales + ", format=" + format + ", translate='" + translate + '\'' + ", with=" + with + '}';
}
/**
* Sets the translation substitutions to be used in this component. Removes
* any previously set substitutions
*
* @param components the components to substitute
*/
public void setWith(List<BaseComponent> components) {
components.forEach(component -> component.parent = this);
with = components;
}
/**
* Adds a text substitution to the component. The text will inherit this
* component's formatting
*
* @param text the text to substitute
*/
public void addWith(String text) {
addWith(new TextComponent(text));
}
/**
* Adds a component substitution to the component. The text will inherit
* this component's formatting
*
* @param component the component to substitute
*/
public void addWith(BaseComponent component) {
if (with == null) {
with = new ArrayList<>();
}
component.parent = this;
with.add(component);
}
@Override
protected void toPlainText(StringBuilder builder) {
String trans;
try {
trans = locales.getString(translate);
} catch (MissingResourceException ex) {
trans = translate;
}
Matcher matcher = format.matcher(trans);
int position = 0;
int i = 0;
while (matcher.find(position)) {
int pos = matcher.start();
if (pos != position) {
builder.append(trans, position, pos);
}
position = matcher.end();
String formatCode = matcher.group(2);
switch (formatCode.charAt(0)) {
case 's':
case 'd':
String withIndex = matcher.group(1);
with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder);
break;
case '%':
builder.append('%');
break;
default:
break;
}
}
if (trans.length() != position) {
builder.append(trans, position, trans.length());
}
super.toPlainText(builder);
}
@Override
protected void toLegacyText(StringBuilder builder) {
String trans;
try {
trans = locales.getString(translate);
} catch (MissingResourceException e) {
trans = translate;
}
Matcher matcher = format.matcher(trans);
int position = 0;
int i = 0;
while (matcher.find(position)) {
int pos = matcher.start();
if (pos != position) {
addFormat(builder);
builder.append(trans, position, pos);
}
position = matcher.end();
String formatCode = matcher.group(2);
switch (formatCode.charAt(0)) {
case 's':
case 'd':
String withIndex = matcher.group(1);
with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder);
break;
case '%':
addFormat(builder);
builder.append('%');
break;
default:
break;
}
}
if (trans.length() != position) {
addFormat(builder);
builder.append(trans, position, trans.length());
}
super.toLegacyText(builder);
}
private void addFormat(StringBuilder builder) {
builder.append(getColor());
if (isBold()) {
builder.append(ChatColor.BOLD);
}
if (isItalic()) {
builder.append(ChatColor.ITALIC);
}
if (isUnderlined()) {
builder.append(ChatColor.UNDERLINE);
}
if (isStrikethrough()) {
builder.append(ChatColor.STRIKETHROUGH);
}
if (isObfuscated()) {
builder.append(ChatColor.MAGIC);
}
}
}

View File

@ -0,0 +1,121 @@
package com.ilummc.tlib.bungee.chat;
import com.google.common.base.Preconditions;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.ilummc.tlib.bungee.api.ChatColor;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.ClickEvent;
import com.ilummc.tlib.bungee.api.chat.HoverEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
/**
* @author md_5
*/
public class BaseComponentSerializer {
protected void deserialize(JsonObject object, BaseComponent component, JsonDeserializationContext context) {
if (object.has("color")) {
component.setColor(ChatColor.valueOf(object.get("color").getAsString().toUpperCase(Locale.ROOT)));
}
if (object.has("bold")) {
component.setBold(object.get("bold").getAsBoolean());
}
if (object.has("italic")) {
component.setItalic(object.get("italic").getAsBoolean());
}
if (object.has("underlined")) {
component.setUnderlined(object.get("underlined").getAsBoolean());
}
if (object.has("strikethrough")) {
component.setStrikethrough(object.get("strikethrough").getAsBoolean());
}
if (object.has("obfuscated")) {
component.setObfuscated(object.get("obfuscated").getAsBoolean());
}
if (object.has("insertion")) {
component.setInsertion(object.get("insertion").getAsString());
}
if (object.has("extra")) {
component.setExtra(Arrays.asList(context.<BaseComponent[]>deserialize(object.get("extra"), BaseComponent[].class)));
}
//Events
if (object.has("clickEvent")) {
JsonObject event = object.getAsJsonObject("clickEvent");
component.setClickEvent(new ClickEvent(
ClickEvent.Action.valueOf(event.get("action").getAsString().toUpperCase(Locale.ROOT)),
event.get("value").getAsString()));
}
if (object.has("hoverEvent")) {
JsonObject event = object.getAsJsonObject("hoverEvent");
BaseComponent[] res;
if (event.get("value").isJsonArray()) {
res = context.deserialize(event.get("value"), BaseComponent[].class);
} else {
res = new BaseComponent[]{context.deserialize(event.get("value"), BaseComponent.class)};
}
component.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(event.get("action").getAsString().toUpperCase(Locale.ROOT)), res));
}
}
protected void serialize(JsonObject object, BaseComponent component, JsonSerializationContext context) {
boolean first = false;
if (ComponentSerializer.serializedComponents.get() == null) {
first = true;
ComponentSerializer.serializedComponents.set(new HashSet<>());
}
try {
Preconditions.checkArgument(!ComponentSerializer.serializedComponents.get().contains(component), "Component loop");
ComponentSerializer.serializedComponents.get().add(component);
if (component.getColorRaw() != null) {
object.addProperty("color", component.getColorRaw().getName());
}
if (component.isBoldRaw() != null) {
object.addProperty("bold", component.isBoldRaw());
}
if (component.isItalicRaw() != null) {
object.addProperty("italic", component.isItalicRaw());
}
if (component.isUnderlinedRaw() != null) {
object.addProperty("underlined", component.isUnderlinedRaw());
}
if (component.isStrikethroughRaw() != null) {
object.addProperty("strikethrough", component.isStrikethroughRaw());
}
if (component.isObfuscatedRaw() != null) {
object.addProperty("obfuscated", component.isObfuscatedRaw());
}
if (component.getInsertion() != null) {
object.addProperty("insertion", component.getInsertion());
}
if (component.getExtra() != null) {
object.add("extra", context.serialize(component.getExtra()));
}
//Events
if (component.getClickEvent() != null) {
JsonObject clickEvent = new JsonObject();
clickEvent.addProperty("action", component.getClickEvent().getAction().toString().toLowerCase(Locale.ROOT));
clickEvent.addProperty("value", component.getClickEvent().getValue());
object.add("clickEvent", clickEvent);
}
if (component.getHoverEvent() != null) {
JsonObject hoverEvent = new JsonObject();
hoverEvent.addProperty("action", component.getHoverEvent().getAction().toString().toLowerCase(Locale.ROOT));
hoverEvent.add("value", context.serialize(component.getHoverEvent().getValue()));
object.add("hoverEvent", hoverEvent);
}
} finally {
ComponentSerializer.serializedComponents.get().remove(component);
if (first) {
ComponentSerializer.serializedComponents.set(null);
}
}
}
}

View File

@ -0,0 +1,58 @@
package com.ilummc.tlib.bungee.chat;
import com.google.gson.*;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.TextComponent;
import com.ilummc.tlib.bungee.api.chat.TranslatableComponent;
import java.lang.reflect.Type;
import java.util.HashSet;
/**
* @author md_5
*/
public class ComponentSerializer implements JsonDeserializer<BaseComponent> {
private final static JsonParser JSON_PARSER = new JsonParser();
private final static Gson gson = new GsonBuilder().
registerTypeAdapter(BaseComponent.class, new ComponentSerializer()).
registerTypeAdapter(TextComponent.class, new TextComponentSerializer()).
registerTypeAdapter(TranslatableComponent.class, new TranslatableComponentSerializer()).
create();
public final static ThreadLocal<HashSet<BaseComponent>> serializedComponents = new ThreadLocal<>();
public static BaseComponent[] parse(String json) {
JsonElement jsonElement = JSON_PARSER.parse(json);
if (jsonElement.isJsonArray()) {
return gson.fromJson(jsonElement, BaseComponent[].class);
} else {
return new BaseComponent[]{gson.fromJson(jsonElement, BaseComponent.class)};
}
}
public static String toString(BaseComponent component) {
return gson.toJson(component);
}
public static String toString(BaseComponent... components) {
if (components.length == 1) {
return gson.toJson(components[0]);
} else {
return gson.toJson(new TextComponent(components));
}
}
@Override
public BaseComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) {
return new TextComponent(json.getAsString());
}
JsonObject object = json.getAsJsonObject();
if (object.has("translate")) {
return context.deserialize(json, TranslatableComponent.class);
}
return context.deserialize(json, TextComponent.class);
}
}

View File

@ -0,0 +1,42 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ilummc.tlib.bungee.chat;
import com.google.gson.*;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.TextComponent;
import java.lang.reflect.Type;
import java.util.List;
/**
* @author md_5
*/
public class TextComponentSerializer extends BaseComponentSerializer implements JsonSerializer<TextComponent>, JsonDeserializer<TextComponent> {
public TextComponentSerializer() {
}
@Override
public TextComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
TextComponent component = new TextComponent();
JsonObject object = json.getAsJsonObject();
this.deserialize(object, component, context);
component.setText(object.get("text").getAsString());
return component;
}
@Override
public JsonElement serialize(TextComponent src, Type typeOfSrc, JsonSerializationContext context) {
List<BaseComponent> extra = src.getExtra();
JsonObject object = new JsonObject();
if (src.hasFormatting() || extra != null && !extra.isEmpty()) {
this.serialize(object, src, context);
}
object.addProperty("text", src.getText());
return object;
}
}

View File

@ -0,0 +1,46 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ilummc.tlib.bungee.chat;
import com.google.gson.*;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.TranslatableComponent;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
* @author md_5
*/
public class TranslatableComponentSerializer extends BaseComponentSerializer implements JsonSerializer<TranslatableComponent>, JsonDeserializer<TranslatableComponent> {
public TranslatableComponentSerializer() {
}
@Override
public TranslatableComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
TranslatableComponent component = new TranslatableComponent();
JsonObject object = json.getAsJsonObject();
this.deserialize(object, component, context);
component.setTranslate(object.get("translate").getAsString());
if (object.has("with")) {
component.setWith(Arrays.asList((BaseComponent[]) context.deserialize(object.get("with"), BaseComponent[].class)));
}
return component;
}
@Override
public JsonElement serialize(TranslatableComponent src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
this.serialize(object, src, context);
object.addProperty("translate", src.getTranslate());
if (src.getWith() != null) {
object.add("with", context.serialize(src.getWith()));
}
return object;
}
}

View File

@ -0,0 +1,42 @@
package com.ilummc.tlib.compat;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public abstract class PlaceholderHook {
private static PlaceholderHook impl;
public static void init() {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
impl = new PlaceholderImpl();
} else {
impl = new AbstractImpl();
}
}
public static String replace(CommandSender sender, String text) {
return sender instanceof Player ? impl.replace(((Player) sender), text) : text;
}
abstract String replace(Player player, String text);
private static class PlaceholderImpl extends PlaceholderHook {
@Override
String replace(Player player, String text) {
return PlaceholderAPI.setPlaceholders(player, text);
}
}
private static class AbstractImpl extends PlaceholderHook {
@Override
String replace(Player player, String text) {
return text;
}
}
}

View File

@ -0,0 +1,59 @@
package com.ilummc.tlib.config;
import com.ilummc.tlib.annotations.TConfig;
import java.util.HashMap;
import java.util.Map;
/**
* @author sky
* @since 2018-04-22 14:31:11
*/
@TConfig(name = "tlib.yml", listenChanges = true)
public class TLibConfig {
private String dataSourceClassName;
private String jdbcUrl = "jdbc:h2:file:~/plugins/TabooLib/h2";
private String driverClassName;
private String username = "";
private String password = "";
private int maximumPoolSize = 4;
private Map<String, Object> settings = new HashMap<String, Object>() {{
put("cachePrepStmts", true);
put("useServerPrepStmts", true);
}};
public String getDataSourceClassName() {
return dataSourceClassName;
}
public String getJdbcUrl() {
return jdbcUrl;
}
public String getDriverClassName() {
return driverClassName;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public int getMaximumPoolSize() {
return maximumPoolSize;
}
public Map<String, Object> getSettings() {
return settings;
}
}

View File

@ -0,0 +1,63 @@
package com.ilummc.tlib.db;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.resources.TLocale;
import org.javalite.activejdbc.Base;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public final class Pool extends ThreadPoolExecutor {
private static final AtomicInteger number = new AtomicInteger(1);
private static final Pool singleton = new Pool();
private final TLibDataSource dataSource;
private Pool() {
super(TLib.getTLib().getConfig().getMaximumPoolSize(),
TLib.getTLib().getConfig().getMaximumPoolSize(),
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
try {
dataSource = new TLibDataSource();
this.setThreadFactory(r -> new Thread(() -> {
Base.open(dataSource.getDataSource());
r.run();
}, "TabooLib-DbPool-" + number.getAndIncrement()));
prestartAllCoreThreads();
TLocale.sendToConsole("DATABASE.CONNECTION-ESTABLISHED", dataSource.getDataSource().getConnection().getMetaData().getDatabaseProductName(),
String.valueOf(TLib.getTLib().getConfig().getMaximumPoolSize()));
} catch (Exception e) {
TLocale.sendToConsole("DATABASE.CONNECTION-ERROR", e.toString());
throw new RuntimeException();
}
}
public static void run(Runnable runnable) {
instance().execute(runnable);
}
public static void init() {
}
public static void unload() {
instance().dataSource.disconnect();
instance().shutdown();
}
public static Pool instance() {
return singleton;
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (t != null) {
Base.close();
}
}
}

View File

@ -0,0 +1,35 @@
package com.ilummc.tlib.db;
import com.ilummc.tlib.TLib;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.javalite.activejdbc.Base;
import javax.sql.DataSource;
import java.util.Properties;
public class TLibDataSource {
private final HikariDataSource dataSource;
TLibDataSource() {
Properties properties = new Properties();
properties.put("jdbcUrl", TLib.getTLib().getConfig().getJdbcUrl());
properties.put("username", TLib.getTLib().getConfig().getUsername());
properties.put("password", TLib.getTLib().getConfig().getPassword());
properties.put("dataSourceClassName", TLib.getTLib().getConfig().getDataSourceClassName());
properties.put("driverClassName", TLib.getTLib().getConfig().getDriverClassName());
TLib.getTLib().getConfig().getSettings().forEach((k, v) -> properties.put("dataSource." + k, v));
dataSource = new HikariDataSource(new HikariConfig(properties));
Base.open(dataSource);
}
public DataSource getDataSource() {
return dataSource;
}
public void disconnect() {
Base.close();
}
}

View File

@ -0,0 +1,87 @@
package com.ilummc.tlib.dependency;
import com.ilummc.eagletdl.EagletTask;
import com.ilummc.eagletdl.ProgressEvent;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
public class TDependency {
public static final String MAVEN_REPO = "http://repo.maven.apache.org/maven2";
/**
* 请求一个插件作为依赖这个插件将会在所有已经添加的 Jenkins 仓库Maven 仓库寻找
* <p>
* 阻塞线程进行下载/加载
*
* @param args 插件名称下载地址可选
* @return 是否成功加载了依赖
*/
public static boolean requestPlugin(String... args) {
return false;
}
/**
* 请求一个库作为依赖这个库将会在 Maven Centraloss.sonatype 以及自定义的 Maven 仓库寻找
* <p>
* 阻塞线程进行下载/加载
*
* @param type 依赖名格式为 groupId:artifactId:version
* @return 是否成功加载库如果加载成功插件将可以任意调用使用的类
*/
public static boolean requestLib(String type, String repo, String url) {
if (type.matches(".*:.*:.*")) {
String[] arr = type.split(":");
File file = new File(Main.getInst().getDataFolder(), "/libs/" + String.join("-", arr) + ".jar");
if (file.exists()) {
TDependencyLoader.addToPath(Main.getInst(), file);
return true;
} else {
if (downloadMaven(repo, arr[0], arr[1], arr[2], file, url)) {
TDependencyLoader.addToPath(Main.getInst(), file);
return true;
} else {
return false;
}
}
}
return false;
}
private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) {
if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) {
TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN");
return false;
}
AtomicBoolean failed = new AtomicBoolean(false);
String link = dl.length() == 0 ? url + "/" + groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar" : dl;
new EagletTask()
.url(link)
.file(target)
.setThreads(getDownloadPoolSize())
.setOnError(event -> {
})
.setOnConnected(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-CONNECTED",
String.join(":", new String[]{groupId, artifactId, version}), ProgressEvent.format(event.getContentLength())))
.setOnProgress(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-PROGRESS",
event.getSpeedFormatted(), event.getPercentageFormatted()))
.setOnComplete(event -> {
if (event.isSuccess()) {
TLocale.Logger.info("DEPENDENCY.DOWNLOAD-SUCCESS",
String.join(":", new String[]{groupId, artifactId, version}));
} else {
failed.set(true);
TLocale.Logger.error("DEPENDENCY.DOWNLOAD-FAILED",
String.join(":", new String[]{groupId, artifactId, version}), link, target.getName());
}
}).start().waitUntil();
return !failed.get();
}
private static int getDownloadPoolSize() {
return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4);
}
}

View File

@ -0,0 +1,32 @@
package com.ilummc.tlib.dependency;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class TDependencyLoader {
public static synchronized void addToPath(Plugin plugin, URL url) {
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(plugin.getClass().getClassLoader(), url);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
public static synchronized void addToPath(Plugin plugin, File file) {
try {
addToPath(plugin, file.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,32 @@
package com.ilummc.tlib.filter;
import org.bukkit.Bukkit;
import java.util.Arrays;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
/**
* @author Bkm016
* @since 2018-04-22
*/
public class TLoggerFilter implements Filter {
public static void init() {
Bukkit.getLogger().setFilter(new TLoggerFilter());
}
@Override
public boolean isLoggable(LogRecord e) {
if (e.getMessage().contains("Cannot load configuration from stream")) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements) {
if (element.getClassName().contains("ConfigUtils")) {
System.out.println(Arrays.asList(e.getParameters()));
}
}
return false;
}
else return !e.getMessage().contains("Enabled plugin with unregistered PluginClassLoader");
}
}

View File

@ -0,0 +1,143 @@
package com.ilummc.tlib.inject;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils;
import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
public class TConfigInjector {
public static void fixUnicode(YamlConfiguration configuration) {
try {
Field field = YamlConfiguration.class.getDeclaredField("yamlOptions");
field.setAccessible(true);
field.set(configuration, NoUnicodeDumperOption.INSTANCE);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
private static final class NoUnicodeDumperOption extends DumperOptions {
private static final NoUnicodeDumperOption INSTANCE = new NoUnicodeDumperOption();
@Override
public void setAllowUnicode(boolean allowUnicode) {
super.setAllowUnicode(false);
}
@Override
public boolean isAllowUnicode() {
return false;
}
@Override
public void setLineBreak(LineBreak lineBreak) {
super.setLineBreak(LineBreak.getPlatformLineBreak());
}
}
public static Object loadConfig(Plugin plugin, Class<?> clazz) {
try {
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
if (!file.exists()) {
if (config.fromJar()) {
plugin.saveResource(config.name(), true);
} else {
saveConfig(plugin, clazz.newInstance());
}
}
Object obj = unserialize(plugin, clazz);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
return obj;
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
}
return null;
}
public static void reloadConfig(Plugin plugin, Object object) {
try {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file));
Object obj = ConfigUtils.mapToObj(map, object);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), object.getClass().getSimpleName());
}
}
public static Object unserialize(Plugin plugin, Class<?> clazz) {
try {
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
return ConfigUtils.confToObj(
ConfigUtils.mapToConf(
ConfigUtils.yamlToMap(
Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName());
return null;
} catch (Exception e) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e1) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
return null;
}
}
}
public static Map<String, Object> serialize(Plugin plugin, Object object) {
try {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers());
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName());
}
return null;
}
public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map map = gson.fromJson(gson.toJson(object), HashMap.class);
YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map);
File target = new File(plugin.getDataFolder(), config.name());
if (!target.exists()) {
target.createNewFile();
}
byte[] arr = configuration.saveToString().getBytes(config.charset());
Files.write(arr, target);
}
}

View File

@ -0,0 +1,82 @@
package com.ilummc.tlib.inject;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.tuple.Triple;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* @author lzzelAliz
*/
public class TConfigWatcher {
private final ScheduledExecutorService service = Executors.newScheduledThreadPool(1,
new BasicThreadFactory.Builder().namingPattern("TConfigWatcherService-%d").build());
private final Map<WatchService, Triple<File, Object, Consumer<Object>>> map = new HashMap<>();
public TConfigWatcher() {
service.scheduleAtFixedRate(() -> map.forEach((service, triple) -> {
WatchKey key;
while ((key = service.poll()) != null) {
for (WatchEvent<?> watchEvent : key.pollEvents()) {
if (triple.getLeft().getName().equals(Objects.toString(watchEvent.context()))) {
triple.getRight().accept(triple.getMiddle());
}
}
key.reset();
}
}), 1000, 100, TimeUnit.MILLISECONDS);
}
public void addOnListen(File file, Object obj, Consumer<Object> consumer) {
try {
WatchService service = FileSystems.getDefault().newWatchService();
file.getParentFile().toPath().register(service, StandardWatchEventKinds.ENTRY_MODIFY);
map.putIfAbsent(service, Triple.of(file, obj, consumer));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public <T> void addListener(File file, T obj, Consumer<T> consumer) {
addOnListen(file, obj, (Consumer<Object>) consumer);
}
public void removeListener(File file) {
synchronized (map) {
map.entrySet().removeIf(entry -> {
if (entry.getValue().getLeft().equals(file)) {
try {
entry.getKey().close();
} catch (IOException ignored) {
}
return true;
}
return false;
});
}
}
public void unregisterAll() {
service.shutdown();
map.forEach((service, pair) -> {
try {
service.close();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

View File

@ -0,0 +1,171 @@
package com.ilummc.tlib.inject;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.*;
import com.ilummc.tlib.dependency.TDependency;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.Ref;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Field;
public class TDependencyInjector {
public static void inject(Plugin plugin, Object o) {
TLocaleLoader.load(plugin, true);
injectDependencies(plugin, o);
injectLogger(plugin, o);
injectConfig(plugin, o);
injectPluginInstance(plugin, o);
}
static void injectOnEnable(Plugin plugin) {
if (!plugin.equals(Main.getInst())) {
inject(plugin, plugin);
}
}
static void onDisable(Plugin plugin) {
eject(plugin, plugin);
}
public static void eject(Plugin plugin, Object o) {
try {
ejectConfig(plugin, o);
} catch (Throwable ignored) {
}
}
private static void ejectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
TConfig config;
if ((config = field.getType().getAnnotation(TConfig.class)) != null && config.saveOnExit()) {
try {
field.setAccessible(true);
TConfigInjector.saveConfig(plugin, field.get(o));
TLocale.Logger.info("CONFIG.SAVE-SUCCESS", plugin.toString(), config.name());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), config.name());
e.printStackTrace();
}
}
}
}
private static void injectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
TConfig config;
if ((config = field.getType().getAnnotation(TConfig.class)) != null) {
field.setAccessible(true);
Object obj = TConfigInjector.loadConfig(plugin, field.getType());
if (obj != null) {
TLocale.Logger.info("CONFIG.LOAD-SUCCESS", plugin.toString(), config.name());
field.set(o, obj);
if (config.listenChanges()) {
TLocale.Logger.info("CONFIG.LISTEN-START", plugin.toString(), config.name());
TLib.getTLib().getConfigWatcher().addOnListen(
new File(plugin.getDataFolder(), config.name()),
obj,
object -> {
try {
TConfigInjector.reloadConfig(plugin, object);
TLocale.Logger.info("CONFIG.RELOAD-SUCCESS", plugin.toString(), config.name());
} catch (Exception ignored) {
TLocale.Logger.warn("CONFIG.RELOAD-FAIL", plugin.toString(), config.name());
}
}
);
}
}
}
} catch (Exception ignored) {
}
}
}
private static void injectLogger(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
Logger logger;
if ((logger = field.getAnnotation(Logger.class)) != null) {
field.getType().asSubclass(com.ilummc.tlib.logger.TLogger.class);
com.ilummc.tlib.logger.TLogger tLogger = new com.ilummc.tlib.logger.TLogger(logger.value(), plugin, logger.level());
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(o, tLogger);
TLoggerManager.setDefaultLogger(plugin, tLogger);
}
} catch (Exception ignored2) {
}
}
}
private static void injectPluginInstance(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
PluginInstance instance;
if ((instance = field.getAnnotation(PluginInstance.class)) != null) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.getType().asSubclass(JavaPlugin.class);
Plugin pl;
if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) {
if (!TDependency.requestPlugin(instance.value())) {
TLocale.Logger.warn("PLUGIN-AUTOLOAD-FAIL", plugin.getName(), instance.value());
return;
} else {
pl = Bukkit.getPluginManager().getPlugin(instance.value());
}
}
if (pl != null) {
field.set(o, pl);
}
}
} catch (Exception ignored) {
}
}
}
private static void injectDependencies(Plugin plugin, Object o) {
Dependency[] dependencies = new Dependency[0];
{
Dependencies d = o.getClass().getAnnotation(Dependencies.class);
if (d != null) {
dependencies = d.value();
}
Dependency d2 = o.getClass().getAnnotation(Dependency.class);
if (d2 != null) {
dependencies = new Dependency[]{d2};
}
}
if (dependencies.length != 0) {
TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName());
for (Dependency dependency : dependencies) {
if (dependency.type() == Dependency.Type.PLUGIN) {
if (TDependency.requestPlugin(dependency.plugin())) {
TLocale.Logger.info("DEPENDENCY.PLUGIN-LOAD-SUCCESS", plugin.getName(), dependency.plugin());
} else {
TLocale.Logger.warn("DEPENDENCY.PLUGIN-LOAD-FAIL", plugin.getName(), dependency.plugin());
}
}
if (dependency.type() == Dependency.Type.LIBRARY) {
if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) {
TLocale.Logger.info("DEPENDENCY.LIBRARY-LOAD-SUCCESS", plugin.getName(), String.join(":", dependency.maven()));
} else {
TLocale.Logger.warn("DEPENDENCY.LIBRARY-LOAD-FAIL", plugin.getName(), String.join(":", dependency.maven()));
}
}
}
TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE");
}
}
}

View File

@ -0,0 +1,25 @@
package com.ilummc.tlib.inject;
import com.ilummc.tlib.logger.TLogger;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.Map;
public class TLoggerManager {
private static final Map<Plugin, TLogger> map = new HashMap<>();
public static void setDefaultLogger(Plugin plugin, TLogger logger) {
map.put(plugin, logger);
}
public static TLogger getLogger(Plugin plugin) {
TLogger logger = map.get(plugin);
if (logger == null) {
logger = TLogger.getUnformatted(plugin);
map.put(plugin, logger);
}
return logger;
}
}

View File

@ -0,0 +1,220 @@
package com.ilummc.tlib.inject;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.*;
import java.io.File;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class TPluginManager implements PluginManager {
private final PluginManager instance;
private final Main main = (Main) Main.getInst();
private static File updateDirectory = null;
private Server server;
private Map<Pattern, PluginLoader> fileAssociations = new HashMap<>();
private List<Plugin> plugins = new ArrayList<>();
private Map<String, Plugin> lookupNames = new HashMap<>();
private SimpleCommandMap commandMap;
private Map<String, Permission> permissions = new HashMap<>();
private Map<Boolean, Set<Permission>> defaultPerms = new LinkedHashMap<>();
private Map<String, Map<Permissible, Boolean>> permSubs = new HashMap<>();
private Map<Boolean, Map<Permissible, Boolean>> defSubs = new HashMap<>();
private boolean useTimings = false;
public TPluginManager() {
instance = Bukkit.getPluginManager();
// clone all Field in SimplePluginManager
cloneField("updateDirectory");
cloneField("server");
cloneField("fileAssociations");
cloneField("plugins");
cloneField("lookupNames");
cloneField("commandMap");
cloneField("permissions");
cloneField("defaultPerms");
cloneField("permSubs");
cloneField("defSubs");
cloneField("useTimings");
}
private void cloneField(String bukkitName) {
try {
Field bukkitField = instance.getClass().getDeclaredField(bukkitName);
Field thisFiled = this.getClass().getDeclaredField(bukkitName);
if (bukkitField == null || thisFiled == null) {
TLocale.Logger.warn("MISC.FIELD-COPY-FAILED", bukkitName);
return;
}
bukkitField.setAccessible(true);
thisFiled.setAccessible(true);
thisFiled.set(this, bukkitField.get(instance));
} catch (Exception e) {
TLocale.Logger.error("MISC.FIELD-COPY-ERROR", bukkitName, e.toString());
}
}
@Override
public void registerInterface(Class<? extends PluginLoader> aClass) throws IllegalArgumentException {
instance.registerInterface(aClass);
}
@Override
public Plugin getPlugin(String s) {
return instance.getPlugin(s);
}
@Override
public Plugin[] getPlugins() {
return instance.getPlugins();
}
@Override
public boolean isPluginEnabled(String s) {
return instance.isPluginEnabled(s);
}
@Override
public boolean isPluginEnabled(Plugin plugin) {
return instance.isPluginEnabled(plugin);
}
@Override
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return instance.loadPlugin(file);
}
@Override
public Plugin[] loadPlugins(File file) {
return instance.loadPlugins(file);
}
@Override
public void disablePlugins() {
for (Plugin plugin : getPlugins()) {
if (plugin != main) {
disablePlugin(plugin);
}
}
disablePlugin(main);
}
@Override
public void clearPlugins() {
instance.clearPlugins();
}
@Override
public void callEvent(Event event) throws IllegalStateException {
instance.callEvent(event);
}
@Override
public void registerEvents(Listener listener, Plugin plugin) {
instance.registerEvents(listener, plugin);
}
@Override
public void registerEvent(Class<? extends Event> aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin) {
instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin);
}
@Override
public void registerEvent(Class<? extends Event> aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin, boolean b) {
instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin, b);
}
@Override
public void enablePlugin(Plugin plugin) {
TDependencyInjector.injectOnEnable(plugin);
instance.enablePlugin(plugin);
}
@Override
public void disablePlugin(Plugin plugin) {
TDependencyInjector.onDisable(plugin);
instance.disablePlugin(plugin);
}
@Override
public Permission getPermission(String s) {
return instance.getPermission(s);
}
@Override
public void addPermission(Permission permission) {
instance.addPermission(permission);
}
@Override
public void removePermission(Permission permission) {
instance.removePermission(permission);
}
@Override
public void removePermission(String s) {
instance.removePermission(s);
}
@Override
public Set<Permission> getDefaultPermissions(boolean b) {
return instance.getDefaultPermissions(b);
}
@Override
public void recalculatePermissionDefaults(Permission permission) {
instance.recalculatePermissionDefaults(permission);
}
@Override
public void subscribeToPermission(String s, Permissible permissible) {
instance.subscribeToPermission(s, permissible);
}
@Override
public void unsubscribeFromPermission(String s, Permissible permissible) {
instance.unsubscribeFromPermission(s, permissible);
}
@Override
public Set<Permissible> getPermissionSubscriptions(String s) {
return instance.getPermissionSubscriptions(s);
}
@Override
public void subscribeToDefaultPerms(boolean b, Permissible permissible) {
instance.subscribeToDefaultPerms(b, permissible);
}
@Override
public void unsubscribeFromDefaultPerms(boolean b, Permissible permissible) {
instance.unsubscribeFromDefaultPerms(b, permissible);
}
@Override
public Set<Permissible> getDefaultPermSubscriptions(boolean b) {
return instance.getDefaultPermSubscriptions(b);
}
@Override
public Set<Permission> getPermissions() {
return instance.getPermissions();
}
@Override
public boolean useTimings() {
return instance.useTimings();
}
}

View File

@ -0,0 +1,90 @@
package com.ilummc.tlib.logger;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
public class TLogger {
public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6;
private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
private final String pattern;
private Plugin plugin;
private int level;
public static TLogger getGlobalLogger() {
return globalLogger;
}
public String getPattern() {
return pattern;
}
public Plugin getPlugin() {
return plugin;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public TLogger(String pattern, Plugin plugin, int level) {
this.pattern = pattern;
this.plugin = plugin;
this.level = level;
}
public void verbose(String msg) {
if (level <= VERBOSE) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§f全部", ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void finest(String msg) {
if (level <= FINEST) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§e良好", ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void fine(String msg) {
if (level <= FINE) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§a正常", ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void info(String msg) {
if (level <= INFO) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§b信息", ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void warn(String msg) {
if (level <= WARN) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§6警告", "§6" + ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void error(String msg) {
if (level <= ERROR) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§c错误", "§c" + ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public void fatal(String msg) {
if (level <= FATAL) {
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg)));
}
}
public static TLogger getUnformatted(Plugin plugin) {
return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", plugin, TLogger.FINE);
}
}

View File

@ -0,0 +1,49 @@
package com.ilummc.tlib.nms;
import com.ilummc.tlib.util.asm.AsmClassTransformer;
import me.skymc.taboolib.TabooLib;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public abstract class ActionBar {
private static ActionBar instance;
static {
if (TabooLib.getVerint() > 11100) {
instance = (ActionBar) AsmClassTransformer.builder().from(Impl_1_12.class).fromVersion("v1_12_R1")
.toVersion(Bukkit.getServer().getClass().getName().split("\\.")[3]).build().transform();
} else {
instance = (ActionBar) AsmClassTransformer.builder().from(Impl_1_8.class).fromVersion("v1_8_R3")
.toVersion(Bukkit.getServer().getClass().getName().split("\\.")[3]).build().transform();
}
}
public static void sendActionBar(Player player, String text) {
instance.send(player, text);
}
public abstract void send(Player player, String text);
public static class Impl_1_8 extends ActionBar {
@Override
public void send(Player player, String text) {
net.minecraft.server.v1_8_R3.ChatComponentText component = new net.minecraft.server.v1_8_R3.ChatComponentText(text);
net.minecraft.server.v1_8_R3.PacketPlayOutChat packet = new net.minecraft.server.v1_8_R3.PacketPlayOutChat(component, (byte) 2);
((org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
}
}
public static class Impl_1_12 extends ActionBar {
@Override
public void send(Player player, String text) {
net.minecraft.server.v1_12_R1.ChatComponentText component = new net.minecraft.server.v1_12_R1.ChatComponentText(text);
net.minecraft.server.v1_12_R1.PacketPlayOutChat packet = new net.minecraft.server.v1_12_R1.PacketPlayOutChat(component,
net.minecraft.server.v1_12_R1.ChatMessageType.a((byte) 2));
((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
}
}
}

View File

@ -0,0 +1,143 @@
package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.ChatColor;
import com.ilummc.tlib.inject.TLoggerManager;
import com.ilummc.tlib.util.Ref;
import com.ilummc.tlib.util.Strings;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class TLocale {
private TLocale() {
throw new AssertionError();
}
static String asString(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args);
}
static List<String> asStringList(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asStringList(getCallerPlugin(callerClass), path, args);
}
private static void sendTo(String path, CommandSender sender, String[] args, Class<?> callerClass) {
TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args);
}
public static void sendToConsole(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, Bukkit.getConsoleSender(), args, clazz));
}
public static void sendTo(CommandSender sender, String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, sender, args, clazz));
}
public static void sendTo(String path, CommandSender sender, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, sender, args, clazz));
}
public static String asString(String path, String... args) {
try {
return asString(path, Ref.getCallerClassNotOptional(3), args);
} catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage()));
return "§4<" + path + "§4>";
}
}
public static List<String> asStringList(String path, String... args) {
try {
return asStringList(path, Ref.getCallerClassNotOptional(3), args);
} catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage()));
return Collections.singletonList("§4<" + path + "§4>");
}
}
public static void reload() {
Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false));
}
private static JavaPlugin getCallerPlugin(Class<?> callerClass) {
try {
Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin");
pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader());
} catch (Exception ignored) {
TLocale.Logger.error("LOCALE.CALLER-PLUGIN-NOT-FOUND", callerClass.getName());
}
return (JavaPlugin) Main.getInst();
}
public static final class Translate extends TLocale {
public static boolean isPlaceholderUseDefault() {
return Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false);
}
public static boolean isPlaceholderPluginEnabled() {
return Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && Bukkit.getPluginManager().getPlugin("PlaceholderAPI").isEnabled();
}
public static String setColored(String args) {
return ChatColor.translateAlternateColorCodes('&', args);
}
public static List<String> setColored(List<String> args) {
return args.stream().map(var -> ChatColor.translateAlternateColorCodes('&', var)).collect(Collectors.toList());
}
public static String setPlaceholders(CommandSender sender, String args) {
return isPlaceholderPluginEnabled() ? sender instanceof Player ? PlaceholderAPI.setPlaceholders((Player) sender, args) : args : args;
}
public static List<String> setPlaceholders(CommandSender sender, List<String> args) {
return isPlaceholderPluginEnabled() ? sender instanceof Player ? PlaceholderAPI.setPlaceholders((Player) sender, args) : args : args;
}
}
public static final class Logger extends TLocale {
public static void info(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).info(asString(path, clazz, args)));
}
public static void warn(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).warn(asString(path, clazz, args)));
}
public static void error(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).error(asString(path, clazz, args)));
}
public static void fatal(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fatal(asString(path, clazz, args)));
}
public static void fine(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fine(asString(path, clazz, args)));
}
public static void finest(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).finest(asString(path, clazz, args)));
}
public static void verbose(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).verbose(asString(path, clazz, args)));
}
}
}

View File

@ -0,0 +1,118 @@
package com.ilummc.tlib.resources;
import com.google.common.collect.ImmutableList;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.resources.type.TLocaleText;
import com.ilummc.tlib.util.Strings;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@ThreadSafe
@SuppressWarnings("rawtypes")
class TLocaleInstance {
private final Map<String, List<TLocaleSerialize>> map = new HashMap<>();
private final Plugin plugin;
private final AtomicInteger latestUpdateNodes = new AtomicInteger();
TLocaleInstance(Plugin plugin) {
this.plugin = plugin;
}
@Override
public String toString() {
return map.toString();
}
public int size() {
return map.size();
}
public Map<String, List<TLocaleSerialize>> getMap() {
return map;
}
public Plugin getPlugin() {
return plugin;
}
public AtomicInteger getLatestUpdateNodes() {
return latestUpdateNodes;
}
public void sendTo(String path, CommandSender sender, String... args) {
try {
map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).forEach(tSender -> {
if (Bukkit.isPrimaryThread()) {
tSender.sendTo(sender, args);
} else {
Bukkit.getScheduler().runTask(plugin, () -> tSender.sendTo(sender, args));
}
});
} catch (Exception | Error e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("SEND-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.toString()));
e.printStackTrace();
}
}
public String asString(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).get(0).asString(args);
}
public List<String> asStringList(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSerialize.getEmpty(path))).get(0).asStringList(args);
}
private static boolean isListString(List list) {
for (Object o : list) {
if (!(o instanceof String)) {
return false;
}
}
return true;
}
public void load(YamlConfiguration configuration) {
load(configuration, false);
}
public void load(YamlConfiguration configuration, boolean cleanup) {
int originNodes = map.size();
int updateNodes = 0;
if (cleanup) {
map.clear();
}
for (String s : configuration.getKeys(true)) {
boolean updated = false;
Object value = configuration.get(s);
if (value instanceof TLocaleSerialize) {
updated = map.put(s, Collections.singletonList((TLocaleSerialize) value)) != null;
} else if (value instanceof List && !((List) value).isEmpty()) {
if (isListString((List) value)) {
updated = map.put(s, Collections.singletonList(TLocaleText.of(value))) != null;
} else {
updated = map.put(s, ((List<?>) value).stream().map(o -> o instanceof TLocaleSerialize ? (TLocaleSerialize) o : TLocaleText.of(String.valueOf(o))).collect(Collectors.toList())) != null;
}
} else if (!(value instanceof ConfigurationSection)) {
String str = String.valueOf(value);
updated = map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSerialize.getEmpty() : TLocaleText.of(str))) != null;
}
if (updated) {
updateNodes++;
}
}
latestUpdateNodes.set(originNodes - updateNodes);
}
}

View File

@ -0,0 +1,164 @@
package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.TLocalePlugin;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.type.*;
import com.ilummc.tlib.util.IO;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
public class TLocaleLoader {
private static final Map<String, TLocaleInstance> map = new ConcurrentHashMap<>();
public static void init() {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT");
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON");
ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND");
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE");
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION");
}
public static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) {
if (Bukkit.isPrimaryThread()) {
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
} else {
synchronized (TLocaleLoader.class) {
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
}
}
}
public static String asString(Plugin plugin, String path, String... args) {
TLocaleInstance tLocaleInstance = map.get(plugin.getName());
if (tLocaleInstance != null) {
return tLocaleInstance.asString(path, args);
} else {
return "";
}
}
public static List<String> asStringList(Plugin plugin, String path, String... args) {
TLocaleInstance tLocaleInstance = map.get(plugin.getName());
if (tLocaleInstance != null) {
return tLocaleInstance.asStringList(path, args);
} else {
return Collections.emptyList();
}
}
/**
* 载入语言文件
*
* @param plugin 载入插件
* @param isCover 是否覆盖
*/
public static void load(Plugin plugin, boolean isCover) {
try {
if (isLoadLocale(plugin, isCover)) {
// 获取文件
File localeFile = getLocaleFile(plugin);
if (localeFile == null) {
return;
}
// 加载文件
infoLogger("TRY-LOADING-LANG", plugin.getName(), localeFile.getName());
YamlConfiguration localeConfiguration = ConfigUtils.loadYaml(plugin, localeFile);
YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile);
// 载入配置
loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream);
// 注册监听
TLib.getTLib().getConfigWatcher().removeListener(localeFile);
TLib.getTLib().getConfigWatcher().addListener(localeFile, null, obj -> {
infoLogger("RELOADING-LANG", plugin.getName());
loadPluginLocale(plugin, localeFile, ConfigUtils.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile));
});
}
} catch (Exception e) {
errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString());
}
}
private static boolean isLoadLocale(Plugin plugin, boolean isCover) {
return (isCover || !isLocaleLoaded(plugin)) && (plugin.equals(Main.getInst()) || isDependWithTabooLib(plugin));
}
private static void infoLogger(String path, String... args) {
TLogger.getGlobalLogger().info(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args));
}
private static void errorLogger(String path, String... args) {
TLogger.getGlobalLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args));
}
private static File getLocaleFile(Plugin plugin) {
releaseLocales(plugin);
return getLocalePriority().stream().map(localeName -> new File(plugin.getDataFolder(), "lang/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null);
}
private static void releaseLocales(Plugin plugin) {
getLocalePriority().stream().filter(localeName -> !new File(plugin.getDataFolder(), "lang/" + localeName + ".yml").exists() && plugin.getResource("lang/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("lang/" + localeName + ".yml", true));
}
public static boolean isLocaleLoaded(Plugin plugin) {
return map.containsKey(plugin.getName());
}
public static boolean isDependWithTabooLib(Plugin plugin) {
return plugin.getClass().getAnnotation(TLocalePlugin.class) != null || plugin.getDescription().getDepend().contains(Main.getInst().getName()) || plugin.getDescription().getSoftDepend().contains(Main.getInst().getName());
}
public static List<String> getLocalePriority() {
return Main.getInst().getConfig().contains("LOCALE.PRIORITY") ? Main.getInst().getConfig().getStringList("LOCALE.PRIORITY") : Collections.singletonList("zh_CN");
}
private static TLocaleInstance getLocaleInstance(Plugin plugin) {
TLocaleInstance instance = new TLocaleInstance(plugin);
map.put(plugin.getName(), instance);
return instance;
}
private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) {
InputStream localeInputSteam = plugin.getClass().getResourceAsStream("/lang/" + localeFile.getName());
try {
String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8"));
YamlConfiguration yaml = new YamlConfiguration();
yaml.loadFromString(yamlText);
return yaml;
} catch (Exception ignored) {
return null;
}
}
private static void loadPluginLocale(Plugin plugin, File localeFile, YamlConfiguration localeConfiguration, YamlConfiguration localeConfigurationAtStream) {
TLocaleInstance localeInstance = getLocaleInstance(plugin);
if (localeConfigurationAtStream != null) {
localeInstance.load(localeConfigurationAtStream);
}
localeInstance.load(localeConfiguration);
if (localeInstance.getLatestUpdateNodes().get() <= 0) {
infoLogger("SUCCESS-LOADING-LANG-NORMAL", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size()));
} else {
infoLogger("SUCCESS-LOADING-LANG-UPDATE", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size()), String.valueOf(localeInstance.getLatestUpdateNodes().get()));
}
}
}

View File

@ -0,0 +1,37 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import java.util.List;
/**
* @Author sky
* @Since 2018-05-12 13:58
*/
public interface TLocaleSender {
/**
* 发送信息
*
* @param sender 发送目标
* @param args 参数
*/
void sendTo(CommandSender sender, String... args);
/**
* 获取文本
*
* @param args 参数
* @return 文本
*/
String asString(String... args);
/**
* 获取文本集合
*
* @param args 参数
* @return 文本集合
*/
List<String> asStringList(String... args);
}

View File

@ -0,0 +1,84 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @Author sky
* @Since 2018-05-12 14:01
*/
public abstract class TLocaleSerialize implements TLocaleSender, ConfigurationSerializable {
public static boolean isPlaceholderEnabled(Map<String, Object> map) {
Object placeholderObject = map.getOrDefault("papi", TLocale.Translate.isPlaceholderUseDefault());
return placeholderObject instanceof Boolean ? (boolean) placeholderObject : placeholderObject instanceof String && "true".equals(placeholderObject);
}
public static String getStringOrDefault(Map<String, Object> map, String path, String def) {
Object var = map.getOrDefault(path, def);
return var instanceof String ? (String) var : def;
}
public static Integer getIntegerOrDefault(Map<String, Object> map, String path, Integer def) {
Object var = map.getOrDefault(path, def);
return var instanceof Integer ? (Integer) var : def;
}
public static Double getDoubleOrDefault(Map<String, Object> map, String path, Double def) {
Object var = map.getOrDefault(path, def);
return var instanceof Double ? (Double) var : def;
}
static TLocaleSerialize getEmpty() {
return new TLocaleSerialize() {
@Override
public void sendTo(CommandSender sender, String... args) {
}
@Override
public Map<String, Object> serialize() {
return null;
}
};
}
static TLocaleSerialize getEmpty(String path) {
return new TLocaleSerialize() {
@Override
public Map<String, Object> serialize() {
return null;
}
@Override
public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>");
}
@Override
public String asString(String... args) {
return "§4<" + path + "§4>";
}
@Override
public List<String> asStringList(String... args) {
return Collections.singletonList("§4<" + path + "§4>");
}
};
}
@Override
public String asString(String... args) {
return "";
}
@Override
public List<String> asStringList(String... args) {
return Collections.emptyList();
}
}

View File

@ -0,0 +1,61 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.nms.ActionBar;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.Immutable;
import java.util.Map;
@Immutable
@SerializableAs("ACTION")
public class TLocaleActionBar extends TLocaleSerialize {
private final String text;
private final boolean papi;
private TLocaleActionBar(String text, boolean papi) {
this.text = text;
this.papi = papi;
}
public static TLocaleActionBar valueOf(Map<String, Object> map) {
String text = ChatColor.translateAlternateColorCodes('&', String.valueOf(map.getOrDefault("text", "Empty Action bar message.")));
return new TLocaleActionBar(text, isPlaceholderEnabled(map));
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player) {
ActionBar.sendActionBar(((Player) sender), replace(sender, text, args));
}
}
private String replace(CommandSender sender, String text, String[] args) {
String s = Strings.replaceWithOrder(text, args);
return papi ? PlaceholderHook.replace(sender, s) : s;
}
@Override
public String asString(String... args) {
return "ActionBar: [" + text + "]";
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = Maps.newHashMap();
map.put("text", text);
if (papi) {
map.put("papi", true);
}
return map;
}
}

View File

@ -0,0 +1,169 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.chat.*;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.ThreadSafe;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ThreadSafe
@SerializableAs("JSON")
public class TLocaleJson extends TLocaleSerialize {
private static final Pattern pattern = Pattern.compile("<([^<>]*)?@([^<>]*)>");
private final List<BaseComponent[]> components;
private final boolean papi;
private final Map<String, Object> map;
private TLocaleJson(List<BaseComponent[]> components, boolean papi, Map<String, Object> map) {
this.components = ImmutableList.copyOf(components);
this.papi = papi;
this.map = map;
}
public static TLocaleJson valueOf(Map<String, Object> map) {
List<String> textList = getTextList(map.getOrDefault("text", "Empty Node"));
// 分析 args 并替换
Object argsObj = map.get("args");
if (argsObj instanceof Map) {
Map<String, Object> section = new HashMap<>(((Map<?, ?>) argsObj).size());
// valueOf(k) 是因为这个键可能加载为一个 Integer 导致 contains(String) 返回 false
((Map<?, ?>) argsObj).forEach((k, v) -> section.put(String.valueOf(k), v));
List<BaseComponent[]> collect = textList.stream().map(s -> {
int index = 0;
String[] template = pattern.split(s);
Matcher matcher = pattern.matcher(s);
// 有可能开头和结尾是替换文本所以做个特判
List<BaseComponent> builder = template.length > index ? new ArrayList<>(Arrays.asList(TextComponent.fromLegacyText(template[index++]))) : new ArrayList<>();
while (matcher.find()) {
String replace = matcher.group();
// 假的 <@>
if (replace.length() <= 2) {
continue;
}
// 真的 <@xxx>
replace = replace.substring(1, replace.length() - 1);
String[] split = replace.split("@");
// @ 前面的字符串
String text = split.length > 1 ? split[0] : "";
// @ 后面的节点名
String node = split.length > 1 ? split[1] : split[0];
// 如果 args 有这个 xxx
if (section.containsKey(node)) {
Map<String, Object> arg = (Map<String, Object>) section.get(node);
text = TLocale.Translate.setColored(String.valueOf(arg.getOrDefault("text", text)));
// 可能有很多个 BaseComponent于是为每个 component 单独设置各种事件
BaseComponent[] component = TextComponent.fromLegacyText(text);
arg.forEach((key, value) -> {
if ("suggest".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value))));
} else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value))));
} else if ("hover".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create())));
}
});
// 添加到原来的 list 里面
builder.addAll(Arrays.asList(component));
} else {
// 这个参数节点并没有找到于是随便放点字符串进去
builder.addAll(Arrays.asList(TextComponent.fromLegacyText(text)));
TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("MISSING-ARGUMENT"), node));
}
// 有可能一开头就是 <@xxx>然后 split 出来就少了一些于是直接加上
if (index < template.length) {
builder.addAll(Arrays.asList(TextComponent.fromLegacyText(template[index++])));
}
}
return builder.toArray(new BaseComponent[0]);
}).collect(Collectors.toList());
return new TLocaleJson(collect, isPlaceholderEnabled(map), map);
}
return new TLocaleJson(textList.stream().map(TextComponent::fromLegacyText).collect(Collectors.toList()), isPlaceholderEnabled(map), map);
}
private static List<String> getTextList(Object textObj) {
if (textObj instanceof List) {
return ((List<?>) textObj).stream().map(Object::toString).map(s -> TLocale.Translate.setColored(s)).collect(Collectors.toList());
} else if (textObj instanceof String) {
return Lists.newArrayList(TLocale.Translate.setColored((String) textObj));
} else {
return Collections.emptyList();
}
}
@Override
public void sendTo(CommandSender sender, String... args) {
components.forEach(comp -> sendRawMessage(sender, replace(comp, sender, args)));
}
@Override
public String asString(String... args) {
return components.toString();
}
@Override
public Map<String, Object> serialize() {
return Maps.newHashMap(map);
}
private void sendRawMessage(CommandSender sender, BaseComponent[] components) {
if (sender instanceof Player) {
JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components));
} else {
sender.sendMessage(TextComponent.toLegacyText(components));
}
}
private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) {
BaseComponent[] components = new BaseComponent[component.length];
for (int i = 0; i < components.length; i++) {
components[i] = replace(component[i].duplicate(), sender, args);
}
return components;
}
private List<BaseComponent> replace(List<BaseComponent> component, CommandSender sender, String... args) {
return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList());
}
private BaseComponent replace(BaseComponent component, CommandSender sender, String... args) {
if (component.getClickEvent() != null) {
ClickEvent clickEvent = new ClickEvent(component.getClickEvent().getAction(), replace(sender, component.getClickEvent().getValue(), args));
component.setClickEvent(clickEvent);
}
if (component.getHoverEvent() != null) {
HoverEvent hoverEvent = new HoverEvent(component.getHoverEvent().getAction(), replace(component.getHoverEvent().getValue(), sender, args));
component.setHoverEvent(hoverEvent);
}
if (component.getExtra() != null) {
component.setExtra(replace(component.getExtra(), sender, args));
}
if (component instanceof TextComponent) {
((TextComponent) component).setText(replace(sender, ((TextComponent) component).getText(), args));
}
return component;
}
private String replace(CommandSender sender, String text, String[] args) {
String s = Strings.replaceWithOrder(text, args);
return papi ? PlaceholderHook.replace(sender, s) : s;
}
}

View File

@ -0,0 +1,68 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.resources.TLocaleSerialize;
import me.skymc.taboolib.sound.SoundPack;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.Immutable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author sky
* @Since 2018-05-06 14:35
*/
@Immutable
@SerializableAs("ACTION")
public class TLocaleSound extends TLocaleSerialize {
private final List<SoundPack> soundPacks;
public TLocaleSound(List<SoundPack> soundPacks) {
this.soundPacks = soundPacks;
}
public static TLocaleSound valueOf(Map<String, Object> map) {
List<SoundPack> soundPacks = new ArrayList<>();
Object sounds = map.containsKey("sounds") ? map.get("sounds") : map.getOrDefault("sound", "");
if (sounds instanceof List) {
soundPacks = ((List<String>) sounds).stream().map(SoundPack::new).collect(Collectors.toList());
} else {
soundPacks.add(new SoundPack(sounds.toString()));
}
return new TLocaleSound(soundPacks);
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player) {
soundPacks.forEach(x -> x.play((Player) sender));
}
}
@Override
public String asString(String... args) {
return toString();
}
@Override
public String toString() {
return "soundPacks=" + "TLocaleSound{" + soundPacks + '}';
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = Maps.newHashMap();
if (soundPacks.size() == 1) {
map.put("sounds", soundPacks.get(0).toString());
} else if (soundPacks.size() > 1) {
map.put("sounds", soundPacks.stream().map(SoundPack::toString).collect(Collectors.toList()));
}
return map;
}
}

View File

@ -0,0 +1,107 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import javax.annotation.concurrent.Immutable;
import java.util.*;
import java.util.stream.Collectors;
@Immutable
@SerializableAs("TEXT")
@SuppressWarnings({"unchecked", "rawtypes"})
public class TLocaleText extends TLocaleSerialize {
private final Object text;
private final boolean usePlaceholder;
private TLocaleText(Object text, boolean usePlaceholder) {
this.usePlaceholder = usePlaceholder;
if (text instanceof String) {
this.text = text;
} else if (text instanceof List) {
this.text = ImmutableList.copyOf(((List) text));
} else {
throw new IllegalArgumentException("Param 'text' can only be an instance of String or List<String>");
}
}
public static TLocaleText of(String s) {
return new TLocaleText(TLocale.Translate.setColored(s), TLocale.Translate.isPlaceholderUseDefault());
}
public static TLocaleText of(Object o) {
return o instanceof String ? of(((String) o)) : new TLocaleText(o, false);
}
public static TLocaleText valueOf(Map<String, Object> map) {
if (map.containsKey("text")) {
Object object = map.get("text");
if (object instanceof String[]) {
return new TLocaleText(Arrays.stream(((String[]) object)).collect(Collectors.toList()), isPlaceholderEnabled(map));
} else {
return new TLocaleText(Objects.toString(object), isPlaceholderEnabled(map));
}
}
return new TLocaleText("§cError chat message loaded.", TLocale.Translate.isPlaceholderUseDefault());
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (text instanceof String) {
sender.sendMessage(replaceText(sender, Strings.replaceWithOrder((String) text, args)));
} else if (text instanceof List) {
((List) text).forEach(s -> sender.sendMessage(replaceText(sender, Strings.replaceWithOrder(String.valueOf(s), args))));
}
}
@Override
public String asString(String... args) {
return Strings.replaceWithOrder(TLocale.Translate.setColored(objectToString(text)), args);
}
@Override
public List<String> asStringList(String... args) {
if (text instanceof List) {
return ((List<String>) text).stream().map(x -> Strings.replaceWithOrder(TLocale.Translate.setColored(x), args)).collect(Collectors.toList());
} else {
return Collections.singletonList(asString(args));
}
}
@Override
public String toString() {
if (text instanceof String[]) {
return Arrays.toString((String[]) text);
} else {
return text.toString();
}
}
@Override
public Map<String, Object> serialize() {
return usePlaceholder ? Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)) : Maps.newHashMap(ImmutableMap.of("text", text));
}
private String replaceText(CommandSender sender, String args) {
return usePlaceholder ? TLocale.Translate.setPlaceholders(sender, args) : TLocale.Translate.setColored(args);
}
private String objectToString(Object text) {
if (text instanceof String) {
return ((String) text);
} else {
StringJoiner joiner = new StringJoiner("\n");
((List<String>) text).forEach(joiner::add);
return joiner.toString();
}
}
}

View File

@ -0,0 +1,92 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.display.TitleUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.Immutable;
import java.util.HashMap;
import java.util.Map;
/**
* @author Bkm016
* @since 2018-04-22
*/
@Immutable
@SerializableAs("TITLE")
public class TLocaleTitle extends TLocaleSerialize {
private final String title;
private final String subtitle;
private final int fadein;
private final int fadeout;
private final int stay;
private boolean usePlaceholder;
private TLocaleTitle(String title, String subString, int fadein, int fadeout, int stay, boolean usePlaceholder) {
this.title = title;
this.subtitle = subString;
this.fadein = fadein;
this.fadeout = fadeout;
this.stay = stay;
this.usePlaceholder = usePlaceholder;
}
public static TLocaleTitle valueOf(Map<String, Object> map) {
TLocaleTitle title;
try {
title = new TLocaleTitle(
getStringOrDefault(map, "title", ""),
getStringOrDefault(map, "subtitle", ""),
getIntegerOrDefault(map, "fadein", 10),
getIntegerOrDefault(map, "fadeout", 10),
getIntegerOrDefault(map, "stay", 10),
isPlaceholderEnabled(map));
} catch (Exception e) {
title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false);
}
return title;
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player) {
TitleUtils.sendTitle((Player) sender, replaceText(sender, title), replaceText(sender, subtitle), fadein, stay, fadeout);
} else {
TLocale.Logger.error("LOCALE.TITLE-SEND-TO-NON-PLAYER", asString(args));
}
}
@Override
public String asString(String... args) {
return Strings.replaceWithOrder(Strings.replaceWithOrder("TITLE: [title: ''{0}'', subtitle: ''{1}'', fadeIn: {2}, fadeOut: {3}]", title, subtitle, fadein, fadeout), args);
}
@Override
public String toString() {
return asString();
}
@Override
public Map<String, Object> serialize() {
HashMap<String, Object> map = Maps.newHashMap();
map.put("papi", usePlaceholder);
map.put("title", title);
map.put("subtitle", subtitle);
map.put("fadein", fadein);
map.put("fadeout", fadeout);
map.put("stay", stay);
return map;
}
private String replaceText(CommandSender sender, String args) {
return usePlaceholder ? TLocale.Translate.setPlaceholders(sender, args) : TLocale.Translate.setColored(args);
}
}

View File

@ -0,0 +1,18 @@
package com.ilummc.tlib.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class IO {
public static byte[] readFully(InputStream inputStream) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf)) > 0) {
stream.write(buf, 0, len);
}
return stream.toByteArray();
}
}

View File

@ -0,0 +1,137 @@
package com.ilummc.tlib.util;
import com.google.gson.annotations.SerializedName;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.util.asm.AsmAnalyser;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import sun.reflect.Reflection;
import javax.annotation.concurrent.ThreadSafe;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@ThreadSafe
public class Ref {
private static final Map<String, List<Field>> cachedFields = new ConcurrentHashMap<>();
public static final int ACC_BRIDGE = 0x0040;
public static final int ACC_SYNTHETIC = 0x1000;
public static List<Field> getDeclaredFields(Class<?> clazz) {
return getDeclaredFields(clazz, 0, true);
}
public static List<Field> getDeclaredFields(String clazz, int excludeModifiers, boolean cache) {
try {
return getDeclaredFields(Class.forName(clazz), excludeModifiers, cache);
} catch (ClassNotFoundException e) {
return Collections.emptyList();
}
}
public static List<Field> getDeclaredFields(Class<?> clazz, int excludeModifiers, boolean cache) {
try {
// 特殊判断
if (clazz == TLib.class) {
return Arrays.asList(clazz.getDeclaredFields());
}
List<Field> fields;
if ((fields = cachedFields.get(clazz.getName())) != null) {
return fields;
}
ClassReader classReader = new ClassReader(clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class"));
AsmAnalyser analyser = new AsmAnalyser(new ClassWriter(ClassWriter.COMPUTE_MAXS), excludeModifiers);
classReader.accept(analyser, ClassReader.SKIP_DEBUG);
fields = analyser.getFields().stream().map(name -> {
try {
return clazz.getDeclaredField(name);
} catch (Throwable ignored) {
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
if (cache) {
cachedFields.putIfAbsent(clazz.getName(), fields);
}
return fields;
} catch (Exception | Error e) {
try {
List<Field> list = Arrays.stream(clazz.getDeclaredFields())
.filter(field -> (field.getModifiers() & excludeModifiers) == 0).collect(Collectors.toList());
cachedFields.putIfAbsent(clazz.getName(), list);
return list;
} catch (Error err) {
return Collections.emptyList();
}
}
}
public static Optional<Class<?>> getCallerClass(int depth) {
return Optional.ofNullable(CallerClass.impl.getCallerClass(depth + 1));
}
public static Class<?> getCallerClassNotOptional(int depth) {
return CallerClass.impl.getCallerClass(depth);
}
public static String getSerializedName(Field field) {
return field.isAnnotationPresent(SerializedName.class) ? field.getAnnotation(SerializedName.class).value() : field.getName();
}
public static Optional<Field> getFieldBySerializedName(Class<?> clazz, String name) {
for (Field field : Ref.getDeclaredFields(clazz, 0, false)) {
if (field.isAnnotationPresent(SerializedName.class)) {
if (field.getAnnotation(SerializedName.class).value().equals(name)) {
return Optional.of(field);
} else if (field.getName().equals(name)) {
return Optional.of(field);
}
}
}
return Optional.empty();
}
private static abstract class CallerClass {
private static CallerClass impl;
static {
try {
Class.forName("sun.reflect.Reflection");
impl = new ReflectionImpl();
} catch (ClassNotFoundException e) {
impl = new StackTraceImpl();
}
}
abstract Class<?> getCallerClass(int i);
private static class ReflectionImpl extends CallerClass {
@SuppressWarnings({"deprecation", "restriction"})
@Override
Class<?> getCallerClass(int i) {
return Reflection.getCallerClass(i);
}
}
private static class StackTraceImpl extends CallerClass {
@Override
Class<?> getCallerClass(int i) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
try {
return Class.forName(elements[i].getClassName());
} catch (ClassNotFoundException e) {
return null;
}
}
}
}
}

View File

@ -0,0 +1,42 @@
package com.ilummc.tlib.util;
public class Strings {
/**
* 优化过的 String#replace比默认快了大概 5
*
* @param template 模板替换文件
* @param args 替换的参数
* @return 替换好的字符串
*/
public static String replaceWithOrder(String template, Object... args) {
if (args.length == 0 || template.length() == 0) {
return template;
}
char[] arr = template.toCharArray();
StringBuilder stringBuilder = new StringBuilder(template.length());
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '{' && Character.isDigit(arr[Math.min(i + 1, arr.length - 1)])
&& arr[Math.min(i + 1, arr.length - 1)] - '0' < args.length
&& arr[Math.min(i + 2, arr.length - 1)] == '}') {
stringBuilder.append(args[arr[i + 1] - '0']);
i += 2;
} else {
stringBuilder.append(arr[i]);
}
}
return stringBuilder.toString();
}
public static String replaceWithOrder(String template, String... args) {
return replaceWithOrder(template, (Object[]) args);
}
public static boolean isBlank(String var) {
return var == null || var.trim().isEmpty();
}
public static boolean isEmpty(CharSequence var) {
return var == null || var.length() == 0;
}
}

View File

@ -0,0 +1,32 @@
package com.ilummc.tlib.util.asm;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.List;
public class AsmAnalyser extends ClassVisitor implements Opcodes {
private final List<String> fields = new ArrayList<>();
private final int excludeModifier;
public AsmAnalyser(ClassVisitor classVisitor, int excludeModifiers) {
super(Opcodes.ASM6, classVisitor);
this.excludeModifier = excludeModifiers;
}
@Override
public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
if ((access & excludeModifier) == 0) {
fields.add(name);
}
return super.visitField(access, name, descriptor, signature, value);
}
public List<String> getFields() {
return fields;
}
}

View File

@ -0,0 +1,13 @@
package com.ilummc.tlib.util.asm;
public class AsmClassLoader extends ClassLoader {
public AsmClassLoader() {
super(AsmClassLoader.class.getClassLoader());
}
public Class<?> createNewClass(String name, byte[] arr) {
return defineClass(name, arr, 0, arr.length, AsmClassLoader.class.getProtectionDomain());
}
}

View File

@ -0,0 +1,159 @@
package com.ilummc.tlib.util.asm;
import org.bukkit.Bukkit;
import org.objectweb.asm.*;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
public class AsmClassTransformer extends ClassVisitor implements Opcodes {
private final Class<?> from;
private final String fromVer, toVer;
private final ClassWriter writer;
private String newClassName, prevName;
private AsmClassTransformer(Class<?> from, String fromVer, String toVer, ClassWriter classWriter) {
super(Opcodes.ASM6, classWriter);
writer = classWriter;
this.from = from;
this.fromVer = fromVer;
this.toVer = toVer;
}
public Object transform() {
try {
ClassReader classReader = new ClassReader(from.getResourceAsStream("/" + from.getName().replace('.', '/') + ".class"));
newClassName = from.getName() + "_TabooLibRemap_" + this.hashCode() + "_" + toVer;
prevName = from.getName().replace('.', '/');
classReader.accept(this, ClassReader.SKIP_DEBUG);
Class<?> clazz = new AsmClassLoader().createNewClass(newClassName, writer.toByteArray());
Field field = from.getClassLoader().getClass().getDeclaredField("classes");
field.setAccessible(true);
((Map<String, Class<?>>) field.get(from.getClassLoader())).put(newClassName, clazz);
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (IOException | NoSuchFieldException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public static Builder builder() {
return new Builder().toVersion(Bukkit.getServer().getClass().getName().split("\\.")[3]);
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor visitor = super.visitMethod(access, name, replace(descriptor), replace(signature), replace(exceptions));
return new AsmMethodTransformer(visitor);
}
@Override
public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
return super.visitField(access, name, replace(descriptor), replace(signature), value);
}
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
super.visitInnerClass(replace(name), outerName, replace(name).substring(outerName.length() + 1), access);
}
private String replace(String text) {
if (text != null) {
return text.replace("net/minecraft/server/" + fromVer, "net/minecraft/server/" + toVer)
.replace("org/bukkit/craftbukkit/" + fromVer, "org/bukkit/craftbukkit/" + toVer)
.replace(prevName, newClassName.replace('.', '/'));
} else {
return null;
}
}
private String[] replace(String[] text) {
if (text != null) {
for (int i = 0; i < text.length; i++) {
text[i] = replace(text[i]);
}
return text;
} else {
return null;
}
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, newClassName.replace('.', '/'), replace(signature),
replace(superName), replace(interfaces));
}
private class AsmMethodTransformer extends MethodVisitor {
AsmMethodTransformer(MethodVisitor visitor) {
super(Opcodes.ASM6, visitor);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
super.visitMethodInsn(opcode, replace(owner), name, replace(descriptor), isInterface);
}
@Override
public void visitLdcInsn(Object value) {
if (value instanceof String) {
super.visitLdcInsn(replace((String) value));
} else {
super.visitLdcInsn(value);
}
}
@Override
public void visitTypeInsn(int opcode, String type) {
super.visitTypeInsn(opcode, replace(type));
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String descriptor) {
super.visitFieldInsn(opcode, replace(owner), name, replace(descriptor));
}
@Override
public void visitLocalVariable(String name, String descriptor, String signature, Label start, Label end, int index) {
super.visitLocalVariable(name, replace(descriptor), replace(signature), start, end, index);
}
}
public static class Builder {
private Class<?> from;
private String fromVersion, toVersion;
public Builder from(Class<?> clazz) {
this.from = clazz;
return this;
}
public Builder fromVersion(String ver) {
fromVersion = ver;
return this;
}
public Builder toVersion(String ver) {
toVersion = ver;
return this;
}
public AsmClassTransformer build() {
return new AsmClassTransformer(from, fromVersion, toVersion, new ClassWriter(ClassWriter.COMPUTE_MAXS));
}
}
}

Some files were not shown because too many files have changed in this diff Show More