This commit is contained in:
Olof Larsson 2011-02-06 13:36:11 +01:00
commit b3ac8f8614
27 changed files with 4173 additions and 0 deletions

19
.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
# Eclipse stuff
/.classpath
/.project
/.settings
# netbeans
/nbproject
# vim
.*.sw[a-p]
# various other potential build files
/build
/bin
/dist
/manifest.mf
# Mac filesystem dust
/.DS_Store

165
LGPL.txt Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER 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.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

674
LICENCE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <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) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <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:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<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>.

7
README.md Normal file
View File

@ -0,0 +1,7 @@
Factions
====================
TODO write this
Compiling
---------
TODO write this

3
packaging/MANIFEST.MF Normal file
View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path: ../gson.jar

View File

@ -0,0 +1,13 @@
Copyright (c) 2008-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

BIN
packaging/gson.jar Normal file

Binary file not shown.

3
packaging/plugin.yml Normal file
View File

@ -0,0 +1,3 @@
name: Factions
version: 1.0 beta
main: com.bukkit.mcteam.factions.Factions

View File

@ -0,0 +1,704 @@
package com.bukkit.mcteam.factions;
import java.util.*;
import org.bukkit.ChatColor;
import com.bukkit.mcteam.factions.entities.*;
import com.bukkit.mcteam.factions.struct.*;
import com.bukkit.mcteam.factions.util.*;
public class Commands {
public static ArrayList<ArrayList<String>> helpPages;
//----------------------------------------------//
// Build the help pages
//----------------------------------------------//
static {
helpPages = new ArrayList<ArrayList<String>>();
ArrayList<String> pageLines;
pageLines = new ArrayList<String>();
pageLines.add(TextUtil.commandHelp(Conf.aliasHelp, "[page]", "Display this, or the next help page"));
pageLines.add(TextUtil.commandHelp(Conf.aliasList, "", "List all factions"));
pageLines.add(TextUtil.commandHelp(Conf.aliasShow, "*[faction name]", "Show faction information")); // TODO display relations!
pageLines.add(TextUtil.commandHelp(Conf.aliasMap, "*[on|off]", "Show territory map, set optional auto update.")); // TODO COMPASS
pageLines.add(TextUtil.commandHelp(Conf.aliasJoin, "[faction name]", "Join a faction"));
pageLines.add(TextUtil.commandHelp(Conf.aliasLeave, "", "Leave your faction"));
pageLines.add(TextUtil.commandHelp(Conf.aliasCreate, "[faction name]", "Create new faction"));
pageLines.add(TextUtil.commandHelp(Conf.aliasName, "[faction name]", "Rename your faction"));
pageLines.add(TextUtil.commandHelp(Conf.aliasDescription, "[description]", "Set the description for your faction"));
helpPages.add(pageLines);
pageLines = new ArrayList<String>();
pageLines.add(TextUtil.commandHelp(Conf.aliasOpen, "", "Switch if invitation is required to join"));
pageLines.add(TextUtil.commandHelp(Conf.aliasTitle, "[player name] *[title]", "Set or remove a players title"));
pageLines.add(TextUtil.commandHelp(Conf.aliasInvite, "[player name]", "Invite player"));
pageLines.add(TextUtil.commandHelp(Conf.aliasDeinvite, "[player name]", "Remove a pending invitation"));
pageLines.add(TextUtil.commandHelp(Conf.aliasKick, "[player name]", "Kick a player from the faction"));
pageLines.add(TextUtil.commandHelp(Conf.aliasModerator, "[player name]", "Give or revoke moderator rights")); // TODO
pageLines.add(TextUtil.commandHelp(Conf.aliasAdmin, "[player name]", "Hand over your admin rights")); // TODO
pageLines.add(TextUtil.commandHelp(Conf.aliasClaim, "", "Claim the land where you are standing"));
pageLines.add(TextUtil.commandHelp(Conf.aliasUnclaim, "", "Unclaim the land where you are standing"));
helpPages.add(pageLines);
pageLines = new ArrayList<String>();
pageLines.add(TextUtil.commandHelp(Conf.aliasRelationAlly, "[faction name]", " "));
pageLines.add(TextUtil.commandHelp(Conf.aliasRelationNeutral, "[faction name]", " "));
pageLines.add(TextUtil.commandHelp(Conf.aliasRelationEnemy, "[faction name]", " "));
pageLines.add("");
pageLines.add(Conf.colorSystem+"Set which relation your WHISH you had to another faction.");
pageLines.add(Conf.colorSystem+"Per default your relation to another faction will be neutral.");
pageLines.add("");
pageLines.add(Conf.colorSystem+"If BOTH factions whishes \"ally\" you will be allies.");
pageLines.add(Conf.colorSystem+"If ONE faction whishes \"enemy\" you will be enemies.");
helpPages.add(pageLines);
pageLines = new ArrayList<String>();
pageLines.add(Conf.colorSystem+"You can never hurt members or allies.");
pageLines.add(Conf.colorSystem+"You can not hurt neutrals in their own territory.");
pageLines.add(Conf.colorSystem+"You can always hurt enemies and players without faction.");
pageLines.add("");
pageLines.add(Conf.colorSystem+"Damage from enemies are reduced in your own territory.");
pageLines.add(Conf.colorSystem+"When you die you loose power. It is restored over time.");
pageLines.add(Conf.colorSystem+"The power of a faction is the sum of all member power.");
pageLines.add(Conf.colorSystem+"The power of a faction determines how much land it can hold.");
pageLines.add(Conf.colorSystem+"You can claim land from a faction if it has to low power.");
helpPages.add(pageLines);
pageLines = new ArrayList<String>();
pageLines.add(Conf.colorSystem+"Only faction members can build and destroy in their own");
pageLines.add(Conf.colorSystem+"territory. Usage of the following items is also restricted:");
pageLines.add(Conf.colorSystem+"Door, Chest, Furnace and Dispenser.");
pageLines.add(" ");
pageLines.add(Conf.colorSystem+"Make sure to put pressure plates in front of doors for your");
pageLines.add(Conf.colorSystem+"guest visitors. Otherwise they can't get through. You can ");
pageLines.add(Conf.colorSystem+"also use this to create member only areas.");
pageLines.add(Conf.colorSystem+"As dispensers are protected you can create traps without");
pageLines.add(Conf.colorSystem+"worrying about those arrows getting stolen.");
helpPages.add(pageLines);
}
//----------------------------------------------//
// Some utils
//----------------------------------------------//
public static Follower findFollower(Follower me, String name, boolean defaultsToMe) {
if (name.length() == 0 && defaultsToMe) {
return me;
}
Follower follower = Follower.find(name);
if (follower != null) {
return follower;
}
me.sendMessage(Conf.colorSystem+"The player \""+name+"\" could not be found");
return null;
}
public static Faction findFaction(Follower me, String name, boolean defaultsToMe) {
if (name.length() == 0 && defaultsToMe) {
return me.getFaction();
}
// Search player names
Follower follower = Follower.find(name);
if (follower != null) {
return follower.getFaction();
}
// Then faction names
Faction faction = Faction.find(name);
if (faction != null) {
return faction;
}
me.sendMessage(Conf.colorSystem+"No faction or player \""+name+"\" was found");
return null;
}
public static boolean canIAdministerYou(Follower i, Follower you) {
if ( ! i.getFaction().equals(you.getFaction())) {
i.sendMessage(you.getFullName(i)+Conf.colorSystem+" is not in the same faction as you.");
return false;
}
if (i.role.value > you.role.value || i.role.equals(Role.ADMIN) ) {
return true;
}
if (you.role.equals(Role.ADMIN)) {
i.sendMessage(Conf.colorSystem+"Only the faction admin can do that.");
} else if (i.role.equals(Role.MODERATOR)) {
i.sendMessage(Conf.colorSystem+"Moderators can't controll eachother...");
} else {
i.sendMessage(Conf.colorSystem+"You must be a faction moderator to do that.");
}
return false;
}
//----------------------------------------------//
// The base command
//----------------------------------------------//
public static void base(Follower me, ArrayList<String> tokens) {
if (tokens.size() == 0) {
help(me);
return;
}
String command = tokens.get(0).toLowerCase();
tokens.remove(0);
if (Conf.aliasHelp.contains(command)) {
int page = 1;
if (tokens.size() > 0) {
page = Integer.parseInt(tokens.get(0));
}
help(me, page);
} else if (Conf.aliasLeave.contains(command)) {
leave(me);
} else if (Conf.aliasJoin.contains(command)) {
join(me, TextUtil.implode(tokens));
} else if (Conf.aliasCreate.contains(command)) {
create(me, TextUtil.implode(tokens));
} else if (Conf.aliasName.contains(command)) {
name(me, TextUtil.implode(tokens));
} else if (Conf.aliasList.contains(command)) {
list(me);
} else if (Conf.aliasShow.contains(command)) {
showFaction(me, TextUtil.implode(tokens));
} else if (Conf.aliasMap.contains(command)) {
showMap(me, TextUtil.implode(tokens));
} else if (Conf.aliasInvite.contains(command)) {
invite(me, TextUtil.implode(tokens));
} else if (Conf.aliasDeinvite.contains(command)) {
deinvite(me, TextUtil.implode(tokens));
} else if (Conf.aliasOpen.contains(command)) {
open(me);
} else if (Conf.aliasTitle.contains(command)) {
title(me, tokens);
} else if (Conf.aliasKick.contains(command)) {
kick(me, TextUtil.implode(tokens));
} else if (Conf.aliasModerator.contains(command)) {
roleChange(me, Role.MODERATOR, TextUtil.implode(tokens));
} else if (Conf.aliasAdmin.contains(command)) {
roleChange(me, Role.ADMIN, TextUtil.implode(tokens));
} else if (Conf.aliasClaim.contains(command)) {
claim(me);
} else if (Conf.aliasUnclaim.contains(command)) {
unclaim(me);
} else if (Conf.aliasRelationAlly.contains(command)) {
relation(me, Relation.ALLY, TextUtil.implode(tokens));
} else if (Conf.aliasRelationNeutral.contains(command)) {
relation(me, Relation.NEUTRAL, TextUtil.implode(tokens));
} else if (Conf.aliasRelationEnemy.contains(command)) {
relation(me, Relation.ENEMY, TextUtil.implode(tokens));
} else if (Conf.aliasDescription.contains(command)) {
description(me, TextUtil.implode(tokens));
} else {
//me.sendMessage(Conf.colorSystem+"Unknown faction command"+Conf.colorCommand+" "+command);
me.sendMessage(Conf.colorSystem+"Unknown faction command"+Conf.colorCommand+" "+command);
//me.getPlayer().sendMessage(TextUtil.repeat(tokens.get(0), Integer.parseInt(tokens.get(1))));
}
}
//----------------------------------------------//
// The other commands
//----------------------------------------------//
public static void help(Follower me) {
help(me, 1);
}
public static void help(Follower me, Integer page) {
me.sendMessage(TextUtil.titleize("Factions Help ("+page+"/"+helpPages.size()+")"), false);
page -= 1;
if (page < 0 || page >= helpPages.size()) {
me.sendMessage(Conf.colorSystem+"That page does not exist");
return;
}
me.sendMessage(helpPages.get(page), false);
}
public static void leave(Follower me) {
Faction faction = me.getFaction();
ArrayList<String> errors = me.leave();
me.sendMessage(errors);
if (errors.size() == 0) {
faction.sendMessage(me.getFullName(faction)+Conf.colorAction+" left your faction.");
me.sendMessage("You left "+faction.getName(me));
}
if (faction.getFollowersAll().size() == 0) {
// Remove this faction
for (Follower follower : Follower.getAll()) {
follower.sendMessage(Conf.colorAction+"The faction "+faction.getName(follower)+Conf.colorAction+" was disbandoned.");
}
EM.factionDelete(faction.id);
}
}
public static void join(Follower me, String name) {
Faction faction = findFaction(me, name, false);
if (faction == null) {
return;
}
ArrayList<String> errors = me.join(faction);
me.sendMessage(errors);
if (errors.size() > 0) {
faction.sendMessage(me.getFullName(faction)+Conf.colorSystem+" tried to join your faction.");
} else {
me.sendMessage(Conf.colorAction+"You successfully joined "+faction.getName(me));
faction.sendMessage(me.getFullName(faction)+Conf.colorAction+" joined your faction.");
}
}
// TODO MOVE OUT
public static void create(Follower me, String name) {
ArrayList<String> errors = me.createFaction(name);
me.sendMessage(errors);
if (errors.size() == 0) {
me.sendMessage(Conf.colorAction+"Faction created!");
}
}
public static void name(Follower me, String name) {
ArrayList<String> errors = new ArrayList<String>();
if (me.factionId == 0) {
errors.add(Conf.colorSystem+"You are not part of any faction");
} else if (me.role.value < Role.MODERATOR.value) {
errors.add(Conf.colorSystem+"You must be moderator to rename your faction");
}
if (Faction.isNameTaken(name) && ! Faction.toComparisonName(name).equals(me.getFaction().getComparisonName())) {
errors.add(Conf.colorSystem+"That name is already taken");
}
errors.addAll(Faction.validateName(name));
if (errors.size() > 0) {
me.sendMessage(errors);
return;
}
Faction myFaction = me.getFaction();
String oldname = myFaction.getName();
myFaction.setName(name);
// Inform
myFaction.sendMessage(me.getFullName(myFaction)+Conf.colorSystem+" changed the name of your faction to "+Conf.colorMember+name);
for (Faction faction : Faction.getAll()) {
if (faction.id == me.factionId) {
continue;
}
faction.sendMessage(Conf.colorSystem+"The faction "+me.getRelationColor(faction)+oldname+Conf.colorSystem+" renamed themselves to "+me.getRelationColor(faction)+name);
}
}
public static void list(Follower me) {
me.sendMessage(TextUtil.titleize("Faction List"), false);
for (Faction faction : Faction.getAll()) {
me.sendMessage(faction.getName(me)+Conf.colorSystem+" ("+faction.getFollowersWhereOnline(true).size()+" / "+faction.getFollowersAll().size()+" online)");
}
}
public static void showFaction(Follower me, String name) {
Faction faction = findFaction(me, name, true);
if (faction == null) {
return;
}
Collection<Follower> admins = faction.getFollowersWhereRole(Role.ADMIN);
Collection<Follower> mods = faction.getFollowersWhereRole(Role.MODERATOR);
Collection<Follower> normals = faction.getFollowersWhereRole(Role.NORMAL);
me.sendMessage(TextUtil.titleize(faction.getName(me)), false);
me.sendMessage(Conf.colorChrome+"Description: "+Conf.colorSystem+faction.getDescription());
if (faction.id != 0) {
me.sendMessage(Conf.colorChrome+"Power: "+Conf.colorSystem+faction.getPowerRounded()+" / "+faction.getPowerMaxRounded()); // TODO this is not so easy to understand
me.sendMessage(Conf.colorChrome+"Land: "+Conf.colorSystem+faction.getLandRounded()+" / "+faction.getLandMaxRounded());
if(faction.getOpen()) {
me.sendMessage(Conf.colorChrome+"Joining: "+Conf.colorSystem+"no invitation is needed");
} else {
me.sendMessage(Conf.colorChrome+"Joining: "+Conf.colorSystem+"invitation is required");
}
}
String onlineList = Conf.colorChrome+"Members online: ";
String offlineList = Conf.colorChrome+"Members offline: ";
String listpart;
for (Follower follower : admins) {
listpart = follower.getFullName(me)+Conf.colorSystem+", ";
if (follower.isOnline()) {
onlineList += listpart;
} else {
offlineList += listpart;
}
}
for (Follower follower : mods) {
listpart = follower.getFullName(me)+Conf.colorSystem+", ";
if (follower.isOnline()) {
onlineList += listpart;
} else {
offlineList += listpart;
}
}
for (Follower follower : normals) {
listpart = follower.getFullName(me)+Conf.colorSystem+", ";
if (follower.isOnline()) {
onlineList += listpart;
} else {
offlineList += listpart;
}
}
if (onlineList.endsWith(", ")) {
onlineList = onlineList.substring(0, onlineList.length()-2);
}
if (offlineList.endsWith(", ")) {
offlineList = offlineList.substring(0, offlineList.length()-2);
}
me.sendMessage(onlineList);
me.sendMessage(offlineList);
}
public static void showMap(Follower me, String mapAutoUpdating) {
if (mapAutoUpdating.length() > 0) {
if (Conf.aliasTrue.contains(mapAutoUpdating.toLowerCase())) {
// Turn on
me.setMapAutoUpdating(true);
me.sendMessage(Conf.colorAction + "Map auto update ENABLED.");
} else {
// Turn off
me.setMapAutoUpdating(false);
me.sendMessage(Conf.colorAction + "Map auto update DISABLED.");
}
} else {
me.sendMessage(Board.getMap(me.getFaction(), Coord.from(me), me.getPlayer().getLocation().getYaw()), false);
}
}
public static void invite(Follower me, String name) {
Follower follower = findFollower(me, name, false);
if (follower == null) {
return;
}
ArrayList<String> errors = me.invite(follower);
me.sendMessage(errors);
if (errors.size() == 0) {
ChatColor relationColor = me.getRelationColor(follower);
follower.sendMessage(relationColor+me.getFullName()+Conf.colorSystem+" invited you to "+relationColor+me.getFaction().getName());
me.getFaction().sendMessage(me.getFullName(me)+Conf.colorSystem+" invited "+follower.getFullName(me)+Conf.colorSystem+" to your faction.");
//me.sendMessage(Conf.colorAction+"You invited "+relationColor+follower.getFullName()+Conf.colorAction+" to "+Relation.MEMBER.getColor()+me.getFaction().getName());
}
}
public static void deinvite(Follower me, String name) { // TODO Move out!
Follower follower = findFollower(me, name, false);
if (follower == null) {
return;
}
ArrayList<String> errors = me.deinvite(follower);
me.sendMessage(errors);
if (errors.size() == 0) {
follower.sendMessage(me.getFullName(follower)+Conf.colorSystem+" revoked your invitation to "+me.getFaction().getName(follower));
me.getFaction().sendMessage(me.getFullName(me)+Conf.colorSystem+" revoked "+follower.getFullName(me)+"'s"+Conf.colorSystem+" invitation.");
}
}
public static void open(Follower me) {
if (me.role.value < Role.MODERATOR.value) {
me.sendMessage(Conf.colorSystem+"You must be moderator to do this");
return;
}
Faction myFaction = me.getFaction();
myFaction.setOpen( ! me.getFaction().getOpen());
String open = myFaction.getOpen() ? "open" : "closed";
// Inform
myFaction.sendMessage(me.getFullName(myFaction)+Conf.colorSystem+" changed the faction to "+open);
for (Faction faction : Faction.getAll()) {
if (faction.id == me.factionId) {
continue;
}
faction.sendMessage(Conf.colorSystem+"The faction "+myFaction.getName(faction)+Conf.colorSystem+" is now "+open);
}
}
public static void title(Follower me, ArrayList<String> tokens) {
if (tokens.size() == 0) {
me.sendMessage(Conf.colorSystem+"You must specify a player name");
return;
}
String name = tokens.get(0);
tokens.remove(0);
Follower you = findFollower(me, name, true);
if (you == null) {
return;
}
if ( ! canIAdministerYou(me, you)) {
return;
}
// All ok! Set the title!
String title = TextUtil.implode(tokens);
you.setTitle(title);
// Inform
Faction myFaction = me.getFaction();
myFaction.sendMessage(me.getFullName(myFaction)+Conf.colorSystem+" changed a title: "+you.getFullName(myFaction));
}
public static void kick(Follower me, String name) {
if (name.length() == 0) {
me.sendMessage(Conf.colorSystem+"You must specify a player name.");
return;
}
Follower you = findFollower(me, name, false);
if (you == null) {
return;
}
ArrayList<String> errors = me.kick(you);
me.sendMessage(errors);
if (errors.size() == 0) {
Faction myFaction = me.getFaction();
myFaction.sendMessage(me.getFullName(myFaction)+Conf.colorSystem+" kicked "+you.getFullName(myFaction)+Conf.colorSystem+" from the faction! :O");
you.sendMessage(me.getFullName(you)+Conf.colorSystem+" kicked you from "+myFaction.getName(you)+Conf.colorSystem+"! :O");
}
}
public static void roleChange(Follower me, Role targetRole, String name) {
if (me.role.value < Role.ADMIN.value) {
me.sendMessage(Conf.colorSystem+"You must be faction admin to do this");
return;
}
if (name.length() == 0) {
me.sendMessage(Conf.colorSystem+"You must specify a player name.");
return;
}
Follower targetFollower = findFollower(me, name, false);
if (targetFollower == null) {
return;
}
if (targetFollower.factionId != me.factionId) {
ChatColor relationColor = me.getRelationColor(targetFollower);
me.sendMessage(relationColor+targetFollower.getFullName()+Conf.colorSystem+" is not a member in your faction.");
return;
}
if (targetFollower == me) {
me.sendMessage(Conf.colorSystem+"The target player musn't be yourself.");
return;
}
if (targetRole == Role.ADMIN) {
me.role = Role.MODERATOR;
targetFollower.role = Role.ADMIN;
// Inform all players
for (Follower follower : Follower.getAll()) {
if (follower.factionId == me.factionId) {
follower.sendMessage(Conf.colorMember+me.getFullName()+Conf.colorSystem+" gave "+Conf.colorMember+targetFollower.getFullName()+" the leadership of your faction.");
} else {
follower.sendMessage(me.getFullName(follower)+Conf.colorSystem+" gave "+targetFollower.getFullName(follower)+" the leadership of "+me.getFaction().getName(follower));
}
}
} else if (targetRole == Role.MODERATOR) {
if (targetFollower.role == Role.MODERATOR) {
// Revoke
targetFollower.role = Role.NORMAL;
me.getFaction().sendMessage(Conf.colorMember+targetFollower.getName()+Conf.colorSystem+" is no longer moderator in your faction.");
} else {
// Give
targetFollower.role = Role.MODERATOR;
me.getFaction().sendMessage(Conf.colorMember+targetFollower.getName()+Conf.colorSystem+" was promoted to moderator in your faction.");
}
}
}
public static void claim(Follower me) {
if (me.factionId == 0) {
me.sendMessage(Conf.colorSystem+"You are not part of any faction.");
return;
}
Coord coord = Coord.from(me);
Faction otherFaction = coord.getFaction();
Faction myFaction = me.getFaction();
if (myFaction.equals(otherFaction)) {
me.sendMessage(Conf.colorSystem+"You already own this land.");
return;
}
if (me.role.value < Role.MODERATOR.value) {
me.sendMessage(Conf.colorSystem+"You must be moderator to claim land.");
return;
}
if (myFaction.getLandRounded() >= myFaction.getLandMaxRounded()) {
me.sendMessage(Conf.colorSystem+"You can't claim more land! You need more power!");
return;
}
if (otherFaction.getRelation(me) == Relation.ALLY) {
me.sendMessage(Conf.colorSystem+"You can't claim the land of your allies.");
return;
}
if (otherFaction.id != 0) {
if ( ! otherFaction.hasLandInflation()) { // TODO more messages
me.sendMessage(me.getRelationColor(otherFaction)+otherFaction.getName()+Conf.colorSystem+" owns this land and are strong enough to keep it.");
return;
}
if ( ! Board.isBorderCoord(coord)) {
me.sendMessage(Conf.colorSystem+"You must start claiming land at the border of the territory.");
return;
}
}
if (otherFaction.id == 0) {
myFaction.sendMessage(Conf.colorMember+me.getFullName()+Conf.colorSystem+" claimed some new land :D");
} else {
// ASDF claimed some of your land 450 blocks NNW of you.
// ASDf claimed some land from FACTION NAME
ChatColor relcolor = myFaction.getRelationColor(otherFaction);
otherFaction.sendMessage(relcolor+me.getFullName()+Conf.colorSystem+" from "+relcolor+myFaction.getName()+Conf.colorSystem+" stole some of your land :O");
myFaction.sendMessage(Conf.colorMember+me.getFullName()+Conf.colorSystem+" claimed some land from "+relcolor+otherFaction.getName());
}
Board.claim(coord, myFaction);
}
public static void unclaim(Follower me) {
if (me.factionId == 0) {
me.sendMessage(Conf.colorSystem+"You are not part of any faction");
return;
}
if (me.role.value < Role.MODERATOR.value) {
me.sendMessage(Conf.colorSystem+"You must be moderator to unclaim land");
return;
}
Coord coord = Coord.from(me.getPlayer());
if ( ! me.getFaction().equals(coord.getFaction())) {
me.sendMessage(Conf.colorSystem+"You don't own this land.");
return;
}
Board.unclaim(coord);
me.sendMessage(Conf.colorAction+"Successfully unclaimed");
}
public static void relation(Follower me, Relation whishedRelation, String otherFactionName) {
if (me.factionId == 0) {
me.sendMessage(Conf.colorSystem+"You are not part of any faction.");
return;
}
if (me.role.value < Role.MODERATOR.value) {
me.sendMessage(Conf.colorSystem+"You must be moderator to set relation to other factions.");
return;
}
if (otherFactionName.length() == 0) {
me.sendMessage(Conf.colorSystem+"You must specify another faction.");
return;
}
Faction otherFaction = findFaction(me, otherFactionName, false);
if (otherFaction == null) {
return;
}
if (otherFaction.id == 0) {
me.sendMessage(Conf.colorSystem+"Nope! You can't :) The default faction is not a real faction.");
return;
}
if (otherFaction.equals(me.getFaction())) {
me.sendMessage(Conf.colorSystem+"Nope! You can't declare a relation to yourself :)");
return;
}
Faction myFaction = me.getFaction();
myFaction.setRelationWish(otherFaction, whishedRelation);
Relation currentRelation = myFaction.getRelation(otherFaction);
ChatColor currentRelationColor = currentRelation.getColor();
if (whishedRelation == currentRelation) {
otherFaction.sendMessage(Conf.colorSystem+"Your faction is now "+currentRelationColor+whishedRelation.toString()+Conf.colorSystem+" to "+currentRelationColor+myFaction.getName());
myFaction.sendMessage(Conf.colorSystem+"Your faction is now "+currentRelationColor+whishedRelation.toString()+Conf.colorSystem+" to "+currentRelationColor+otherFaction.getName());
} else {
otherFaction.sendMessage(currentRelationColor+myFaction.getName()+Conf.colorSystem+ " whishes to be your "+whishedRelation.getColor()+whishedRelation.toString());
otherFaction.sendMessage(Conf.colorSystem+"Type "+Conf.colorCommand+Conf.aliasBase.get(0)+" "+whishedRelation+" "+myFaction.getName()+Conf.colorSystem+" to accept.");
myFaction.sendMessage(currentRelationColor+otherFaction.getName()+Conf.colorSystem+ " were informed you wishes to be "+whishedRelation.getColor()+whishedRelation);
}
}
public static void description(Follower me, String desc) {
if (me.factionId == 0) {
me.sendMessage(Conf.colorSystem+"You are not part of any faction");
return;
}
if (me.role.value < Role.MODERATOR.value) {
me.sendMessage(Conf.colorSystem+"You must be moderator to set the description");
return;
}
me.getFaction().setDescription(desc);
me.sendMessage(Conf.colorAction+"The new decription was set :D");
// Broadcast the description to everyone
for (Follower follower : EM.followerGetAll()) {
follower.sendMessage(Conf.colorSystem+"The faction "+follower.getRelationColor(me)+me.getFaction().getName()+Conf.colorSystem+" changed their description to:");
follower.sendMessage(Conf.colorSystem+desc);
}
}
}

View File

@ -0,0 +1,72 @@
package com.bukkit.mcteam.factions;
import java.io.File;
import org.bukkit.Server;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.bukkit.mcteam.factions.entities.*;
import com.bukkit.mcteam.factions.util.Log;
public class Factions extends JavaPlugin {
public static PluginLoader pluginLoader;
public static Server server;
public static PluginDescriptionFile desc;
public static File folder;
public static File plugin;
public static ClassLoader cLoader;
private final FactionsPlayerListener playerListener = new FactionsPlayerListener(this);
private final FactionsEntityListener entityListener = new FactionsEntityListener(this);
private final FactionsBlockListener blockListener = new FactionsBlockListener(this);
public Factions(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
Factions.pluginLoader = pluginLoader;
Factions.server = instance;
Factions.desc = desc;
Factions.folder = folder;
Factions.plugin = plugin;
Factions.cLoader = cLoader;
Log.info("=== INIT START ===");
long timeInitStart = System.currentTimeMillis();
Log.info("You are running version: "+desc.getVersion());
EM.loadAll();
// Register events
PluginManager pm = instance.getPluginManager();
pm.registerEvent(Event.Type.PLAYER_COMMAND, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGEDBY_ENTITY, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_DAMAGED, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PLACED, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_INTERACT, this.blockListener, Event.Priority.Normal, this);
Log.info("=== INIT DONE (Took "+(System.currentTimeMillis()-timeInitStart)+"ms) ===");
Log.threshold = Conf.logThreshold;
}
@Override
public void onDisable() {
// TODO Auto-generated method stub
}
@Override
public void onEnable() {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,101 @@
package com.bukkit.mcteam.factions;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockDamageLevel;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockInteractEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;
import com.bukkit.mcteam.factions.entities.*;
import com.bukkit.mcteam.factions.util.TextUtil;
public class FactionsBlockListener extends BlockListener {
public Factions plugin;
public FactionsBlockListener(Factions plugin) {
this.plugin = plugin;
}
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return; // Alright. lets listen to that.
}
if ( ! this.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock(), "build")) {
event.setCancelled(true);
}
}
@Override
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return; // Alright. lets listen to that.
}
if (event.getDamageLevel() == BlockDamageLevel.BROKEN && ! this.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock(), "destroy")) {
event.setCancelled(true);
}
}
public boolean playerCanBuildDestroyBlock(Player player, Block block, String action) {
Coord coord = Coord.parseCoord(block);
Faction otherFaction = coord.getFaction();
if (otherFaction.id == 0) {
return true; // This is no faction territory. You may build or break stuff here.
}
Follower me = Follower.get(player);
Faction myFaction = me.getFaction();
// Cancel if we are not in our own territory
if (myFaction != otherFaction) {
me.sendMessage(Conf.colorSystem+"You can't "+action+" in the territory of "+otherFaction.getName(myFaction));
otherFaction.sendMessage(me.getFullName(otherFaction)+Conf.colorSystem+" tried to "+action+" "+TextUtil.getMaterialName(block.getType())+" in your territory");
return false;
}
return true;
}
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.isCancelled()) {
return; // Alright. lets listen to that.
}
if ( ! (event.getEntity() instanceof Player)) {
// So far mobs does not interact with the environment :P
return;
}
Block block = event.getBlock();
Player player = (Player) event.getEntity();
if ( ! canPlayerUseRightclickBlock(player, block)) {
event.setCancelled(true);
}
}
public boolean canPlayerUseRightclickBlock(Player player, Block block) {
Material material = block.getType();
// We only care about some material types.
if ( ! Conf.territoryProtectedMaterials.contains(material)) {
return true;
}
Follower me = Follower.get(player);
Faction myFaction = me.getFaction();
Coord blockCoord = Coord.from(block.getLocation());
Faction otherFaction = blockCoord.getFaction();
if (otherFaction.id != 0 && myFaction != otherFaction) {
me.sendMessage(Conf.colorSystem+"You can't use "+TextUtil.getMaterialName(material)+" in the territory of "+otherFaction.getName(myFaction));
otherFaction.sendMessage(me.getFullName(otherFaction)+Conf.colorSystem+" tried to use "+TextUtil.getMaterialName(material)+" in your territory");
return false;
}
return true;
}
}

View File

@ -0,0 +1,97 @@
package com.bukkit.mcteam.factions;
import java.text.DecimalFormat;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
import com.bukkit.mcteam.factions.entities.Conf;
import com.bukkit.mcteam.factions.entities.Follower;
import com.bukkit.mcteam.factions.struct.Relation;
import com.bukkit.mcteam.factions.util.Log;
public class FactionsEntityListener extends EntityListener {
public Factions plugin;
public FactionsEntityListener(Factions plugin) {
this.plugin = plugin;
}
@Override
public void onEntityDeath(EntityDeathEvent event) {
Entity entity = event.getEntity();
if ( ! (entity instanceof Player)) {
return;
}
Player player = (Player) entity;
Follower follower = Follower.get(player);
follower.onDeath();
follower.sendMessage(Conf.colorSystem+"Your power is now "+follower.getPowerRounded()+" / "+follower.getPowerMaxRounded());
}
/**
* Who can I hurt?
* I can never hurt members or allies.
* I can always hurt enemies.
* I can hurt neutrals as long as they are outside their own territory.
*/
@Override
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return; // Some other plugin decided. Alright then.
}
Entity entity = event.getEntity();
if ( ! (entity instanceof Player)) {
return;
}
Entity damager = event.getDamager();
if ( ! (damager instanceof Player)) {
return;
}
Log.debug(((Player)entity).getName()+ " is the defender");
Log.debug(((Player)damager).getName()+ " is the damager");
Follower defender = Follower.get((Player)entity);
Follower attacker = Follower.get((Player)damager);
Relation relation = defender.getRelation(attacker);
// Players without faction may be hurt anywhere
if (defender.factionId == 0) {
return;
}
// You can never hurt faction members or allies
if (relation == Relation.MEMBER || relation == Relation.ALLY) {
attacker.sendMessage(Conf.colorSystem+"You can't hurt "+relation.getColor()+defender.getFullName());
event.setCancelled(true);
return;
}
// You can not hurt neutrals in their own territory.
if (relation == Relation.NEUTRAL && defender.isInOwnTerritory()) {
attacker.sendMessage(Conf.colorSystem+"You can't hurt "+relation.getColor()+defender.getFullName()+" in their own territory.");
defender.sendMessage(relation.getColor()+attacker.getFullName()+Conf.colorSystem+" tried to hurt you.");
event.setCancelled(true);
return;
}
// Damage will be dealt. However check if the damage should be reduced.
if (defender.isInOwnTerritory()) {
int damage = event.getDamage();
int toHeal = (int)Math.round(damage * Conf.territoryShieldFactor);
defender.heal(toHeal);
// Send message
DecimalFormat formatter = new DecimalFormat("#.#");
String hearts = formatter.format(toHeal / 2.0);
defender.sendMessage(Conf.colorSystem+"Enemy damage reduced by "+ChatColor.RED+hearts+Conf.colorSystem+" hearts.");
}
}
}

View File

@ -0,0 +1,103 @@
package com.bukkit.mcteam.factions;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.*;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;
import com.bukkit.mcteam.factions.entities.*;
import com.bukkit.mcteam.factions.util.*;
public class FactionsPlayerListener extends PlayerListener{
public Factions plugin;
public FactionsPlayerListener(Factions plugin) {
this.plugin = plugin;
}
/**
* If someone says something that starts with the factions base command
* we handle that command.
*/
@Override
public void onPlayerCommand(PlayerChatEvent event) {
Player player = event.getPlayer();
String msg = event.getMessage();
if (handleCommandOrChat(player, msg)) {
event.setCancelled(true);
}
}
@Override
public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
String msg = event.getMessage();
// Process the command or
if ( ! handleCommandOrChat(player, msg) && Conf.useRelationColoredChat) {
for (Player receiver : Factions.server.getOnlinePlayers()) {
Follower follower = Follower.get(player);
receiver.sendMessage("<"+follower.getFullName(Follower.get(receiver))+ChatColor.WHITE+"> "+msg);
}
}
event.setCancelled(true);
}
public boolean handleCommandOrChat(Player player, String msg) {
ArrayList<String> tokens = TextUtil.split(msg.trim());
if (Conf.aliasBase.contains(tokens.get(0))) {
tokens.remove(0);
Follower follower = Follower.get(player);
Commands.base(follower, tokens);
return true;
}
return false;
}
@Override
public void onPlayerJoin(PlayerEvent event) {
EM.onPlayerLogin(event.getPlayer());
//Follower.get(event.getPlayer()).sendJoinInfo();
}
@Override
public void onPlayerQuit(PlayerEvent event) {
Follower follower = Follower.get(event.getPlayer());
Log.debug("Saved follower on player quit: "+follower.getFullName());
follower.save(); // We save the followers on logout in order to save their non autosaved state like power.
EM.onPlayerLogout(event.getPlayer()); // Remove the player link.
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
// Did we change coord?
Location from = event.getFrom();
Location to = event.getTo();
Coord coordFrom = Coord.from(from);
Coord coordTo = Coord.from(to);
if (coordFrom.equals(coordTo)) {
return;
}
// Yes we did change coord (:
Follower me = Follower.get(event.getPlayer());
if (me.isMapAutoUpdating()) {
me.sendMessage(Board.getMap(me.getFaction(), Coord.from(me), me.getPlayer().getLocation().getYaw()), false);
} else {
// Did we change "host"(faction)?
Faction factionFrom = Board.getFactionAt(coordFrom);
Faction factionTo = Board.getFactionAt(coordTo);
if ( factionFrom != factionTo) {
me.sendFactionHereMessage();
}
}
}
}

View File

@ -0,0 +1,156 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.ChatColor;
import com.bukkit.mcteam.factions.util.TextUtil;
import com.bukkit.mcteam.util.AsciiCompass;
//import com.bukkit.mcteam.factions.util.*;
public class Board {
protected static Map<Coord, Integer> coordFactionIds;
static {
coordFactionIds = new HashMap<Coord, Integer>();
}
public static Faction getFactionAt(Coord coord) {
return Faction.get(getFactionIdAt(coord));
}
public static int getFactionIdAt(Coord coord) {
Integer factionId = coordFactionIds.get(coord);
if (factionId == null) {
return 0; // No faction
}
return factionId;
}
public static void unclaim(Coord coord) {
coordFactionIds.remove(coord);
save();
}
public static void claim(Coord coord, Faction faction) {
coordFactionIds.put(coord, faction.id);
save();
}
public static boolean isBorderCoord(Coord coord) {
Faction faction = Board.getFactionAt(coord);
Coord a = coord.getRelative(1, 0);
Coord b = coord.getRelative(-1, 0);
Coord c = coord.getRelative(0, 1);
Coord d = coord.getRelative(0, -1);
return faction != a.getFaction() && faction != b.getFaction() && faction != c.getFaction() && faction != d.getFaction();
}
public static void purgeFaction(Faction faction) {
purgeFaction(faction.id);
}
public static void purgeFaction(int factionId) {
Iterator<Entry<Coord, Integer>> iter = coordFactionIds.entrySet().iterator();
while (iter.hasNext()) {
Entry<Coord, Integer> entry = iter.next();
if (entry.getValue().equals(factionId)) {
iter.remove();
}
}
}
public static int getFactionCoordCount(Faction faction) {
return getFactionCoordCount(faction.id);
}
public static int getFactionCoordCount(int factionId) {
int ret = 0;
for (int thatFactionId : coordFactionIds.values()) {
if(thatFactionId == factionId) {
ret += 1;
}
}
return ret;
}
//----------------------------------------------//
// Map generation
//----------------------------------------------//
/**
* The map is relative to a coord and a faction
* north is in the direction of decreasing x
* east is in the direction of decreasing z
*/
public static ArrayList<String> getMap(Faction faction, Coord coord, double inDegrees) {
ArrayList<String> ret = new ArrayList<String>();
ret.add(TextUtil.titleize("("+coord+") "+coord.getFaction().getName(faction)));
int halfWidth = Conf.mapWidth / 2;
int halfHeight = Conf.mapHeight / 2;
Coord topLeft = coord.getRelative(-halfHeight, halfWidth);
int width = halfWidth * 2 + 1;
int height = halfHeight * 2 + 1;
// For each row
for (int dx = 0; dx < height; dx++) {
// Draw and add that row
String row = "";
for (int dz = 0; dz > -width; dz--) {
if(dz == -(halfWidth) && dx == halfHeight) {
row += ChatColor.AQUA+"+";
} else {
Coord coordHere = topLeft.getRelative(dx, dz);
Faction factionHere = coordHere.getFaction();
if (factionHere.id == 0) {
row += ChatColor.GRAY+"-";
} else {
row += factionHere.getRelation(faction).getColor()+"+";
}
}
}
ret.add(row);
}
// Get the compass
ArrayList<String> asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.RED, Conf.colorChrome);
// Pad the compass some
asciiCompass.set(0, asciiCompass.get(0));
asciiCompass.set(1, asciiCompass.get(1));
asciiCompass.set(2, asciiCompass.get(2));
// Add the compass
ret.set(1, asciiCompass.get(0)+ret.get(1).substring(3*3));
ret.set(2, asciiCompass.get(1)+ret.get(2).substring(3*3));
ret.set(3, asciiCompass.get(2)+ret.get(3).substring(3*3));
return ret;
}
//----------------------------------------------//
// Persistance
//----------------------------------------------//
public static boolean save() {
return EM.boardSave();
}
}

View File

@ -0,0 +1,211 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.*;
import com.bukkit.mcteam.factions.struct.Relation;
public class Conf {
public static Integer logThreshold;
public static String prefixAdmin;
public static String prefixMod;
public static int factionNameMinLength;
public static int factionNameMaxLength;
public static int mapHeight;
public static int mapWidth;
public static double territoryShieldFactor;
// Chat control:
public static boolean useRelationColoredChat; // This can interfere with other chat formatting plugins. Test to turn it on or off.
// TODO experiment with displayname feature of bukkit
// TODO test to set format instead of overriding and offer a non colored mut **Title alternative...
// Colors
public static ChatColor colorMember;
public static ChatColor colorAlly;
public static ChatColor colorNeutral;
public static ChatColor colorEnemy;
public static ChatColor colorSystem;
public static ChatColor colorAction;
public static ChatColor colorChrome;
public static ChatColor colorCommand;
public static ChatColor colorParameter;
// Command names / aliases
public static List<String> aliasBase = new ArrayList<String>();
public static List<String> aliasHelp = new ArrayList<String>();
public static List<String> aliasList = new ArrayList<String>();
public static List<String> aliasShow = new ArrayList<String>();
public static List<String> aliasMap = new ArrayList<String>();
public static List<String> aliasHere = new ArrayList<String>();
public static List<String> aliasJoin = new ArrayList<String>();
public static List<String> aliasLeave = new ArrayList<String>();
public static List<String> aliasCreate = new ArrayList<String>();
public static List<String> aliasName = new ArrayList<String>();
public static List<String> aliasTitle = new ArrayList<String>();
public static List<String> aliasInvite = new ArrayList<String>();
public static List<String> aliasDeinvite = new ArrayList<String>();
public static List<String> aliasOpen = new ArrayList<String>();
public static List<String> aliasKick = new ArrayList<String>();
public static List<String> aliasModerator = new ArrayList<String>();
public static List<String> aliasAdmin = new ArrayList<String>();
public static List<String> aliasClaim = new ArrayList<String>();
public static List<String> aliasUnclaim = new ArrayList<String>();
public static List<String> aliasRelationAlly = new ArrayList<String>();
public static List<String> aliasRelationNeutral = new ArrayList<String>();
public static List<String> aliasRelationEnemy = new ArrayList<String>();
public static List<String> aliasDescription = new ArrayList<String>();
// Value aliases
public static List<String> aliasTrue = new ArrayList<String>();
// Power
public static double powerPerLand;
public static double powerPerPlayer;
public static double powerPerMinute; // Default health rate
public static double powerPerDeath;
public static double powerDefaultBonus;
// Protected blocks
public static List<Material> territoryProtectedMaterials = new ArrayList<Material>();
static {
logThreshold = 10;
prefixAdmin = "**";
prefixMod = "*";
factionNameMinLength = 3;
factionNameMaxLength = 40;
mapHeight = 8;
mapWidth = 49;
territoryShieldFactor = 0.33;
useRelationColoredChat = true;
colorMember = ChatColor.GREEN;
colorAlly = ChatColor.LIGHT_PURPLE;
colorNeutral = ChatColor.WHITE;
colorEnemy = ChatColor.RED;
colorSystem = ChatColor.YELLOW;
colorAction = ChatColor.LIGHT_PURPLE;
colorChrome = ChatColor.GOLD;
colorCommand = ChatColor.AQUA;
colorParameter = ChatColor.DARK_AQUA;
aliasBase.add("/f");
aliasBase.add("f");
aliasBase.add("/faction");
aliasBase.add("faction");
aliasBase.add("/factions");
aliasBase.add("factions");
aliasHelp.add("help");
aliasHelp.add("h");
aliasHelp.add("?");
aliasList.add("list");
aliasList.add("ls");
aliasShow.add("show");
aliasShow.add("who");
aliasMap.add("map");
aliasHere.add("here");
aliasJoin.add("join");
aliasLeave.add("leave");
aliasCreate.add("create");
aliasCreate.add("new");
aliasName.add("name");
aliasName.add("rename");
aliasTitle.add("title");
aliasInvite.add("invite");
aliasInvite.add("inv");
aliasDeinvite.add("deinvite");
aliasDeinvite.add("deinv");
aliasOpen.add("open");
aliasOpen.add("close");
aliasKick.add("kick");
aliasModerator.add("mod");
aliasAdmin.add("admin");
aliasClaim.add("claim");
aliasUnclaim.add("unclaim");
aliasUnclaim.add("declaim");
aliasRelationAlly.add("ally");
aliasRelationNeutral.add("neutral");
aliasRelationEnemy.add("enemy");
aliasDescription.add("desc");
aliasTrue.add("true");
aliasTrue.add("yes");
aliasTrue.add("y");
aliasTrue.add("ok");
aliasTrue.add("on");
aliasTrue.add("+");
powerPerLand = 1; // 1 power grants one land
powerPerPlayer = 5; // One player has 5 power
powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one death
powerPerDeath = 1; //A death makes you loose 2 power
powerDefaultBonus = 0; //A faction normally has a power bonus
territoryProtectedMaterials.add(Material.WOODEN_DOOR);
territoryProtectedMaterials.add(Material.DISPENSER);
territoryProtectedMaterials.add(Material.CHEST);
territoryProtectedMaterials.add(Material.FURNACE);
}
//----------------------------------------------//
// Color picking and stuff
//----------------------------------------------//
public static ChatColor relationColor(Relation relation) {
if (relation == Relation.MEMBER) {
return colorMember;
} else if (relation == Relation.ALLY) {
return colorAlly;
} else if (relation == Relation.NEUTRAL) {
return colorNeutral;
} else { //if (relation == FactionRelation.ENEMY) {
return colorEnemy;
}
}
//----------------------------------------------//
// Persistance
//----------------------------------------------//
public static boolean save() {
return EM.configSave();
}
}

View File

@ -0,0 +1,77 @@
package com.bukkit.mcteam.factions.entities;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
public class Coord {
protected static transient int cellSize = 16;
public int x, z;
public Coord(int x, int z) {
this.x = x;
this.z = z;
}
// TODO implements cloneable
public Coord(Coord coord) {
this.x = coord.x;
this.z = coord.z;
}
public Coord() {
// Noarg constructor for google gson.
}
public Coord getRelative(int dx, int dz) {
return new Coord(this.x + dx, this.z + dz);
}
public static Coord from(int x, int z) {
return new Coord(x / cellSize - (x < 0 ? 1 : 0), z / cellSize - (z < 0 ? 1 : 0));
}
public static Coord from(Player player) {
return from(player.getLocation());
}
public static Coord from(Follower follower) {
return from(follower.getPlayer());
}
public static Coord from(Location loc) {
return from(loc.getBlockX(), loc.getBlockZ());
}
public static Coord parseCoord(Block block) {
return from(block.getX(), block.getZ());
}
public Faction getFaction() {
return Board.getFactionAt(this);
}
@Override
public String toString() {
return this.x + "," + this.z;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + x;
result = 31 * result + z;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Coord))
return false;
Coord o = (Coord) obj;
return this.x == o.x && this.z == o.z;
}
}

View File

@ -0,0 +1,316 @@
package com.bukkit.mcteam.factions.entities;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.Factions;
import com.bukkit.mcteam.factions.util.*;
import com.bukkit.mcteam.util.DiscUtil;
import com.google.gson.*;
/**
* This is a entity manager that persists object to json.
* Before using the the EM you should always EM.loadAll().
* The methods assume that all on disc is loaded into memory.
*/
public class EM {
protected static Map<String, Follower> followers = new HashMap<String, Follower>(); // Where String is a lowercase playername
protected static Map<Integer, Faction> factions = new HashMap<Integer, Faction>(); // Where Integer is a primary auto increment key
protected static int nextFactionId;
// hardcoded config
protected final static String ext = ".json";
protected final static File folderBase = Factions.folder;
protected final static File folderFaction = new File(folderBase, "faction");
protected final static File folderFollower = new File(folderBase, "follower");
protected final static File fileConfig = new File(folderBase, "conf"+ext);
protected final static File fileBoard = new File(folderBase, "board"+ext);
public final static Gson gson = new GsonBuilder()
.setPrettyPrinting()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE)
.registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter()) // a "must have" adapter for GSON
.create();
public static void loadAll() {
configLoad();
Log.threshold = Conf.logThreshold;
boardLoad();
followerLoadAll();
factionLoadAll();
}
//----------------------------------------------//
// Config methods (load, save)
//----------------------------------------------//
public static boolean configLoad() {
if (fileConfig.exists()) {
try {
gson.fromJson(DiscUtil.read(fileConfig), Conf.class);
Log.info("Config was loaded from disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to load the config");
return false;
}
}
Log.info("No conf.json found! Creating a new one with the default values");
//configSave(); // FOR DEBUGGING...
return true;
}
public static boolean configSave() {
try {
DiscUtil.write(fileConfig, gson.toJson(new Conf()));
Log.debug("Config was saved to disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the config");
return false;
}
}
//----------------------------------------------//
// Board methods (load, save)
//----------------------------------------------//
public static boolean boardLoad() {
if (fileBoard.exists()) {
try {
gson.fromJson(DiscUtil.read(fileBoard), Board.class);
Log.info("Board was loaded from disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to load the board");
return false;
}
}
Log.info("No board.json found! Creating a new one with the default values");
//boardSave(); // FOR DEBUGGING...
return true;
}
public static boolean boardSave() {
try {
DiscUtil.write(fileBoard, gson.toJson(new Board()));
Log.debug("Board was saved to disc");
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the board");
return false;
}
}
//----------------------------------------------//
// Follower methods (loadAll, get, save)
//----------------------------------------------//
/**
* This method will create a follower entity and assign the link to the corresponding player.
*/
public static void onPlayerLogin(Player player) {
Follower follower = followerGet(player);
follower.player = player;
}
public static void onPlayerLogout(Player player) {
followers.get(player.getName()).player = null;
}
/**
* This method loads all followers from disc into memory.
*/
public static void followerLoadAll() {
Log.info("Loading all followers from disc...");
folderFollower.mkdirs();
class jsonFileFilter implements FileFilter {
public boolean accept(File file) {
return (file.getName().toLowerCase().endsWith(ext) && file.isFile());
}
}
File[] jsonFiles = folderFollower.listFiles(new jsonFileFilter());
for (File jsonFile : jsonFiles) {
// Extract the name from the filename. The name is filename minus ".json"
String name = jsonFile.getName();
name = name.substring(0, name.length() - ext.length());
try {
Follower follower = gson.fromJson(DiscUtil.read(jsonFile), Follower.class);
follower.id = name;
followers.put(follower.id, follower);
Log.debug("loaded follower "+name);
} catch (Exception e) {
e.printStackTrace();
Log.warn("failed to load follower "+name);
}
}
}
public static Collection<Follower> followerGetAll() {
return followers.values();
}
/**
* This method returns the follower object for a player
* A new Follower will be created if the player did not have one
*/
public static Follower followerGet(Player player) {
String key = followerKey(player);
if (followers.containsKey(key)) {
return followers.get(key);
}
return followerCreate(player);
}
public static boolean followerSave(String id) {
Object obj = followers.get(id);
if (obj == null) {
Log.warn("Could not save follower "+id+" as it was not loaded");
return false;
}
folderFollower.mkdirs();
File file = new File(folderFollower, id+ext);
try {
DiscUtil.write(file, gson.toJson(obj));
Log.debug("Saved the follower "+id);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("Failed to save the follower "+id);
return false;
}
}
protected static String followerKey(Player player) {
return player.getName();
}
protected static Follower followerCreate(Player player) {
Log.debug("Creating new follower "+followerKey(player));
Follower follower = new Follower();
follower.id = followerKey(player);
followers.put(follower.id, follower);
follower.save();
return follower;
}
//----------------------------------------------//
// Faction methods (loadAll, get, create, delete, save)
//----------------------------------------------//
/**
* This method loads all followers from disc into memory.
*/
public static void factionLoadAll() {
Log.info("Loading all factions from disc...");
folderFaction.mkdirs();
class jsonFileFilter implements FileFilter
{
public boolean accept(File file) {
return (file.getName().toLowerCase().endsWith(ext) && file.isFile());
}
}
nextFactionId = 0;
File[] jsonFiles = folderFaction.listFiles(new jsonFileFilter());
for (File jsonFile : jsonFiles) {
// Extract the name from the filename. The name is filename minus ".json"
String name = jsonFile.getName();
name = name.substring(0, name.length() - ext.length());
int id = Integer.parseInt(name);
// Eventually push next id forward
if (nextFactionId < id) {
nextFactionId = id;
}
try {
Faction faction = gson.fromJson(DiscUtil.read(jsonFile), Faction.class);
faction.id = id;
factions.put(faction.id, faction);
Log.debug("loaded faction "+id);
} catch (Exception e) {
e.printStackTrace();
Log.warn("Failed to load faction "+id);
}
}
nextFactionId += 1; // make it the next id and not the current highest.
// Make sure the default neutral faction exists
if ( ! factions.containsKey(0)) {
Faction faction = new Faction();
faction.name = "*No faction*";
faction.description = "\"The faction for the factionless :P\"";
faction.id = 0;
factions.put(faction.id, faction);
}
}
public static Faction factionGet(Integer factionId) {
return factions.get(factionId);
}
public static Collection<Faction> factionGetAll() {
return factions.values();
}
public static Faction factionCreate(){
Faction faction = new Faction();
faction.id = nextFactionId;
nextFactionId += 1;
factions.put(faction.id, faction);
Log.debug("created new faction "+faction.id);
faction.save();
return faction;
}
public static boolean factionDelete(Integer id) {
// NOTE that this does not do any security checks.
// Follower might get orphaned foreign id's
// purge from board
Board.purgeFaction(id);
// Remove the file
File file = new File(folderFaction, id+ext);
file.delete();
// Remove the faction
factions.remove(id);
return true; // TODO
}
public static boolean factionSave(Integer id) {
Object obj = factions.get(id);
if (obj == null) {
Log.warn("Could not save faction "+id+" as it was not loaded");
return false;
}
folderFaction.mkdirs();
File file = new File(folderFaction, id+ext);
try {
DiscUtil.write(file, gson.toJson(obj));
Log.debug("saved the faction "+id);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.warn("failed to save the faction "+id);
return false;
}
}
}

View File

@ -0,0 +1,363 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.Factions;
import com.bukkit.mcteam.factions.struct.Relation;
import com.bukkit.mcteam.factions.struct.Role;
import com.bukkit.mcteam.factions.util.Log;
import com.bukkit.mcteam.util.ChatFixUtil;
public class Faction {
public transient int id;
protected Map<Integer, Relation> relationWish;
protected Set<String> invites; // Where string is a follower id (lower case name)
protected boolean open;
protected String name;
protected String description;
public Faction() {
this.relationWish = new HashMap<Integer, Relation>();
this.invites = new HashSet<String>();
this.open = true;
this.name = "Untitled Faction :(";
this.description = "Default faction description :(";
}
// -------------------------------
// Information
// -------------------------------
public String getName() {
return this.getName("");
}
public String getName(String prefix) {
return prefix+this.name;
}
public String getName(Faction otherFaction) {
return this.getName(otherFaction.getRelationColor(this).toString());
}
public String getName(Follower otherFollower) {
return this.getName(otherFollower.getRelationColor(this).toString());
}
public void setName(String newName) {
this.name = newName;
this.save();
}
public String getDescription() {
return this.description;
}
public void setDescription(String value) {
this.description = value;
this.save();
}
public boolean getOpen() {
return open;
}
public void setOpen(boolean isOpen) {
open = isOpen;
this.save();
}
//----------------------------------------------//
// Power
//----------------------------------------------//
public double getPower() {
double ret = this.getPowerBonus();
for (Follower follower : this.getFollowersAll()) {
ret += follower.getPower();
}
return ret;
}
public double getPowerBonus() {
return Conf.powerDefaultBonus; // TODO this could be modified by commands later on
}
public double getPowerMax() {
double ret = this.getPowerBonus();
for (Follower follower : this.getFollowersAll()) {
ret += follower.getPowerMax();
}
return ret;
}
public int getPowerRounded() {
return (int) Math.round(this.getPower());
}
public int getPowerMaxRounded() {
return (int) Math.round(this.getPowerMax());
}
public int getLandRounded() {
return Board.getFactionCoordCount(this);
}
public double getLandMax() {
return this.getPower() / Conf.powerPerLand;
}
public int getLandMaxRounded() {
return (int) Math.round(this.getLandMax());
}
public boolean hasLandInflation() {
return Board.getFactionCoordCount(this) > this.getLandMaxRounded();
}
// -------------------------------
// Membership management
// -------------------------------
public ArrayList<String> invite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
Log.debug("follower.getFaction().id"+follower.getFaction().id);
Log.debug("this.id"+this.id);
if (follower.getFaction().equals(this)) { // error här?
errors.add(Conf.colorSystem+follower.getFullName()+" is already a member of "+this.getName());
}
if(errors.size() > 0) {
return errors;
}
this.invites.add(follower.id);
this.save();
return errors;
}
public ArrayList<String> deinvite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if (follower.getFaction().equals(this)) {
errors.add(Conf.colorSystem+follower.getFullName()+" is already a member of "+this.getName());
errors.add(Conf.colorSystem+"You might want to "+Conf.colorCommand+Conf.aliasBase.get(0)+" "+Conf.aliasKick.get(0)+Conf.colorParameter+" "+follower.getName());
}
if(errors.size() > 0) {
return errors;
}
this.invites.remove(follower.id);
this.save();
return errors;
}
public ArrayList<String> kick(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
removeFollower(follower);
return errors;
}
public boolean isInvited(Follower follower) {
return invites.contains(follower.id);
}
// -------------------------------
// Followers
// -------------------------------
public ArrayList<Follower> getFollowersAll() {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id) {
ret.add(follower);
}
}
return ret;
}
public ArrayList<Follower> getFollowersWhereOnline(boolean online) {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id && follower.isOnline() == online) {
ret.add(follower);
}
}
return ret;
}
public ArrayList<Follower> getFollowersWhereRole(Role role) {
ArrayList<Follower> ret = new ArrayList<Follower>();
for (Follower follower : Follower.getAll()) {
if (follower.factionId == this.id && follower.role.equals(role)) {
ret.add(follower);
}
}
return ret;
}
public void removeFollower(Follower follower) {
if (this.id != follower.factionId) {
return; // safety check
}
this.invites.remove(follower.id);
follower.resetFactionData();
follower.save();
this.save();
}
public ArrayList<Player> getOnlinePlayers() {
ArrayList<Player> ret = new ArrayList<Player>();
for (Player player: Factions.server.getOnlinePlayers()) {
Follower follower = Follower.get(player);
if (follower.factionId == this.id) {
ret.add(player);
}
}
return ret;
}
//----------------------------------------------//
// Faction name
//----------------------------------------------//
private transient static ArrayList<String> nameWhitelist = new ArrayList<String>(Arrays.asList(new String []{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z"
}));
public static String toComparisonName(String name) {
String ret = "";
for (char c : name.toCharArray()) {
if (nameWhitelist.contains(String.valueOf(c))) {
ret += c;
}
}
return ret.toLowerCase();
}
public static ArrayList<String> validateName(String name) {
ArrayList<String> errors = new ArrayList<String>();
if(Faction.toComparisonName(name).length() < Conf.factionNameMinLength) {
errors.add(Conf.colorSystem+"That name is to short");
}
if(name.length() > Conf.factionNameMaxLength) {
errors.add(Conf.colorSystem+"That name is to long");
}
return errors;
}
public String getComparisonName() {
return Faction.toComparisonName(this.name);
}
public static Faction find(String name) {
String compName = Faction.toComparisonName(name);
for (Faction faction : Faction.getAll()) {
if (faction.getComparisonName().equals(compName)) {
return faction;
}
}
return null;
}
public static boolean isNameTaken(String name) {
return Faction.find(name) != null;
}
//----------------------------------------------//
// Messages - Directly connected to ChatFixUtil
//----------------------------------------------//
public void sendMessage(String message, boolean fix) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), message, fix);
}
public void sendMessage(List<String> messages, boolean fix) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), messages, fix);
}
public void sendMessage(String message) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), message, true);
}
public void sendMessage(List<String> messages) {
ChatFixUtil.sendMessage(this.getOnlinePlayers(), messages, true);
}
// -------------------------------
// Relation and relation colors
// -------------------------------
public Relation getRelationWish(Faction otherFaction) {
if (this.relationWish.containsKey(otherFaction.id)){
return this.relationWish.get(otherFaction.id);
}
return Relation.NEUTRAL;
}
public void setRelationWish(Faction otherFaction, Relation relation) {
if (this.relationWish.containsKey(otherFaction.id) && relation.equals(Relation.NEUTRAL)){
this.relationWish.remove(otherFaction.id);
return;
}
this.relationWish.put(otherFaction.id, relation);
}
public Relation getRelation(Faction otherFaction) {
if (otherFaction.id == 0 || this.id == 0) {
return Relation.NEUTRAL;
}
if (otherFaction.equals(this)) {
return Relation.MEMBER;
}
if(this.getRelationWish(otherFaction).value >= otherFaction.getRelationWish(this).value) {
return otherFaction.getRelationWish(this);
}
return this.getRelationWish(otherFaction);
}
public Relation getRelation(Follower follower) {
return getRelation(follower.getFaction());
}
public ChatColor getRelationColor(Faction otherFaction) {
return this.getRelation(otherFaction).getColor();
}
public ChatColor getRelationColor(Follower follower) {
return this.getRelation(follower).getColor();
}
//----------------------------------------------//
// Persistance and entity management
//----------------------------------------------//
public static Faction create() {
return EM.factionCreate();
}
public static Faction get(Integer factionId) {
return EM.factionGet(factionId);
}
public static Collection<Faction> getAll() {
return EM.factionGetAll();
}
public boolean save() {
return EM.factionSave(this.id);
}
}

View File

@ -0,0 +1,400 @@
package com.bukkit.mcteam.factions.entities;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.struct.*;
import com.bukkit.mcteam.factions.util.Log;
import com.bukkit.mcteam.util.ChatFixUtil;
public class Follower {
public transient String id; // The is the name of the player
public transient Player player; // The is the name of the player
public int factionId;
public Role role;
private String title;
private double power;
private long lastPowerUpdateTime;
private boolean mapAutoUpdating;
public Follower() {
this.resetFactionData();
this.power = this.getPowerMax();
this.lastPowerUpdateTime = System.currentTimeMillis();
this.mapAutoUpdating = false;
}
protected void resetFactionData() {
this.factionId = 0; // The default neutral faction
this.role = Role.NORMAL;
this.title = "";
}
public Player getPlayer() {
return this.player;
}
public boolean isOnline() {
return this.getPlayer() != null;
}
public boolean isMapAutoUpdating() {
return mapAutoUpdating;
}
public void setMapAutoUpdating(boolean mapAutoUpdating) {
this.mapAutoUpdating = mapAutoUpdating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
this.save();
}
//----------------------------------------------//
// Health
//----------------------------------------------//
public void heal(int amnt) {
Player player = this.getPlayer();
if (player == null) {
return;
}
player.setHealth(player.getHealth() + amnt);
}
//----------------------------------------------//
// Power
//----------------------------------------------//
public double getPower() {
this.updatePower();
return this.power;
}
protected void alterPower(double delta) {
this.power += delta;
if (this.power > this.getPowerMax()) {
this.power = this.getPowerMax();
} else if (this.power < this.getPowerMin()) {
this.power = this.getPowerMin();
}
Log.debug("Power of "+this.getFullName()+" is now: "+this.power);
}
public double getPowerMax() {
return Conf.powerPerPlayer;
}
public double getPowerMin() {
return -Conf.powerPerPlayer;
}
public int getPowerRounded() {
return (int) Math.round(this.getPower());
}
public int getPowerMaxRounded() {
return (int) Math.round(this.getPowerMax());
}
public int getPowerMinRounded() {
return (int) Math.round(this.getPowerMin());
}
protected void updatePower() {
long now = System.currentTimeMillis();
long millisPassed = now - this.lastPowerUpdateTime;
this.lastPowerUpdateTime = now;
int millisPerMinute = 60*1000;
this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute);
//this.save(); // This would save to often. So we save this on player quit instead.
}
public void onDeath() {
this.updatePower();
this.alterPower(-Conf.powerPerDeath);
}
//----------------------------------------------//
// Territory
//----------------------------------------------//
public boolean isInOwnTerritory() {
return Board.getFactionAt(this.getCoord()) == this.getFaction();
}
public boolean isInOthersTerritory() {
Faction factionHere = Board.getFactionAt(this.getCoord());
return factionHere.id != 0 && factionHere != this.getFaction();
}
public Coord getCoord() {
return Coord.from(this);
}
public void sendFactionHereMessage() {
Faction factionHere = Board.getFactionAt(this.getCoord());
String msg = Conf.colorSystem+" ~ "+factionHere.getName(this);
this.sendMessage(msg);
}
//----------------------------------------------//
// Faction management
//----------------------------------------------//
public Faction getFaction() {
return EM.factionGet(factionId);
}
public ArrayList<String> join(Faction faction) {
ArrayList<String> errors = new ArrayList<String>();
if (faction.id == this.factionId) {
errors.add(Conf.colorSystem+"You are already a member of "+faction.getRelationColor(this)+faction.getName());
}
if( ! faction.getOpen() && ! faction.isInvited(this)) {
errors.add(Conf.colorSystem+"This guild requires invitation.");
}
if (this.factionId != 0) {
errors.add(Conf.colorSystem+"You must leave your current faction first.");
}
if (errors.size() > 0) {
return errors;
}
this.resetFactionData();
if(faction.getFollowersAll().size() == 0) {
this.role = Role.ADMIN;
} else {
this.role = Role.NORMAL;
}
this.factionId = faction.id;
faction.deinvite(this);
this.save();
return errors;
}
public ArrayList<String> leave() {
ArrayList<String> errors = new ArrayList<String>();
if (this.role == Role.ADMIN && this.getFaction().getFollowersAll().size() > 1) {
errors.add(Conf.colorSystem+"You must give the admin role to someone else first.");
}
if(this.factionId == 0) {
errors.add(Conf.colorSystem+"You are not member of any faction.");
}
if (errors.size() > 0) {
return errors;
}
this.resetFactionData();
this.save();
return errors;
}
public ArrayList<String> createFaction(String name) {
ArrayList<String> errors = new ArrayList<String>();
if (this.factionId != 0) {
errors.add(Conf.colorSystem+"You must leave your current faction first.");
}
if (Faction.isNameTaken(name)) {
errors.add(Conf.colorSystem+"That name is already in use.");
}
errors.addAll(Faction.validateName(name));
if (errors.size() > 0) {
return errors;
}
Faction faction = EM.factionCreate();
faction.setName(name);
faction.save();
this.join(faction);
this.role = Role.ADMIN;
this.save();
return errors;
}
public ArrayList<String> invite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
//Log.debug("this.role: "+this.role);
//Log.debug("this.role.value: "+this.role.value);
//Log.debug("FactionRole.MODERATOR.value: "+FactionRole.MODERATOR.value);
if (this.role.value < Role.MODERATOR.value) {
errors.add(Conf.colorSystem+"You must me be a moderator to invite.");
}
if(errors.size() > 0) {
return errors;
}
return this.getFaction().invite(follower);
}
public ArrayList<String> deinvite(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if (this.role.value < Role.MODERATOR.value) {
errors.add(Conf.colorSystem+"You must me be a moderator to deinvite.");
}
if(errors.size() > 0) {
return errors;
}
return follower.getFaction().deinvite(follower);
}
public ArrayList<String> kick(Follower follower) {
ArrayList<String> errors = new ArrayList<String>();
if ( ! follower.getFaction().equals(this.getFaction())) {
errors.add(this.getRelationColor(follower)+follower.getFullName()+Conf.colorSystem+" is not a member of "+Conf.colorMember+this.getFaction().getName());
} else if (follower.equals(this)) {
errors.add(Conf.colorSystem+"You can not kick yourself.");
errors.add(Conf.colorSystem+"You might want to "+Conf.colorCommand+Conf.aliasBase.get(0)+" "+Conf.aliasLeave.get(0));
} else if (follower.role.value >= this.role.value) { // TODO add more informative messages.
errors.add(Conf.colorSystem+"Your rank is to low to kick this player.");
}
if(errors.size() > 0) {
return errors;
}
return follower.getFaction().kick(follower);
}
//----------------------------------------------//
// Login info
//----------------------------------------------//
public void sendJoinInfo() { // TODO Missplaced!?
// Do we even whant to use message of the day...
// Perhaps that is up to another plugin...
//this.getPlayer().sendMessage(ChatColor.GREEN + "This is a faction server! Type "+Conf.colorCommand+"/f"+ChatColor.GREEN +" for more info :D");
}
//----------------------------------------------//
// Messages - Directly connected to ChatFixUtil
//----------------------------------------------//
public void sendMessage(String message, boolean fix) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, message, fix);
}
public void sendMessage(List<String> messages, boolean fix) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, messages, fix);
}
public void sendMessage(String message) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, message, true);
}
public void sendMessage(List<String> messages) {
Player player = this.getPlayer();
ChatFixUtil.sendMessage(player, messages, true);
}
//----------------------------------------------//
// Search
//----------------------------------------------//
public static Follower find(String name) {
for (Follower follower : EM.followerGetAll()) {
if (follower.getName().equalsIgnoreCase(name.trim())) {
return follower;
}
}
return null;
}
// -------------------------------
// Relation and relation colors
// -------------------------------
public Relation getRelation(Faction faction) {
return faction.getRelation(this);
}
public Relation getRelation(Follower follower) {
return this.getFaction().getRelation(follower);
}
public ChatColor getRelationColor(Faction faction) {
return faction.getRelationColor(this);
}
public ChatColor getRelationColor(Follower follower) {
return this.getRelation(follower).getColor();
}
//----------------------------------------------//
// Display the name of this follower
//----------------------------------------------//
public String getName() {
return this.id;
}
public String getFullName() {
return getFullName("");
}
public String getFullName(Faction otherFaction) {
return getFullName(otherFaction.getRelationColor(this).toString());
}
public String getFullName(Follower otherFollower) {
return getFullName(otherFollower.getRelationColor(this).toString());
}
public String getFullName(String prefix) {
String ret = prefix;
if (this.role.equals(Role.ADMIN)) {
ret += Conf.prefixAdmin;
} else if (this.role.equals(Role.MODERATOR)) {
ret += Conf.prefixMod;
}
if (this.title.length() > 0) {
ret += this.title + " ";
}
ret += this.getName();
return ret;
}
//----------------------------------------------//
// Persistance and entity management
//----------------------------------------------//
public boolean save() {
return EM.followerSave(this.id);
}
public static Follower get(Player player) {
return EM.followerGet(player);
}
public static Collection<Follower> getAll() {
return EM.followerGetAll();
}
}

View File

@ -0,0 +1,48 @@
package com.bukkit.mcteam.factions.struct;
import org.bukkit.ChatColor;
import com.bukkit.mcteam.factions.entities.*;
public enum Relation {
MEMBER(3, "member"),
ALLY(2, "ally"),
NEUTRAL(1, "neutral"),
ENEMY(0, "enemy");
//UNKNOWN(-1, "unknown");
public final int value;
public final String nicename;
private Relation(final int value, final String nicename) {
this.value = value;
this.nicename = nicename;
}
@Override
public String toString() {
return this.nicename;
}
public ChatColor getColor() {
return Conf.relationColor(this);
}
/*public String getChartDot() {
return Conf.chartDot(this);
}
public static Relation from(String str) {
if (str.equalsIgnoreCase("member")) {
return Relation.MEMBER;
} else if (str.equalsIgnoreCase("ally")) {
return Relation.ALLY;
} else if (str.equalsIgnoreCase("neutral")) {
return Relation.NEUTRAL;
} else if (str.equalsIgnoreCase("enemy")) {
return Relation.ENEMY;
}
return Relation.UNKNOWN;
}*/
}

View File

@ -0,0 +1,20 @@
package com.bukkit.mcteam.factions.struct;
public enum Role {
ADMIN(2, "admin"),
MODERATOR(1, "moderator"),
NORMAL(0, "normal player");
public final int value;
public final String nicename;
private Role(final int value, final String nicename) {
this.value = value;
this.nicename = nicename;
}
@Override
public String toString() {
return this.nicename;
}
}

View File

@ -0,0 +1,39 @@
package com.bukkit.mcteam.factions.util;
import java.util.*;
import org.bukkit.entity.Player;
import com.bukkit.mcteam.factions.Factions;
public class Log {
public static String prefix = Factions.desc.getName();
public static ArrayList<Player> debuggers = new ArrayList<Player>();
public static int threshold = 10;
public static void log(int level, String prefix, String msg) {
if (threshold <= level) {
msg = Log.prefix+prefix+msg;
System.out.println(msg);
for(Player debugger : debuggers) {
debugger.sendMessage(msg);
}
}
}
public static void debug (String msg) {
log(10, " debug: ", msg);
}
public static void info (String msg) {
log(20, " info: ", msg);
}
public static void warn (String msg) {
log(30, " warn: ", msg);
}
public static void severe (String msg) {
log(40, " severe: ", msg);
}
}

View File

@ -0,0 +1,63 @@
package com.bukkit.mcteam.factions.util;
import java.util.*;
import org.bukkit.Material;
import com.bukkit.mcteam.factions.entities.*;
public class TextUtil {
public static String titleize(String str) {
String line = Conf.colorChrome+repeat("_", 60);
String center = ".[ " + Conf.colorSystem + str + Conf.colorChrome + " ].";
int pivot = line.length() / 2;
int eatLeft = center.length() / 2;
int eatRight = center.length() - eatLeft;
return line.substring(0, pivot - eatLeft) + center + line.substring(pivot + eatRight);
}
public static String repeat(String s, int times) {
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
public static ArrayList<String> split(String str) {
return new ArrayList<String>(Arrays.asList(str.trim().split("\\s+")));
}
public static String implode(List<String> list, String glue) {
String ret = "";
for (int i=0; i<list.size(); i++) {
if (i!=0) {
ret += glue;
}
ret += list.get(i);
}
return ret;
}
public static String implode(List<String> list) {
return implode(list, " ");
}
public static String commandHelp(List<String> aliases, String param, String desc) {
ArrayList<String> parts = new ArrayList<String>();
parts.add(Conf.colorCommand+Conf.aliasBase.get(0));
parts.add(TextUtil.implode(aliases, ", "));
if (param.length() > 0) {
parts.add(Conf.colorParameter+param);
}
if (desc.length() > 0) {
parts.add(Conf.colorSystem+desc);
}
//Log.debug(TextUtil.implode(parts, " "));
return TextUtil.implode(parts, " ");
}
public static String getMaterialName(Material material) {
String ret = material.toString();
ret = ret.replace('_', ' ');
ret = ret.toLowerCase();
return ret.substring(0, 1).toUpperCase()+ret.substring(1);
}
}

View File

@ -0,0 +1,89 @@
package com.bukkit.mcteam.util;
import java.util.*;
import org.bukkit.ChatColor;
public class AsciiCompass {
public enum Point {
N('N'),
NE('/'),
E('W'),
SE('\\'),
S('S'),
SW('/'),
W('W'),
NW('\\');
public final char asciiChar;
private Point(final char asciiChar) {
this.asciiChar = asciiChar;
}
@Override
public String toString() {
return String.valueOf(this.asciiChar);
}
public String toString(boolean isActive, ChatColor colorActive, ChatColor colorDefault) {
return (isActive ? colorActive : colorDefault)+String.valueOf(this.asciiChar);
}
}
public static AsciiCompass.Point getCompassPointForDirection(double inDegrees) {
double degrees = (inDegrees - 90) % 360 ;
if (degrees < 0)
degrees += 360;
if (0 <= degrees && degrees < 22.5)
return AsciiCompass.Point.N;
else if (22.5 <= degrees && degrees < 67.5)
return AsciiCompass.Point.NE;
else if (67.5 <= degrees && degrees < 112.5)
return AsciiCompass.Point.E;
else if (112.5 <= degrees && degrees < 157.5)
return AsciiCompass.Point.SE;
else if (157.5 <= degrees && degrees < 202.5)
return AsciiCompass.Point.S;
else if (202.5 <= degrees && degrees < 247.5)
return AsciiCompass.Point.SW;
else if (247.5 <= degrees && degrees < 292.5)
return AsciiCompass.Point.W;
else if (292.5 <= degrees && degrees < 337.5)
return AsciiCompass.Point.NW;
else if (337.5 <= degrees && degrees < 360.0)
return AsciiCompass.Point.N;
else
return null;
}
public static ArrayList<String> getAsciiCompass(Point point, ChatColor colorActive, ChatColor colorDefault) {
ArrayList<String> ret = new ArrayList<String>();
String row;
row = "";
row += Point.NW.toString(Point.NW == point, colorActive, colorDefault);
row += Point.N.toString(Point.N == point, colorActive, colorDefault);
row += Point.NE.toString(Point.NE == point, colorActive, colorDefault);
ret.add(row);
row = "";
row += Point.W.toString(Point.W == point, colorActive, colorDefault);
row += colorDefault+"+";
row += Point.E.toString(Point.E == point, colorActive, colorDefault);
ret.add(row);
row = "";
row += Point.SW.toString(Point.SW == point, colorActive, colorDefault);
row += Point.S.toString(Point.S == point, colorActive, colorDefault);
row += Point.SE.toString(Point.SE == point, colorActive, colorDefault);
ret.add(row);
return ret;
}
public static ArrayList<String> getAsciiCompass(double inDegrees, ChatColor colorActive, ChatColor colorDefault) {
return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault);
}
}

View File

@ -0,0 +1,230 @@
package com.bukkit.mcteam.util;
import java.util.*;
import org.bukkit.entity.Player;
/**
* The purpose of this tool is twofold:
* 1: Avoid client crashes due to bad color formating.
* 2: Make color continue on word wrapping
*
* In minecraft the degree sign is used as a prefix to another char to create a color.
* For example the code for white is "\u00A7f".
* The "\u00A7" is the unicode notation for the degree sign and the "f" means white.
*
* When does minecraft wrap the text? After how many chars?
* Answer:
* Because the font isn't monospace this differs depending on what you write.
* However we can fit 53 "M" without wrapping and the 54th char would then wrap (be at the beginning of the next line instead)
* As there is no broader char than "M" we can know for sure the minimum line length is 53.
* Note that this means the number of DISPLAYED chars per row is 53.
* A degree sign and the char after will NOT count, as they will not be displayed as chars.
*
* Good to know: Numbers have the same font width as an M.
*
* When does the client crash?
* Answer:
* When a row ends with a degree char and optionally another sign after.
* Another way to say the same: When a line ends with either a broken or valid color notation.
* AND
* The client will ALWAYS crash if the sign after the last displayed char in a row is a degree char.
* A goofy way to explatin it:
* For a line with only "M" and numbers, the fiftyfourth "displayed char" musn't be a degree sign.
*
* WARNING:
* Above is a hypothesis I have created based on what my experiments have shown.
* I am fairly sure it is correct but please help me test it further.
*/
public class ChatFixUtil {
public final static char deg = '\u00A7';
public final static int lineLength = 53;
/**
* This method wraps the msg for you at row lengths of 53,
* avoids client crash scenarios and makes the previous color continue on
* the next line.
*
* The upsides with filtering your messages through this method are:
* - No client crashes.
* - Line wrapping with preserved color.
*
* The downsides are:
* - The width of the chat window will not be used to it's fullest.
* For example you can fit more that 53 commas (,) in a chatwindow row
* but the line would break after 53 displayed chars.
*
* Suggested usage:
* NO NEED TO USE the fix method for static help pages in your plugin.
* As the text is static you can make sure there is no client crash yourself
* and be able to use the full line length.
*
* DO USE in cases like where you output colored messages with playernames in your
* plugin. As the player names have different length there is potential for client crash.
*/
public static ArrayList<String> fix(String msg) {
// Make sure the end of msg is good
msg = cleanMsgEnding(msg);
ArrayList<String> ret = new ArrayList<String>();
int displen = 0; // The number of displayed chars in row so far.
String row = "";
String latestColor = null;
for (int i = 0; i < msg.length(); i++) {
if (displen == lineLength) {
// it is time to start on the next row!
ret.add(row);
displen = 0;
row = "";
if (latestColor != null) {
row += deg+latestColor;
}
}
char c = msg.charAt(i);
if (c == deg) {
latestColor = String.valueOf(msg.charAt(i+1));
row += deg+latestColor;
i++;
} else {
displen += 1;
row += c;
}
}
ret.add(row);
return ret;
}
public static ArrayList<String> fix(List<String> messages) {
ArrayList<String> ret = new ArrayList<String>();
for(String message : messages) {
ret.addAll(fix(message));
}
return ret;
}
/**
* Removes the ending chars as long as they are deg or deg+'anychar' or a space
* As I see it we would never want those chars at the end of a msg.
*/
protected static String cleanMsgEnding (String msg) {
while (msg.length() > 0) {
if (msg.endsWith(String.valueOf(deg)) || msg.endsWith(" ")) {
msg = msg.substring(0, msg.length()-1);
} else if (msg.length() >= 2 && msg.charAt(msg.length() - 2) == deg) {
msg = msg.substring(0, msg.length()-2);
} else {
break;
}
}
return msg;
}
/**
* This test util assumes line break after 53 displayed chars.
* The fix method above breaks like that so this method should
* be a valid way to test if a message row would crash a client.
*/
public static String thisMsgWouldCrashClient(String str) {
// There would always be crash if we end with deg or deg+'anychar'
if (str.length() >= 1 && str.charAt(str.length() - 1) == deg) {
return "Crash: The str ends with deg.";
} else if (str.length() >= 2 && str.charAt(str.length() - 2) == deg) {
return "Crash: The str ends with deg+'anychar'.";
}
int displayedChars = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == deg && displayedChars == lineLength) {
return "Crash: Deg as fiftyforth \"displayed\" char";
} else if (c == deg) {
i++; // this and next: they are not displayed... skip them...
} else {
displayedChars += 1;
}
}
return "all ok";
}
//----------------------------------------------//
// Methods for effectively sending messages
//----------------------------------------------//
//----------------------------------------------//
// One player
//----------------------------------------------//
public static void sendMessage(Player player, String message, boolean fix) {
if (fix) {
List<String> messages = ChatFixUtil.fix(message);
sendMessage(player, messages, false);
} else {
if (player != null) {
player.sendMessage(message);
}
}
}
public static void sendMessage(Player player, List<String> messages, boolean fix) {
if (fix) {
messages = ChatFixUtil.fix(messages);
}
for (String message : messages) {
sendMessage(player, message, false);
}
}
public static void sendMessage(Player player, String message) {
sendMessage(player, message, true);
}
public static void sendMessage(Player player, List<String> messages) {
sendMessage(player, messages, true);
}
//----------------------------------------------//
// Many Players
//----------------------------------------------//
public static void sendMessage(Collection<Player> players, String message, boolean fix) {
if (fix) {
List<String> messages = ChatFixUtil.fix(message);
sendMessage(players, messages, false);
} else {
for (Player player : players) {
sendMessage(player, message, false);
}
}
}
public static void sendMessage(Collection<Player> players, List<String> messages, boolean fix) {
if (fix) {
messages = ChatFixUtil.fix(messages);
}
for (String message : messages) {
sendMessage(players, message, false);
}
}
public static void sendMessage(Collection<Player> players, String message) {
sendMessage(players, message, true);
}
public static void sendMessage(Collection<Player> players, List<String> messages) {
sendMessage(players, messages, true);
}
}

View File

@ -0,0 +1,32 @@
package com.bukkit.mcteam.util;
import java.io.*;
/**
* Harddisc related methods such as read and write.
*/
public class DiscUtil {
/**
* Convenience function for writing a string to a file.
*/
public static void write(File file, String content) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
out.write(content);
out.close();
}
/**
* Convenience function for reading a file as a string.
*/
public static String read(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null) {
ret += line;
}
return ret;
}
}

View File

@ -0,0 +1,168 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Adapts maps containing complex keys as arrays of map entries.
*
* <h3>Maps as JSON objects</h3>
* The standard GSON map type adapter converts Java {@link Map Maps} to JSON
* Objects. This requires that map keys can be serialized as strings; this is
* insufficient for some key types. For example, consider a map whose keys are
* points on a grid. The default JSON form encodes reasonably: <pre> {@code
* Map<Point, String> original = new LinkedHashMap<Point, String>();
* original.put(new Point(5, 6), "a");
* original.put(new Point(8, 8), "b");
* System.out.println(gson.toJson(original, type));
* }</pre>
* The above code prints this JSON object:<pre> {@code
* {
* "(5,6)": "a",
* "(8,8)": "b"
* }
* }</pre>
* But GSON is unable to deserialize this value because the JSON string name is
* just the {@link Object#toString() toString()} of the map key. Attempting to
* convert the above JSON to an object fails with a parse exception:
* <pre>com.google.gson.JsonParseException: Expecting object found: "(5,6)"
* at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler
* at com.google.gson.ObjectNavigator.navigateClassFields
* ...</pre>
*
* <h3>Maps as JSON arrays</h3>
* An alternative approach taken by this type adapter is to encode maps as
* arrays of map entries. Each map entry is a two element array containing a key
* and a value. This approach is more flexible because any type can be used as
* the map's key; not just strings. But it's also less portable because the
* receiver of such JSON must be aware of the map entry convention.
*
* <p>Register this adapter when you are creating your GSON instance.
* <pre> {@code
* Gson gson = new GsonBuilder()
* .registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter())
* .create();
* }</pre>
* This will change the structure of the JSON emitted by the code above. Now we
* get an array. In this case the arrays elements are map entries:
* <pre> {@code
* [
* [
* {
* "x": 5,
* "y": 6
* },
* "a",
* ],
* [
* {
* "x": 8,
* "y": 8
* },
* "b"
* ]
* ]
* }</pre>
* This format will serialize and deserialize just fine as long as this adapter
* is registered.
*
* <p>This adapter returns regular JSON objects for maps whose keys are not
* complex. A key is complex if its JSON-serialized form is an array or an
* object.
*/
public final class MapAsArrayTypeAdapter
implements JsonSerializer<Map<?, ?>>, JsonDeserializer<Map<?, ?>> {
public Map<?, ?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Map<Object, Object> result = new LinkedHashMap<Object, Object>();
Type[] keyAndValueType = typeToTypeArguments(typeOfT);
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
JsonArray entryArray = array.get(i).getAsJsonArray();
Object k = context.deserialize(entryArray.get(0), keyAndValueType[0]);
Object v = context.deserialize(entryArray.get(1), keyAndValueType[1]);
result.put(k, v);
}
checkSize(array, array.size(), result, result.size());
} else {
JsonObject object = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Object k = context.deserialize(new JsonPrimitive(entry.getKey()), keyAndValueType[0]);
Object v = context.deserialize(entry.getValue(), keyAndValueType[1]);
result.put(k, v);
}
checkSize(object, object.entrySet().size(), result, result.size());
}
return result;
}
public JsonElement serialize(Map<?, ?> src, Type typeOfSrc, JsonSerializationContext context) {
Type[] keyAndValueType = typeToTypeArguments(typeOfSrc);
boolean serializeAsArray = false;
List<JsonElement> keysAndValues = new ArrayList<JsonElement>();
for (Map.Entry<?, ?> entry : src.entrySet()) {
JsonElement key = context.serialize(entry.getKey(), keyAndValueType[0]);
serializeAsArray |= key.isJsonObject() || key.isJsonArray();
keysAndValues.add(key);
keysAndValues.add(context.serialize(entry.getValue(), keyAndValueType[1]));
}
if (serializeAsArray) {
JsonArray result = new JsonArray();
for (int i = 0; i < keysAndValues.size(); i+=2) {
JsonArray entryArray = new JsonArray();
entryArray.add(keysAndValues.get(i));
entryArray.add(keysAndValues.get(i + 1));
result.add(entryArray);
}
return result;
} else {
JsonObject result = new JsonObject();
for (int i = 0; i < keysAndValues.size(); i+=2) {
result.add(keysAndValues.get(i).getAsString(), keysAndValues.get(i + 1));
}
checkSize(src, src.size(), result, result.entrySet().size());
return result;
}
}
private Type[] typeToTypeArguments(Type typeOfT) {
if (typeOfT instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) typeOfT).getActualTypeArguments();
if (typeArguments.length != 2) {
throw new IllegalArgumentException("MapAsArrayTypeAdapter cannot handle " + typeOfT);
}
return typeArguments;
}
return new Type[] { Object.class, Object.class };
}
private void checkSize(Object input, int inputSize, Object output, int outputSize) {
if (inputSize != outputSize) {
throw new JsonSyntaxException("Input size " + inputSize + " != output size " + outputSize
+ " for input " + input + " and output " + output);
}
}
}