diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..88063ce4122606dc88f27eefba9fe88f58cd8ddf
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,17 @@
+# General
+/bak
+
+# Eclipse
+.project
+.classpath
+.settings
+WebContent
+
+# Maven
+/bin
+/target
+/assembly
+
+# Testing
+/servers
+C:\\nppdf32Log\\debuglog.txt
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ef7e7efc09c9d471c391f05b9567966928085840
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+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.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+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:
+
+ {project} Copyright (C) {year} {fullname}
+ 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
+.
diff --git a/db/mysql-with-inserts.sql b/db/mysql-with-inserts.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a35a9527a562f1131d8191831126d9608f7dd436
--- /dev/null
+++ b/db/mysql-with-inserts.sql
@@ -0,0 +1,32 @@
+CREATE DATABASE `daaexample`;
+
+CREATE TABLE `daaexample`.`people` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) NOT NULL,
+ `surname` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+CREATE TABLE `daaexample`.`users` (
+ `login` varchar(100) NOT NULL,
+ `password` varchar(64) NOT NULL,
+ `role` varchar(10) NOT NULL,
+ PRIMARY KEY (`login`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
+
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Antón','Pérez');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Manuel','Martínez');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Laura','Reboredo');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Perico','Palotes');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Ana','María');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'María','Nuevo');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fernández');
+INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez');
+
+-- The password for each user is its login suffixed with "pass". For example, user "admin" has the password "adminpass".
+INSERT INTO `daaexample`.`users` (`login`,`password`,`role`)
+VALUES ('admin', '713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca','ADMIN');
+INSERT INTO `daaexample`.`users` (`login`,`password`,`role`)
+VALUES ('normal', '7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83','USER');
diff --git a/db/mysql.sql b/db/mysql.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ed7cd936f0e30ae075eef4ed0260ba9526e61245
--- /dev/null
+++ b/db/mysql.sql
@@ -0,0 +1,17 @@
+CREATE DATABASE `daaexample`;
+
+CREATE TABLE `daaexample`.`people` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) NOT NULL,
+ `surname` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+CREATE TABLE `daaexample`.`users` (
+ `login` varchar(100) NOT NULL,
+ `password` varchar(64) NOT NULL,
+ `role` varchar(10) NOT NULL,
+ PRIMARY KEY (`login`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5a27e31724fee2ce1ac0d9d11f3b1151b2c722e7
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,774 @@
+
+ 4.0.0
+ es.uvigo.esei.daa
+ example
+ war
+ 0.1.10
+ DAA Example
+
+
+
+ GNU GENERAL PUBLIC LICENSE, Version 3
+ http://www.gnu.org/licenses/gpl.html
+ repo
+
+
+
+
+
+ 1.8
+ 1.8
+ UTF-8
+ UTF-8
+ ${project.basedir}/servers
+ false
+ true
+ 8.5.27
+ 6300
+
+
+ 3.1.0
+ 2.25
+ 2.2.0
+ 1.7.21
+
+
+ 4.12
+ 2.0.0.0
+ 3.5.1
+ 3.141.59
+ 4.3.14.RELEASE
+ 2.5.1
+ 1.3.0
+ 2.3.3
+ 5.1.45
+ v0.24.0
+ 2.4.2
+
+
+ 2.20.1
+ 2.20.1
+ 2.20.1
+ 3.2.0
+ 0.8.0
+ 1.6.6
+ 1.0.0
+ 1.8
+ 1.0.6
+
+
+
+
+ javax.servlet
+ javax.servlet-api
+ ${java.servlet.version}
+ provided
+
+
+
+ org.glassfish.jersey.containers
+ jersey-container-servlet
+ ${jersey.version}
+
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
+ ${jersey.version}
+
+
+
+ org.slf4j
+ slf4j-jdk14
+ ${slf4j-jdk14.version}
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.hamcrest
+ java-hamcrest
+ ${java-hamcrest.version}
+
+
+
+ org.easymock
+ easymock
+ ${easymock.version}
+ test
+
+
+
+ org.glassfish.jersey.test-framework.providers
+ jersey-test-framework-provider-grizzly2
+ ${jersey.version}
+ test
+
+
+
+ org.apache.commons
+ commons-dbcp2
+ ${commons-dbcp2.version}
+ test
+
+
+
+ org.seleniumhq.selenium
+ selenium-java
+ ${selenium-java.version}
+ test
+
+
+
+ org.springframework
+ spring-test
+ ${spring-test.version}
+ test
+
+
+
+ org.springframework
+ spring-context
+ ${spring-test.version}
+ test
+
+
+
+ org.springframework
+ spring-jdbc
+ ${spring-test.version}
+ test
+
+
+
+ org.dbunit
+ dbunit
+ ${dbunit.version}
+ jar
+ test
+
+
+
+ com.github.springtestdbunit
+ spring-test-dbunit
+ ${spring-test-dbunit.version}
+ test
+
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+ test
+
+
+
+ mysql
+ mysql-connector-java
+ ${mysql.version}
+ test
+
+
+
+ nl.jqno.equalsverifier
+ equalsverifier
+ ${equalsverifier.version}
+
+
+
+
+ DAAExample
+
+
+
+ maven-war-plugin
+ org.apache.maven.plugins
+ ${maven-war-plugin.version}
+
+ ${project.finalName}
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/UnitTestSuite.java
+
+
+ ${geckodriver.uncompressed.path}
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ **/IntegrationTestSuite.java
+
+
+
+
+ default-integration-tests
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-report-plugin
+ ${maven-surefire-report-plugin.version}
+
+
+
+ test-report
+ test
+
+ report-only
+
+
+
+ integration-test-report
+ integration-test
+
+ report-only
+ failsafe-report-only
+
+
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ ${jacoco-maven-plugin.version}
+
+
+ ${jacoco.port}
+
+
+
+ default-prepare-agent
+
+ prepare-agent
+
+
+
+ coverage-report
+ test
+
+ report
+
+
+
+ default-check
+
+ check
+
+
+
+ jacoco-report
+ post-integration-test
+
+ report
+
+
+ ${project.reporting.outputDirectory}/jacoco-it
+
+
+
+
+
+
+
+
+
+ org.eclipse.m2e
+ lifecycle-mapping
+ 1.0.0
+
+
+
+
+
+
+ org.apache.maven.plugins
+
+
+ maven-antrun-plugin
+
+ [1.3,)
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ acceptance-tests-cargo
+
+ false
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ **/IntegrationTestSuite.java
+ **/AcceptanceTestSuite.java
+
+
+ ${geckodriver.uncompressed.path}
+
+
+
+
+ default-integration-tests
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ ${jacoco-maven-plugin.version}
+
+ ${jacoco.port}
+
+
+
+ jacoco-agent
+ pre-integration-test
+
+ prepare-agent
+
+
+ jacoco.agent.itArgLine
+
+
+
+ jacoco-report
+ post-integration-test
+
+ dump
+ report
+
+
+ ${project.reporting.outputDirectory}/jacoco-it
+
+
+
+
+
+
+
+ fr.avianey.mojo
+ hsqldb-maven-plugin
+ ${hsqldb-maven-plugin.version}
+
+
+
+ org.hsqldb.jdbc.JDBCDriver
+ mem:daatestdb
+ localhost
+ daatestdb
+ sa
+
+
+
+
+
+
+ start-hsqldb
+ pre-integration-test
+
+ start
+
+
+
+ stop-hsqldb
+ post-integration-test
+
+ stop
+
+
+
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+
+ tomcat8x
+
+ https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/${tomcat.version}/tomcat-${tomcat.version}.zip
+ ${project.servers.directory}/downloads
+ ${project.servers.directory}/extracts
+
+
+
+ org.hsqldb
+ hsqldb
+
+
+
+
+
+ ${project.build.directory}/catalina-base
+
+
+ tomcat/server.hsqldb.xml
+ conf/server.xml
+
+
+
+ ${jacoco.agent.itArgLine},output=tcpserver,port=${jacoco.port}
+ -Drunmode=TEST
+ 9080
+
+ cargo.datasource.jndi=jdbc/daaexample|
+ cargo.datasource.driver=org.hsqldb.jdbc.JDBCDriver|
+ cargo.datasource.url=jdbc:hsqldb:hsql://localhost/daatestdb|
+ cargo.datasource.username=sa|
+ cargo.datasource.password=|
+ cargo.datasource.maxActive=8|
+ cargo.datasource.maxIdle=4|
+ cargo.datasource.maxWait=10000
+
+
+
+
+
+
+ start-tomcat
+ pre-integration-test
+
+ start
+
+
+ ${cargo.tomcat.start.skip}
+
+
+
+ run-tomcat
+ pre-integration-test
+
+ run
+
+
+ ${cargo.tomcat.run.skip}
+
+
+
+ stop-tomcat
+ post-integration-test
+
+ stop
+
+
+
+
+
+
+
+
+
+ run-tomcat-mysql
+
+ false
+
+
+
+
+
+ com.fizzed
+ fizzed-watcher-maven-plugin
+ ${fizzed-watcher-maven-plugin.version}
+
+ true
+
+
+ src/main
+
+
+
+ package
+ cargo:redeploy
+
+
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+
+ tomcat8x
+
+ https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/${tomcat.version}/tomcat-${tomcat.version}.zip
+ ${project.servers.directory}/downloads
+ ${project.servers.directory}/extracts
+
+
+
+ mysql
+ mysql-connector-java
+
+
+
+
+
+ ${project.build.directory}/catalina-base
+
+
+ tomcat/server.mysql.xml
+ conf/server.xml
+
+
+
+ 9080
+
+ cargo.datasource.jndi=jdbc/daaexample|
+ cargo.datasource.driver=com.mysql.jdbc.Driver|
+ cargo.datasource.url=jdbc:mysql://localhost/daaexample|
+ cargo.datasource.username=daa|
+ cargo.datasource.password=daa|
+ cargo.datasource.maxActive=8|
+ cargo.datasource.maxIdle=4|
+ cargo.datasource.maxWait=10000
+
+
+
+
+
+
+
+
+
+
+ geckodriver-download-unix
+
+
+ unix
+
+
+
+ https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz
+ ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator}
+ ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz
+ ${geckodriver.basepath}${file.separator}geckodriver
+
+
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+ ${maven-antrun-plugin.version}
+
+
+ download-geckodriver
+ process-test-resources
+
+
+
+
+
+
+
+
+
+ run
+
+
+
+
+
+
+
+
+
+ geckodriver-download-windows
+
+
+ windows
+
+
+
+ https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip
+ ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}
+ ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip
+ ${geckodriver.basepath}${file.separator}geckodriver.exe
+
+
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+ ${maven-antrun-plugin.version}
+
+
+ download-geckodriver
+ process-test-resources
+
+
+
+
+
+
+
+
+
+ run
+
+
+
+
+
+
+
+
+
+ geckodriver-properties-unix-amd64
+
+
+ unix
+ amd64
+
+
+
+ linux64
+
+
+
+
+ geckodriver-properties-unix-x86
+
+
+ unix
+ x86
+
+
+
+ linux86
+
+
+
+
+ geckodriver-properties-windows-amd64
+
+
+ windows
+ amd64
+
+
+
+ win64
+
+
+
+
+ geckodriver-properties-windows-x86
+
+
+ windows
+ x86
+
+
+
+ win32
+
+
+
+
+ geckodriver-properties-and-download-mac
+
+
+ mac
+
+
+
+ macos
+ https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz
+ ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}
+ ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz
+ ${geckodriver.basepath}${file.separator}geckodriver
+
+
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+ ${maven-antrun-plugin.version}
+
+
+ download-geckodriver
+ process-test-resources
+
+
+
+
+
+
+
+
+
+ run
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java b/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a67f22f93bf402148426fd8becb0ce7c8f37dfc
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java
@@ -0,0 +1,40 @@
+package es.uvigo.esei.daa;
+
+import static java.util.stream.Collectors.toSet;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+
+import es.uvigo.esei.daa.rest.PeopleResource;
+import es.uvigo.esei.daa.rest.UsersResource;
+
+/**
+ * Configuration of the REST application. This class includes the resources and
+ * configuration parameter used in the REST API of the application.
+ *
+ * @author Miguel Reboiro Jato
+ *
+ */
+@ApplicationPath("/rest/*")
+public class DAAExampleApplication extends Application {
+ @Override
+ public Set> getClasses() {
+ return Stream.of(
+ PeopleResource.class,
+ UsersResource.class
+ ).collect(toSet());
+ }
+
+ @Override
+ public Map getProperties() {
+ // Activates JSON automatic conversion in JAX-RS
+ return Collections.singletonMap(
+ "com.sun.jersey.api.json.POJOMappingFeature", true
+ );
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/dao/DAO.java b/src/main/java/es/uvigo/esei/daa/dao/DAO.java
new file mode 100644
index 0000000000000000000000000000000000000000..18568740a647888a33ac61160285b631bdc01366
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/dao/DAO.java
@@ -0,0 +1,47 @@
+package es.uvigo.esei.daa.dao;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.sql.DataSource;
+
+/**
+ * Simple base class for DAO (Data Access Object) classes. This super-class is
+ * responsible for providing a {@link java.sql.Connection} to its sub-classes.
+ *
+ * @author Miguel Reboiro Jato
+ *
+ */
+public abstract class DAO {
+ private final static Logger LOG = Logger.getLogger(DAO.class.getName());
+ private final static String JNDI_NAME = "java:/comp/env/jdbc/daaexample";
+
+ private DataSource dataSource;
+
+ /**
+ * Constructs a new instance of {@link DAO}.
+ */
+ public DAO() {
+ try {
+ this.dataSource = (DataSource) new InitialContext().lookup(JNDI_NAME);
+ } catch (NamingException e) {
+ LOG.log(Level.SEVERE, "Error initializing DAO", e);
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Returns an open {@link java.sql.Connection}.
+ *
+ * @return an open {@link java.sql.Connection}.
+ * @throws SQLException if an error happens while establishing the
+ * connection with the database.
+ */
+ protected Connection getConnection() throws SQLException {
+ return this.dataSource.getConnection();
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/dao/DAOException.java b/src/main/java/es/uvigo/esei/daa/dao/DAOException.java
new file mode 100644
index 0000000000000000000000000000000000000000..ffd4233f07cfcbbed73c264c235efd0317b9ffcf
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/dao/DAOException.java
@@ -0,0 +1,83 @@
+package es.uvigo.esei.daa.dao;
+
+/**
+ * A general exception class for the DAO layer.
+ *
+ * @author Miguel Reboiro Jato
+ */
+public class DAOException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new instance of {@link DAOException} with {@code null} as
+ * its detail message.
+ * The cause is not initialized, and may subsequently be initialized by a
+ * call to {@link #initCause}.
+ *
+ */
+ public DAOException() {
+ }
+
+ /**
+ * Constructs a new instance of {@link DAOException} with the specified
+ * detail message. The cause is not initialized, and may subsequently be
+ * initialized by a call to {@link #initCause}.
+ *
+ * @param message the detail message. The detail message is saved for later
+ * retrieval by the {@link #getMessage()} method.
+ */
+ public DAOException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new instance of {@link DAOException} with the specified
+ * cause and a detail message of
+ * {@code (cause==null ? null : cause.toString())} (which typically contains
+ * the class and detail message of {@code cause}). This constructor is
+ * useful for exceptions that are little more than wrappers for other
+ * throwables (for example, {@link java.security.PrivilegedActionException}).
+ *
+ * @param cause the cause (which is saved for later retrieval by the
+ * {@link #getCause()} method). (A {@code null} value is permitted, and
+ * indicates that the cause is nonexistent or unknown.)
+ */
+ public DAOException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new instance of {@link DAOException} with the specified
+ * detail message and cause.
+ *
+ *
Note that the detail message associated with {@code cause} is
+ * not automatically incorporated in this exception's detail message.
+ *
+ * @param message the detail message (which is saved for later retrieval
+ * by the {@link #getMessage()} method).
+ * @param cause the cause (which is saved for later retrieval by the
+ * {@link #getCause()} method). A {@code null} value is permitted, and
+ * indicates that the cause is nonexistent or unknown.
+ */
+ public DAOException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new instance of {@link DAOException} with the specified
+ * detail message, cause, suppression enabled or disabled, and writable
+ * stack trace enabled or disabled.
+ *
+ * @param message the detail message.
+ * @param cause the cause. A {@code null} value is permitted, and indicates
+ * that the cause is nonexistent or unknown.
+ * @param enableSuppression whether or not suppression is enabled or
+ * disabled.
+ * @param writableStackTrace whether or not the stack trace should be
+ * writable.
+ */
+ public DAOException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java
new file mode 100644
index 0000000000000000000000000000000000000000..1d99edb26140ee773f06c8afbf0f40923f1848b2
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java
@@ -0,0 +1,191 @@
+package es.uvigo.esei.daa.dao;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import es.uvigo.esei.daa.entities.Person;
+
+/**
+ * DAO class for the {@link Person} entities.
+ *
+ * @author Miguel Reboiro Jato
+ *
+ */
+public class PeopleDAO extends DAO {
+ private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName());
+
+ /**
+ * Returns a person stored persisted in the system.
+ *
+ * @param id identifier of the person.
+ * @return a person with the provided identifier.
+ * @throws DAOException if an error happens while retrieving the person.
+ * @throws IllegalArgumentException if the provided id does not corresponds
+ * with any persisted person.
+ */
+ public Person get(int id)
+ throws DAOException, IllegalArgumentException {
+ try (final Connection conn = this.getConnection()) {
+ final String query = "SELECT * FROM people WHERE id=?";
+
+ try (final PreparedStatement statement = conn.prepareStatement(query)) {
+ statement.setInt(1, id);
+
+ try (final ResultSet result = statement.executeQuery()) {
+ if (result.next()) {
+ return rowToEntity(result);
+ } else {
+ throw new IllegalArgumentException("Invalid id");
+ }
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error getting a person", e);
+ throw new DAOException(e);
+ }
+ }
+
+ /**
+ * Returns a list with all the people persisted in the system.
+ *
+ * @return a list with all the people persisted in the system.
+ * @throws DAOException if an error happens while retrieving the people.
+ */
+ public List list() throws DAOException {
+ try (final Connection conn = this.getConnection()) {
+ final String query = "SELECT * FROM people";
+
+ try (final PreparedStatement statement = conn.prepareStatement(query)) {
+ try (final ResultSet result = statement.executeQuery()) {
+ final List people = new LinkedList<>();
+
+ while (result.next()) {
+ people.add(rowToEntity(result));
+ }
+
+ return people;
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error listing people", e);
+ throw new DAOException(e);
+ }
+ }
+
+ /**
+ * Persists a new person in the system. An identifier will be assigned
+ * automatically to the new person.
+ *
+ * @param name name of the new person. Can't be {@code null}.
+ * @param surname surname of the new person. Can't be {@code null}.
+ * @return a {@link Person} entity representing the persisted person.
+ * @throws DAOException if an error happens while persisting the new person.
+ * @throws IllegalArgumentException if the name or surname are {@code null}.
+ */
+ public Person add(String name, String surname)
+ throws DAOException, IllegalArgumentException {
+ if (name == null || surname == null) {
+ throw new IllegalArgumentException("name and surname can't be null");
+ }
+
+ try (Connection conn = this.getConnection()) {
+ final String query = "INSERT INTO people VALUES(null, ?, ?)";
+
+ try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
+ statement.setString(1, name);
+ statement.setString(2, surname);
+
+ if (statement.executeUpdate() == 1) {
+ try (ResultSet resultKeys = statement.getGeneratedKeys()) {
+ if (resultKeys.next()) {
+ return new Person(resultKeys.getInt(1), name, surname);
+ } else {
+ LOG.log(Level.SEVERE, "Error retrieving inserted id");
+ throw new SQLException("Error retrieving inserted id");
+ }
+ }
+ } else {
+ LOG.log(Level.SEVERE, "Error inserting value");
+ throw new SQLException("Error inserting value");
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error adding a person", e);
+ throw new DAOException(e);
+ }
+ }
+
+ /**
+ * Modifies a person previously persisted in the system. The person will be
+ * retrieved by the provided id and its current name and surname will be
+ * replaced with the provided.
+ *
+ * @param person a {@link Person} entity with the new data.
+ * @throws DAOException if an error happens while modifying the new person.
+ * @throws IllegalArgumentException if the person is {@code null}.
+ */
+ public void modify(Person person)
+ throws DAOException, IllegalArgumentException {
+ if (person == null) {
+ throw new IllegalArgumentException("person can't be null");
+ }
+
+ try (Connection conn = this.getConnection()) {
+ final String query = "UPDATE people SET name=?, surname=? WHERE id=?";
+
+ try (PreparedStatement statement = conn.prepareStatement(query)) {
+ statement.setString(1, person.getName());
+ statement.setString(2, person.getSurname());
+ statement.setInt(3, person.getId());
+
+ if (statement.executeUpdate() != 1) {
+ throw new IllegalArgumentException("name and surname can't be null");
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error modifying a person", e);
+ throw new DAOException();
+ }
+ }
+
+ /**
+ * Removes a persisted person from the system.
+ *
+ * @param id identifier of the person to be deleted.
+ * @throws DAOException if an error happens while deleting the person.
+ * @throws IllegalArgumentException if the provided id does not corresponds
+ * with any persisted person.
+ */
+ public void delete(int id)
+ throws DAOException, IllegalArgumentException {
+ try (final Connection conn = this.getConnection()) {
+ final String query = "DELETE FROM people WHERE id=?";
+
+ try (final PreparedStatement statement = conn.prepareStatement(query)) {
+ statement.setInt(1, id);
+
+ if (statement.executeUpdate() != 1) {
+ throw new IllegalArgumentException("Invalid id");
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error deleting a person", e);
+ throw new DAOException(e);
+ }
+ }
+
+ private Person rowToEntity(ResultSet row) throws SQLException {
+ return new Person(
+ row.getInt("id"),
+ row.getString("name"),
+ row.getString("surname")
+ );
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/dao/UsersDAO.java b/src/main/java/es/uvigo/esei/daa/dao/UsersDAO.java
new file mode 100644
index 0000000000000000000000000000000000000000..70d47b233f0c7fdfff0fd48fca10a463eed124f0
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/dao/UsersDAO.java
@@ -0,0 +1,107 @@
+package es.uvigo.esei.daa.dao;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import es.uvigo.esei.daa.entities.User;
+
+/**
+ * DAO class for managing the users of the system.
+ *
+ * @author Miguel Reboiro Jato
+ */
+public class UsersDAO extends DAO {
+ private final static Logger LOG = Logger.getLogger(UsersDAO.class.getName());
+
+ /**
+ * Returns a user stored persisted in the system.
+ *
+ * @param login the login of the user to be retrieved.
+ * @return a user with the provided login.
+ * @throws DAOException if an error happens while retrieving the user.
+ * @throws IllegalArgumentException if the provided login does not
+ * corresponds with any persisted user.
+ */
+ public User get(String login) throws DAOException {
+ try (final Connection conn = this.getConnection()) {
+ final String query = "SELECT * FROM users WHERE login=?";
+
+ try (final PreparedStatement statement = conn.prepareStatement(query)) {
+ statement.setString(1, login);
+
+ try (final ResultSet result = statement.executeQuery()) {
+ if (result.next()) {
+ return rowToEntity(result);
+ } else {
+ throw new IllegalArgumentException("Invalid id");
+ }
+ }
+ }
+ } catch (SQLException e) {
+ LOG.log(Level.SEVERE, "Error checking login", e);
+ throw new DAOException(e);
+ }
+ }
+
+ /**
+ * Checks if the provided credentials (login and password) correspond with a
+ * valid user registered in the system.
+ *
+ *
The password is stored in the system "salted" and encoded with the
+ * SHA-256 algorithm.
+ *
+ * @param login the login of the user.
+ * @param password the password of the user.
+ * @return {@code true} if the credentials are valid. {@code false}
+ * otherwise.
+ * @throws DAOException if an error happens while checking the credentials.
+ */
+ public boolean checkLogin(String login, String password) throws DAOException {
+ try {
+ final User user = this.get(login);
+
+ final String dbPassword = user.getPassword();
+ final String shaPassword = encodeSha256(password);
+
+ return shaPassword.equals(dbPassword);
+ } catch (IllegalArgumentException iae) {
+ return false;
+ }
+ }
+
+ private final static String encodeSha256(String text) {
+ try {
+ final MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ final byte[] digested = digest.digest(text.getBytes());
+
+ return hexToString(digested);
+ } catch (NoSuchAlgorithmException e) {
+ LOG.log(Level.SEVERE, "SHA-256 not supported", e);
+ throw new RuntimeException(e);
+ }
+ }
+
+ private final static String hexToString(byte[] hex) {
+ final StringBuilder sb = new StringBuilder();
+
+ for (byte b : hex) {
+ sb.append(String.format("%02x", b & 0xff));
+ }
+
+ return sb.toString();
+ }
+
+ private User rowToEntity(ResultSet result) throws SQLException {
+ return new User(
+ result.getString("login"),
+ result.getString("password"),
+ result.getString("role")
+ );
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/entities/Person.java b/src/main/java/es/uvigo/esei/daa/entities/Person.java
new file mode 100644
index 0000000000000000000000000000000000000000..b2f3285a5263ba6f4316d1dfa1eadfd45ae0b2d8
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/entities/Person.java
@@ -0,0 +1,99 @@
+package es.uvigo.esei.daa.entities;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * An entity that represents a person.
+ *
+ * @author Miguel Reboiro Jato
+ */
+public class Person {
+ private int id;
+ private String name;
+ private String surname;
+
+ // Constructor needed for the JSON conversion
+ Person() {}
+
+ /**
+ * Constructs a new instance of {@link Person}.
+ *
+ * @param id identifier of the person.
+ * @param name name of the person.
+ * @param surname surname of the person.
+ */
+ public Person(int id, String name, String surname) {
+ this.id = id;
+ this.setName(name);
+ this.setSurname(surname);
+ }
+
+ /**
+ * Returns the identifier of the person.
+ *
+ * @return the identifier of the person.
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Returns the name of the person.
+ *
+ * @return the name of the person.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Set the name of this person.
+ *
+ * @param name the new name of the person.
+ * @throws NullPointerException if the {@code name} is {@code null}.
+ */
+ public void setName(String name) {
+ this.name = requireNonNull(name, "Name can't be null");
+ }
+
+ /**
+ * Returns the surname of the person.
+ *
+ * @return the surname of the person.
+ */
+ public String getSurname() {
+ return surname;
+ }
+
+ /**
+ * Set the surname of this person.
+ *
+ * @param surname the new surname of the person.
+ * @throws NullPointerException if the {@code surname} is {@code null}.
+ */
+ public void setSurname(String surname) {
+ this.surname = requireNonNull(surname, "Surname can't be null");
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + id;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (!(obj instanceof Person))
+ return false;
+ Person other = (Person) obj;
+ if (id != other.id)
+ return false;
+ return true;
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/entities/User.java b/src/main/java/es/uvigo/esei/daa/entities/User.java
new file mode 100644
index 0000000000000000000000000000000000000000..cb13b8e8c4e42b57595e75222994ac88c40c6210
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/entities/User.java
@@ -0,0 +1,88 @@
+package es.uvigo.esei.daa.entities;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * An entity that represents a user.
+ *
+ * @author Miguel Reboiro Jato
+ */
+public class User {
+ private String login;
+ private String password;
+ private String role;
+
+ // Constructor needed for the JSON conversion
+ User() {}
+
+ /**
+ * Constructs a new instance of {@link User}.
+ *
+ * @param login login that identifies the user in the system.
+ * @param password password of the user encoded using SHA-256 and with the
+ * "salt" prefix added.
+ */
+ public User(String login, String password, String role) {
+ this.setLogin(login);
+ this.setPassword(password);
+ this.setRole(role);
+ }
+
+ /**
+ * Returns the login of the user.
+ *
+ * @return the login of the user.
+ */
+ public String getLogin() {
+ return login;
+ }
+
+ /**
+ * Sets the login of the user.
+ *
+ * @param login the login that identifies the user in the system.
+ */
+ public void setLogin(String login) {
+ this.login = requireNonNull(login, "Login can't be null");
+ }
+
+ /**
+ * Returns the password of the user.
+ *
+ * @return the password of the user.
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the users password.
+ * @param password the password of the user encoded using SHA-256 and with
+ * the "salt" prefix added.
+ */
+ public void setPassword(String password) {
+ requireNonNull(password, "Password can't be null");
+ if (!password.matches("[a-zA-Z0-9]{64}"))
+ throw new IllegalArgumentException("Password must be a valid SHA-256");
+
+ this.password = password;
+ }
+
+ /**
+ * Returns the role of the user.
+ *
+ * @return the role of the user.
+ */
+ public String getRole() {
+ return role;
+ }
+
+ /**
+ * Sets the role of the user.
+ *
+ * @param role the role of the user
+ */
+ public void setRole(String role) {
+ this.role = requireNonNull(role, "Role can't be null");
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java b/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java
new file mode 100644
index 0000000000000000000000000000000000000000..09b8834c7b71d5176e012bcd6076d36eb275bb29
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java
@@ -0,0 +1,211 @@
+package es.uvigo.esei.daa.rest;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.FormParam;
+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.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import es.uvigo.esei.daa.dao.DAOException;
+import es.uvigo.esei.daa.dao.PeopleDAO;
+import es.uvigo.esei.daa.entities.Person;
+
+/**
+ * REST resource for managing people.
+ *
+ * @author Miguel Reboiro Jato.
+ */
+@Path("/people")
+@Produces(MediaType.APPLICATION_JSON)
+public class PeopleResource {
+ private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName());
+
+ private final PeopleDAO dao;
+
+ /**
+ * Constructs a new instance of {@link PeopleResource}.
+ */
+ public PeopleResource() {
+ this(new PeopleDAO());
+ }
+
+ // Needed for testing purposes
+ PeopleResource(PeopleDAO dao) {
+ this.dao = dao;
+ }
+
+ /**
+ * Returns a person with the provided identifier.
+ *
+ * @param id the identifier of the person to retrieve.
+ * @return a 200 OK response with a person that has the provided identifier.
+ * If the identifier does not corresponds with any user, a 400 Bad Request
+ * response with an error message will be returned. If an error happens
+ * while retrieving the list, a 500 Internal Server Error response with an
+ * error message will be returned.
+ */
+ @GET
+ @Path("/{id}")
+ public Response get(
+ @PathParam("id") int id
+ ) {
+ try {
+ final Person person = this.dao.get(id);
+
+ return Response.ok(person).build();
+ } catch (IllegalArgumentException iae) {
+ LOG.log(Level.FINE, "Invalid person id in get method", iae);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(iae.getMessage())
+ .build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error getting a person", e);
+
+ return Response.serverError()
+ .entity(e.getMessage())
+ .build();
+ }
+ }
+
+ /**
+ * Returns the complete list of people stored in the system.
+ *
+ * @return a 200 OK response with the complete list of people stored in the
+ * system. If an error happens while retrieving the list, a 500 Internal
+ * Server Error response with an error message will be returned.
+ */
+ @GET
+ public Response list() {
+ try {
+ return Response.ok(this.dao.list()).build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error listing people", e);
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ /**
+ * Creates a new person in the system.
+ *
+ * @param name the name of the new person.
+ * @param surname the surname of the new person.
+ * @return a 200 OK response with a person that has been created. If the
+ * name or the surname are not provided, a 400 Bad Request response with an
+ * error message will be returned. If an error happens while retrieving the
+ * list, a 500 Internal Server Error response with an error message will be
+ * returned.
+ */
+ @POST
+ public Response add(
+ @FormParam("name") String name,
+ @FormParam("surname") String surname
+ ) {
+ try {
+ final Person newPerson = this.dao.add(name, surname);
+
+ return Response.ok(newPerson).build();
+ } catch (IllegalArgumentException iae) {
+ LOG.log(Level.FINE, "Invalid person id in add method", iae);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(iae.getMessage())
+ .build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error adding a person", e);
+
+ return Response.serverError()
+ .entity(e.getMessage())
+ .build();
+ }
+ }
+
+ /**
+ * Modifies the data of a person.
+ *
+ * @param id identifier of the person to modify.
+ * @param name the new name of the person.
+ * @param surname the new surname of the person.
+ * @return a 200 OK response with a person that has been modified. If the
+ * identifier does not corresponds with any user or the name or surname are
+ * not provided, a 400 Bad Request response with an error message will be
+ * returned. If an error happens while retrieving the list, a 500 Internal
+ * Server Error response with an error message will be returned.
+ */
+ @PUT
+ @Path("/{id}")
+ public Response modify(
+ @PathParam("id") int id,
+ @FormParam("name") String name,
+ @FormParam("surname") String surname
+ ) {
+ try {
+ final Person modifiedPerson = new Person(id, name, surname);
+ this.dao.modify(modifiedPerson);
+
+ return Response.ok(modifiedPerson).build();
+ } catch (NullPointerException npe) {
+ final String message = String.format("Invalid data for person (name: %s, surname: %s)", name, surname);
+
+ LOG.log(Level.FINE, message);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(message)
+ .build();
+ } catch (IllegalArgumentException iae) {
+ LOG.log(Level.FINE, "Invalid person id in modify method", iae);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(iae.getMessage())
+ .build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error modifying a person", e);
+
+ return Response.serverError()
+ .entity(e.getMessage())
+ .build();
+ }
+ }
+
+ /**
+ * Deletes a person from the system.
+ *
+ * @param id the identifier of the person to be deleted.
+ * @return a 200 OK response with the identifier of the person that has
+ * been deleted. If the identifier does not corresponds with any user, a 400
+ * Bad Request response with an error message will be returned. If an error
+ * happens while retrieving the list, a 500 Internal Server Error response
+ * with an error message will be returned.
+ */
+ @DELETE
+ @Path("/{id}")
+ public Response delete(
+ @PathParam("id") int id
+ ) {
+ try {
+ this.dao.delete(id);
+
+ return Response.ok(id).build();
+ } catch (IllegalArgumentException iae) {
+ LOG.log(Level.FINE, "Invalid person id in delete method", iae);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(iae.getMessage())
+ .build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error deleting a person", e);
+
+ return Response.serverError()
+ .entity(e.getMessage())
+ .build();
+ }
+ }
+}
diff --git a/src/main/java/es/uvigo/esei/daa/rest/UsersResource.java b/src/main/java/es/uvigo/esei/daa/rest/UsersResource.java
new file mode 100644
index 0000000000000000000000000000000000000000..858c52c566cb156e62e80cff75a9961d0c56d100
--- /dev/null
+++ b/src/main/java/es/uvigo/esei/daa/rest/UsersResource.java
@@ -0,0 +1,100 @@
+package es.uvigo.esei.daa.rest;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.SecurityContext;
+
+import es.uvigo.esei.daa.dao.DAOException;
+import es.uvigo.esei.daa.dao.UsersDAO;
+/**
+ * REST resource for managing users.
+ *
+ * @author Miguel Reboiro Jato.
+ */
+@Path("/users")
+@Produces(MediaType.APPLICATION_JSON)
+public class UsersResource {
+ private final static Logger LOG = Logger.getLogger(UsersResource.class.getName());
+
+ private final UsersDAO dao;
+
+ private @Context SecurityContext security;
+
+ /**
+ * Constructs a new instance of {@link UsersResource}.
+ */
+ public UsersResource() {
+ this(new UsersDAO());
+ }
+
+ // Needed for testing purposes
+ UsersResource(UsersDAO dao) {
+ this(dao, null);
+ }
+
+ // Needed for testing purposes
+ UsersResource(UsersDAO dao, SecurityContext security) {
+ this.dao = dao;
+ this.security = security;
+ }
+
+ /**
+ * Returns a user with the provided login.
+ *
+ * @param login the identifier of the user to retrieve.
+ * @return a 200 OK response with an user that has the provided login.
+ * If the request is done without providing the login credentials or using
+ * invalid credentials a 401 Unauthorized response will be returned. If the
+ * credentials are provided and a regular user (i.e. non admin user) tries
+ * to access the data of other user, a 403 Forbidden response will be
+ * returned. If the credentials are OK, but the login does not corresponds
+ * with any user, a 400 Bad Request response with an error message will be
+ * returned. If an error happens while retrieving the list, a 500 Internal
+ * Server Error response with an error message will be returned.
+ */
+ @GET
+ @Path("/{login}")
+ public Response get(
+ @PathParam("login") String login
+ ) {
+ final String loggedUser = getLogin();
+
+ // Each user can only access his or her own data. Only the admin user
+ // can access the data of any user.
+ if (loggedUser.equals(login) || this.isAdmin()) {
+ try {
+ return Response.ok(dao.get(login)).build();
+ } catch (IllegalArgumentException iae) {
+ LOG.log(Level.FINE, "Invalid user login in get method", iae);
+
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(iae.getMessage())
+ .build();
+ } catch (DAOException e) {
+ LOG.log(Level.SEVERE, "Error getting an user", e);
+
+ return Response.serverError()
+ .entity(e.getMessage())
+ .build();
+ }
+ } else {
+ return Response.status(Response.Status.UNAUTHORIZED).build();
+ }
+ }
+
+ private String getLogin() {
+ return this.security.getUserPrincipal().getName();
+ }
+
+ private boolean isAdmin() {
+ return this.security.isUserInRole("ADMIN");
+ }
+}
diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000000000000000000000000000000000..df238ce0ca0c0ad5e6a5ada13d6cbccc3bae4c62
--- /dev/null
+++ b/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,56 @@
+
+
+ DAAExample
+
+
+ index.html
+
+
+
+
+ Protected Area
+ /rest/*
+ PUT
+ DELETE
+ GET
+ POST
+ OPTIONS
+
+
+ ADMIN
+ USER
+
+
+
+
+
+ Admin Area
+ /rest/people/*
+ PUT
+ DELETE
+ GET
+ POST
+ OPTIONS
+
+
+ ADMIN
+
+
+
+
+
+ ADMIN
+
+
+ USER
+
+
+
+ BASIC
+ DAAExample
+
+
\ No newline at end of file
diff --git a/src/main/webapp/css/login.css b/src/main/webapp/css/login.css
new file mode 100644
index 0000000000000000000000000000000000000000..d6b2a480a9bd014c3943ba4687b3f7bf43da3ee5
--- /dev/null
+++ b/src/main/webapp/css/login.css
@@ -0,0 +1,48 @@
+html, body {
+ height: 100%;
+}
+
+body {
+ display: -ms-flexbox;
+ display: -webkit-box;
+ display: flex;
+ -ms-flex-align: center;
+ -ms-flex-pack: center;
+ -webkit-box-align: center;
+ align-items: center;
+ -webkit-box-pack: center;
+ justify-content: center;
+ padding-top: 40px;
+ padding-bottom: 40px;
+}
+
+#form-signin {
+ width: 100%;
+ max-width: 330px;
+ padding: 15px;
+ margin: 0 auto;
+}
+
+#form-signin .form-control {
+ position: relative;
+ box-sizing: border-box;
+ height: auto;
+ padding: 10px;
+ font-size: 16px;
+}
+
+#form-signin .form-control:focus {
+ z-index: 2;
+}
+
+#login {
+ margin-bottom: -1px;
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+
+#password {
+ margin-bottom: 10px;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
\ No newline at end of file
diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..095822992f63e7069860e253b35ffe70bdb51902
--- /dev/null
+++ b/src/main/webapp/index.html
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+DAA Example - Login
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/webapp/js/dao/people.js b/src/main/webapp/js/dao/people.js
new file mode 100644
index 0000000000000000000000000000000000000000..29618ee5eafbab06acb34bd0320c8c9e5604ac40
--- /dev/null
+++ b/src/main/webapp/js/dao/people.js
@@ -0,0 +1,51 @@
+var PeopleDAO = (function() {
+ var resourcePath = "rest/people/";
+ var requestByAjax = function(data, done, fail, always) {
+ done = typeof done !== 'undefined' ? done : function() {};
+ fail = typeof fail !== 'undefined' ? fail : function() {};
+ always = typeof always !== 'undefined' ? always : function() {};
+
+ let authToken = localStorage.getItem('authorization-token');
+ if (authToken !== null) {
+ data.beforeSend = function(xhr) {
+ xhr.setRequestHeader('Authorization', 'Basic ' + authToken);
+ };
+ }
+
+ $.ajax(data).done(done).fail(fail).always(always);
+ };
+
+ function PeopleDAO() {
+ this.listPeople = function(done, fail, always) {
+ requestByAjax({
+ url : resourcePath,
+ type : 'GET'
+ }, done, fail, always);
+ };
+
+ this.addPerson = function(person, done, fail, always) {
+ requestByAjax({
+ url : resourcePath,
+ type : 'POST',
+ data : person
+ }, done, fail, always);
+ };
+
+ this.modifyPerson = function(person, done, fail, always) {
+ requestByAjax({
+ url : resourcePath + person.id,
+ type : 'PUT',
+ data : person
+ }, done, fail, always);
+ };
+
+ this.deletePerson = function(id, done, fail, always) {
+ requestByAjax({
+ url : resourcePath + id,
+ type : 'DELETE',
+ }, done, fail, always);
+ };
+ }
+
+ return PeopleDAO;
+})();
\ No newline at end of file
diff --git a/src/main/webapp/js/login.js b/src/main/webapp/js/login.js
new file mode 100644
index 0000000000000000000000000000000000000000..585c1dd56307fddd688b1c31dcca474c8be76672
--- /dev/null
+++ b/src/main/webapp/js/login.js
@@ -0,0 +1,21 @@
+function doLogin(login, password) {
+ $.ajax({
+ url: 'rest/users/' + login,
+ type: 'GET',
+ beforeSend: function (xhr) {
+ xhr.setRequestHeader('Authorization', 'Basic ' + btoa(login + ":" + password));
+ }
+ })
+ .done(function() {
+ localStorage.setItem('authorization-token', btoa(login + ":" + password));
+ window.location = 'main.html';
+ })
+ .fail(function() {
+ alert('Invalid login and/or password.');
+ });
+}
+
+function doLogout() {
+ localStorage.removeItem('authorization-token');
+ window.location = 'index.html';
+}
\ No newline at end of file
diff --git a/src/main/webapp/js/view/people.js b/src/main/webapp/js/view/people.js
new file mode 100644
index 0000000000000000000000000000000000000000..eae588463f74e5678f664f74617b3f72a8daa74b
--- /dev/null
+++ b/src/main/webapp/js/view/people.js
@@ -0,0 +1,193 @@
+var PeopleView = (function() {
+ var dao;
+
+ // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
+ var self;
+
+ var formId = 'people-form';
+ var listId = 'people-list';
+ var formQuery = '#' + formId;
+ var listQuery = '#' + listId;
+
+ function PeopleView(peopleDao, formContainerId, listContainerId) {
+ dao = peopleDao;
+ self = this;
+
+ insertPeopleForm($('#' + formContainerId));
+ insertPeopleList($('#' + listContainerId));
+
+ this.init = function() {
+ dao.listPeople(function(people) {
+ $.each(people, function(key, person) {
+ appendToTable(person);
+ });
+ });
+
+ // La acción por defecto de enviar formulario (submit) se sobreescribe
+ // para que el envío sea a través de AJAX
+ $(formQuery).submit(function(event) {
+ var person = self.getPersonInForm();
+
+ if (self.isEditing()) {
+ dao.modifyPerson(person,
+ function(person) {
+ $('#person-' + person.id + ' td.name').text(person.name);
+ $('#person-' + person.id + ' td.surname').text(person.surname);
+ self.resetForm();
+ },
+ showErrorMessage,
+ self.enableForm
+ );
+ } else {
+ dao.addPerson(person,
+ function(person) {
+ appendToTable(person);
+ self.resetForm();
+ },
+ showErrorMessage,
+ self.enableForm
+ );
+ }
+
+ return false;
+ });
+
+ $('#btnClear').click(this.resetForm);
+ };
+
+ this.getPersonInForm = function() {
+ var form = $(formQuery);
+ return {
+ 'id': form.find('input[name="id"]').val(),
+ 'name': form.find('input[name="name"]').val(),
+ 'surname': form.find('input[name="surname"]').val()
+ };
+ };
+
+ this.getPersonInRow = function(id) {
+ var row = $('#person-' + id);
+
+ if (row !== undefined) {
+ return {
+ 'id': id,
+ 'name': row.find('td.name').text(),
+ 'surname': row.find('td.surname').text()
+ };
+ } else {
+ return undefined;
+ }
+ };
+
+ this.editPerson = function(id) {
+ var row = $('#person-' + id);
+
+ if (row !== undefined) {
+ var form = $(formQuery);
+
+ form.find('input[name="id"]').val(id);
+ form.find('input[name="name"]').val(row.find('td.name').text());
+ form.find('input[name="surname"]').val(row.find('td.surname').text());
+
+ $('input#btnSubmit').val('Modificar');
+ }
+ };
+
+ this.deletePerson = function(id) {
+ if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) {
+ dao.deletePerson(id,
+ function() {
+ $('tr#person-' + id).remove();
+ },
+ showErrorMessage
+ );
+ }
+ };
+
+ this.isEditing = function() {
+ return $(formQuery + ' input[name="id"]').val() != "";
+ };
+
+ this.disableForm = function() {
+ $(formQuery + ' input').prop('disabled', true);
+ };
+
+ this.enableForm = function() {
+ $(formQuery + ' input').prop('disabled', false);
+ };
+
+ this.resetForm = function() {
+ $(formQuery)[0].reset();
+ $(formQuery + ' input[name="id"]').val('');
+ $('#btnSubmit').val('Crear');
+ };
+ };
+
+ var insertPeopleList = function(parent) {
+ parent.append(
+ '
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/java/es/uvigo/esei/daa/DAAExampleTestApplication.java b/src/test/java/es/uvigo/esei/daa/DAAExampleTestApplication.java
new file mode 100644
index 0000000000000000000000000000000000000000..43b5809bf3c4fc31f47c7e7d960c7acdba0aa762
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/DAAExampleTestApplication.java
@@ -0,0 +1,22 @@
+package es.uvigo.esei.daa;
+
+import static java.util.Collections.unmodifiableSet;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.ws.rs.ApplicationPath;
+
+import es.uvigo.esei.daa.filters.AuthorizationFilter;
+
+@ApplicationPath("/rest/*")
+public class DAAExampleTestApplication extends DAAExampleApplication {
+ @Override
+ public Set> getClasses() {
+ final Set> classes = new HashSet<>(super.getClasses());
+
+ classes.add(AuthorizationFilter.class);
+
+ return unmodifiableSet(classes);
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOTest.java b/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..68d93675fe9e7004aa2f7a29d50fa33d51da1a3e
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOTest.java
@@ -0,0 +1,136 @@
+package es.uvigo.esei.daa.dao;
+
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newName;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newSurname;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.nonExistentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.nonExistentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.people;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.peopleWithout;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.containsPeopleInAnyOrder;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.equalsToPerson;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import javax.sql.DataSource;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.github.springtestdbunit.DbUnitTestExecutionListener;
+import com.github.springtestdbunit.annotation.DatabaseSetup;
+import com.github.springtestdbunit.annotation.ExpectedDatabase;
+
+import es.uvigo.esei.daa.entities.Person;
+import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
+import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
+import es.uvigo.esei.daa.listeners.DbManagement;
+import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:contexts/mem-context.xml")
+@TestExecutionListeners({
+ DbUnitTestExecutionListener.class,
+ DbManagementTestExecutionListener.class,
+ ApplicationContextJndiBindingTestExecutionListener.class
+})
+@ApplicationContextBinding(
+ jndiUrl = "java:/comp/env/jdbc/daaexample",
+ type = DataSource.class
+)
+@DbManagement(
+ create = "classpath:db/hsqldb.sql",
+ drop = "classpath:db/hsqldb-drop.sql"
+)
+@DatabaseSetup("/datasets/dataset.xml")
+@ExpectedDatabase("/datasets/dataset.xml")
+public class PeopleDAOTest {
+ private PeopleDAO dao;
+
+ @Before
+ public void setUp() throws Exception {
+ this.dao = new PeopleDAO();
+ }
+
+ @Test
+ public void testList() throws DAOException {
+ assertThat(this.dao.list(), containsPeopleInAnyOrder(people()));
+ }
+
+ @Test
+ public void testGet() throws DAOException {
+ final Person person = this.dao.get(existentId());
+
+ assertThat(person, is(equalsToPerson(existentPerson())));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetNonExistentId() throws DAOException {
+ this.dao.get(nonExistentId());
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-delete.xml")
+ public void testDelete() throws DAOException {
+ this.dao.delete(existentId());
+
+ assertThat(this.dao.list(), containsPeopleInAnyOrder(peopleWithout(existentId())));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testDeleteNonExistentId() throws DAOException {
+ this.dao.delete(nonExistentId());
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-modify.xml")
+ public void testModify() throws DAOException {
+ final Person person = existentPerson();
+ person.setName(newName());
+ person.setSurname(newSurname());
+
+ this.dao.modify(person);
+
+ final Person persistentPerson = this.dao.get(person.getId());
+
+ assertThat(persistentPerson, is(equalsToPerson(person)));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testModifyNonExistentId() throws DAOException {
+ this.dao.modify(nonExistentPerson());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testModifyNullPerson() throws DAOException {
+ this.dao.modify(null);
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-add.xml")
+ public void testAdd() throws DAOException {
+ final Person person = this.dao.add(newName(), newSurname());
+
+ assertThat(person, is(equalsToPerson(newPerson())));
+
+ final Person persistentPerson = this.dao.get(person.getId());
+
+ assertThat(persistentPerson, is(equalsToPerson(newPerson())));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAddNullName() throws DAOException {
+ this.dao.add(null, newSurname());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAddNullSurname() throws DAOException {
+ this.dao.add(newName(), null);
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOUnitTest.java b/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOUnitTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..94ac74b92a0cf20ef651f4f7e4cdd7b908f0ee50
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/dao/PeopleDAOUnitTest.java
@@ -0,0 +1,259 @@
+package es.uvigo.esei.daa.dao;
+
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newName;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newSurname;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.people;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.containsPeopleInAnyOrder;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.equalsToPerson;
+import static org.easymock.EasyMock.anyString;
+import static org.easymock.EasyMock.eq;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.reset;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.sql.SQLException;
+
+import org.junit.Test;
+
+import com.mysql.jdbc.Statement;
+
+import es.uvigo.esei.daa.entities.Person;
+import es.uvigo.esei.daa.util.DatabaseQueryUnitTest;
+
+public class PeopleDAOUnitTest extends DatabaseQueryUnitTest {
+ @Test
+ public void testList() throws Exception {
+ final Person[] people = people();
+
+ for (Person person : people) {
+ expectPersonRow(person);
+ }
+ expect(result.next()).andReturn(false);
+ result.close();
+
+ replayAll();
+ final PeopleDAO peopleDAO = new PeopleDAO();
+
+ assertThat(peopleDAO.list(), containsPeopleInAnyOrder(people));
+ }
+
+ @Test(expected = DAOException.class)
+ public void testListUnexpectedException() throws Exception {
+ expect(result.next()).andThrow(new SQLException());
+ result.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.list();
+ }
+
+ @Test
+ public void testGet() throws Exception {
+ final Person existentPerson = existentPerson();
+
+ expectPersonRow(existentPerson);
+ result.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+
+ assertThat(peopleDAO.get(existentId()), is(equalTo(existentPerson)));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetMissing() throws Exception {
+ expect(result.next()).andReturn(false);
+ result.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.get(existentId());
+ }
+
+ @Test(expected = DAOException.class)
+ public void testGetUnexpectedException() throws Exception {
+ expect(result.next()).andThrow(new SQLException());
+ result.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.get(existentId());
+ }
+
+ @Test
+ public void testAdd() throws Exception {
+ final Person person = newPerson();
+ reset(connection);
+ expect(connection.prepareStatement(anyString(), eq(Statement.RETURN_GENERATED_KEYS)))
+ .andReturn(statement);
+ expect(statement.executeUpdate()).andReturn(1);
+ expect(statement.getGeneratedKeys()).andReturn(result);
+
+ // Key retrieval
+ expect(result.next()).andReturn(true);
+ expect(result.getInt(1)).andReturn(person.getId());
+ connection.close();
+ result.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ final Person newPerson = peopleDAO.add(person.getName(), person.getSurname());
+
+ assertThat(newPerson, is(equalsToPerson(person)));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAddNullName() throws Exception {
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+
+ resetAll(); // No expectations
+
+ peopleDAO.add(null, newSurname());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testAddNullSurname() throws Exception {
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+
+ resetAll(); // No expectations
+
+ peopleDAO.add(newName(), null);
+ }
+
+ @Test(expected = DAOException.class)
+ public void testAddZeroUpdatedRows() throws Exception {
+ reset(connection);
+ expect(connection.prepareStatement(anyString(), eq(1)))
+ .andReturn(statement);
+ expect(statement.executeUpdate()).andReturn(0);
+ connection.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.add(newName(), newSurname());
+ }
+
+ @Test(expected = DAOException.class)
+ public void testAddNoGeneratedKey() throws Exception {
+ reset(connection);
+ expect(connection.prepareStatement(anyString(), eq(1)))
+ .andReturn(statement);
+ expect(statement.executeUpdate()).andReturn(1);
+ expect(statement.getGeneratedKeys()).andReturn(result);
+ expect(result.next()).andReturn(false);
+ result.close();
+ connection.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.add(newName(), newSurname());
+ }
+
+ @Test(expected = DAOException.class)
+ public void testAddUnexpectedException() throws Exception {
+ reset(connection);
+ expect(connection.prepareStatement(anyString(), eq(1)))
+ .andReturn(statement);
+ expect(statement.executeUpdate()).andThrow(new SQLException());
+ connection.close();
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.add(newName(), newSurname());
+ }
+
+ @Test
+ public void testDelete() throws Exception {
+ expect(statement.executeUpdate()).andReturn(1);
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.delete(existentId());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testDeleteInvalidId() throws Exception {
+ expect(statement.executeUpdate()).andReturn(0);
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.delete(existentId());
+ }
+
+ @Test(expected = DAOException.class)
+ public void testDeleteUnexpectedException() throws Exception {
+ expect(statement.executeUpdate()).andThrow(new SQLException());
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.delete(existentId());
+ }
+
+ @Test
+ public void testModify() throws Exception {
+ expect(statement.executeUpdate()).andReturn(1);
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.modify(existentPerson());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testModifyNullPerson() throws Exception {
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+
+ resetAll(); // No expectations
+
+ peopleDAO.modify(null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testModifyZeroUpdatedRows() throws Exception {
+ expect(statement.executeUpdate()).andReturn(0);
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.modify(existentPerson());
+ }
+
+ @Test(expected = DAOException.class)
+ public void testModifyUnexpectedException() throws Exception {
+ expect(statement.executeUpdate()).andThrow(new SQLException());
+
+ replayAll();
+
+ final PeopleDAO peopleDAO = new PeopleDAO();
+ peopleDAO.modify(existentPerson());
+ }
+
+ private void expectPersonRow(Person person) throws SQLException {
+ expect(result.next()).andReturn(true);
+ expect(result.getInt("id")).andReturn(person.getId());
+ expect(result.getString("name")).andReturn(person.getName());
+ expect(result.getString("surname")).andReturn(person.getSurname());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java b/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java
new file mode 100644
index 0000000000000000000000000000000000000000..764a44f32ca073bfff43697da7e915ab6c0b4d9b
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java
@@ -0,0 +1,74 @@
+package es.uvigo.esei.daa.dataset;
+
+import static java.util.Arrays.binarySearch;
+import static java.util.Arrays.stream;
+
+import java.util.Arrays;
+import java.util.function.Predicate;
+
+import es.uvigo.esei.daa.entities.Person;
+
+public final class PeopleDataset {
+ private PeopleDataset() {}
+
+ public static Person[] people() {
+ return new Person[] {
+ new Person(1, "Antón", "Álvarez"),
+ new Person(2, "Ana", "Amargo"),
+ new Person(3, "Manuel", "Martínez"),
+ new Person(4, "María", "Márquez"),
+ new Person(5, "Lorenzo", "López"),
+ new Person(6, "Laura", "Laredo"),
+ new Person(7, "Perico", "Palotes"),
+ new Person(8, "Patricia", "Pérez"),
+ new Person(9, "Julia", "Justa"),
+ new Person(10, "Juan", "Jiménez")
+ };
+ }
+
+ public static Person[] peopleWithout(int ... ids) {
+ Arrays.sort(ids);
+
+ final Predicate hasValidId = person ->
+ binarySearch(ids, person.getId()) < 0;
+
+ return stream(people())
+ .filter(hasValidId)
+ .toArray(Person[]::new);
+ }
+
+ public static Person person(int id) {
+ return stream(people())
+ .filter(person -> person.getId() == id)
+ .findAny()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public static int existentId() {
+ return 5;
+ }
+
+ public static int nonExistentId() {
+ return 1234;
+ }
+
+ public static Person existentPerson() {
+ return person(existentId());
+ }
+
+ public static Person nonExistentPerson() {
+ return new Person(nonExistentId(), "Jane", "Smith");
+ }
+
+ public static String newName() {
+ return "John";
+ }
+
+ public static String newSurname() {
+ return "Doe";
+ }
+
+ public static Person newPerson() {
+ return new Person(people().length + 1, newName(), newSurname());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/dataset/UsersDataset.java b/src/test/java/es/uvigo/esei/daa/dataset/UsersDataset.java
new file mode 100644
index 0000000000000000000000000000000000000000..82cbcdeec1e23abcc76b0832958f33bce13c02df
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/dataset/UsersDataset.java
@@ -0,0 +1,38 @@
+package es.uvigo.esei.daa.dataset;
+
+import java.util.Arrays;
+import java.util.Base64;
+
+import es.uvigo.esei.daa.entities.User;
+
+public final class UsersDataset {
+ private UsersDataset() {}
+
+ public static User[] users() {
+ return new User[] {
+ new User(adminLogin(), "713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca", "ADMIN"),
+ new User(normalLogin(), "7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83", "USER")
+ };
+ }
+
+ public static User user(String login) {
+ return Arrays.stream(users())
+ .filter(user -> user.getLogin().equals(login))
+ .findAny()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public static String adminLogin() {
+ return "admin";
+ }
+
+ public static String normalLogin() {
+ return "normal";
+ }
+
+ public static String userToken(String login) {
+ final String chain = login + ":" + login + "pass";
+
+ return Base64.getEncoder().encodeToString(chain.getBytes());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/entities/PersonUnitTest.java b/src/test/java/es/uvigo/esei/daa/entities/PersonUnitTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..a648f5ddbaa0f9221a2ccfbed9e2a7d295c51a4d
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/entities/PersonUnitTest.java
@@ -0,0 +1,93 @@
+package es.uvigo.esei.daa.entities;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+import nl.jqno.equalsverifier.Warning;
+
+public class PersonUnitTest {
+ @Test
+ public void testPersonIntStringString() {
+ final int id = 1;
+ final String name = "John";
+ final String surname = "Doe";
+
+ final Person person = new Person(id, name, surname);
+
+ assertThat(person.getId(), is(equalTo(id)));
+ assertThat(person.getName(), is(equalTo(name)));
+ assertThat(person.getSurname(), is(equalTo(surname)));
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testPersonIntStringStringNullName() {
+ new Person(1, null, "Doe");
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testPersonIntStringStringNullSurname() {
+ new Person(1, "John", null);
+ }
+
+ @Test
+ public void testSetName() {
+ final int id = 1;
+ final String surname = "Doe";
+
+ final Person person = new Person(id, "John", surname);
+ person.setName("Juan");
+
+ assertThat(person.getId(), is(equalTo(id)));
+ assertThat(person.getName(), is(equalTo("Juan")));
+ assertThat(person.getSurname(), is(equalTo(surname)));
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testSetNullName() {
+ final Person person = new Person(1, "John", "Doe");
+
+ person.setName(null);
+ }
+
+ @Test
+ public void testSetSurname() {
+ final int id = 1;
+ final String name = "John";
+
+ final Person person = new Person(id, name, "Doe");
+ person.setSurname("Dolores");
+
+ assertThat(person.getId(), is(equalTo(id)));
+ assertThat(person.getName(), is(equalTo(name)));
+ assertThat(person.getSurname(), is(equalTo("Dolores")));
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testSetNullSurname() {
+ final Person person = new Person(1, "John", "Doe");
+
+ person.setSurname(null);
+ }
+
+ @Test
+ public void testEqualsObject() {
+ final Person personA = new Person(1, "Name A", "Surname A");
+ final Person personB = new Person(1, "Name B", "Surname B");
+
+ assertTrue(personA.equals(personB));
+ }
+
+ @Test
+ public void testEqualsHashcode() {
+ EqualsVerifier.forClass(Person.class)
+ .withIgnoredFields("name", "surname")
+ .suppress(Warning.STRICT_INHERITANCE)
+ .suppress(Warning.NONFINAL_FIELDS)
+ .verify();
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/filters/AuthorizationFilter.java b/src/test/java/es/uvigo/esei/daa/filters/AuthorizationFilter.java
new file mode 100644
index 0000000000000000000000000000000000000000..6c058a1b0ecb05adb6bb2f2d6ade5a832d273888
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/filters/AuthorizationFilter.java
@@ -0,0 +1,101 @@
+package es.uvigo.esei.daa.filters;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Base64;
+
+import javax.annotation.Priority;
+import javax.ws.rs.Priorities;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.Provider;
+
+import es.uvigo.esei.daa.dao.DAOException;
+import es.uvigo.esei.daa.dao.UsersDAO;
+import es.uvigo.esei.daa.entities.User;
+
+@Provider
+@Priority(Priorities.AUTHENTICATION)
+public class AuthorizationFilter implements ContainerRequestFilter {
+ private final UsersDAO dao;
+
+ public AuthorizationFilter() {
+ this.dao = new UsersDAO();
+ }
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ // Get the authentication passed in HTTP headers parameters
+ final String auth = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
+
+ if (auth == null) {
+ requestContext.abortWith(createResponse());
+ } else {
+ final byte[] decodedToken = Base64.getDecoder()
+ .decode(auth.substring(6));
+
+ final String userColonPass = new String(decodedToken);
+ final String[] userPass = userColonPass.split(":", 2);
+
+ if (userPass.length == 2) {
+ try {
+ if (this.dao.checkLogin(userPass[0], userPass[1])) {
+ final User user = this.dao.get(userPass[0]);
+
+ requestContext.setSecurityContext(new UserSecurityContext(user));
+ } else {
+ requestContext.abortWith(createResponse());
+ }
+ } catch (DAOException e) {
+ requestContext.abortWith(createResponse());
+ }
+ } else {
+ requestContext.abortWith(createResponse());
+ }
+ }
+ }
+
+ private static Response createResponse() {
+ return Response.status(Status.UNAUTHORIZED)
+ .header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"DAAExample\"")
+ .entity("Page requires login.")
+ .build();
+ }
+
+ private static final class UserSecurityContext implements SecurityContext {
+ private final User user;
+
+ private UserSecurityContext(User user) {
+ this.user = user;
+ }
+
+ @Override
+ public boolean isUserInRole(String role) {
+ return user.getRole().equals(role);
+ }
+
+ @Override
+ public boolean isSecure() {
+ return false;
+ }
+
+ @Override
+ public Principal getUserPrincipal() {
+ return new Principal() {
+ @Override
+ public String getName() {
+ return user.getLogin();
+ }
+ };
+ }
+
+ @Override
+ public String getAuthenticationScheme() {
+ return SecurityContext.BASIC_AUTH;
+ }
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBinding.java b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBinding.java
new file mode 100644
index 0000000000000000000000000000000000000000..e22da5ee48c5a1e173c0b13e839459a1c07bc326
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBinding.java
@@ -0,0 +1,18 @@
+package es.uvigo.esei.daa.listeners;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+@Repeatable(ApplicationContextBindings.class)
+public @interface ApplicationContextBinding {
+ public String jndiUrl();
+ public String name() default "";
+ public Class> type() default None.class;
+
+ public final static class None {}
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBindings.java b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBindings.java
new file mode 100644
index 0000000000000000000000000000000000000000..1b728ff2058a532b83e81dbbc58cce485d280787
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextBindings.java
@@ -0,0 +1,12 @@
+package es.uvigo.esei.daa.listeners;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ApplicationContextBindings {
+ public ApplicationContextBinding[] value();
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextJndiBindingTestExecutionListener.java b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextJndiBindingTestExecutionListener.java
new file mode 100644
index 0000000000000000000000000000000000000000..0708cc00d9a041a4463988c5c9fe6f32676baa83
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/ApplicationContextJndiBindingTestExecutionListener.java
@@ -0,0 +1,44 @@
+package es.uvigo.esei.daa.listeners;
+
+import org.springframework.mock.jndi.SimpleNamingContextBuilder;
+import org.springframework.test.context.TestContext;
+import org.springframework.test.context.support.AbstractTestExecutionListener;
+
+import es.uvigo.esei.daa.listeners.ApplicationContextBinding.None;
+
+
+public class ApplicationContextJndiBindingTestExecutionListener extends AbstractTestExecutionListener {
+ private SimpleNamingContextBuilder contextBuilder;
+
+ @Override
+ public void beforeTestClass(TestContext testContext) throws Exception {
+ final Class> testClass = testContext.getTestClass();
+
+ final ApplicationContextBinding[] bindings = testClass.getAnnotationsByType(ApplicationContextBinding.class);
+
+ this.contextBuilder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
+ for (ApplicationContextBinding binding : bindings) {
+ final String bindingName = binding.name();
+ final Class> bindingType = binding.type();
+
+ Object bean;
+ if (bindingName.isEmpty() && bindingType.equals(None.class)) {
+ throw new IllegalArgumentException("name or type attributes must be configured in ApplicationContextBinding");
+ } else if (bindingName.isEmpty()) {
+ bean = testContext.getApplicationContext().getBean(bindingType);
+ } else if (bindingType.equals(None.class)) {
+ bean = testContext.getApplicationContext().getBean(bindingName);
+ } else {
+ bean = testContext.getApplicationContext().getBean(bindingName, bindingType);
+ }
+
+ this.contextBuilder.bind(binding.jndiUrl(), bean);
+ }
+ }
+
+ @Override
+ public void afterTestClass(TestContext testContext) throws Exception {
+ this.contextBuilder.clear();
+ this.contextBuilder = null;
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/DbManagement.java b/src/test/java/es/uvigo/esei/daa/listeners/DbManagement.java
new file mode 100644
index 0000000000000000000000000000000000000000..13bb496c9d48692f3a2fe6fc9af9a3bb6ad91ddc
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/DbManagement.java
@@ -0,0 +1,14 @@
+package es.uvigo.esei.daa.listeners;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface DbManagement {
+ public String[] create() default "";
+ public String[] drop() default "";
+ public DbManagementAction action() default DbManagementAction.CREATE_DROP;
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/DbManagementAction.java b/src/test/java/es/uvigo/esei/daa/listeners/DbManagementAction.java
new file mode 100644
index 0000000000000000000000000000000000000000..0e23a1c5e9dd556be92f66245647b774c8af3b49
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/DbManagementAction.java
@@ -0,0 +1,5 @@
+package es.uvigo.esei.daa.listeners;
+
+public enum DbManagementAction {
+ DROP_CREATE_DROP, CREATE_DROP, ONLY_CREATE, ONLY_DROP;
+}
diff --git a/src/test/java/es/uvigo/esei/daa/listeners/DbManagementTestExecutionListener.java b/src/test/java/es/uvigo/esei/daa/listeners/DbManagementTestExecutionListener.java
new file mode 100644
index 0000000000000000000000000000000000000000..6ec05f6b5833431d0b22c052f466f6e72dc85075
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/listeners/DbManagementTestExecutionListener.java
@@ -0,0 +1,113 @@
+package es.uvigo.esei.daa.listeners;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import javax.sql.DataSource;
+
+import org.springframework.test.context.TestContext;
+import org.springframework.test.context.support.AbstractTestExecutionListener;
+
+public class DbManagementTestExecutionListener extends AbstractTestExecutionListener {
+ private DbManagement configuration;
+ private DataSource datasource;
+
+ @Override
+ public void beforeTestClass(TestContext testContext) throws Exception {
+ final Class> testClass = testContext.getTestClass();
+ this.configuration = testClass.getAnnotation(DbManagement.class);
+
+ if (this.configuration == null)
+ throw new IllegalStateException(String.format(
+ "Missing %s annotation in %s class",
+ DbManagement.class.getSimpleName(), testClass.getName()
+ ));
+
+ this.datasource = testContext.getApplicationContext().getBean(DataSource.class);
+
+ switch (this.configuration.action()) {
+ case DROP_CREATE_DROP:
+ executeDrop();
+ case CREATE_DROP:
+ case ONLY_CREATE:
+ executeCreate();
+ break;
+ default:
+ }
+ }
+
+ @Override
+ public void afterTestClass(TestContext testContext) throws Exception {
+ try {
+ switch (this.configuration.action()) {
+ case DROP_CREATE_DROP:
+ case CREATE_DROP:
+ case ONLY_DROP:
+ executeDrop();
+ break;
+ default:
+ }
+ } finally {
+ this.configuration = null;
+ this.datasource = null;
+ }
+ }
+
+ private void executeCreate() throws SQLException, IOException {
+ this.executeQueries(configuration.create());
+ }
+
+ private void executeDrop() throws SQLException, IOException {
+ this.executeQueries(configuration.drop());
+ }
+
+ private void executeQueries(String ... queriesPaths)
+ throws SQLException, IOException {
+ try (Connection connection = this.datasource.getConnection()) {
+ try (Statement statement = connection.createStatement()) {
+ for (String queryPath : queriesPaths) {
+ final String queries = readFile(queryPath);
+ for (String query : queries.split(";")) {
+ query = query.trim();
+ if (!query.trim().isEmpty()) {
+ statement.addBatch(query);
+ }
+ }
+ }
+ statement.executeBatch();
+ }
+ }
+ }
+
+ private static String readFile(String path) throws IOException {
+ final String classpathPrefix = "classpath:";
+
+ if (path.startsWith(classpathPrefix)) {
+ path = path.substring(classpathPrefix.length());
+
+ final ClassLoader classLoader =
+ DbManagementTestExecutionListener.class.getClassLoader();
+
+ final InputStream fileIS = classLoader.getResourceAsStream(path);
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS))) {
+ final StringBuilder sb = new StringBuilder();
+
+ String line;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line);
+ }
+
+ return sb.toString();
+ }
+ } else {
+ return new String(Files.readAllBytes(Paths.get(path)));
+ }
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/matchers/HasHttpStatus.java b/src/test/java/es/uvigo/esei/daa/matchers/HasHttpStatus.java
new file mode 100644
index 0000000000000000000000000000000000000000..8da8cb196f99243c5dbf04e183fb232ad475f2be
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/matchers/HasHttpStatus.java
@@ -0,0 +1,95 @@
+/*
+ * #%L
+ * PanDrugsDB Backend
+ * %%
+ * Copyright (C) 2015 Fátima Al-Shahrour, Elena Piñeiro, Daniel Glez-Peña and Miguel Reboiro-Jato
+ * %%
+ * 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
+ * .
+ * #L%
+ */
+package es.uvigo.esei.daa.matchers;
+
+import static java.util.Objects.requireNonNull;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.Response.StatusType;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
+
+public class HasHttpStatus extends TypeSafeMatcher {
+ private final StatusType expectedStatus;
+
+ public HasHttpStatus(StatusType expectedStatus) {
+ this.expectedStatus = requireNonNull(expectedStatus);
+ }
+
+ public HasHttpStatus(int expectedStatus) {
+ this(Status.fromStatusCode(expectedStatus));
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendValue(this.expectedStatus);
+ }
+
+ @Override
+ protected void describeMismatchSafely(Response item, Description mismatchDescription) {
+ mismatchDescription.appendText("was ").appendValue(item.getStatusInfo());
+ }
+
+ @Override
+ protected boolean matchesSafely(Response item) {
+ return item != null && expectedStatus.getStatusCode() == item.getStatusInfo().getStatusCode();
+ }
+
+ @Factory
+ public static Matcher hasHttpStatus(StatusType expectedStatus) {
+ return new HasHttpStatus(expectedStatus);
+ }
+
+ @Factory
+ public static Matcher hasHttpStatus(int expectedStatus) {
+ return new HasHttpStatus(expectedStatus);
+ }
+
+ @Factory
+ public static Matcher hasOkStatus() {
+ return new HasHttpStatus(Response.Status.OK);
+ }
+
+ @Factory
+ public static Matcher hasBadRequestStatus() {
+ return new HasHttpStatus(Response.Status.BAD_REQUEST);
+ }
+
+ @Factory
+ public static Matcher hasInternalServerErrorStatus() {
+ return new HasHttpStatus(Response.Status.INTERNAL_SERVER_ERROR);
+ }
+
+ @Factory
+ public static Matcher hasUnauthorized() {
+ return new HasHttpStatus(Response.Status.UNAUTHORIZED);
+ }
+
+ @Factory
+ public static Matcher hasForbidden() {
+ return new HasHttpStatus(Response.Status.FORBIDDEN);
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToEntity.java b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToEntity.java
new file mode 100644
index 0000000000000000000000000000000000000000..a85dbc5c84f3c2eb2d182b7dfffc73a851be2123
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToEntity.java
@@ -0,0 +1,364 @@
+package es.uvigo.esei.daa.matchers;
+
+import static java.util.Arrays.asList;
+import static java.util.Arrays.stream;
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
+
+/**
+ * An abstract {@link Matcher} that can be used to create new matchers that
+ * compare entities by their attributes.
+ *
+ * @author Miguel Reboiro Jato
+ *
+ * @param the type of the entities to be matched.
+ */
+public abstract class IsEqualToEntity extends TypeSafeMatcher {
+ /**
+ * The expected entity.
+ */
+ protected final T expected;
+
+ private Consumer describeTo;
+
+ /**
+ * Constructs a new instance of {@link IsEqualToEntity}.
+ *
+ * @param entity the expected tentity.
+ */
+ public IsEqualToEntity(final T entity) {
+ this.expected = requireNonNull(entity);
+ }
+
+ @Override
+ public void describeTo(final Description description) {
+ if (this.describeTo != null)
+ this.describeTo.accept(description);
+ }
+
+ /**
+ * Adds a new description using the template:
+ *
+ * {@code entity with value '' for }
+ *
+ *
+ * @param attribute the name of the attribute compared.
+ * @param expected the expected value.
+ */
+ protected void addTemplatedDescription(final String attribute, final Object expected) {
+ this.describeTo = d -> d.appendText(String.format(
+ "%s entity with value '%s' for %s",
+ this.expected.getClass().getSimpleName(),
+ expected, attribute
+ ));
+ }
+
+ /**
+ * Adds as the description of this matcher the
+ * {@link Matcher#describeTo(Description)} method of other matcher.
+ *
+ * @param matcher the matcher whose description will be used.
+ */
+ protected void addMatcherDescription(final Matcher> matcher) {
+ this.describeTo = matcher::describeTo;
+ }
+
+ /**
+ * Cleans the current description.
+ */
+ protected void clearDescribeTo() {
+ this.describeTo = null;
+ }
+
+ protected boolean checkAttribute(
+ final String attribute,
+ final Function getter, final T actual,
+ final Function> matcherFactory
+ ) {
+ final R expectedValue = getter.apply(this.expected);
+ final R actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || actualValue == null) {
+ this.addTemplatedDescription(attribute, expectedValue);
+ return false;
+ } else {
+ final Matcher matcher = matcherFactory.apply(expectedValue);
+ if (matcher.matches(actualValue)) {
+ return true;
+ } else {
+ this.addMatcherDescription(matcher);
+
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Compares the expected and the actual value of an array attribute. The
+ * elements of the attribute will be checked using a custom matcher.
+ * If the comparison fails, the description of the error will be updated.
+ *
+ * @param attribute the name of the attribute compared.
+ * @param getter the getter function of the attribute.
+ * @param actual the actual entity being compared to the expected entity.
+ * @param matcherFactory a function that creates a matcher for the expected
+ * array values.
+ * @param type of the value returned by the getter.
+ * @return {@code true} if the value of the expected and actual attributes
+ * are equals and {@code false} otherwise. If the result is {@code false},
+ * the current description will be updated.
+ */
+ protected boolean checkArrayAttribute(
+ final String attribute,
+ final Function getter, final T actual,
+ final Function>> matcherFactory
+ ) {
+ final R[] expectedValue = getter.apply(this.expected);
+ final R[] actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || actualValue == null) {
+ this.addTemplatedDescription(attribute, expectedValue);
+ return false;
+ } else {
+ final Matcher> matcher =
+ matcherFactory.apply(expectedValue);
+
+ if (matcher.matches(asList(actualValue))) {
+ return true;
+ } else {
+ this.addMatcherDescription(matcher);
+
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Compares the expected and the actual value of an iterable attribute. The
+ * elements of the attribute will be checked using a custom matcher.
+ * If the comparison fails, the description of the error will be updated.
+ *
+ * @param attribute the name of the attribute compared.
+ * @param getter the getter function of the attribute.
+ * @param actual the actual entity being compared to the expected entity.
+ * @param matcherFactory a function that creates a matcher for the expected
+ * iterable values.
+ * @param type of the value returned by the getter.
+ * @return {@code true} if the value of the expected and actual attributes
+ * are equals and {@code false} otherwise. If the result is {@code false},
+ * the current description will be updated.
+ */
+ protected boolean checkIterableAttribute(
+ final String attribute,
+ final Function> getter, final T actual,
+ final Function, Matcher>> matcherFactory
+ ) {
+ final Iterable expectedValue = getter.apply(this.expected);
+ final Iterable actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || actualValue == null) {
+ this.addTemplatedDescription(attribute, expectedValue);
+ return false;
+ } else {
+ final Matcher> matcher =
+ matcherFactory.apply(expectedValue);
+
+ if (matcher.matches(actualValue)) {
+ return true;
+ } else {
+ this.addMatcherDescription(matcher);
+
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Compares the expected and the actual value of an attribute. If the
+ * comparison fails, the description of the error will be updated.
+ *
+ * @param attribute the name of the attribute compared.
+ * @param getter the getter function of the attribute.
+ * @param actual the actual entity being compared to the expected entity.
+ * @param type of the value returned by the getter.
+ * @return {@code true} if the value of the expected and actual attributes
+ * are equals and {@code false} otherwise. If the result is {@code false},
+ * the current description will be updated.
+ */
+ protected boolean checkAttribute(
+ final String attribute, final Function getter, final T actual
+ ) {
+ final R expectedValue = getter.apply(this.expected);
+ final R actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || !expectedValue.equals(actualValue)) {
+ this.addTemplatedDescription(attribute, expectedValue);
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ /**
+ * Compares the expected and the actual value of an array attribute. If the
+ * comparison fails, the description of the error will be updated.
+ *
+ * @param attribute the name of the attribute compared.
+ * @param getter the getter function of the attribute.
+ * @param actual the actual entity being compared to the expected entity.
+ * @param type of the value returned by the getter.
+ * @return {@code true} if the value of the expected and actual attributes
+ * are equals and {@code false} otherwise. If the result is {@code false},
+ * the current description will be updated.
+ */
+ protected boolean checkArrayAttribute(
+ final String attribute, final Function getter, final T actual
+ ) {
+ final R[] expectedValue = getter.apply(this.expected);
+ final R[] actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || actualValue == null) {
+ this.addTemplatedDescription(attribute, expectedValue == null ? "null" : Arrays.toString(expectedValue));
+ return false;
+ } else if (!Arrays.equals(expectedValue, actualValue)) {
+ this.addTemplatedDescription(attribute, Arrays.toString(expectedValue));
+ return false;
+ } else
+ return true;
+ }
+
+ /**
+ * Compares the expected and the actual value of an int array attribute. If
+ * the comparison fails, the description of the error will be updated.
+ *
+ * @param attribute the name of the attribute compared.
+ * @param getter the getter function of the attribute.
+ * @param actual the actual entity being compared to the expected entity.
+ * @param type of the value returned by the getter.
+ * @return {@code true} if the value of the expected and actual attributes
+ * are equals and {@code false} otherwise. If the result is {@code false},
+ * the current description will be updated.
+ */
+ protected boolean checkIntArrayAttribute(
+ final String attribute, final Function getter, final T actual
+ ) {
+ final int[] expectedValue = getter.apply(this.expected);
+ final int[] actualValue = getter.apply(actual);
+
+ if (expectedValue == null && actualValue == null) {
+ return true;
+ } else if (expectedValue == null || actualValue == null) {
+ this.addTemplatedDescription(attribute, expectedValue == null ? "null" : Arrays.toString(expectedValue));
+ return false;
+ } else if (!Arrays.equals(expectedValue, actualValue)) {
+ this.addTemplatedDescription(attribute, Arrays.toString(expectedValue));
+ return false;
+ } else
+ return true;
+ }
+
+ /**
+ * Utility method that generates a {@link Matcher} that compares several
+ * entities.
+ *
+ * @param converter a function to create a matcher for an entity.
+ * @param entities the entities to be used as the expected values.
+ * @param type of the entity.
+ * @return a new {@link Matcher} that compares several entities.
+ */
+ @SafeVarargs
+ protected static Matcher> containsEntityInAnyOrder(
+ final Function> converter, final T ... entities
+ ) {
+ final Collection> entitiesMatchers = stream(entities)
+ .map(converter)
+ .collect(toList());
+
+ return containsInAnyOrder(entitiesMatchers);
+ }
+
+ /**
+ * Utility method that generates a {@link Matcher} that compares several
+ * entities.
+ *
+ * @param converter a function to create a matcher for an entity.
+ * @param entities the entities to be used as the expected values.
+ * @param type of the entity.
+ * @return a new {@link Matcher} that compares several entities.
+ */
+ protected static Matcher> containsEntityInAnyOrder(
+ final Function> converter, final Iterable entities
+ ) {
+ final Collection> entitiesMatchers =
+ StreamSupport.stream(entities.spliterator(), false)
+ .map(converter)
+ .collect(toList());
+
+ return containsInAnyOrder(entitiesMatchers);
+ }
+
+ /**
+ * Utility method that generates a {@link Matcher} that compares several
+ * entities in the same received order.
+ *
+ * @param converter A function to create a matcher for an entity.
+ * @param entities The entities to be used as the expected values, in the
+ * order to be compared.
+ * @param The type of the entity.
+ *
+ * @return A new {@link Matcher} that compares several entities in the same
+ * received order.
+ */
+ @SafeVarargs
+ protected static Matcher> containsEntityInOrder(
+ final Function> converter, final T ... entities
+ ) {
+ return contains(stream(entities).map(converter).collect(toList()));
+ }
+
+ /**
+ * Utility method that generates a {@link Matcher} that compares several
+ * entities in the same received order.
+ *
+ * @param converter A function to create a matcher for an entity.
+ * @param entities The entities to be used as the expected values, in the
+ * order to be compared.
+ * @param The type of the entity.
+ *
+ * @return A new {@link Matcher} that compares several entities in the same
+ * received order.
+ */
+ protected static Matcher> containsEntityInOrder(
+ final Function> converter, final Iterable entities
+ ) {
+ final List> matchersList =
+ StreamSupport.stream(entities.spliterator(), false)
+ .map(converter)
+ .collect(toList());
+
+ return contains(matchersList);
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToPerson.java b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToPerson.java
new file mode 100644
index 0000000000000000000000000000000000000000..6c06e5f0ff2b8d7e69d96da15b7af78cfd3c62e3
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToPerson.java
@@ -0,0 +1,56 @@
+package es.uvigo.esei.daa.matchers;
+
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import es.uvigo.esei.daa.entities.Person;
+
+public class IsEqualToPerson extends IsEqualToEntity {
+ public IsEqualToPerson(Person entity) {
+ super(entity);
+ }
+
+ @Override
+ protected boolean matchesSafely(Person actual) {
+ this.clearDescribeTo();
+
+ if (actual == null) {
+ this.addTemplatedDescription("actual", expected.toString());
+ return false;
+ } else {
+ return checkAttribute("id", Person::getId, actual)
+ && checkAttribute("name", Person::getName, actual)
+ && checkAttribute("surname", Person::getSurname, actual);
+ }
+ }
+
+ /**
+ * Factory method that creates a new {@link IsEqualToEntity} matcher with
+ * the provided {@link Person} as the expected value.
+ *
+ * @param person the expected person.
+ * @return a new {@link IsEqualToEntity} matcher with the provided
+ * {@link Person} as the expected value.
+ */
+ @Factory
+ public static IsEqualToPerson equalsToPerson(Person person) {
+ return new IsEqualToPerson(person);
+ }
+
+ /**
+ * Factory method that returns a new {@link Matcher} that includes several
+ * {@link IsEqualToPerson} matchers, each one using an {@link Person} of the
+ * provided ones as the expected value.
+ *
+ * @param persons the persons to be used as the expected values.
+ * @return a new {@link Matcher} that includes several
+ * {@link IsEqualToPerson} matchers, each one using an {@link Person} of the
+ * provided ones as the expected value.
+ * @see IsEqualToEntity#containsEntityInAnyOrder(java.util.function.Function, Object...)
+ */
+ @Factory
+ public static Matcher> containsPeopleInAnyOrder(Person ... persons) {
+ return containsEntityInAnyOrder(IsEqualToPerson::equalsToPerson, persons);
+ }
+
+}
diff --git a/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToUser.java b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToUser.java
new file mode 100644
index 0000000000000000000000000000000000000000..689674ea1e7e97580ce16377bc3109a668e4768c
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/matchers/IsEqualToUser.java
@@ -0,0 +1,56 @@
+package es.uvigo.esei.daa.matchers;
+
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import es.uvigo.esei.daa.entities.Person;
+import es.uvigo.esei.daa.entities.User;
+
+public class IsEqualToUser extends IsEqualToEntity {
+ public IsEqualToUser(User entity) {
+ super(entity);
+ }
+
+ @Override
+ protected boolean matchesSafely(User actual) {
+ this.clearDescribeTo();
+
+ if (actual == null) {
+ this.addTemplatedDescription("actual", expected.toString());
+ return false;
+ } else {
+ return checkAttribute("login", User::getLogin, actual)
+ && checkAttribute("password", User::getPassword, actual);
+ }
+ }
+
+ /**
+ * Factory method that creates a new {@link IsEqualToEntity} matcher with
+ * the provided {@link Person} as the expected value.
+ *
+ * @param user the expected person.
+ * @return a new {@link IsEqualToEntity} matcher with the provided
+ * {@link Person} as the expected value.
+ */
+ @Factory
+ public static IsEqualToUser equalsToUser(User user) {
+ return new IsEqualToUser(user);
+ }
+
+ /**
+ * Factory method that returns a new {@link Matcher} that includes several
+ * {@link IsEqualToUser} matchers, each one using an {@link Person} of the
+ * provided ones as the expected value.
+ *
+ * @param users the persons to be used as the expected values.
+ * @return a new {@link Matcher} that includes several
+ * {@link IsEqualToUser} matchers, each one using an {@link Person} of the
+ * provided ones as the expected value.
+ * @see IsEqualToEntity#containsEntityInAnyOrder(java.util.function.Function, Object...)
+ */
+ @Factory
+ public static Matcher> containsPeopleInAnyOrder(User ... users) {
+ return containsEntityInAnyOrder(IsEqualToUser::equalsToUser, users);
+ }
+
+}
diff --git a/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceTest.java b/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..3fe2f7401b5f0fe84822a35f2d5bb1d32333c12a
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceTest.java
@@ -0,0 +1,226 @@
+package es.uvigo.esei.daa.rest;
+
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newName;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newSurname;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.nonExistentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.people;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasBadRequestStatus;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.containsPeopleInAnyOrder;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.equalsToPerson;
+import static javax.ws.rs.client.Entity.entity;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.sql.DataSource;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.test.JerseyTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
+import com.github.springtestdbunit.DbUnitTestExecutionListener;
+import com.github.springtestdbunit.annotation.DatabaseSetup;
+import com.github.springtestdbunit.annotation.ExpectedDatabase;
+
+import es.uvigo.esei.daa.DAAExampleApplication;
+import es.uvigo.esei.daa.entities.Person;
+import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
+import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
+import es.uvigo.esei.daa.listeners.DbManagement;
+import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:contexts/mem-context.xml")
+@TestExecutionListeners({
+ DbUnitTestExecutionListener.class,
+ DbManagementTestExecutionListener.class,
+ ApplicationContextJndiBindingTestExecutionListener.class
+})
+@ApplicationContextBinding(
+ jndiUrl = "java:/comp/env/jdbc/daaexample",
+ type = DataSource.class
+)
+@DbManagement(
+ create = "classpath:db/hsqldb.sql",
+ drop = "classpath:db/hsqldb-drop.sql"
+)
+@DatabaseSetup("/datasets/dataset.xml")
+@ExpectedDatabase("/datasets/dataset.xml")
+public class PeopleResourceTest extends JerseyTest {
+ @Override
+ protected Application configure() {
+ return new DAAExampleApplication();
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ super.configureClient(config);
+
+ // Enables JSON transformation in client
+ config.register(JacksonJsonProvider.class);
+ config.property("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE);
+ }
+
+ @Test
+ public void testList() throws IOException {
+ final Response response = target("people").request().get();
+ assertThat(response, hasOkStatus());
+
+ final List people = response.readEntity(new GenericType>(){});
+
+ assertThat(people, containsPeopleInAnyOrder(people()));
+ }
+
+ @Test
+ public void testGet() throws IOException {
+ final Response response = target("people/" + existentId()).request().get();
+ assertThat(response, hasOkStatus());
+
+ final Person person = response.readEntity(Person.class);
+
+ assertThat(person, is(equalsToPerson(existentPerson())));
+ }
+
+ @Test
+ public void testGetInvalidId() throws IOException {
+ final Response response = target("people/" + nonExistentId()).request().get();
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-add.xml")
+ public void testAdd() throws IOException {
+ final Form form = new Form();
+ form.param("name", newName());
+ form.param("surname", newSurname());
+
+ final Response response = target("people")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+ assertThat(response, hasOkStatus());
+
+ final Person person = response.readEntity(Person.class);
+
+ assertThat(person, is(equalsToPerson(newPerson())));
+ }
+
+ @Test
+ public void testAddMissingName() throws IOException {
+ final Form form = new Form();
+ form.param("surname", newSurname());
+
+ final Response response = target("people")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testAddMissingSurname() throws IOException {
+ final Form form = new Form();
+ form.param("name", newName());
+
+ final Response response = target("people")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-modify.xml")
+ public void testModify() throws IOException {
+ final Form form = new Form();
+ form.param("name", newName());
+ form.param("surname", newSurname());
+
+ final Response response = target("people/" + existentId())
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+ assertThat(response, hasOkStatus());
+
+ final Person modifiedPerson = response.readEntity(Person.class);
+
+ final Person person = existentPerson();
+ person.setName(newName());
+ person.setSurname(newSurname());
+
+ assertThat(modifiedPerson, is(equalsToPerson(person)));
+ }
+
+ @Test
+ public void testModifyName() throws IOException {
+ final Form form = new Form();
+ form.param("name", newName());
+
+ final Response response = target("people/" + existentId())
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testModifySurname() throws IOException {
+ final Form form = new Form();
+ form.param("surname", newSurname());
+
+ final Response response = target("people/" + existentId())
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testModifyInvalidId() throws IOException {
+ final Form form = new Form();
+ form.param("name", newName());
+ form.param("surname", newSurname());
+
+ final Response response = target("people/" + nonExistentId())
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-delete.xml")
+ public void testDelete() throws IOException {
+ final Response response = target("people/" + existentId()).request().delete();
+
+ assertThat(response, hasOkStatus());
+
+ final Integer deletedId = response.readEntity(Integer.class);
+
+ assertThat(deletedId, is(equalTo(existentId())));
+ }
+
+ @Test
+ public void testDeleteInvalidId() throws IOException {
+ final Response response = target("people/" + nonExistentId()).request().delete();
+
+ assertThat(response, hasBadRequestStatus());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceUnitTest.java b/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceUnitTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..5cb75654a8eca50305099a1cf3959f052e8f1e38
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/rest/PeopleResourceUnitTest.java
@@ -0,0 +1,242 @@
+package es.uvigo.esei.daa.rest;
+
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newName;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newSurname;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.people;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasBadRequestStatus;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasInternalServerErrorStatus;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.containsPeopleInAnyOrder;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.equalsToPerson;
+import static java.util.Arrays.asList;
+import static org.easymock.EasyMock.anyInt;
+import static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.anyString;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.expectLastCall;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.util.List;
+
+import javax.ws.rs.core.Response;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import es.uvigo.esei.daa.dao.DAOException;
+import es.uvigo.esei.daa.dao.PeopleDAO;
+import es.uvigo.esei.daa.entities.Person;
+
+public class PeopleResourceUnitTest {
+ private PeopleDAO daoMock;
+ private PeopleResource resource;
+
+ @Before
+ public void setUp() throws Exception {
+ daoMock = createMock(PeopleDAO.class);
+ resource = new PeopleResource(daoMock);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ try {
+ verify(daoMock);
+ } finally {
+ daoMock = null;
+ resource = null;
+ }
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testList() throws Exception {
+ final List people = asList(people());
+
+ expect(daoMock.list()).andReturn(people);
+
+ replay(daoMock);
+
+ final Response response = resource.list();
+
+ assertThat(response, hasOkStatus());
+ assertThat((List) response.getEntity(), containsPeopleInAnyOrder(people()));
+ }
+
+ @Test
+ public void testListDAOException() throws Exception {
+ expect(daoMock.list()).andThrow(new DAOException());
+
+ replay(daoMock);
+
+ final Response response = resource.list();
+
+ assertThat(response, hasInternalServerErrorStatus());
+ }
+
+ @Test
+ public void testGet() throws Exception {
+ final Person person = existentPerson();
+
+ expect(daoMock.get(person.getId())).andReturn(person);
+
+ replay(daoMock);
+
+ final Response response = resource.get(person.getId());
+
+ assertThat(response, hasOkStatus());
+ assertThat((Person) response.getEntity(), is(equalsToPerson(person)));
+ }
+
+ @Test
+ public void testGetDAOException() throws Exception {
+ expect(daoMock.get(anyInt())).andThrow(new DAOException());
+
+ replay(daoMock);
+
+ final Response response = resource.get(existentId());
+
+ assertThat(response, hasInternalServerErrorStatus());
+ }
+
+ @Test
+ public void testGetIllegalArgumentException() throws Exception {
+ expect(daoMock.get(anyInt())).andThrow(new IllegalArgumentException());
+
+ replay(daoMock);
+
+ final Response response = resource.get(existentId());
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testDelete() throws Exception {
+ daoMock.delete(anyInt());
+
+ replay(daoMock);
+
+ final Response response = resource.delete(1);
+
+ assertThat(response, hasOkStatus());
+ }
+
+ @Test
+ public void testDeleteDAOException() throws Exception {
+ daoMock.delete(anyInt());
+ expectLastCall().andThrow(new DAOException());
+
+ replay(daoMock);
+
+ final Response response = resource.delete(1);
+
+ assertThat(response, hasInternalServerErrorStatus());
+ }
+
+ @Test
+ public void testDeleteIllegalArgumentException() throws Exception {
+ daoMock.delete(anyInt());
+ expectLastCall().andThrow(new IllegalArgumentException());
+ replay(daoMock);
+
+ final Response response = resource.delete(1);
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testModify() throws Exception {
+ final Person person = existentPerson();
+ person.setName(newName());
+ person.setSurname(newSurname());
+
+ daoMock.modify(person);
+
+ replay(daoMock);
+
+ final Response response = resource.modify(
+ person.getId(), person.getName(), person.getSurname());
+
+ assertThat(response, hasOkStatus());
+ assertEquals(person, response.getEntity());
+ }
+
+ @Test
+ public void testModifyDAOException() throws Exception {
+ daoMock.modify(anyObject());
+ expectLastCall().andThrow(new DAOException());
+
+ replay(daoMock);
+
+ final Response response = resource.modify(existentId(), newName(), newSurname());
+
+ assertThat(response, hasInternalServerErrorStatus());
+ }
+
+ @Test
+ public void testModifyIllegalArgumentException() throws Exception {
+ daoMock.modify(anyObject());
+ expectLastCall().andThrow(new IllegalArgumentException());
+
+ replay(daoMock);
+
+ final Response response = resource.modify(existentId(), newName(), newSurname());
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testModifyNullPointerException() throws Exception {
+ daoMock.modify(anyObject());
+ expectLastCall().andThrow(new NullPointerException());
+
+ replay(daoMock);
+
+ final Response response = resource.modify(existentId(), newName(), newSurname());
+
+ assertThat(response, hasBadRequestStatus());
+ }
+
+ @Test
+ public void testAdd() throws Exception {
+ expect(daoMock.add(newName(), newSurname()))
+ .andReturn(newPerson());
+ replay(daoMock);
+
+
+ final Response response = resource.add(newName(), newSurname());
+
+ assertThat(response, hasOkStatus());
+ assertThat((Person) response.getEntity(), is(equalsToPerson(newPerson())));
+ }
+
+ @Test
+ public void testAddDAOException() throws Exception {
+ expect(daoMock.add(anyString(), anyString()))
+ .andThrow(new DAOException());
+ replay(daoMock);
+
+ final Response response = resource.add(newName(), newSurname());
+
+ assertThat(response, hasInternalServerErrorStatus());
+ }
+
+ @Test
+ public void testAddIllegalArgumentException() throws Exception {
+ expect(daoMock.add(anyString(), anyString()))
+ .andThrow(new IllegalArgumentException());
+ replay(daoMock);
+
+ final Response response = resource.add(newName(), newSurname());
+
+ assertThat(response, hasBadRequestStatus());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/rest/UsersResourceTest.java b/src/test/java/es/uvigo/esei/daa/rest/UsersResourceTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..ed9a674b5d7e31dfa146d95222182a7fc9195010
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/rest/UsersResourceTest.java
@@ -0,0 +1,158 @@
+package es.uvigo.esei.daa.rest;
+
+import static es.uvigo.esei.daa.dataset.UsersDataset.adminLogin;
+import static es.uvigo.esei.daa.dataset.UsersDataset.normalLogin;
+import static es.uvigo.esei.daa.dataset.UsersDataset.user;
+import static es.uvigo.esei.daa.dataset.UsersDataset.userToken;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
+import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasUnauthorized;
+import static es.uvigo.esei.daa.matchers.IsEqualToUser.equalsToUser;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+
+import javax.sql.DataSource;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.Response;
+
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.servlet.ServletContainer;
+import org.glassfish.jersey.test.DeploymentContext;
+import org.glassfish.jersey.test.JerseyTest;
+import org.glassfish.jersey.test.ServletDeploymentContext;
+import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
+import org.glassfish.jersey.test.spi.TestContainerFactory;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
+import com.github.springtestdbunit.DbUnitTestExecutionListener;
+import com.github.springtestdbunit.annotation.DatabaseSetup;
+import com.github.springtestdbunit.annotation.ExpectedDatabase;
+
+import es.uvigo.esei.daa.DAAExampleTestApplication;
+import es.uvigo.esei.daa.entities.User;
+import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
+import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
+import es.uvigo.esei.daa.listeners.DbManagement;
+import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:contexts/mem-context.xml")
+@TestExecutionListeners({
+ DbUnitTestExecutionListener.class,
+ DbManagementTestExecutionListener.class,
+ ApplicationContextJndiBindingTestExecutionListener.class
+})
+@ApplicationContextBinding(
+ jndiUrl = "java:/comp/env/jdbc/daaexample",
+ type = DataSource.class
+)
+@DbManagement(
+ create = "classpath:db/hsqldb.sql",
+ drop = "classpath:db/hsqldb-drop.sql"
+)
+@DatabaseSetup("/datasets/dataset.xml")
+@ExpectedDatabase("/datasets/dataset.xml")
+public class UsersResourceTest extends JerseyTest {
+ @Override
+ protected Application configure() {
+ return new DAAExampleTestApplication();
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ super.configureClient(config);
+
+ // Enables JSON transformation in client
+ config.register(JacksonJsonProvider.class);
+ config.property("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE);
+ }
+
+ @Override
+ protected TestContainerFactory getTestContainerFactory() {
+ return new GrizzlyWebTestContainerFactory();
+ }
+
+ @Override
+ protected DeploymentContext configureDeployment() {
+ return ServletDeploymentContext.forServlet(
+ new ServletContainer(ResourceConfig.forApplication(configure()))
+ )
+ .servletPath("/rest")
+ .build();
+ }
+
+ @Test
+ public void testGetAdminOwnUser() throws IOException {
+ final String admin = adminLogin();
+
+ final Response response = target("users/" + admin).request()
+ .header("Authorization", "Basic " + userToken(admin))
+ .get();
+ assertThat(response, hasOkStatus());
+
+ final User user = response.readEntity(User.class);
+
+ assertThat(user, is(equalsToUser(user(admin))));
+ }
+
+ @Test
+ public void testGetAdminOtherUser() throws IOException {
+ final String admin = adminLogin();
+ final String otherUser = normalLogin();
+
+ final Response response = target("users/" + otherUser).request()
+ .header("Authorization", "Basic " + userToken(admin))
+ .get();
+ assertThat(response, hasOkStatus());
+
+ final User user = response.readEntity(User.class);
+
+ assertThat(user, is(equalsToUser(user(otherUser))));
+ }
+
+ @Test
+ public void testGetNormalOwnUser() throws IOException {
+ final String login = normalLogin();
+
+ final Response response = target("users/" + login).request()
+ .header("Authorization", "Basic " + userToken(login))
+ .get();
+ assertThat(response, hasOkStatus());
+
+ final User user = response.readEntity(User.class);
+
+ assertThat(user, is(equalsToUser(user(login))));
+ }
+
+ @Test
+ public void testGetNoCredentials() throws IOException {
+ final Response response = target("users/" + normalLogin()).request().get();
+
+ assertThat(response, hasUnauthorized());
+ }
+
+ @Test
+ public void testGetBadCredentials() throws IOException {
+ final Response response = target("users/" + adminLogin()).request()
+ .header("Authorization", "Basic YmFkOmNyZWRlbnRpYWxz")
+ .get();
+
+ assertThat(response, hasUnauthorized());
+ }
+
+ @Test
+ public void testGetIllegalAccess() throws IOException {
+ final Response response = target("users/" + adminLogin()).request()
+ .header("Authorization", "Basic " + userToken(normalLogin()))
+ .get();
+
+ assertThat(response, hasUnauthorized());
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/suites/AcceptanceTestSuite.java b/src/test/java/es/uvigo/esei/daa/suites/AcceptanceTestSuite.java
new file mode 100644
index 0000000000000000000000000000000000000000..9e7fcdae98a373f1c05365a54f4c40f3166f0ba4
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/suites/AcceptanceTestSuite.java
@@ -0,0 +1,15 @@
+package es.uvigo.esei.daa.suites;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+import es.uvigo.esei.daa.web.PeopleWebTest;
+
+@SuiteClasses({
+ PeopleWebTest.class
+})
+@RunWith(Suite.class)
+public class AcceptanceTestSuite {
+
+}
diff --git a/src/test/java/es/uvigo/esei/daa/suites/IntegrationTestSuite.java b/src/test/java/es/uvigo/esei/daa/suites/IntegrationTestSuite.java
new file mode 100644
index 0000000000000000000000000000000000000000..822c83f44b63c0c998e6b17c1ab25bddbd750a63
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/suites/IntegrationTestSuite.java
@@ -0,0 +1,18 @@
+package es.uvigo.esei.daa.suites;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+import es.uvigo.esei.daa.dao.PeopleDAOTest;
+import es.uvigo.esei.daa.rest.PeopleResourceTest;
+import es.uvigo.esei.daa.rest.UsersResourceTest;
+
+@SuiteClasses({
+ PeopleDAOTest.class,
+ PeopleResourceTest.class,
+ UsersResourceTest.class
+})
+@RunWith(Suite.class)
+public class IntegrationTestSuite {
+}
diff --git a/src/test/java/es/uvigo/esei/daa/suites/UnitTestSuite.java b/src/test/java/es/uvigo/esei/daa/suites/UnitTestSuite.java
new file mode 100644
index 0000000000000000000000000000000000000000..a21ca3663b624f6cf2ea326a347de55ae8f96ca9
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/suites/UnitTestSuite.java
@@ -0,0 +1,18 @@
+package es.uvigo.esei.daa.suites;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+import es.uvigo.esei.daa.dao.PeopleDAOUnitTest;
+import es.uvigo.esei.daa.entities.PersonUnitTest;
+import es.uvigo.esei.daa.rest.PeopleResourceUnitTest;
+
+@SuiteClasses({
+ PersonUnitTest.class,
+ PeopleDAOUnitTest.class,
+ PeopleResourceUnitTest.class
+})
+@RunWith(Suite.class)
+public class UnitTestSuite {
+}
diff --git a/src/test/java/es/uvigo/esei/daa/util/AdditionalConditions.java b/src/test/java/es/uvigo/esei/daa/util/AdditionalConditions.java
new file mode 100644
index 0000000000000000000000000000000000000000..68bb9225e2f3d972c3f93428ea588d0f78ebdde2
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/util/AdditionalConditions.java
@@ -0,0 +1,14 @@
+package es.uvigo.esei.daa.util;
+
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.support.ui.ExpectedCondition;
+
+/*
+ * Implementation based on https://stackoverflow.com/questions/33348600/selenium-wait-for-ajax-content-to-load-universal-approach
+ */
+public class AdditionalConditions {
+ public static ExpectedCondition jQueryAjaxCallsHaveCompleted() {
+ return driver ->
+ (Boolean) ((JavascriptExecutor) driver).executeScript("return (window.jQuery !== null) && (jQuery.active === 0)");
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/util/ContextUtils.java b/src/test/java/es/uvigo/esei/daa/util/ContextUtils.java
new file mode 100644
index 0000000000000000000000000000000000000000..331044f0f1f201bf6d93b2805d08ac4c85031b4c
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/util/ContextUtils.java
@@ -0,0 +1,24 @@
+package es.uvigo.esei.daa.util;
+
+import javax.naming.NamingException;
+import javax.sql.DataSource;
+
+import org.springframework.mock.jndi.SimpleNamingContextBuilder;
+
+public final class ContextUtils {
+ private final static SimpleNamingContextBuilder CONTEXT_BUILDER =
+ new SimpleNamingContextBuilder();
+
+ private ContextUtils() {}
+
+ public static void createFakeContext(DataSource datasource)
+ throws IllegalStateException, NamingException {
+ CONTEXT_BUILDER.bind("java:/comp/env/jdbc/daaexample", datasource);
+ CONTEXT_BUILDER.activate();
+ }
+
+ public static void clearContextBuilder() {
+ CONTEXT_BUILDER.clear();
+ CONTEXT_BUILDER.deactivate();
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/util/DatabaseQueryUnitTest.java b/src/test/java/es/uvigo/esei/daa/util/DatabaseQueryUnitTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..e541cb7ce2edb3b91ed6c40164b296ef10a3f34c
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/util/DatabaseQueryUnitTest.java
@@ -0,0 +1,106 @@
+package es.uvigo.esei.daa.util;
+
+import static org.easymock.EasyMock.anyString;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+import static org.easymock.EasyMock.verify;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+
+import javax.sql.DataSource;
+
+import org.junit.After;
+import org.junit.Before;
+
+import com.mysql.jdbc.PreparedStatement;
+
+/**
+ * Super-class for unit tests in the DAO layer.
+ *
+ *
The default {@link DatabaseQueryUnitTest#setUp()} method in this class
+ * create mocks for the datasource, connection, statement, and result variables
+ * that can be used by the DAO object under test.
+ *
+ * @author Miguel Reboiro Jato
+ */
+public abstract class DatabaseQueryUnitTest {
+ protected DataSource datasource;
+ protected Connection connection;
+ protected PreparedStatement statement;
+ protected ResultSet result;
+
+ protected boolean verify;
+
+ /**
+ * Configures the mocks and enables the verification.
+ *
+ * @throws Exception if an error happens while configuring the mocks.
+ */
+ @Before
+ public void setUp() throws Exception {
+ datasource = createMock(DataSource.class);
+ connection = createMock(Connection.class);
+ statement = createNiceMock(PreparedStatement.class);
+ result = createMock(ResultSet.class);
+
+ expect(datasource.getConnection())
+ .andReturn(connection);
+ expect(connection.prepareStatement(anyString()))
+ .andReturn(statement)
+ .anyTimes(); // statement is optional
+ expect(statement.executeQuery())
+ .andReturn(result)
+ .anyTimes(); // executeQuery is optional
+ statement.close();
+ connection.close();
+
+ verify = true;
+ }
+
+ /**
+ * Removes the default behavior of the mock instances and disables the mock
+ * verification.
+ */
+ protected void resetAll() {
+ reset(result, statement, connection, datasource);
+ verify = false;
+ }
+
+ /**
+ * Replays the configured behavior of the mock instances and enables the
+ * mock verification. The mocked datasource is also added to a new context.
+ */
+ protected void replayAll()
+ throws Exception {
+ replay(result, statement, connection, datasource);
+ verify = true;
+
+ ContextUtils.createFakeContext(datasource);
+ }
+
+ /**
+ * Clears the context and verifies the mocks if the verification is enabled.
+ *
+ * @throws Exception if an error happens during verification.
+ */
+ @After
+ public void tearDown() throws Exception {
+ ContextUtils.clearContextBuilder();
+
+ try {
+ if (verify) {
+ verify(datasource, connection, statement, result);
+ verify = false;
+ }
+ } finally {
+ datasource = null;
+ connection = null;
+ statement = null;
+ result = null;
+ }
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/web/PeopleWebTest.java b/src/test/java/es/uvigo/esei/daa/web/PeopleWebTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..81313c8bdab5129e4a6f26e11bd69c78d520fd4f
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/web/PeopleWebTest.java
@@ -0,0 +1,134 @@
+package es.uvigo.esei.daa.web;
+
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentId;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newName;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newPerson;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.newSurname;
+import static es.uvigo.esei.daa.dataset.PeopleDataset.people;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.containsPeopleInAnyOrder;
+import static es.uvigo.esei.daa.matchers.IsEqualToPerson.equalsToPerson;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+
+import java.util.concurrent.TimeUnit;
+
+import javax.sql.DataSource;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.firefox.FirefoxDriver;
+import org.openqa.selenium.firefox.FirefoxOptions;
+import org.openqa.selenium.firefox.FirefoxProfile;
+import org.openqa.selenium.html5.LocalStorage;
+import org.openqa.selenium.remote.DesiredCapabilities;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.github.springtestdbunit.DbUnitTestExecutionListener;
+import com.github.springtestdbunit.annotation.DatabaseSetup;
+import com.github.springtestdbunit.annotation.ExpectedDatabase;
+
+import es.uvigo.esei.daa.entities.Person;
+import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
+import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
+import es.uvigo.esei.daa.listeners.DbManagement;
+import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
+import es.uvigo.esei.daa.web.pages.MainPage;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:contexts/hsql-context.xml")
+@TestExecutionListeners({
+ DbUnitTestExecutionListener.class,
+ DbManagementTestExecutionListener.class,
+ ApplicationContextJndiBindingTestExecutionListener.class
+})
+@ApplicationContextBinding(
+ jndiUrl = "java:/comp/env/jdbc/daaexample",
+ type = DataSource.class
+)
+@DbManagement(
+ create = "classpath:db/hsqldb.sql",
+ drop = "classpath:db/hsqldb-drop.sql"
+)
+@DatabaseSetup("/datasets/dataset.xml")
+@ExpectedDatabase("/datasets/dataset.xml")
+public class PeopleWebTest {
+ private static final int DEFAULT_WAIT_TIME = 1;
+
+ private WebDriver driver;
+ private MainPage mainPage;
+
+ @Before
+ public void setUp() throws Exception {
+ final String baseUrl = "http://localhost:9080/DAAExample/";
+
+ final FirefoxProfile profile = new FirefoxProfile();
+ profile.setPreference("browser.privatebrowsing.autostart", true);
+
+ final FirefoxOptions options = new FirefoxOptions(DesiredCapabilities.firefox());
+ options.setProfile(profile);
+
+ final FirefoxDriver firefoxDriver;
+ driver = firefoxDriver = new FirefoxDriver();
+ driver.get(baseUrl);
+
+ // Driver will wait DEFAULT_WAIT_TIME if it doesn't find and element.
+ driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_TIME, TimeUnit.SECONDS);
+ driver.manage().window().maximize();
+
+ // Login as "admin:adminpass"
+ final LocalStorage localStorage = firefoxDriver.getLocalStorage();
+ localStorage.setItem("authorization-token", "YWRtaW46YWRtaW5wYXNz");
+
+ mainPage = new MainPage(driver, baseUrl);
+ mainPage.navigateTo();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ driver.quit();
+ driver = null;
+ mainPage = null;
+ }
+
+ @Test
+ public void testList() throws Exception {
+ assertThat(mainPage.listPeople(), containsPeopleInAnyOrder(people()));
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-add.xml")
+ public void testAdd() throws Exception {
+ final Person newPerson = mainPage.addPerson(newName(), newSurname());
+
+ assertThat(newPerson, is(equalsToPerson(newPerson())));
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-modify.xml")
+ public void testEdit() throws Exception {
+ final Person person = existentPerson();
+ person.setName(newName());
+ person.setSurname(newSurname());
+
+ mainPage.editPerson(person);
+
+ final Person webPerson = mainPage.getPerson(person.getId());
+
+ assertThat(webPerson, is(equalsToPerson(person)));
+ }
+
+ @Test
+ @ExpectedDatabase("/datasets/dataset-delete.xml")
+ public void testDelete() throws Exception {
+ mainPage.deletePerson(existentId());
+
+ assertFalse(mainPage.hasPerson(existentId()));
+ }
+}
diff --git a/src/test/java/es/uvigo/esei/daa/web/pages/MainPage.java b/src/test/java/es/uvigo/esei/daa/web/pages/MainPage.java
new file mode 100644
index 0000000000000000000000000000000000000000..97b6a1a230a6f8135a33e1beae89b06a0d14504d
--- /dev/null
+++ b/src/test/java/es/uvigo/esei/daa/web/pages/MainPage.java
@@ -0,0 +1,242 @@
+package es.uvigo.esei.daa.web.pages;
+
+import static es.uvigo.esei.daa.util.AdditionalConditions.jQueryAjaxCallsHaveCompleted;
+import static java.util.stream.Collectors.toList;
+import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
+import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElement;
+
+import java.util.List;
+
+import org.openqa.selenium.By;
+import org.openqa.selenium.NoSuchElementException;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.ui.WebDriverWait;
+
+import es.uvigo.esei.daa.entities.Person;
+
+public class MainPage {
+ private static final String TABLE_ID = "people-list";
+ private static final String FORM_ID = "people-form";
+
+ private static final String ID_PREFIX = "person-";
+
+ private final WebDriver driver;
+
+ private final WebDriverWait wait;
+
+ private final String baseUrl;
+
+ public MainPage(WebDriver driver, String baseUrl) {
+ this.driver = driver;
+ this.baseUrl = baseUrl;
+
+ this.wait = new WebDriverWait(driver, 1);
+ }
+
+ public void navigateTo() {
+ this.driver.get(this.baseUrl + "main.html");
+
+ this.wait.until(presenceOfElementLocated(By.id("people-list")));
+ }
+
+ public int countPeople() {
+ return new PeopleTable(this.driver).countPeople();
+ }
+
+ public List listPeople() {
+ return new PeopleTable(this.driver).listPeople();
+ }
+
+ public Person getLastPerson() {
+ return new PeopleTable(this.driver).getPersonInLastRow();
+ }
+
+ public Person getPerson(int id) {
+ return new PeopleTable(this.driver).getPersonById(id);
+ }
+
+ public boolean hasPerson(int id) {
+ return new PeopleTable(this.driver).hasPerson(id);
+ }
+
+ public Person addPerson(String name, String surname) {
+ final PersonForm form = new PersonForm(this.driver);
+
+ form.clear();
+ form.setName(name);
+ form.setSurname(surname);
+ form.submit();
+
+ final PeopleTable table = new PeopleTable(driver);
+ return table.getPerson(name, surname);
+ }
+
+ public void editPerson(Person person) {
+ final PeopleTable table = new PeopleTable(this.driver);
+ table.editPerson(person.getId());
+
+ final PersonForm form = new PersonForm(this.driver);
+ form.setName(person.getName());
+ form.setSurname(person.getSurname());
+ form.submit();
+ }
+
+ public void deletePerson(int id) {
+ final PeopleTable table = new PeopleTable(this.driver);
+
+ table.deletePerson(id);
+
+ wait.until(jQueryAjaxCallsHaveCompleted());
+ }
+
+ private final static class PeopleTable {
+ private final WebDriver driver;
+
+ private final WebElement table;
+
+ public PeopleTable(WebDriver driver) {
+ this.driver = driver;
+
+ this.table = this.driver.findElement(By.id(TABLE_ID));
+ }
+
+ public boolean hasPerson(int id) {
+ try {
+ return this.getPersonRow(id) != null;
+ } catch (NoSuchElementException nsee) {
+ return false;
+ }
+ }
+
+ public void editPerson(int id) {
+ final WebElement personRow = this.getPersonRow(id);
+
+ personRow.findElement(By.className("edit")).click();
+ }
+
+ public void deletePerson(int id) {
+ final WebElement personRow = this.getPersonRow(id);
+
+ personRow.findElement(By.className("delete")).click();
+
+ this.acceptDialog();
+ }
+
+ public Person getPersonById(int id) {
+ return rowToPerson(getPersonRow(id));
+ }
+
+ public Person getPerson(String name, String surname) {
+ return rowToPerson(getPersonRow(name, surname));
+ }
+
+ public Person getPersonInLastRow() {
+ final WebElement row = this.table.findElement(By.cssSelector("tbody > tr:last-child"));
+
+ return rowToPerson(row);
+ }
+
+ private WebElement getPersonRow(int id) {
+ return this.table.findElement(By.id(ID_PREFIX + id));
+ }
+
+ public WebElement getPersonRow(String name, String surname) {
+ final List rows = table.findElements(By.cssSelector("tbody > tr"));
+
+ for (WebElement row : rows) {
+ final String rowName = row.findElement(By.className("name")).getText();
+ final String rowSurname = row.findElement(By.className("surname")).getText();
+
+ if (rowName.equals(name) && rowSurname.equals(surname)) {
+ return row;
+ }
+ }
+
+ throw new IllegalArgumentException(String.format("No row found with name '%s' and surname '%s'", name, surname));
+ }
+
+ public int countPeople() {
+ return getRows().size();
+ }
+
+ public List listPeople() {
+ return getRows().stream()
+ .map(this::rowToPerson)
+ .collect(toList());
+ }
+
+ private List getRows() {
+ final String xpathQuery = "//tbody/tr[starts-with(@id, '" + ID_PREFIX + "')]";
+
+ return this.table.findElements(By.xpath(xpathQuery));
+ }
+
+ private Person rowToPerson(WebElement row) {
+ return new Person(
+ Integer.parseInt(row.getAttribute("id").substring(ID_PREFIX.length())),
+ row.findElement(By.className("name")).getText(),
+ row.findElement(By.className("surname")).getText()
+ );
+ }
+
+ private void acceptDialog() {
+ driver.switchTo().alert().accept();
+ }
+ }
+
+ public final static class PersonForm {
+ private final WebDriverWait wait;
+
+ private final WebElement fieldName;
+ private final WebElement fieldSurname;
+ private final WebElement buttonClear;
+ private final WebElement buttonSubmit;
+
+ public PersonForm(WebDriver driver) {
+ this.wait = new WebDriverWait(driver, 1);
+
+ final WebElement form = driver.findElement(By.id(FORM_ID));
+
+ this.fieldName = form.findElement(By.name("name"));
+ this.fieldSurname = form.findElement(By.name("surname"));
+ this.buttonClear = form.findElement(By.id("btnClear"));
+ this.buttonSubmit = form.findElement(By.id("btnSubmit"));
+ }
+
+ public void submit() {
+ this.buttonSubmit.click();
+
+ this.waitForCleanFields();
+ }
+
+ public void clear() {
+ this.buttonClear.click();
+
+ this.waitForCleanFields();
+ }
+
+ public void setName(String name) {
+ this.fieldName.clear();
+ this.fieldName.sendKeys(name);
+ }
+
+ public void setSurname(String surname) {
+ this.fieldSurname.clear();
+ this.fieldSurname.sendKeys(surname);
+ }
+
+ public String getName() {
+ return this.fieldName.getText();
+ }
+
+ public String getSurname() {
+ return this.fieldSurname.getText();
+ }
+
+ private void waitForCleanFields() {
+ wait.until(textToBePresentInElement(fieldName, ""));
+ wait.until(textToBePresentInElement(fieldSurname, ""));
+ }
+ }
+}
diff --git a/src/test/resources/contexts/hsql-context.xml b/src/test/resources/contexts/hsql-context.xml
new file mode 100644
index 0000000000000000000000000000000000000000..0e1ec2eef039755bb68f9542a745806772e5cf22
--- /dev/null
+++ b/src/test/resources/contexts/hsql-context.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/contexts/mem-context.xml b/src/test/resources/contexts/mem-context.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a37be3358a4bdc5d6e9e630b12210a2da842f9d2
--- /dev/null
+++ b/src/test/resources/contexts/mem-context.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/datasets/dataset-add.xml b/src/test/resources/datasets/dataset-add.xml
new file mode 100644
index 0000000000000000000000000000000000000000..9a75a999a98510f7d6d32992877e71772e8f536c
--- /dev/null
+++ b/src/test/resources/datasets/dataset-add.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/datasets/dataset-delete.xml b/src/test/resources/datasets/dataset-delete.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e49223db335c0f49f7d78cdcb3f27e80e14d30da
--- /dev/null
+++ b/src/test/resources/datasets/dataset-delete.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/datasets/dataset-modify.xml b/src/test/resources/datasets/dataset-modify.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e2dfc903798c9e26431fbaf42bea176a05fc59c
--- /dev/null
+++ b/src/test/resources/datasets/dataset-modify.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/datasets/dataset.dtd b/src/test/resources/datasets/dataset.dtd
new file mode 100644
index 0000000000000000000000000000000000000000..e64500f9760310832c4352657d6b41454a653582
--- /dev/null
+++ b/src/test/resources/datasets/dataset.dtd
@@ -0,0 +1,14 @@
+
+
+
+
+
+
diff --git a/src/test/resources/datasets/dataset.xml b/src/test/resources/datasets/dataset.xml
new file mode 100644
index 0000000000000000000000000000000000000000..3f48cc9b6888070b9fb5b4c42bee31f8eae267b6
--- /dev/null
+++ b/src/test/resources/datasets/dataset.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/resources/db/hsqldb-drop.sql b/src/test/resources/db/hsqldb-drop.sql
new file mode 100644
index 0000000000000000000000000000000000000000..31f86431b16948308e44087e73b488fc3043628a
--- /dev/null
+++ b/src/test/resources/db/hsqldb-drop.sql
@@ -0,0 +1,2 @@
+DROP TABLE People IF EXISTS;
+DROP TABLE Users IF EXISTS;
diff --git a/src/test/resources/db/hsqldb.sql b/src/test/resources/db/hsqldb.sql
new file mode 100644
index 0000000000000000000000000000000000000000..a62944149d65c732b38a85ca9455f804265fd185
--- /dev/null
+++ b/src/test/resources/db/hsqldb.sql
@@ -0,0 +1,13 @@
+CREATE TABLE people (
+ id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ surname VARCHAR(100) NOT NULL,
+ PRIMARY KEY (id)
+);
+
+CREATE TABLE users (
+ login VARCHAR(100) NOT NULL,
+ password VARCHAR(64) NOT NULL,
+ role VARCHAR(5) NOT NULL,
+ PRIMARY KEY (login)
+);
\ No newline at end of file
diff --git a/src/test/webapp/META-INF/context.xml b/src/test/webapp/META-INF/context.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dbba264d1c4141c9fe643ecd89e1e82e68525c9b
--- /dev/null
+++ b/src/test/webapp/META-INF/context.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/test/webapp/rest/people/add.html b/src/test/webapp/rest/people/add.html
new file mode 100644
index 0000000000000000000000000000000000000000..c0f7b7df36c086b33d5cd3d060db6152f17887ba
--- /dev/null
+++ b/src/test/webapp/rest/people/add.html
@@ -0,0 +1,132 @@
+
+
+
+
+
+
+add
+
+
+