PK STb=%X_ _ READMEAll documentation located at http://www.lunatech-labs.com/open-source/resteasy-crud-play-modulePK z\;=|wfK K COPYING GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
PK `]%>T T build.xml
PK hc>=Ys" " manifestversion=1.1
frameworkVersions=1.1
PK |\;=p COPYING.LESSER GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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.
PK Tb=yA A , app/rest/resteasy/crud/ExceptionHandler.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package rest.resteasy.crud;
import java.net.HttpURLConnection;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Variant;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.hibernate.PropertyValueException;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.jboss.resteasy.spi.Failure;
import play.Logger;
import play.modules.resteasy.crud.InvalidResponse;
/**
* Maps RESTEasy failures to responses, finds Hibernate Validation exceptions
* and maps them to InvalidResponse and tries to unwrap exceptions generally.
* @author Stéphane Épardaud
*/
@Provider
public class ExceptionHandler implements ExceptionMapper {
@Context
private Request request;
public Response toResponse(Throwable t) {
Logger.debug("Exception mapper called");
InvalidValue[] invalidValues = findInvalidValues(t);
if (invalidValues != null) {
InvalidResponse r = new InvalidResponse();
if (invalidValues != null) {
for (InvalidValue val : invalidValues) {
r.addError(val.getPropertyName(), val.getMessage());
}
}
List variants = Variant.mediaTypes(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE,
MediaType.valueOf("application/*+xml"),
MediaType.TEXT_XML_TYPE).build();
Variant variant = request.selectVariant(variants);
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST)
.entity(r).variant(variant).build();
}
// also handle "normal" JAX-RS exceptions
WebApplicationException wx = findWebApplicationException(t);
if (wx != null) {
return wx.getResponse();
}
// handle security checks as well
/* FIXME: play port: fix auth
if (t instanceof AuthorizationException) {
return Response.status(HttpURLConnection.HTTP_FORBIDDEN).entity(
t.getMessage()).build();
}
*/
// and RESTEasy failures (grrr)
if (t instanceof Failure) {
Failure f = (Failure) t;
if (f.getResponse() != null)
return f.getResponse();
if (f.getErrorCode() != -1)
return Response.status(f.getErrorCode()).entity(f.getMessage())
.build();
// fall through
}
Logger.error(t, "Uncaught exception");
return Response.serverError().build();
}
private WebApplicationException findWebApplicationException(Throwable t) {
if (t instanceof WebApplicationException)
return (WebApplicationException) t;
if (t.getCause() != null)
return findWebApplicationException(t.getCause());
return null;
}
private InvalidValue[] findInvalidValues(Throwable t) {
if (t instanceof InvalidStateException)
return ((InvalidStateException) t).getInvalidValues();
if (t instanceof PropertyValueException) {
PropertyValueException x = (PropertyValueException) t;
// watch it, keep this in sync with exception handling
InvalidValue invalidValue = new InvalidValue(x.getMessage(), null,
x.getPropertyName(), null, null);
InvalidValue[] invalidValues = new InvalidValue[1];
invalidValues[0] = invalidValue;
return invalidValues;
}
if (t.getCause() != null)
return findInvalidValues(t.getCause());
return null;
}
}
PK x]%>E;ZOt t debian/controlSource: play-1.1-resteasy-crud-module-1.1
Section: unknown
Priority: extra
Maintainer: Stephane Epardaud
Build-Depends: debhelper (>= 7), play-1.1
Standards-Version: 3.8.3
Package: play-1.1-resteasy-crud-module-1.1
Architecture: all
Depends: ${misc:Depends}, play-1.1-resteasy-module-1.3 (>= 1.3.1ubuntu1)
Description: Your play module description
PK Qb=[1
debian/compat7
PK ]%>5; ; debian/rules#!/usr/bin/make -f
#-*- makefile -*-
# Made with the aid of dh_make, by Craig Small
# Sample debian/rules that uses debhelper. GNU copyright 1997 by Joey Hess.
# Some lines taken from debmake, by Christoph Lameter.
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
VERSION=1.1
MODULE_NAME=resteasy-crud
PLAY_VERSION=1.1
APP=play-$(PLAY_VERSION)-resteasy-crud-module-$(VERSION)
MODULE=$(MODULE_NAME)-$(VERSION)
DEB_PATH=debian/$(APP)
INSTALL_PATH=/usr/share/play-modules/$(PLAY_VERSION)/$(MODULE)
%:
dh $@
override_dh_auto_build:
/bin/echo -e '\n\n' | play-$(PLAY_VERSION) build-module
override_dh_auto_install:
install -d $(DEB_PATH)$(INSTALL_PATH)
for d in lib src app conf; \
do if test -d $$d; \
then rsync -r --exclude .svn --exclude .CVS $$d $(DEB_PATH)$(INSTALL_PATH); \
fi; \
done
PK I]%>BenW debian/changelogplay-1.1-resteasy-crud-module-1.1 (1.1ubuntu1) maverick; urgency=low
* Upgraded to RESTEasy 2.1
* Depend on play-1.1-resteasy-module-1.3 (>= 1.3.1ubuntu1)
* Removed need for security UEL plug
* Removed need for DataTable subclass
-- Stephane Epardaud Wed, 05 Jan 2011 11:39:57 +0100
play-1.1-resteasy-crud-module-1.0 (1.0) maverick; urgency=low
* Initial release
-- Stephane Epardaud Tue, 02 Nov 2010 10:12:48 +0100
PK tk=k* * docs/manual.textileh1. This is a test
For a manual on githubPK #ha=b( ( src/play.plugins10:play.modules.resteasy.crud.CRUDPluginPK Vb=, , 3 src/play/modules/resteasy/crud/InvalidResponse.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The type returned to the client if validation fails.
*
* @author Stéphane Épardaud
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class InvalidResponse {
/**
* Per-field errors.
*/
private List errors = new ArrayList();
/**
* Global errors.
*/
private List globalErrors = new ArrayList();
public InvalidResponse() {
}
public InvalidResponse(List errors) {
this.errors = errors;
}
public void addError(String field, String error) {
errors.add(new InvalidResponseField(field, error));
}
public void addGlobalError(String error) {
globalErrors.add(error);
}
public List getErrors() {
return errors;
}
public void setErrors(List errors) {
this.errors = errors;
}
public List getGlobalErrors() {
return globalErrors;
}
public void setGlobalErrors(List globalErrors) {
this.globalErrors = globalErrors;
}
}PK `$>apTV TV 0 src/play/modules/resteasy/crud/RESTResource.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import play.Logger;
import play.db.Model;
import play.db.Model.Factory;
import play.db.Model.Manager;
import play.db.Model.Property;
/**
* Your CRUD resource must subclass this to gain automagic resources.
*
* @author Stéphane Épardaud
*/
public abstract class RESTResource {
/**
* Queries the permission system for a permission
* @param target the object we want a permission for, can be a Class if this is a general permission
* @param name the name of the permission
* @return true if the current user has this permission, false otherwise
*/
protected boolean hasPermission(Object target, String name){
return CRUDSecure.hasPermission(target, name);
}
/**
* Throws a FORBIDDEN exception if the user doesn't have the given permission
* @param target the object we want a permission for, can be a Class if this is a general permission
* @param name the name of the permission
*/
protected void checkPermission(Object target, String name) {
if (!hasPermission(target, name))
throw new WebApplicationException(HttpURLConnection.HTTP_FORBIDDEN);
}
/**
* Throws a NOT_FOUND if the given parameter is null
* @param the type of parameter
* @param o the parameter to check
* @return the parameter
*/
protected T checkNotFound(T o) {
if (o == null)
throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
return o;
}
/**
* Throws a NOT_FOUND with the given message if the given parameter is null
* @param the type of parameter
* @param o the parameter to check
* @param msg the message format
* @param params the message parameters
* @return the parameter
*/
protected T checkNotFound(T o, String msg, Object... params) {
if (o == null)
throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_NOT_FOUND).entity(String.format(msg, params)).build());
return o;
}
/**
* Throws BAD_REQUEST if the given parameters are not null or are not empty collections
* @param objects the objects to check
*/
protected void checkEmpty(Object... objects) {
for(Object o : objects){
if (o == null)
continue;
if (o instanceof Collection && ((Collection>) o).isEmpty())
continue;
throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
}
}
/**
* Checks that we have the insert permission for the o object, and that oDB is not null and we have the update permission on it.
* @param the parameter type
* @param o the new object we want to get values from
* @param oDB the old object we want to update
* @return the old object
*/
protected T checkForUpdate(T o, T oDB) {
checkPermission(o, "insert");
checkNotFound(oDB);
checkPermission(oDB, "update");
return oDB;
}
/**
* Override if you have special checks for autocomplete queries
* @param values the autocomplete query values
*/
protected void checkAutoCompleteQuery(String... values) {
}
/**
* Returns a NOT_FOUND response
*/
protected Response notFound() {
return status(HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Returns a FORBIDDEN response
*/
protected Response forbidden() {
return status(HttpURLConnection.HTTP_FORBIDDEN);
}
/**
* Returns a BAD_REQUEST response
*/
protected Response badRequest() {
return status(HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Returns a BAD_REQUEST response with the specified message
* @param message the message format
* @param args the message parameters
*/
protected Response badRequest(String message, Object... args) {
return status(HttpURLConnection.HTTP_BAD_REQUEST, message, args);
}
/**
* Returns a NO_CONTENT response
*/
protected Response noContent() {
return status(HttpURLConnection.HTTP_NO_CONTENT);
}
/**
* Returns a CREATED response
*/
protected Response created() {
return status(HttpURLConnection.HTTP_CREATED);
}
/**
* Returns an INTERNAL_ERROR response
*/
protected Response internalError() {
return status(HttpURLConnection.HTTP_INTERNAL_ERROR);
}
/**
* Returns an OK response
*/
protected Response ok() {
return status(HttpURLConnection.HTTP_OK);
}
/**
* Returns an OK response with the given entity
* @param entity the entity to send
*/
protected Response ok(Object entity) {
return status(HttpURLConnection.HTTP_OK, entity);
}
/**
* Returns an INTERNAL_ERROR response with the specified message
* @param message the message format
* @param args the message parameters
*/
protected Response internalError(String msg, Object... args) {
return status(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, args);
}
/**
* Returns an INTERNAL_ERROR response with the specified message and logs the given error
* @param t the error to log
* @param message the message format
* @param args the message parameters
*/
protected Response internalError(Throwable t, String msg, Object... args) {
Logger.error(t, msg, args);
return status(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, args);
}
/**
* Returns a response with the specified status code
* @param code the status code
*/
protected Response status(int code){
Logger.info("Returning code %s", code);
return Response.status(code).build();
}
/**
* Returns a response with the specified status code and message
* @param code the status code
* @param message the message format
* @param args the message parameters
*/
protected Response status(int code, String message, Object... args){
String entity = String.format(message, args)+"\n";
return status(code, entity);
}
/**
* Returns a response with the specified status code and entity
* @param code the status code
* @param entity the response entity
*/
protected Response status(int code, Object entity){
Logger.info("Returning code %s: %s", code, entity);
return Response.status(code).entity(entity).build();
}
/**
* Throws a WebApplicationException with the given response
* @param r the response to send to the client
*/
protected void respond(Response r) {
throw toThrowable(r);
}
/**
* Makes a WebApplicationException with the given response
* @param r the response to wrap in a WebApplicationException
* @return the WebApplicationException
*/
protected WebApplicationException toThrowable(Response r) {
return new WebApplicationException(r);
}
/**
* Makes an OK response with the given list of autocomplete results as entity
* @param list the list of autocomplete results
*/
protected Response autoComplete(List list) {
return ok(new JAXBList(list));
}
/**
* Throws an InvalidStateException for the given validation error
* @param entity the entity with an invalid value
* @param message the error message
* @param field the invalid field
* @param value the invalid value
*/
protected void throwConstraintValidation(Object entity, String message,
String field, Object value) {
throw new InvalidStateException(new InvalidValue[] { new InvalidValue(
message, entity.getClass(), field, value, entity) });
}
//
// CRUD
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for getting a list of entities.
* @param model the model type
* @param q the query for the list of entities
* @return a response with the list of entities
*/
public Response list(Class model, DataTableQuery q){
logQuery(q);
checkPermission(model, "select");
PagedQuery carriers = findPaged(model);
return makeQueryResponse(q, carriers, model,
getSortableColumns(model), q.uriInfo);
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for getting a single entity.
* @param model the model type
* @param id the entity id
* @return a response with entity
*/
public Response get(Class model, Object id) {
Factory factory = Manager.factoryFor(model);
@SuppressWarnings("unchecked")
T entity = (T)factory.findById(id);
checkNotFound(entity, "Entity of type %s with id of %s could not be found", model.getName(), id);
checkPermission(entity, "select");
return ok(entity);
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for deleting an entity
* @param model the model type
* @param id the entity id
* @return a response with no content
*/
public Response delete(Class model, Object id) {
Factory factory = Manager.factoryFor(model);
@SuppressWarnings("unchecked")
T entity = (T)factory.findById(id);
checkNotFound(entity, "Entity of type %s with id of %s could not be found", model.getName(), id);
checkPermission(entity, "delete");
entity._delete();
return noContent();
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for adding an entity.
* @param model the model type
* @param elem the new entity
* @return a response with no content
*/
public Response add(Class model, final T elem, UriInfo uriInfo) {
checkPermission(elem, "insert");
// check non-editable field
walkProperties(model, new PropertyWalker(){
@Override
public void walk(Property property, Field field, CRUDField crud) {
Object newValue;
try {
newValue = PropertyUtils.getSimpleProperty(elem, property.name);
} catch (Exception e) {
throw toThrowable(internalError(e, "Failed to get property %s", property.name));
}
// if that field is not editable, let us barf
if(crud == null || !crud.editable())
checkEmpty(newValue);
}
});
elem._save();
return created();
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for editing an entity.
* @param model the model type
* @param id the entity id to update
* @param elem the new values for the entity
* @return a response with no content
*/
public Response edit(Class model, Object id, final T elem) {
Factory factory = Manager.factoryFor(model);
@SuppressWarnings("unchecked")
final T elemFromDB = (T)factory.findById(id);
checkForUpdate(elem, elemFromDB);
// copy every field
walkProperties(model, new PropertyWalker(){
@Override
public void walk(Property property, Field field, CRUDField crud) {
Object newValue;
try {
newValue = PropertyUtils.getSimpleProperty(elem, property.name);
} catch (Exception e) {
throw toThrowable(internalError(e, "Failed to get property %s", property.name));
}
// if that field is not editable, let us barf
if(crud == null || !crud.editable())
checkEmpty(newValue);
else{
// we can set it
try{
PropertyUtils.setSimpleProperty(elemFromDB, property.name, newValue);
} catch (Exception e) {
throw toThrowable(internalError(e, "Failed to set property %s", property.name));
}
}
}
});
elemFromDB._save();
return noContent();
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for getting a list of autocomplete entries for the given field and query
* @param model the model type
* @param field the field to autocomplete
* @param q the query for the autocompletion
* @return a response with the list of autocomplete enties
*/
public Response autoComplete(Class model, String field, String q) {
checkAutoCompleteQuery(q);
checkPermission(model, "select");
return autoComplete(AutoComplete.getAutoComplete(model, field, q));
}
/**
* Override this method to implement your own endpoint, otherwise it will be magically bound to the
* right path and parameters for getting a descriptor for CRUD fields.
* @param model the model type
* @return a response with the CRUD fields descriptor
*/
public Response descriptor(Class model) {
checkPermission(model, "select");
return Response.ok(new Descriptor(model)).build();
}
/**
* The CRUD fields descriptor
*
* @param The type of entity
* @author Stéphane Épardaud
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public static class Descriptor {
@XmlElement
public List columns = new ArrayList();
// For JAXB
public Descriptor(){}
public Descriptor(Class model) {
walkProperties(model, new PropertyWalker(){
@Override
public void walk(Property property, Field field, CRUDField crud) {
addColumn(property, field, crud);
}
});
CRUDOrder crudOrder = model.getAnnotation(CRUDOrder.class);
if(crudOrder != null){
List sortedColumns = new ArrayList();
for(String field : crudOrder.value()){
int i = findColumn(field);
if(i == -1)
throw new RuntimeException("No such field in model: "+field);
sortedColumns.add(columns.remove(i));
}
// now add any remaining column
sortedColumns.addAll(columns);
// and swap
columns = sortedColumns;
}
}
private int findColumn(String field) {
for(int i=0;i
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public static class Column {
@XmlElement
public String name;
@XmlElement
public String field;
@XmlElement
public boolean editable;
@XmlElement
public boolean sortable;
@XmlElement
public boolean autocomplete;
@XmlElement
public String type;
@XmlElement
public List validators = new ArrayList();
// For JAXB
public Column(){}
public Column(Property p, Field field, CRUDField crud) {
this.field = name = p.name;
editable = false;
autocomplete = false;
sortable = false;
Class> fieldType = field.getType();
setType(fieldType);
if(crud != null){
if(crud.name().length() > 0)
name = crud.name();
editable = crud.editable();
autocomplete = crud.autoComplete();
sortable = crud.sortable();
Type crudType = crud.type();
if(crudType != Type.DEFAULT)
type = crudType.name();
}
addValidation(field);
}
private void addValidation(Field field) {
if(field.isAnnotationPresent(NotEmpty.class)
|| field.isAnnotationPresent(NotNull.class))
validators.add("notempty");
}
private void setType(Class> fieldType) {
if(fieldType == String.class){
type = Type.STRING.name();
}else if(fieldType == Integer.class
|| fieldType == Integer.TYPE){
type = Type.INTEGER.name();
}else if(fieldType == Boolean.class){
type = Type.BOOLEAN.name();
}else
throw new RuntimeException("Unknown field type: "+fieldType.getName());
}
}
/**
* Walks every property with CRUDFIeld
*/
public interface PropertyWalker {
public void walk(Property property, Field field, CRUDField crud);
}
/**
* Walks every property with CRUDFIeld
*/
protected static void walkProperties(Class model, PropertyWalker walker){
// FIXME: make this faster (10x slower than doing it manually for some reason)
Factory factory = Manager.factoryFor(model);
for(Property prop : factory.listProperties()){
Field field = prop.field;
CRUDField crud = field.getAnnotation(CRUDField.class);
walker.walk(prop, field, crud);
}
}
/**
* Gets the list of sortable columns for the given model
*/
protected Set getSortableColumns(Class model) {
final Set ret = new HashSet();
walkProperties(model, new PropertyWalker(){
@Override
public void walk(Property property, Field field, CRUDField crud) {
if(crud != null && crud.sortable())
ret.add(property.name);
}
});
return ret;
}
/**
* Gets the list of searchable columns for the given model
*/
protected Set getSearchableColumns(Class model) {
final Set ret = new HashSet();
walkProperties(model, new PropertyWalker(){
@Override
public void walk(Property property, Field field, CRUDField crud) {
if(crud != null && crud.searchable())
ret.add(property.name);
}
});
return ret;
}
/**
* Makes a paged query for the given entity
*/
protected PagedQuery findPaged(Class model) {
PagedQuery query = new PagedQuery("FROM "+model.getSimpleName());
query.searchFields(getSearchableColumns(model));
return query;
}
/**
* Makes a query response
* @param the entity type
* @param q the query
* @param results the paged query results
* @param klass the entity type
* @param validColumns the list of valid search columns
* @param permissions the set of permissions to check and include in the response if the user has them
* @return the response
*/
protected Response makeQueryResponse(DataTableQuery q,
PagedQuery results, Class klass, Set validColumns,
UriInfo uriInfo, String... permissions) {
return makeQueryResponse(q, results, klass, validColumns, null,
uriInfo, permissions);
}
/**
* Makes a query response
* @param the entity type
* @param q the query
* @param results the paged query results
* @param klass the entity type
* @param oob the OutOfBounds object to include in the response, if not null
* @param validColumns the list of valid search columns
* @param permissions the set of permissions to check and include in the response if the user has them
* @return the response
*/
protected Response makeQueryResponse(DataTableQuery q,
PagedQuery results, Class klass, Set validColumns,
Object oob, UriInfo uriInfo, String... permissions) {
results.start = (long)q.start;
results.limit = (long)q.length;
if (isSortValid(q.sort, validColumns))
results.order = q.sort;
if(!StringUtils.isEmpty(q.search))
results.search = q.search;
DataTable dataTable = makeDataTable(q.echo,
results.getCount(), results.getResultList(), klass, oob,
uriInfo);
// add any permission we have
for (String permission : permissions) {
if (hasPermission(dataTable.facadeFor(), permission))
dataTable.addPermission(permission);
}
Logger.info("Returning 200 with entity: %s", dataTable);
return Response.ok(dataTable).build();
}
/**
* Override this to make your own DataTable with the appropriate {@link @XmlSeeAlso} annotation.
* If you do not, one will be provided for you with only T as JAXB context.
*/
protected DataTable makeDataTable(String echo, long count, List results, Class type, Object oob, UriInfo uriInfo){
return new DataTable(echo, count, results, type, oob, uriInfo);
}
/**
* Checks if the given sort query is valid according to the valid columns
* @param sort the query
* @param validColumns the valid columns
*/
protected boolean isSortValid(String sort, Set validColumns) {
if (sort == null)
return false;
final StringTokenizer tokenizer = new StringTokenizer(sort, ",");
// we need at least one
if (!tokenizer.hasMoreTokens())
return false;
while (tokenizer.hasMoreTokens()) {
final String fragment = tokenizer.nextToken().trim();
String field;
if (fragment.toLowerCase().endsWith(" desc"))
field = fragment.substring(0, fragment.length() - 5).trim();
else if (fragment.toLowerCase().endsWith(" asc"))
field = fragment.substring(0, fragment.length() - 4).trim();
else
field = fragment;
// can be an int or an allowed name
if (!field.matches("\\d+") && !validColumns.contains(field))
return false;
}
return true;
}
/**
* Logs an entity query
*/
protected void logQuery(DataTableQuery q) {
Logger.info("GET start: %s, length: %s, echo: %s, sort: %s, search: %s",
q.start, q.length, q.echo, q.sort, q.search);
}
}
PK Ub=ßn n - src/play/modules/resteasy/crud/CRUDOrder.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Set on your entity to override the CRUD fields order.
*
* @author Stéphane Épardaud
*/
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
public @interface CRUDOrder {
/**
* Sets the CRUD fields order. Specify property names, not DB column names.
*/
public String[] value();
}
PK Zb=Ny y ( src/play/modules/resteasy/crud/Type.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
/**
* Specifies a field type.
* @author Stéphane Épardaud
*/
public enum Type {
/**
* Infer type from property
*/
DEFAULT,
/**
* String type
*/
STRING,
/**
* Int type
*/
INTEGER,
/**
* Boolean type
*/
BOOLEAN,
/**
* Date type
*/
DATE;
}
PK @$>uD D 6 src/play/modules/resteasy/crud/PlayFunctionMapper.javapackage play.modules.resteasy.crud;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.el.FunctionMapper;
import org.jboss.el.lang.ExtendedFunctionMapper;
import play.Logger;
import play.Play;
import play.classloading.ApplicationClasses.ApplicationClass;
import play.exceptions.UnexpectedException;
import play.modules.resteasy.crud.CRUDSecure.CRUDSecurity;
/**
* Resolves Seam Security EL functions, s:hasRole() and s:hasPermission()
* by decorating a delegate Unified EL FunctionMapper
*
* @author Shane Bryzak
*/
public class PlayFunctionMapper extends ExtendedFunctionMapper
{
private FunctionMapper functionMapper;
private static Map methods;
public PlayFunctionMapper(FunctionMapper functionMapper)
{
this.functionMapper = functionMapper;
}
@Override
public Method resolveFunction(String prefix, String localName)
{
if ( "p".equals(prefix) )
{
init();
return methods.get(localName);
}
else if (functionMapper != null)
{
return functionMapper.resolveFunction(prefix, localName);
}
else
{
return null;
}
}
@Override
public Method resolveFunction(String prefix, String localName, int paramCount)
{
if ( "p".equals(prefix) )
{
init();
return methods.get(localName);
}
else if (functionMapper != null)
{
return functionMapper.resolveFunction(prefix, localName);
}
else
{
return null;
}
}
@SuppressWarnings("unchecked")
private static void init() {
if(methods != null)
return;
methods = new HashMap();
List classes = Play.classes.getAssignableClasses(CRUDSecurity.class);
Class security;
if(classes.isEmpty()){
Logger.warn("No CRUDSecurity implementation found, all security checks will be denied");
security = CRUDSecurity.class;
}else
security = (Class) classes.get(0).javaClass;
try {
methods.put("hasPermission", security.getMethod("hasPermission", Object.class, String.class));
methods.put("hasRole", security.getMethod("hasRole", String.class));
} catch (SecurityException e) {
throw new UnexpectedException(e);
} catch (NoSuchMethodException e) {
Logger.warn("Missing function in your CRUDSecurity subclass: "+e.getMessage());
throw new UnexpectedException(e);
}
}
}
PK Vb=N< < 8 src/play/modules/resteasy/crud/InvalidResponseField.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Per-field error response.
*
* @author Stéphane Épardaud
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class InvalidResponseField {
private String field;
private String error;
public InvalidResponseField() {
}
public InvalidResponseField(String field, String error) {
this.field = field;
this.error = error;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
PK Vb=e . src/play/modules/resteasy/crud/PagedQuery.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.persistence.Query;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.db.jpa.JPA;
/**
* Builds paged queries.
*
* @author Stéphane Épardaud
* @param The type of entity returned
*/
public class PagedQuery {
private String hql;
public String order;
public String group;
public Map parameters = new HashMap();
public String search;
public List searchFields = new ArrayList();
public Long start;
public Long limit;
private Long count;
public PagedQuery(String hql){
this.hql = hql;
}
public PagedQuery searchFields(String... searchFields){
this.searchFields.clear();
Collections.addAll(this.searchFields, searchFields);
return this;
}
public PagedQuery searchFields(Set searchFields){
this.searchFields.clear();
this.searchFields.addAll(searchFields);
return this;
}
private String getHQLQuery(boolean forSelect){
String hql = this.hql;
if (!StringUtils.isEmpty(search) && !searchFields.isEmpty()) {
if (hql.toLowerCase().contains(" where ")) {
hql += " AND (";
} else {
hql += " WHERE (";
}
boolean first = true;
for (String field : searchFields) {
if (!first) {
hql += " OR ";
} else
first = false;
hql += "LOCATE(lower(:_search), lower(" + field + ")) > 0";
}
hql += ")";
parameters.put("_search", search);
}
if(forSelect && !StringUtils.isEmpty(group))
hql += " GROUP BY " +group;
if(forSelect && !StringUtils.isEmpty(order))
hql += " ORDER BY " +order;
return hql;
}
private Query getCountQuery() {
String hql = getHQLQuery(false);
hql = hql.trim();
// FIXME: make this safe
int fromClause = hql.toLowerCase().indexOf("from ");
String count;
if(StringUtils.isEmpty(group))
count = "COUNT(*) ";
else{
count = "COUNT(DISTINCT "+group+") ";
}
hql = "SELECT "+count + hql.substring(fromClause);
return getQuery(hql);
}
private Query getQuery() {
return getQuery(getHQLQuery(true));
}
private Query getQuery(String hql) {
Logger.info("Making HQL query: %s", hql);
Query query = JPA.em().createQuery(hql);
for(Entry entry : parameters.entrySet()){
query.setParameter(entry.getKey(), entry.getValue());
Logger.info(" Query param %s => %s", entry.getKey(), entry.getValue());
}
return query;
}
public long getCount(){
if(count == null){
Query query = getCountQuery();
count = (Long) query.getSingleResult();
}
return count;
}
public List getResultList(){
Query query = getQuery();
if(start != null)
query.setFirstResult(start.intValue());
if(limit != null)
query.setMaxResults(limit.intValue());
return query.getResultList();
}
}
PK Obb=R5 5 . src/play/modules/resteasy/crud/CRUDPlugin.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.classloading.ApplicationClasses.ApplicationClass;
/**
* Enhances RESTResource classes
*
* @author Stéphane Épardaud
*/
public class CRUDPlugin extends PlayPlugin {
public void enhance(ApplicationClass applicationClass) throws Exception {
Thread.currentThread().setContextClassLoader(Play.classloader);
new CRUDEnhancer().enhanceThisClass(applicationClass);
}
}
PK
Zb=\qV$ $ 6 src/play/modules/resteasy/crud/UnmarshallingError.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.net.HttpURLConnection;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.xml.bind.ValidationEvent;
/**
* Wraps XML validation errors
* @author Stéphane Épardaud
*/
public class UnmarshallingError extends WebApplicationException {
public UnmarshallingError(List events) {
super(buildResponse(events));
}
private static Response buildResponse(List events) {
InvalidResponse response = new InvalidResponse();
for(ValidationEvent e : events)
response.addGlobalError(e.getMessage());
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).entity(response).build();
}
}
PK .Ub=2x. ( src/play/modules/resteasy/crud/CRUD.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import play.db.Model;
/**
* Place this on your RESTResource subclass to indicate what model this
* resource is responsible for.
*
* @author Stéphane Épardaud
*/
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
public @interface CRUD {
/**
* The type of entity this resource is responsible for.
*/
public Class extends Model> model();
/**
* A URL for single entities. Should include a template parameter with the entity id. Ex: /foo/{id}
*/
public String single() default "";
/**
* A URL for collections of entities. Ex: /foo
*/
public String collection() default "";
}
PK Vb=d)b , src/play/modules/resteasy/crud/JAXBList.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* List used for autocompletion
*
* @author Stéphane Épardaud
*/
@XmlRootElement(name = "collection")
public class JAXBList {
@XmlElement(name = "values")
private List list;
public JAXBList(List list) {
this.list = list;
}
public JAXBList() {
}
}
PK d$>tS S 0 src/play/modules/resteasy/crud/CRUDEnhancer.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ConstPool;
import javassist.bytecode.ParameterAnnotationsAttribute;
import javassist.bytecode.annotation.AnnotationMemberValue;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
import org.jboss.resteasy.links.AddLinks;
import org.jboss.resteasy.links.ELProvider;
import org.jboss.resteasy.links.LinkELProvider;
import org.jboss.resteasy.links.LinkResource;
import play.Logger;
import play.Play;
import play.classloading.ApplicationClasses.ApplicationClass;
import play.classloading.enhancers.Enhancer;
import play.db.Model;
import play.db.Model.Factory;
import play.db.Model.Manager;
import play.db.Model.Property;
/**
* Enhance JAX-RS classes by giving them code if they don't already have them.
*/
public class CRUDEnhancer extends Enhancer {
public static class Signature {
public String name;
public Class> returnClass;
public List parameters = new ArrayList();
public List> annotations = new ArrayList>();
public Signature(Class> returnClass, String name, AnnotationRef>... annotations){
this.name = name;
this.returnClass = returnClass;
for(AnnotationRef> a : annotations)
this.annotations.add(a);
}
public Signature param(Class> type, String name, AnnotationRef>... annotations){
parameters.add(new Param(type, name, annotations));
return this;
}
public String signature(){
StringBuilder ret = new StringBuilder("(");
ret.append(typeSignature(returnClass));
ret.append(")");
boolean first = true;
for(Param param : parameters){
if(first)
first = false;
else
ret.append(",");
ret.append(typeSignature(param.type));
}
return ret.toString();
}
public String decl(){
StringBuilder ret = new StringBuilder("public ");
ret.append(t(returnClass));
ret.append(" ").append(name).append("(");
boolean first = true;
for(Param param : parameters){
if(first)
first = false;
else
ret.append(",");
ret.append(t(param.type)).append(" ").append(param.name);
}
ret.append(")");
return ret.toString();
}
public CtMethod method(CtClass ctClass, Class> crudModel) throws CannotCompileException, NotFoundException{
StringBuilder ret = new StringBuilder(decl());
ret.append("{ return super.").append(name).append("(");
ret.append(t(crudModel)).append(".class");
for(Param param : parameters){
ret.append(", ").append(param.name);
}
ret.append("); }");
// make the method
CtMethod method = CtMethod.make(ret.toString(),
ctClass);
// now add the annotations
return annotate(method);
}
private CtMethod annotate(CtMethod method) throws NotFoundException {
ConstPool cp = method.getDeclaringClass().getClassFile().getConstPool();
// parameters
ParameterAnnotationsAttribute paramAnnotations = getParameterAnnotations(method);
for(int i=0;i a : this.annotations)
createAnnotation(annotations, a.type, a.getProperties(cp));
return method;
}
}
public static class Param {
public Class> type;
public String name;
public List> annotations = new ArrayList>();
public Param(Class> type, String name, AnnotationRef>... annotations) {
this.type = type;
this.name = name;
for(AnnotationRef> a : annotations)
this.annotations.add(a);
}
public void createAnnotations(int i,
ParameterAnnotationsAttribute paramAnnotations, ConstPool cp) {
for(AnnotationRef> a : annotations){
createAnnotation(i, paramAnnotations, a.type, a.getProperties(cp));
}
}
}
public static class AnnotationRef {
public Class type;
public Map properties = new HashMap();
public AnnotationRef(Class type){
this.type = type;
}
public Map getProperties(ConstPool cp) {
Map ret = new HashMap();
for(Entry prop : properties.entrySet()){
ret.put(prop.getKey(), makeMemberValue(prop.getValue(), cp));
}
return ret;
}
public AnnotationRef(Class type, Object value){
this(type);
properties.put("value", value);
}
public AnnotationRef p(String name, Object value){
properties.put(name, value);
return this;
}
}
public void enhanceThisClass(ApplicationClass applicationClass) throws Exception {
CtClass ctClass = makeClass(applicationClass);
if (!ctClass.subtypeOf(classPool.get(RESTResource.class.getName()))) {
Logger.debug("Not a RESTResource subclass");
return;
}
// Enhance only JAX-RS model entities
CRUD restCRUD = getAnnotation(ctClass, CRUD.class);
if (restCRUD == null) {
Logger.debug("Missing CRUD annotation");
return;
}
Logger.info("Enhancing CRUD entity %s", ctClass.getName());
ConstPool cp = ctClass.getClassFile().getConstPool();
Factory factory = Manager.factoryFor(restCRUD.model());
Class> idType = factory.keyType();
String idName = getLastTemplateName(restCRUD.single());
AnnotationsAttribute annotations = getAnnotations(ctClass);
if(!hasAnnotation(ctClass, Path.class)){
createAnnotation(annotations, Path.class, map(cp, "/"));
}
if(!hasAnnotation(ctClass, LinkELProvider.class)){
createAnnotation(annotations, LinkELProvider.class, map(cp, PlayELProvider.class));
}
String[] mediaTypes = new String[]{MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON};
if(!hasAnnotation(ctClass, Produces.class)){
createAnnotation(annotations, Produces.class, map(cp, mediaTypes));
}
// list
Signature listSignature = new Signature(Response.class, "list", a(GET.class), a(AddLinks.class),
a(Path.class, restCRUD.collection()),
linkResourceAnnotation(restCRUD.model(), "list", "select"));
listSignature.param(DataTableQuery.class, "q", a(Form.class));
if(!hasMethod(ctClass, listSignature.name, listSignature.signature())){
CtMethod list = listSignature.method(ctClass, restCRUD.model());
ctClass.addMethod(list);
}
// get
Signature getSignature = new Signature(Response.class, "get", a(GET.class), a(AddLinks.class),
a(Path.class, restCRUD.single()),
linkResourceAnnotation(restCRUD.model(), "self", "select"));
getSignature.param(idType, "id", a(PathParam.class, idName));
if(!hasMethod(ctClass, getSignature.name, getSignature.signature())){
ctClass.addMethod(getSignature.method(ctClass, restCRUD.model()));
}
// delete
Signature deleteSignature = new Signature(Response.class, "delete", a(DELETE.class),
a(Path.class, restCRUD.single()),
linkResourceAnnotation(restCRUD.model(), "remove", "delete"));
deleteSignature.param(idType, "id", a(PathParam.class, idName));
if(!hasMethod(ctClass, deleteSignature.name, deleteSignature.signature())){
CtMethod delete = deleteSignature.method(ctClass, restCRUD.model());
ctClass.addMethod(delete);
}
// add
Signature addSignature = new Signature(Response.class, "add", a(POST.class),
a(Path.class, restCRUD.collection()),
a(Consumes.class, mediaTypes),
linkResourceAnnotation(restCRUD.model(), "add", "insert"));
addSignature.param(restCRUD.model(), "elem", a(Validate.class));
addSignature.param(UriInfo.class, "uriInfo", a(Context.class));
if(!hasMethod(ctClass, addSignature.name, addSignature.signature())){
CtMethod add = addSignature.method(ctClass, restCRUD.model());
ctClass.addMethod(add);
}
// edit
Signature editSignature = new Signature(Response.class, "edit", a(PUT.class),
a(Path.class, restCRUD.single()),
a(Consumes.class, mediaTypes),
linkResourceAnnotation(restCRUD.model(), "update", "update"));
editSignature.param(idType, "id", a(PathParam.class, idName));
editSignature.param(restCRUD.model(), "elem", a(Validate.class));
if(!hasMethod(ctClass, editSignature.name, editSignature.signature())){
CtMethod edit = editSignature.method(ctClass, restCRUD.model());
ctClass.addMethod(edit);
}
// autocomplete
for(Property property : factory.listProperties()){
Field field = property.field;
String fieldName = field.getName();
CRUDField crud = field.getAnnotation(CRUDField.class);
if(crud == null)
continue;
if(crud.autoComplete()){
// autocomplete
Signature autoCompleteSignature = new Signature(Response.class, fieldName+"AutoComplete",
a(GET.class), a(Path.class, restCRUD.collection()+ "/auto-complete/"+fieldName),
linkResourceAnnotation(restCRUD.model(), "autocomplete/"+fieldName, "select"));
autoCompleteSignature.param(String.class, "q", a(QueryParam.class, "q"));
if(!hasMethod(ctClass, autoCompleteSignature.name, autoCompleteSignature.signature())){
CtMethod edit = CtMethod.make(autoCompleteSignature.decl() + " {"
+" return super.autoComplete(" + restCRUD.model().getName() + ".class, \""+fieldName+"\", q); }",
ctClass);
autoCompleteSignature.annotate(edit);
ctClass.addMethod(edit);
}
}
}
// descriptor
Signature descriptorSignature = new Signature(Response.class, "descriptor", a(GET.class),
a(Path.class, restCRUD.collection() + "/descriptor"),
linkResourceAnnotation(restCRUD.model(), "descriptor", "select"));
if(!hasMethod(ctClass, descriptorSignature.name, descriptorSignature.signature())){
CtMethod descriptor = descriptorSignature.method(ctClass, restCRUD.model());
ctClass.addMethod(descriptor);
}
Signature makeDataTableSignature = new Signature(DataTable.class, "makeDataTable");
makeDataTableSignature.param(String.class, "echo");
makeDataTableSignature.param(Long.TYPE, "count");
makeDataTableSignature.param(List.class, "results");
makeDataTableSignature.param(Class.class, "type");
makeDataTableSignature.param(Object.class, "oob");
makeDataTableSignature.param(UriInfo.class, "uriInfo");
if(!hasMethod(ctClass, makeDataTableSignature.name, makeDataTableSignature.signature())){
makeDataTable(ctClass, makeDataTableSignature, restCRUD.model());
}
// Done.
applicationClass.enhancedByteCode = ctClass.toBytecode();
ctClass.defrost();
}
private void makeDataTable(CtClass ctClass, Signature makeDataTableSignature, Class extends Model> modelClass)
throws Exception {
// we need the class itself
CtClass dataTableClass = ctClass.makeNestedClass("__DataTable", true);
ClassPool cp = ctClass.getClassPool();
// its superclass
dataTableClass.setSuperclass(cp.get(DataTable.class.getName()));
// its constructor
CtClass[] parameters = new CtClass[makeDataTableSignature.parameters.size()];
for(int i=0;i linkResourceAnnotation(
Class extends Model> model, String rel, String permission) {
return a(LinkResource.class, model).p("rel", rel)
.p("constraint", "${p:hasPermission(this, '"+permission+"')}");
}
private AnnotationRef a(Class annotationType) {
return new AnnotationRef(annotationType);
}
private AnnotationRef a(Class annotationType, Object value) {
return new AnnotationRef(annotationType, value);
}
public static String t(Class> type) {
return type.getName();
}
private static String typeSignature(Class> type) {
if(type.isPrimitive()){
if(type == Long.TYPE)
return "J";
throw new IllegalArgumentException("Primitive types not implemented: "+type);
}
return "L"+type.getName()+";";
}
private String getLastTemplateName(String url) {
if(url == null)
throw new RuntimeException("Missing url template");
int start = url.lastIndexOf('{');
int end = url.lastIndexOf('}');
if(start == -1 || end == -1 || start > end)
throw new RuntimeException("Missing template in url: "+url);
String name = url.substring(start+1, end);
if(name.length() == 0)
throw new RuntimeException("Empty template in url: "+url);
return name;
}
private boolean hasMethod(CtClass ctClass, String name, String signature) {
try {
CtMethod method = ctClass.getMethod(name, signature);
return method.getDeclaringClass() == ctClass;
} catch (NotFoundException e) {
return false;
}
}
public static interface ParamMap extends Map{
public ParamMap add(K key, Object value);
}
public static abstract class HashParamMap extends HashMap implements ParamMap{}
private ParamMap map(final ConstPool cp, String key, Object value) {
ParamMap map = new HashParamMap(){
@Override
public ParamMap add(String key, Object value) {
put(key, makeMemberValue(value, cp));
return this;
}
};
map.put(key, makeMemberValue(value, cp));
return map;
}
private ParamMap map(ConstPool cp, Object value) {
return map(cp, "value", value);
}
private static MemberValue makeMemberValue(Object value, ConstPool cp) {
if(value instanceof String)
return new StringMemberValue((String)value, cp);
if(value instanceof Class)
return new ClassMemberValue(((Class>)value).getName(), cp);
if(value instanceof javassist.bytecode.annotation.Annotation)
return new AnnotationMemberValue((javassist.bytecode.annotation.Annotation)value, cp);
if(value.getClass().isArray()){
ArrayMemberValue ret = new ArrayMemberValue(cp);
Object[] values = (Object[])value;
MemberValue[] elements = new MemberValue[values.length];
for (int i = 0; i < elements.length; i++) {
elements[i] = makeMemberValue(values[i], cp);
}
ret.setValue(elements);
return ret;
}
throw new RuntimeException("Invalid member value: "+value);
}
protected boolean hasAnnotation(CtClass ctClass, Class extends Annotation> type) throws ClassNotFoundException {
return hasAnnotation(ctClass, type.getName());
}
protected T getAnnotation(CtClass ctClass, Class type) throws ClassNotFoundException {
for (Object object : ctClass.getAvailableAnnotations()) {
Annotation ann = (Annotation) object;
if (ann.annotationType() == type) {
return (T)ann;
}
}
return null;
}
protected static ParameterAnnotationsAttribute getParameterAnnotations(CtMethod ctMethod) throws NotFoundException {
ParameterAnnotationsAttribute annotationsAttribute = (ParameterAnnotationsAttribute) ctMethod.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag);
if (annotationsAttribute == null) {
annotationsAttribute = new ParameterAnnotationsAttribute(ctMethod.getMethodInfo().getConstPool(), ParameterAnnotationsAttribute.visibleTag);
javassist.bytecode.annotation.Annotation[][] newAnnotations = new javassist.bytecode.annotation.Annotation[ctMethod.getParameterTypes().length][];
for(int v=0;v < newAnnotations.length;v++)
newAnnotations[v] = new javassist.bytecode.annotation.Annotation[0];
annotationsAttribute.setAnnotations(newAnnotations);
ctMethod.getMethodInfo().addAttribute(annotationsAttribute);
}
return annotationsAttribute;
}
protected static void createAnnotation(int i, ParameterAnnotationsAttribute attribute, Class extends Annotation> annotationType) {
createAnnotation(i, attribute, annotationType, new HashMap());
}
protected static void createAnnotation(int i, ParameterAnnotationsAttribute attribute, Class extends Annotation> annotationType, Map members) {
javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation(annotationType.getName(), attribute.getConstPool());
for (Map.Entry member : members.entrySet()) {
annotation.addMemberValue(member.getKey(), member.getValue());
}
// add the annotation to the existing list
javassist.bytecode.annotation.Annotation[][] annotations = attribute.getAnnotations();
// get this param's annotation
javassist.bytecode.annotation.Annotation[] paramAnnotations = annotations[i];
// grow the array
javassist.bytecode.annotation.Annotation[] newParamAnnotations = new javassist.bytecode.annotation.Annotation[paramAnnotations.length+1];
System.arraycopy(paramAnnotations, 0, newParamAnnotations, 0, paramAnnotations.length);
newParamAnnotations[paramAnnotations.length] = annotation;
annotations[i] = newParamAnnotations;
attribute.setAnnotations(annotations);
}
protected static javassist.bytecode.annotation.Annotation createAnnotation(Class extends Annotation> annotationType, Map members, ConstPool cp) {
javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation(annotationType.getName(), cp);
for (Map.Entry member : members.entrySet()) {
annotation.addMemberValue(member.getKey(), member.getValue());
}
return annotation;
}
}
PK Ub=K&N N - src/play/modules/resteasy/crud/CRUDField.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a field as handled by the CRUD module. If this annotation is not present on a field it will
* not be taken into account by the CRUD module.
*
* @author Stéphane Épardaud
*/
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.FIELD)
public @interface CRUDField {
/**
* Presentation name for the field
*/
public String name() default "";
/**
* Set to true if the field should be searched for when the user searches for entries
*/
public boolean searchable() default false;
/**
* Set to true if the field is user-editable
*/
public boolean editable() default false;
/**
* Set to true if the field can be used to sort the list of entities
*/
public boolean sortable() default false;
/**
* Set to true if we should produce autocomplete resources for this field
*/
public boolean autoComplete() default false;
/**
* Set to something else than Type.DEFAULT to override the field type, otherwise it is implied from the
* entity's field type.
*/
public Type type() default Type.DEFAULT;
}
PK Tb=\ 0 src/play/modules/resteasy/crud/AutoComplete.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.util.List;
import javax.persistence.Query;
import org.apache.commons.lang.StringUtils;
import play.db.jpa.JPA;
/**
* Utilities for getting field completion.
*
* @author Stéphane Épardaud
*/
public class AutoComplete {
/**
* Default number of autocomplete results
*/
public static final int AUTOCOMPLETE_MAX_RESULTS = 10;
/**
* Gets a list of autocomplete for the given entity and field.
* @param entity the type of entity
* @param field the property of the entity to autocomplete for.
* @param q an optional query for the completion
* @return a list of max AUTOCOMPLETE_MAX_RESULTS autocomplete results
*/
public static List getAutoComplete(Class> entity, String field, String q) {
String hql = "SELECT DISTINCT " + field + " FROM " + entity.getName();
if (!StringUtils.isEmpty(q))
hql += " WHERE LOCATE(lower(:q), lower(" + field + ")) > 0";
hql += " ORDER BY " + field;
Query query = JPA.em().createQuery(hql);
query.setMaxResults(AUTOCOMPLETE_MAX_RESULTS);
if (!StringUtils.isEmpty(q))
query.setParameter("q", q);
return (List)query.getResultList();
}
}
PK Vb=}_ _ 2 src/play/modules/resteasy/crud/DataTableQuery.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
/**
* The query type, for getting lists of entities
*
* @author Stéphane Épardaud
*/
public class DataTableQuery {
/**
* Start offset, defaults to 0
*/
@QueryParam("start")
@DefaultValue("0")
public int start;
/**
* Number of entries returned, defaults to 10
*/
@QueryParam("length")
@DefaultValue("10")
public int length;
/**
* Sort order, as specified by: (<fieldName> (ASC|DESC)?) (, <fieldName> (ASC|DESC)?)*
*/
@QueryParam("sort")
public String sort;
/**
* String to search for in all searcheable fields, to filter results
*/
@QueryParam("search")
public String search;
/**
* This has to be returned as-is in the response
*/
@QueryParam("echo")
public String echo;
/**
* Include Out-Of-Bounds result as well. Defaults to false.
*/
@QueryParam("oob")
public boolean oob;
@Context
public UriInfo uriInfo;
}
PK 6Zb=('adF
F
- src/play/modules/resteasy/crud/Validator.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Unmarshaller.Listener;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import org.jboss.resteasy.annotations.DecorateTypes;
import org.jboss.resteasy.spi.interception.DecoratorProcessor;
import play.Logger;
/**
* Validator for the {@link @Validate} entity.
*
* @author Stéphane Épardaud
*/
@DecorateTypes({"text/*+xml", "application/*+xml", "application/xml", "application/json", "application/*+json"})
public class Validator implements DecoratorProcessor{
static class ErrorCollector extends Listener implements ValidationEventHandler {
private List events = new ArrayList();
@Override
public boolean handleEvent(ValidationEvent event) {
Logger.info("Validation event: %s", event);
if(event.getSeverity() == ValidationEvent.ERROR || event.getSeverity() == ValidationEvent.FATAL_ERROR)
events.add(event);
return true;
}
@Override
public void afterUnmarshal(Object target, Object parent) {
super.afterUnmarshal(target, parent);
if(!events.isEmpty())
throw new UnmarshallingError(events);
}
}
@Override
public Unmarshaller decorate(Unmarshaller target, Validate annotation,
Class type, Annotation[] annotations, MediaType mediaType) {
try {
ErrorCollector errorCollector = new ErrorCollector();
target.setEventHandler(errorCollector);
target.setListener(errorCollector);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
return target;
}
}
PK +Zb=j , src/play/modules/resteasy/crud/Validate.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.jboss.resteasy.annotations.Decorator;
import org.jboss.resteasy.links.impl.LinkDecorator;
/**
* Place this on your entity or on the JAX-RS method, or parameter if you wish to validate the entity
* when it is deserialised, and to throw an error if it is not valid.
*
* @author Stéphane Épardaud
*/
@Target( { ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER,
ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Decorator(processor = Validator.class, target = Unmarshaller.class)
@Documented
public @interface Validate {
}
PK +$>` 2 src/play/modules/resteasy/crud/PlayELProvider.javapackage play.modules.resteasy.crud;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.FunctionMapper;
import javax.el.VariableMapper;
import org.jboss.resteasy.links.ELProvider;
public class PlayELProvider implements ELProvider {
public ELContext getContext(final ELContext ctx) {
return new ELContext() {
private PlayFunctionMapper functionMapper;
@Override
public ELResolver getELResolver() {
return ctx.getELResolver();
}
@Override
public FunctionMapper getFunctionMapper() {
if (functionMapper == null)
functionMapper = new PlayFunctionMapper(ctx
.getFunctionMapper());
return functionMapper;
}
@Override
public VariableMapper getVariableMapper() {
return ctx.getVariableMapper();
}
};
}
}
PK c$>L<] . src/play/modules/resteasy/crud/CRUDSecure.javapackage play.modules.resteasy.crud;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import play.Play;
import play.utils.Java;
public class CRUDSecure {
public static boolean hasPermission(Object target, String permission){
return (Boolean) CRUDSecurity.invoke("hasPermission", target, permission);
}
public static boolean hasRole(String role){
return (Boolean) CRUDSecurity.invoke("hasRole", role);
}
public static class CRUDSecurity {
public static boolean hasPermission(Object target, String permission){
return false;
}
public static boolean hasRole(String role){
return false;
}
public static Object invoke(String m, Object... args) {
Class> security = null;
List classes = Play.classloader.getAssignableClasses(CRUDSecurity.class);
if(classes.size() == 0) {
security = CRUDSecurity.class;
} else {
security = classes.get(0);
}
try {
Method method;
if(m.equals("hasPermission"))
method = security.getMethod(m, Object.class, String.class);
else if(m.equals("hasRole"))
method = security.getMethod(m, String.class);
else
throw new NoSuchMethodException("No such method: "+m);
return method.invoke(null, args);
} catch(InvocationTargetException e) {
if(e.getTargetException() instanceof RuntimeException)
throw (RuntimeException)e.getTargetException();
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
PK "Vb=> - src/play/modules/resteasy/crud/DataTable.java/*
This file is part of resteasy-crud-play-module.
Copyright Lunatech Research 2010
resteasy-crud-play-module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
resteasy-crud-play-module 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Lesser Public License
along with resteasy-crud-play-module. If not, see .
*/
package play.modules.resteasy.crud;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.tools.JavaCompiler;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
import org.jboss.resteasy.links.RESTServiceDiscovery;
import org.jboss.resteasy.links.ResourceFacade;
/**
* The DataTable type for listing entities. You should subclass this to define a {@link javax.xml.bin.annotations.XmlSeeAlso}
* with all your entity types.
*
* You will also want to include this if you're producing JSON:
*
* @Mapped(namespaceMap = { @XmlNsMap(namespace = "http://www.w3.org/2001/XMLSchema-instance", jsonName = "xsi"),
* @XmlNsMap(namespace = "http://www.w3.org/2005/Atom", jsonName = "atom") })
*
*
* @author Stéphane Épardaud
* @param The type of the entities listed in this table.
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@Mapped(namespaceMap = { @XmlNsMap(namespace = "http://www.w3.org/2001/XMLSchema-instance", jsonName = "xsi"),
@XmlNsMap(namespace = "http://www.w3.org/2005/Atom", jsonName = "atom") })
public class DataTable implements ResourceFacade {
@XmlElementRef
private RESTServiceDiscovery rest;
@XmlElement(name = "permission")
private final List permissions = new ArrayList();
@XmlElement
private String echo;
@XmlElement
private long size;
@XmlElement(name = "rows")
private List rows = new ArrayList();
@XmlElement
private Object oob;
private Class type;
private UriInfo uriInfo;
public DataTable() {}
public DataTable(String echo, long size, List rows, Class klass, Object oob, UriInfo uriInfo) {
this.echo = echo;
this.size = size;
this.rows = rows;
this.oob = oob;
this.type = klass;
this.uriInfo = uriInfo;
}
@XmlElement
public String getType() {
// this is incredibly stupid but the JSON mapping is so
return type.getSimpleName().substring(0, 1).toLowerCase() + type.getSimpleName().substring(1);
}
public Class facadeFor() {
return type;
}
public Map pathParameters() {
MultivaluedMap pathParameters = uriInfo.getPathParameters();
Map ret = new HashMap();
for(Entry> entry: pathParameters.entrySet()){
ret.put(entry.getKey(), entry.getValue().get(0));
}
return ret;
}
public void addPermission(String permission) {
permissions.add(permission);
}
public String toString(){
return "DataTable["
+"type: "+getType()+", "
+"facadeFor: "+type.getName()+", "
+"rows: "+rows+", "
+"size: "+size+", "
+"oob: "+oob+", "
+"]";
}
}
PK Ta=&n