Commit 0e57ea10 authored by Jorge Pérez Robles's avatar Jorge Pérez Robles

proyecto

parent 08bc7837
# General
/bak
# Eclipse
.project
.classpath
.settings
WebContent
# Maven
/bin
/target
/assembly
# Testing
/servers
C:\\nppdf32Log\\debuglog.txt
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{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
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
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=utf8mb4;
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=utf8mb4;
CREATE TABLE `daaexample`.`pet` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`owner` int NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (owner) REFERENCES people(name) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE USER 'daa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'daa';
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost';
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');
INSERT INTO `daaexample`.`pet` (`id`,`name`,`owner`) VALUES (1,'mascota1',1);
-- 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');
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=utf8mb4;
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=utf8mb4;
CREATE TABLE `daaexample`.`pet` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`owner` int NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (owner) REFERENCES people(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE USER 'daa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'daa';
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost';
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.uvigo.esei.daa</groupId>
<artifactId>example</artifactId>
<packaging>war</packaging>
<version>0.2.0-SNAPSHOT</version>
<name>DAA Example</name>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<!-- General configuration -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.servers.directory>${project.basedir}/servers</project.servers.directory>
<cargo.tomcat.start.skip>false</cargo.tomcat.start.skip>
<skip-npm-build>false</skip-npm-build>
<cargo.tomcat.run.skip>true</cargo.tomcat.run.skip>
<tomcat.version>8.5.27</tomcat.version>
<jacoco.port>6300</jacoco.port>
<!-- General dependencies -->
<java.servlet.version>3.1.0</java.servlet.version>
<jersey.version>2.25</jersey.version>
<commons-dbcp2.version>2.2.0</commons-dbcp2.version>
<slf4j-jdk14.version>1.7.21</slf4j-jdk14.version>
<!-- Tests dependencies -->
<junit.version>4.12</junit.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<easymock.version>3.5.1</easymock.version>
<selenium-java.version>3.141.59</selenium-java.version>
<spring-test.version>4.3.14.RELEASE</spring-test.version>
<dbunit.version>2.5.1</dbunit.version>
<spring-test-dbunit.version>1.3.0</spring-test-dbunit.version>
<hsqldb.version>2.3.3</hsqldb.version>
<mysql.version>5.1.45</mysql.version>
<equalsverifier.version>2.4.2</equalsverifier.version>
<!-- Plugins -->
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-failsafe-plugin.version>2.20.1</maven-failsafe-plugin.version>
<maven-surefire-plugin.version>2.20.1</maven-surefire-plugin.version>
<maven-surefire-report-plugin.version>2.20.1</maven-surefire-report-plugin.version>
<maven-war-plugin.version>3.2.0</maven-war-plugin.version>
<jacoco-maven-plugin.version>0.8.0</jacoco-maven-plugin.version>
<cargo-maven2-plugin.version>1.6.6</cargo-maven2-plugin.version>
<hsqldb-maven-plugin.version>1.0.0</hsqldb-maven-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<fizzed-watcher-maven-plugin.version>1.0.6</fizzed-watcher-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${java.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4j-jdk14.version}</version>
</dependency>
<!-- Test Scope -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium-java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>${dbunit.version}</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>${spring-test-dbunit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>${equalsverifier.version}</version>
</dependency>
</dependencies>
<build>
<finalName>DAAExample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<excludes>
<exclude>angular/**</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${project.finalName}</warName>
<excludes>
<exclude>angular/**</exclude>
</excludes>
<webappDirectory>${war.webapp.directory}</webappDirectory>
<webResources>
<webResource>
<directory>${project.basedir}/src/main/webapp</directory>
</webResource>
<webResource>
<directory>${project.basedir}/src/main/angular/dist/angular</directory>
</webResource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>exec-npm-install</id>
<phase>generate-sources</phase>
<configuration>
<skip>${skip-npm-install}</skip>
<workingDirectory>${project.basedir}/src/main/angular</workingDirectory>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
<goals>
<goal>exec</goal>
</goals>
</execution>
<execution>
<id>exec-npm-ng-build</id>
<phase>generate-sources</phase>
<configuration>
<skip>${skip-npm-build}</skip>
<workingDirectory>${project.basedir}/src/main/angular</workingDirectory>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<includes>
<includes>**/UnitTestSuite.java</includes>
</includes>
<systemPropertyVariables>
<webdriver.gecko.driver>${geckodriver.uncompressed.path}</webdriver.gecko.driver>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<configuration>
<includes>
<includes>**/IntegrationTestSuite.java</includes>
</includes>
</configuration>
<executions>
<execution>
<id>default-integration-tests</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${maven-surefire-report-plugin.version}</version>
<executions>
<execution>
<id>test-report</id>
<phase>test</phase>
<goals>
<goal>report-only</goal>
</goals>
</execution>
<execution>
<id>integration-test-report</id>
<phase>integration-test</phase>
<goals>
<goal>report-only</goal>
<goal>failsafe-report-only</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco-maven-plugin.version}</version>
<configuration>
<rules />
<port>${jacoco.port}</port>
</configuration>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>coverage-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>jacoco-report</id>
<phase>post-integration-test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.codehaus.mojo
</groupId>
<artifactId>
exec-maven-plugin
</artifactId>
<versionRange>
[1.6.0,)
</versionRange>
<goals>
<goal>exec</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-antrun-plugin
</artifactId>
<versionRange>
[1.8,)
</versionRange>
<goals>
<goal>run</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>run</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<skipTests>true</skipTests>
<skip-npm-install>true</skip-npm-install>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.fizzed</groupId>
<artifactId>fizzed-watcher-maven-plugin</artifactId>
<version>${fizzed-watcher-maven-plugin.version}</version>
<configuration>
<skipTouch>true</skipTouch>
<watches>
<watch>
<directory>src/main/java</directory>
</watch>
<watch>
<directory>src/main/webapp</directory>
</watch>
<watch>
<directory>src/main/angular/src</directory>
</watch>
</watches>
<goals>
<goal>package</goal>
<goal>cargo:redeploy</goal>
</goals>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
<zipUrlInstaller>
<url>https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/${tomcat.version}/tomcat-${tomcat.version}.zip</url>
<downloadDir>${project.servers.directory}/downloads</downloadDir>
<extractDir>${project.servers.directory}/extracts</extractDir>
</zipUrlInstaller>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</container>
<configuration>
<home>${project.build.directory}/catalina-base</home>
<files>
<copy>
<file>tomcat/server.mysql.xml</file>
<tofile>conf/server.xml</tofile>
</copy>
</files>
<properties>
<cargo.servlet.port>9080</cargo.servlet.port>
<cargo.datasource.datasource.h2>
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
</cargo.datasource.datasource.h2>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-independent-autoredeploy</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<skipTests>true</skipTests>
<skip-npm-install>true</skip-npm-install>
<skip-npm-build>true</skip-npm-build>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<workingDirectory>${project.basedir}/src/main/angular</workingDirectory>
<executable>npm</executable>
<goal>exec</goal>
</configuration>
<executions>
<execution>
<id>npm-build</id>
<configuration>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-start</id>
<configuration>
<async>true</async>
<asyncDestroyOnShutdown>true</asyncDestroyOnShutdown>
<arguments>
<argument>start</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.fizzed</groupId>
<artifactId>fizzed-watcher-maven-plugin</artifactId>
<version>${fizzed-watcher-maven-plugin.version}</version>
<configuration>
<skipTouch>true</skipTouch>
<watches>
<watch>
<directory>src/main/java</directory>
</watch>
<watch>
<directory>src/main/webapp</directory>
</watch>
</watches>
<goals>
<goal>package</goal>
<goal>cargo:redeploy</goal>
</goals>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
<zipUrlInstaller>
<url>https://repo1.maven.org/maven2/org/apache/tomcat/tomcat/${tomcat.version}/tomcat-${tomcat.version}.zip</url>
<downloadDir>${project.servers.directory}/downloads</downloadDir>
<extractDir>${project.servers.directory}/extracts</extractDir>
</zipUrlInstaller>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</container>
<configuration>
<home>${project.build.directory}/catalina-base</home>
<files>
<copy>
<file>tomcat/server.mysql.xml</file>
<tofile>conf/server.xml</tofile>
</copy>
</files>
<properties>
<cargo.servlet.port>9080</cargo.servlet.port>
<cargo.datasource.datasource.h2>
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
</cargo.datasource.datasource.h2>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
# Angular
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.1.0.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {
"@schematics/angular:component": {
"styleext": "scss"
}
},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular:build"
},
"configurations": {
"production": {
"browserTarget": "angular:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "angular:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"angular-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "angular:serve"
},
"configurations": {
"production": {
"devServerTarget": "angular:serve:production"
}
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "angular"
}
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
#
# For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11
\ No newline at end of file
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.e2e.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
\ No newline at end of file
import { AppPage } from './app.po';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Welcome to angular!');
});
});
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get('/');
}
getTitleText() {
return element(by.css('app-root h1')).getText();
}
}
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "daa-example",
"version": "0.2.0-alpha.11",
"scripts": {
"ng": "./node_modules/.bin/ng",
"start": "./node_modules/.bin/ng serve",
"build": "./node_modules/.bin/ng build --base-href .",
"test": "./node_modules/.bin/ng test",
"lint": "./node_modules/.bin/ng lint",
"e2e": "./node_modules/.bin/ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.14",
"@angular/cdk": "^8.2.3",
"@angular/common": "~8.2.14",
"@angular/compiler": "~8.2.14",
"@angular/core": "~8.2.14",
"@angular/forms": "~8.2.14",
"@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~8.2.14",
"@angular/router": "~8.2.14",
"angular2-notifications": "^3.0.0",
"bootstrap": "^4.4.1",
"jquery": "^3.4.1",
"popper.js": "^1.16.1",
"core-js": "^2.5.4",
"rxjs": "~6.5.4",
"tslib": "^1.9.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.25",
"@angular/cli": "~8.3.25",
"@angular/compiler-cli": "~8.2.14",
"@angular/language-service": "~8.2.14",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~3.1.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.5.3"
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {UnauthenticatedGuard} from './guards/unauthenticated.guard';
import {AuthenticatedGuard} from './guards/authenticated.guard';
import {LoginPanelComponent} from './components/login-panel/login-panel.component';
import {MainPanelComponent} from './components/main-panel/main-panel.component';
import {PetMainComponent} from './modules/pet/components/pet-main/pet-main.component';
const routes: Routes = [
{
path: 'welcome',
pathMatch: 'full',
component: LoginPanelComponent,
canActivate: [UnauthenticatedGuard]
},
{
path: '',
component: MainPanelComponent,
canActivate: [AuthenticatedGuard],
children: [
{
path: '',
redirectTo: 'people',
pathMatch: 'full'
},
{
path: 'people',
loadChildren: () => import('./modules/people/people.module').then(m => m.PeopleModule)
}
]
},
{
path: 'pets',
component: MainPanelComponent,
canActivate: [AuthenticatedGuard],
children: [
{
path: '',
redirectTo: 'pet',
pathMatch: 'full'
},
{
path: 'pet',
loadChildren: () => import('./modules/pet/pet.module').then(m => m.PetModule)
}
]
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<router-outlet></router-outlet>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'angular'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('angular');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to angular!');
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular';
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {LoginPanelComponent} from './components/login-panel/login-panel.component';
import {MainPanelComponent} from './components/main-panel/main-panel.component';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import {CommonModule, HashLocationStrategy, LocationStrategy} from '@angular/common';
import {AuthenticationInterceptor} from './interceptors/authentication.interceptor';
import {PetMainComponent} from './modules/pet/components/pet-main/pet-main.component';
@NgModule({
declarations: [
AppComponent,
LoginPanelComponent,
MainPanelComponent,
],
imports: [
AppRoutingModule,
BrowserModule,
CommonModule,
FormsModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptor,
multi: true
},
{
provide: LocationStrategy,
useClass: HashLocationStrategy
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<div id="container">
<div class="form-singin">
<h1 class="h1 mb-3 font-weight-normal">DAA Example - Angular</h1>
<label for="login" class="sr-only">Usuario</label>
<input id="login" name="login" type="text" class="form-control" placeholder="Usuario" required autofocus
[(ngModel)]="login"/>
<label for="password" class="sr-only">Contraseña</label>
<input id="password" name="password" type="password" class="form-control" placeholder="Contraseña" required
[(ngModel)]="password"/>
<button class="btn btn-lg btn-primary btn-block mt-3" (click)="onLogin()">Entrar</button>
</div>
</div>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
#container {
height: 100%;
width: 100%;
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;
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginPanelComponent } from './login-panel.component';
describe('LoginPanelComponent', () => {
let component: LoginPanelComponent;
let fixture: ComponentFixture<LoginPanelComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginPanelComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Component} from '@angular/core';
import {Router} from '@angular/router';
import {AuthenticationService} from '../../services/authentication.service';
import {UserModel} from '../../models';
@Component({
selector: 'app-login-panel',
templateUrl: './login-panel.component.html',
styleUrls: ['./login-panel.component.scss']
})
export class LoginPanelComponent {
public login: string;
public password: string;
public constructor(
private readonly authenticationService: AuthenticationService,
private readonly router: Router
) {
this.login = '';
this.password = '';
}
public onLogin(): void {
const credentials: UserModel = {
login: this.login,
password: this.password
};
this.authenticationService.tryLogin(credentials)
.subscribe(() => this.router.navigate(['/']));
}
}
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<header>
<div class="navbar navbar-dark bg-dark box-shadow">
<div class="container d-flex justify-content-between">
<a href="#" class="navbar-brand d-flex align-items-center">
<strong>DAA Example</strong>
</a>
<button class="btn btn-dark" role="button" (click)="onLogout()">Cerrar sesión</button>
</div>
</div>
</header>
<div class="container">
<router-outlet></router-outlet>
</div>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MainPanelComponent } from './main-panel.component';
describe('MainPanelComponent', () => {
let component: MainPanelComponent;
let fixture: ComponentFixture<MainPanelComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MainPanelComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MainPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Component} from '@angular/core';
import {Observable} from 'rxjs';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
import {map} from 'rxjs/operators';
import {Router} from '@angular/router';
import {AuthenticationService} from '../../services/authentication.service';
@Component({
selector: 'app-main-panel',
templateUrl: './main-panel.component.html',
styleUrls: ['./main-panel.component.scss']
})
export class MainPanelComponent {
public readonly isHandset$: Observable<boolean>;
public constructor(
private readonly authenticationService: AuthenticationService,
private readonly breakpointObserver: BreakpointObserver,
private readonly router: Router
) {
this.isHandset$ = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches)
);
}
public onLogout(): void {
this.authenticationService.logout();
this.router.navigate(['welcome']);
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {inject, TestBed} from '@angular/core/testing';
import {AuthenticatedGuard} from './authenticated.guard';
describe('AuthenticatedGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthenticatedGuard]
});
});
it('should ...', inject([AuthenticatedGuard], (guard: AuthenticatedGuard) => {
expect(guard).toBeTruthy();
}));
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {AuthenticationService} from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticatedGuard implements CanActivate {
public constructor(
private readonly authenticationService: AuthenticationService,
private readonly router: Router
) {}
public canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable<boolean> {
if (this.authenticationService.isLogged()) {
return true;
} else {
return this.authenticationService.tryLoginWithStoredCredentials()
.pipe(
map(user => user !== null),
tap(isLogged => {
if (!isLogged) {
this.router.navigate(['welcome']);
}
})
);
}
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {inject, TestBed} from '@angular/core/testing';
import {UnauthenticatedGuard} from './unauthenticated.guard';
describe('UnauthenticatedGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UnauthenticatedGuard]
});
});
it('should ...', inject([UnauthenticatedGuard], (guard: UnauthenticatedGuard) => {
expect(guard).toBeTruthy();
}));
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {map, tap} from 'rxjs/operators';
import {Observable} from 'rxjs';
import {AuthenticationService} from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class UnauthenticatedGuard implements CanActivate {
public constructor(
private readonly authenticationService: AuthenticationService,
private readonly router: Router
) {}
public canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable<boolean> {
if (this.authenticationService.isLogged()) {
this.router.navigate([]);
return false;
} else {
return this.authenticationService.tryLoginWithStoredCredentials()
.pipe(
map(user => user === null),
tap(isNotLogged => {
if (!isNotLogged) {
this.router.navigate([]);
}
})
);
}
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {AuthenticationService} from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationInterceptor implements HttpInterceptor {
public constructor(public authenticationService: AuthenticationService) {
}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const user = this.authenticationService.loggedUser;
if (user !== null) {
request = request.clone({
setHeaders: {
Authorization: 'Basic ' + btoa(user.login + ':' + user.password)
}
});
}
return next.handle(request);
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
export * from './user.model';
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
export interface UserModel {
readonly login: string;
readonly password: string;
}
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<form id="people-form" class="mb-5 mb-10">
<input name="id" type="hidden" value=""/>
<div class="row">
<div class="col-sm-4">
<input name="name" type="text" value="" placeholder="Nombre" class="form-control" required [(ngModel)]="name"/>
</div>
<div class="col-sm-5">
<input name="surname" type="text" value="" placeholder="Apellido" class="form-control" required
[(ngModel)]="surname"/>
</div>
<div class="col-sm-3">
<button id="btnSubmit" class="btn btn-primary"
(click)="onModify()">{{person.id === undefined ? 'Crear' : 'Editar'}}</button>
<button id="btnClear" class="btn" (click)="onClean()">Limpiar</button>
</div>
<div class="col-sm-2">
<button class="btn btn-primary pet" (click)="onPet()">Pets</button>
</div>
</div>
</form>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PeopleFormComponent } from './people-form.component';
describe('PeopleFormComponent', () => {
let component: PeopleFormComponent;
let fixture: ComponentFixture<PeopleFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PeopleFormComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PeopleFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PersonModel} from '../../models/person.model';
import {Router, RouterLink} from '@angular/router';
@Component({
selector: 'app-people-form',
templateUrl: './people-form.component.html',
styleUrls: ['./people-form.component.scss']
})
export class PeopleFormComponent {
public activePerson: PersonModel;
@Output()
public readonly modify: EventEmitter<PersonModel>;
@Output()
public readonly clean: EventEmitter<never>;
public name: string;
public surname: string;
public constructor(private readonly router: Router) {
this.modify = new EventEmitter<PersonModel>();
this.clean = new EventEmitter<never>();
}
@Input()
public set person(person: PersonModel) {
this.activePerson = person;
this.name = person.name;
this.surname = person.surname;
}
public get person(): PersonModel {
return this.activePerson;
}
public onModify() {
this.modify.emit({
id: this.person.id,
name: this.name,
surname: this.surname
});
}
public onClean() {
this.clean.emit();
}
public onPet() {
this.router.navigate(['/pets']);
}
}
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<table id="people-list" class="table">
<thead>
<tr class="row">
<th class="col-sm-4">Nombre</th>
<th class="col-sm-5">Apellido</th>
<th class="col-sm-3">&nbsp;</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of people" class="row" id="person-{{person.id}}">
<td class="col-sm-4 name">{{person.name}}</td>
<td class="col-sm-5 surname">{{person.surname}}</td>
<td class="col-sm-3">
<button class="btn btn-primary edit" (click)="onEdit(person)">Edit</button>
<button class="btn btn-warning delete" (click)="onDelete(person)">Delete</button>
</td>
</tr>
</tbody>
</table>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PeopleListComponent } from './people-list.component';
describe('PeopleListComponent', () => {
let component: PeopleListComponent;
let fixture: ComponentFixture<PeopleListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PeopleListComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PeopleListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PersonModel} from '../../models/person.model';
import {Router, RouterLink} from '@angular/router';
import {PeopleService} from '../../services/people.service';
import {PetService} from '../../../pet/services/pet.service';
import { PetModel } from 'src/app/modules/pet/models/pet.model';
@Component({
selector: 'app-people-list',
templateUrl: './people-list.component.html',
styleUrls: ['./people-list.component.scss']
})
export class PeopleListComponent {
@Input()
public people: PersonModel[] = [];
@Output()
public readonly edit: EventEmitter<PersonModel>;
@Output()
public readonly delete: EventEmitter<PersonModel>;
public pet: PetModel[];
public constructor(private readonly petService: PetService, private readonly router: Router) {
this.edit = new EventEmitter<PersonModel>();
this.delete = new EventEmitter<PersonModel>();
//this.onPet = new
}
public onEdit(person: PersonModel) {
this.edit.emit(person);
}
public onDelete(person: PersonModel) {
this.delete.emit(person);
}
public onPet(person: PersonModel) {
this.router.navigate(['/pet']);
console.log(person.id);
}
}
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<h1 class="display-5 mt-3 mb-3">Personas</h1>
<app-people-form [person]="activePerson" (clean)="onCleanForm()" (modify)="onModifyForm($event)"></app-people-form>
<app-people-list [people]="people" (edit)="onEdit($event)" (delete)="onDelete($event)" (pet)="onPet($event)"></app-people-list>
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PeopleMainComponent } from './people-main.component';
describe('PeopleMainComponent', () => {
let component: PeopleMainComponent;
let fixture: ComponentFixture<PeopleMainComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PeopleMainComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PeopleMainComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { Component, OnInit } from '@angular/core';
import {PersonModel} from '../../models/person.model';
import {PeopleService} from '../../services/people.service';
import {map, mergeMap} from 'rxjs/operators';
@Component({
selector: 'app-people-main',
templateUrl: './people-main.component.html',
styleUrls: ['./people-main.component.scss']
})
export class PeopleMainComponent implements OnInit {
public activePerson: PersonModel;
public people: PersonModel[];
public constructor(
private readonly peopleService: PeopleService
) {
this.people = [];
this.clearActivePerson();
}
public ngOnInit(): void {
this.peopleService.list()
.subscribe(people => this.people = people);
}
public onEdit(person: PersonModel): void {
this.activePerson = person;
}
public onDelete(person: PersonModel): void {
if (confirm(`¿Estás seguro de que deseas eliminar a ${person.name} ${person.surname}?`)) {
this.peopleService.delete(person)
.pipe(
mergeMap(() => this.peopleService.list())
)
.subscribe(people => this.people = people);
}
}
public onCleanForm(): void {
this.clearActivePerson();
}
public onModifyForm(person: PersonModel): void {
if (person.id === undefined) {
this.peopleService.create(person)
.pipe(
mergeMap(() => this.peopleService.list())
)
.subscribe(people => {
this.people = people;
this.clearActivePerson();
});
} else {
this.peopleService.modify(person)
.pipe(
mergeMap(() => this.peopleService.list())
)
.subscribe(people => {
this.people = people;
this.clearActivePerson();
});
}
}
private clearActivePerson(): void {
this.activePerson = { id: undefined, name: '', surname: '' };
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
export class PersonModel {
id?: number;
name: string;
surname: string;
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {PeopleMainComponent} from './components/people-main/people-main.component';
const routes: Routes = [
{
path: '',
component: PeopleMainComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PeopleRoutingModule { }
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {PeopleRoutingModule} from './people-routing.module';
import {PeopleListComponent} from './components/people-list/people-list.component';
import {PeopleFormComponent} from './components/people-form/people-form.component';
import {PeopleMainComponent} from './components/people-main/people-main.component';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
PeopleFormComponent,
PeopleListComponent,
PeopleMainComponent
],
imports: [
CommonModule,
FormsModule,
PeopleRoutingModule
]
})
export class PeopleModule {
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { TestBed } from '@angular/core/testing';
import { PeopleService } from './people.service';
describe('PeopleService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: PeopleService = TestBed.get(PeopleService);
expect(service).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {environment} from '../../../../environments/environment';
import {Observable} from 'rxjs';
import {PersonModel} from '../models/person.model';
@Injectable({
providedIn: 'root'
})
export class PeopleService {
public constructor(private readonly http: HttpClient) { }
public list(): Observable<PersonModel[]> {
return this.http.get<PersonModel[]>(`${environment.restApi}/people`);
}
public create(person: PersonModel): Observable<PersonModel> {
const data = new HttpParams()
.set('name', person.name)
.set('surname', person.surname);
return this.http.post<PersonModel>(`${environment.restApi}/people`, data);
}
public modify(person: PersonModel): Observable<PersonModel> {
const data = new HttpParams()
.set('name', person.name)
.set('surname', person.surname);
return this.http.put<PersonModel>(`${environment.restApi}/people/${person.id}`, data);
}
public delete(person: PersonModel): Observable<number> {
return this.http.delete<number>(`${environment.restApi}/people/${person.id}`);
}
}
<form id="pet-form" class="mb-5 mb-10">
<input name="id" type="hidden" value=""/>
<div class="row">
<div class="col-sm-5">
<input name="name" type="text" value="" placeholder="Nombre" class="form-control" required
[(ngModel)]="name"/>
</div>
<div class="col-sm-5">
<select name = "selectpersonas" [(ngModel)]="owner" *ngIf="pet.id === undefined">
<option [value]="person.id" *ngFor="let person of people">{{person.name}} {{person.surname}}</option>
</select>
</div>
<div class="col-sm-3">
<button type="button" id="btnSubmit" class="btn btn-primary"
(click)="onModify()">{{pet.id === undefined ? 'Crear' : 'Editar'}}</button>
<button type="button" id="btnClear" class="btn" (click)="onClean()">Limpiar</button>
</div>
</div>
</form>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PetFormComponent } from './pet-form.component';
describe('PetFormComponent', () => {
let component: PetFormComponent;
let fixture: ComponentFixture<PetFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PetFormComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PetFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
\ No newline at end of file
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PetModel} from '../../models/pet.model';
import { PersonModel } from 'src/app/modules/people/models/person.model';
@Component({
selector: 'app-pet-form',
templateUrl: './pet-form.component.html',
styleUrls: ['./pet-form.component.scss']
})
export class PetFormComponent {
public activePet: PetModel;
@Output()
public readonly modify: EventEmitter<PetModel>;
@Output()
public readonly clean: EventEmitter<never>;
public name: string;
public owner: string;
public constructor() {
this.modify = new EventEmitter<PetModel>();
this.clean = new EventEmitter<never>();
}
@Input()
public people: PersonModel[] = [];
@Input()
public set pet(pet: PetModel) {
this.activePet = pet;
this.name = pet.name;
this.owner = pet.owner;
}
public get pet(): PetModel {
return this.activePet;
}
public onModify() {
this.modify.emit({
id: this.pet.id,
name: this.name,
owner: this.owner
});
}
public onClean() {
this.clean.emit();
}
}
\ No newline at end of file
<table id="pet-list" class="table">
<thead>
<tr class="row">
<th class="col-sm-4">Nombre</th>
<th class="col-sm-3">&nbsp;</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let pet of pet" class="row" id="pet-{{pet.id}}">
<td class="col-sm-4 name">{{pet.name}}</td>
<td class="col-sm-3">
<button class="btn btn-primary edit" (click)="onEdit(pet)">Edit</button>
<button class="btn btn-warning delete" (click)="onDelete(pet)">Delete</button>
</td>
</tr>
</tbody>
</table>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PetListComponent } from './pet-list.component';
describe('PeopleListComponent', () => {
let component: PetListComponent;
let fixture: ComponentFixture<PetListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PetListComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PetListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
\ No newline at end of file
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PetModel} from '../../models/pet.model';
import {PetService} from '../../services/pet.service';
import {PersonModel} from '../../../people/models/person.model';
import {PeopleService} from '../../../people/services/people.service';
@Component({
selector: 'app-pet-list',
templateUrl: './pet-list.component.html',
styleUrls: ['./pet-list.component.scss']
})
export class PetListComponent {
@Input()
public pet: PetModel[] = [];
@Output()
public readonly edit: EventEmitter<PetModel>;
@Output()
public readonly delete: EventEmitter<PetModel>;
public constructor() {
this.edit = new EventEmitter<PetModel>();
this.delete = new EventEmitter<PetModel>();
}
public onEdit(pet: PetModel) {
this.edit.emit(pet);
}
public onDelete(pet: PetModel) {
this.delete.emit(pet);
}
}
\ No newline at end of file
<h1 class="display-5 mt-3 mb-3">Mascotas</h1>
<app-pet-form [pet]="activePet" [people]="people" (clean)="onCleanForm()" (modify)="onModifyForm($event)"></app-pet-form>
<app-pet-list [pet]="pet" (edit)="onEdit($event)" (delete)="onDelete($event)"></app-pet-list>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PetMainComponent } from './pet-main.component';
describe('PetMainComponent', () => {
let component: PetMainComponent;
let fixture: ComponentFixture<PetMainComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PetMainComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PetMainComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
\ No newline at end of file
import { Component, OnInit } from '@angular/core';
import {PetModel} from '../../models/pet.model';
import {PetService} from '../../services/pet.service';
import {PersonModel} from '../../../people/models/person.model';
import {map, mergeMap} from 'rxjs/operators';
import { PeopleService } from 'src/app/modules/people/services/people.service';
@Component({
selector: 'app-pet-main',
templateUrl: './pet-main.component.html',
styleUrls: ['./pet-main.component.scss']
})
export class PetMainComponent implements OnInit {
public activePet: PetModel;
public pet: PetModel[];
public people: PersonModel[];
public constructor(
private readonly petService: PetService,
private readonly peopleSevice: PeopleService
) {
this.pet = [];
this.clearActivePet();
}
public ngOnInit(): void {
//console.log("aqui estamos");
this.petService.list()
.subscribe(pet => this.pet = pet);
this.peopleSevice.list()
.subscribe(people => this.people = people)
}
public onEdit(pet: PetModel): void {
this.activePet = pet;
}
public onCleanForm(): void {
this.clearActivePet();
}
private clearActivePet(): void {
this.activePet = { id: undefined, name: '', owner: undefined};
}
public onModifyForm(pet: PetModel): void {
if (pet.id === undefined) {
console.log(pet);
this.petService.create(pet)
.pipe(
mergeMap(() => this.petService.list())
)
.subscribe(pet => {
this.pet = pet;
this.clearActivePet();
});
} else {
this.petService.modify(pet)
.pipe(
mergeMap(() => this.petService.list())
)
.subscribe(pet => {
this.pet = pet;
this.clearActivePet();
});
}
}
public onDelete(pet: PetModel): void {
if (confirm(`¿Estás seguro de que deseas eliminar a ${pet.name}?`)) {
this.petService.delete(pet)
.pipe(
mergeMap(() => this.petService.list())
)
.subscribe(pet => this.pet = pet);
}
}
}
export class PetModel {
id?: number;
name: string;
owner: string;
}
\ No newline at end of file
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {PetMainComponent} from './components/pet-main/pet-main.component';
const routes: Routes = [
{
path: '',
component: PetMainComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PetRoutingModule { }
\ No newline at end of file
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {PetRoutingModule} from './pet-routing.module';
import {PetListComponent} from './components/pet-list/pet-list.component';
import {PetFormComponent} from './components/pet-form/pet-form.component';
import {PetMainComponent} from './components/pet-main/pet-main.component';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
PetFormComponent,
PetListComponent,
PetMainComponent
],
imports: [
CommonModule,
FormsModule,
PetRoutingModule
]
})
export class PetModule {
}
\ No newline at end of file
import { TestBed } from '@angular/core/testing';
import { PetService } from './pet.service';
describe('PetService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: PetService = TestBed.get(PetService);
expect(service).toBeTruthy();
});
});
\ No newline at end of file
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {environment} from '../../../../environments/environment';
import {Observable} from 'rxjs';
import {PetModel} from '../models/pet.model';
@Injectable({
providedIn: 'root'
})
export class PetService {
public constructor(private readonly http: HttpClient) { }
public list(/*idpersona: number*/): Observable<PetModel[]> {
return this.http.get<PetModel[]>(`${environment.restApi}/pet`);// esto despues de pet /${idpersona}
}
public create(pet: PetModel): Observable<PetModel> {
//console.log(pet);
const data = new HttpParams()
.set('name', pet.name)
.set('owner',pet.owner);
return this.http.post<PetModel>(`${environment.restApi}/pet`, data);
}
public modify(pet: PetModel): Observable<PetModel> {
//console.log(pet);
const data = new HttpParams()
.set('name', pet.name)
.set('owner',pet.owner);
return this.http.put<PetModel>(`${environment.restApi}/pet/${pet.id}`, data);
}
public delete(pet: PetModel): Observable<number> {
return this.http.delete<number>(`${environment.restApi}/pet/${pet.id}`);
}
}
\ No newline at end of file
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { TestBed } from '@angular/core/testing';
import { AuthenticationService } from './authentication.service';
describe('AuthenticationService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AuthenticationService = TestBed.get(AuthenticationService);
expect(service).toBeTruthy();
});
});
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {UserModel} from '../models';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {catchError, tap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private static readonly USER_STORAGE_KEY = 'user';
private readonly _loggedUser$: BehaviorSubject<UserModel | null>;
private static clearCredentials(): void {
localStorage.removeItem(AuthenticationService.USER_STORAGE_KEY);
}
private static loadCredentials(): UserModel | null {
const serializedCredentials = localStorage.getItem(AuthenticationService.USER_STORAGE_KEY);
if (serializedCredentials !== null) {
return JSON.parse(serializedCredentials);
} else {
return null;
}
}
private static storeCredentials(login: string, password: string): void {
const credentials: UserModel = {login, password};
localStorage.setItem(AuthenticationService.USER_STORAGE_KEY, JSON.stringify(credentials));
}
public constructor(
private readonly http: HttpClient
) {
this._loggedUser$ = new BehaviorSubject<UserModel | null>(null);
}
public get loggedUser$(): Observable<UserModel | null> {
return this._loggedUser$.asObservable();
}
public get loggedUser(): UserModel | null {
return this._loggedUser$.value;
}
public isLogged(): boolean {
return this.loggedUser !== null;
}
public logout(): void {
AuthenticationService.clearCredentials();
this._loggedUser$.next(null);
}
public tryLoginWithStoredCredentials(): Observable<UserModel | null> {
const credentials = AuthenticationService.loadCredentials();
if (credentials !== null) {
return this.tryLogin(credentials);
} else {
return of<UserModel | null>(null);
}
}
public tryLogin(login: UserModel): Observable<UserModel | null>;
public tryLogin(login: string, password: string): Observable<UserModel | null>;
public tryLogin(login: string | UserModel, password?: string): Observable<UserModel> {
let userLogin: string;
let userPassword: string;
if (typeof login === 'string') {
if (password === undefined) {
throw new TypeError('password can\'t be null when login is string');
}
userLogin = login;
userPassword = password;
} else {
userLogin = login.login;
userPassword = login.password;
}
AuthenticationService.storeCredentials(userLogin, userPassword);
const headers = new HttpHeaders()
.set('Authorization', 'Basic ' + btoa(userLogin + ':' + userPassword));
return this.http.get<never>(`${environment.restApi}/users/${userLogin}`, {
headers: headers
})
.pipe(
tap(user => this._loggedUser$.next({
login: userLogin,
password: userPassword
})),
catchError(error => {
this._loggedUser$.next(null);
throw error;
})
);
}
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
export const environment = {
production: true,
restApi: 'http://daaexample.com:9080/DAAExample/rest'
};
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
restApi: 'http://localhost:9080/DAAExample/rest'
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
<!--
~ DAA Example
~
~ Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DAA Example</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
/**
* If the application will be indexed by Google Search, the following is required.
* Googlebot uses a renderer based on Chrome 41.
* https://developers.google.com/search/docs/guides/rendering
**/
// import 'core-js/es6/array';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
**/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
*/
// (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
// (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
// (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
/*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*/
// (window as any).__Zone_enable_cross_context_check = true;
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
/*!
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
/* You can add global styles to this file, and also import other style files */
html, body {
height: 100%;
}
/*
* DAA Example
*
* Copyright (C) 2019 - 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 <http://www.gnu.org/licenses/>.
*/
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"test.ts",
"polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
{
"extends": "../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
]
}
}
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"downlevelIteration": true,
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "esnext",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}
{
"rulesDirectory": [
"node_modules/codelyzer"
],
"rules": {
"arrow-return-shorthand": true,
"callable-types": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"curly": true,
"deprecation": {
"severity": "warn"
},
"eofline": true,
"forin": true,
"import-blacklist": [
true,
"rxjs/Rx"
],
"import-spacing": true,
"indent": [
true,
"spaces"
],
"interface-over-type-literal": true,
"label-position": true,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-arg": true,
"no-bitwise": true,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-super": true,
"no-empty": false,
"no-empty-interface": true,
"no-eval": true,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-misused-new": true,
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unnecessary-initializer": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-var-keyword": true,
"object-literal-sort-keys": false,
"one-line": [
true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
"prefer-const": true,
"quotemark": [
true,
"single"
],
"radix": true,
"semicolon": [
true,
"always"
],
"triple-equals": [
true,
"allow-null-check"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"unified-signatures": true,
"variable-name": false,
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
],
"no-output-on-prefix": true,
"no-inputs-metadata-property": true,
"no-outputs-metadata-property": true,
"no-host-metadata-property": true,
"no-input-rename": true,
"no-output-rename": true,
"use-lifecycle-interface": true,
"use-pipe-transform-interface": true,
"component-class-suffix": true,
"directive-class-suffix": true
}
}
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.PetResource;
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<Class<?>> getClasses() {
return Stream.of(
PeopleResource.class,
UsersResource.class,
PetResource.class
).collect(toSet());
}
@Override
public Map<String, Object> getProperties() {
// Activates JSON automatic conversion in JAX-RS
return Collections.singletonMap(
"com.sun.jersey.api.json.POJOMappingFeature", true
);
}
}
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();
}
}
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.
*
* <p>Note that the detail message associated with {@code cause} is
* <i>not</i> 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);
}
}
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<Person> 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<Person> 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")
);
}
}
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.Pet;
public class PetDAO extends DAO {
private final static Logger LOG = Logger.getLogger(PetDAO.class.getName());
/**
* Returns a person stored persisted in the system.
*
* @param id identifier of the pet.
* @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 Pet get(int id)
throws DAOException, IllegalArgumentException {
try (final Connection conn = this.getConnection()) {
final String query = "SELECT * FROM pet 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 pet", 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<Pet> list() throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "SELECT * FROM pet";
//console.log("aqui estamos");
try (final PreparedStatement statement = conn.prepareStatement(query)) {
try (final ResultSet result = statement.executeQuery()) {
final List<Pet> pet = new LinkedList<>();
while (result.next()) {
pet.add(rowToEntity(result));
}
return pet;
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error listing pet", 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 owner 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 Pet add(String name, String owner)
throws DAOException, IllegalArgumentException {
if (name == null || owner == null) {
throw new IllegalArgumentException("name and owner can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "INSERT INTO pet VALUES(null, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, name);
statement.setString(2, owner);
if (statement.executeUpdate() == 1) {
try (ResultSet resultKeys = statement.getGeneratedKeys()) {
if (resultKeys.next()) {
return new Pet(resultKeys.getInt(1), name, owner);
} 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 pet", 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 pet 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(Pet pet)
throws DAOException, IllegalArgumentException {
if (pet == null) {
throw new IllegalArgumentException("pet can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "UPDATE pet SET name=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, pet.getName());
statement.setInt(2, pet.getId());
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name and owner can't be null");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error modifying a pet", 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 pet 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 pet", e);
throw new DAOException(e);
}
}
private Pet rowToEntity(ResultSet row) throws SQLException {
return new Pet(
row.getInt("id"),
row.getString("name"),
row.getString("owner")
);
}
}
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.
*
* <p>The password is stored in the system "salted" and encoded with the
* SHA-256 algorithm.</p>
*
* @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")
);
}
}
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;
}
}
package es.uvigo.esei.daa.entities;
import static java.util.Objects.requireNonNull;
/**
* An entity that represents a person.
*
* @author Miguel Reboiro Jato
*/
public class Pet {
private int id;
private String name;
private String owner;
// Constructor needed for the JSON conversion
Pet() {}
/**
* 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 Pet(int id, String name, String owner) {
this.id = id;
this.setName(name);
this.setOwner(owner);
}
/**
* 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 getOwner() {
return owner;
}
/**
* Set the surname of this person.
*
* @param owner the new surname of the person.
* @throws NullPointerException if the {@code owner} is {@code null}.
*/
public void setOwner(String owner) {
this.owner = requireNonNull(owner, "owner 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 Pet))
return false;
Pet other = (Pet) obj;
if (id != other.id)
return false;
return true;
}
}
\ No newline at end of file
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");
}
}
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();
}
}
}
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.PetDAO;
import es.uvigo.esei.daa.entities.Pet;
/**
* REST resource for managing people.
*
* @author Miguel Reboiro Jato.
*/
@Path("/pet")
@Produces(MediaType.APPLICATION_JSON)
public class PetResource {
private final static Logger LOG = Logger.getLogger(PetResource.class.getName());
private final PetDAO dao;
/**
* Constructs a new instance of {@link PeopleResource}.
*/
public PetResource() {
this(new PetDAO());
}
// Needed for testing purposes
PetResource(PetDAO 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 Pet pet = this.dao.get(id);
return Response.ok(pet).build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet 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 pet", 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 pet", 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("owner") String owner
) {
try {
final Pet newPet = this.dao.add(name, owner);
return Response.ok(newPet).build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet 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 pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
/**
* Modifies the data of a pet.
*
* @param id identifier of the person to modify.
* @param name the new name of the person.
* @param owner 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("owner") String owner
) {
try {
final Pet modifiedPet = new Pet(id, name, owner);
this.dao.modify(modifiedPet);
return Response.ok(modifiedPet).build();
} catch (NullPointerException npe) {
final String message = String.format("Invalid data for pet (name: %s)", name);
LOG.log(Level.FINE, message);
return Response.status(Response.Status.BAD_REQUEST)
.entity(message)
.build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet 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 pet", 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 pet 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 pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
}
\ No newline at end of file
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");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>DAAExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, DELETE, PUT</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/rest/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>/rest/people/*</url-pattern>
<http-method>GET</http-method>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<!-- Security roles referenced by this web application -->
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<role-name>USER</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>DAAExample</realm-name>
</login-config>
</web-app>
\ No newline at end of file
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<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>(super.getClasses());
classes.add(AuthorizationFilter.class);
return unmodifiableSet(classes);
}
}
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);
}
}
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());
}
}
package es.uvigo.esei.daa.dao;
import static org.junit.Assert.*;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import javax.sql.DataSource;
import org.junit.Before;
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.listeners.ApplicationContextBinding;
import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
import es.uvigo.esei.daa.listeners.DbManagement;
import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
//////////////////////////////////////
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetInAnyOrder;
import es.uvigo.esei.daa.entities.Pet;
import static es.uvigo.esei.daa.dataset.PetDataset.existentId;
import static es.uvigo.esei.daa.dataset.PetDataset.existentPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newName;
import static es.uvigo.esei.daa.dataset.PetDataset.newPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newOwner;
import static es.uvigo.esei.daa.dataset.PetDataset.nonExistentId;
import static es.uvigo.esei.daa.dataset.PetDataset.nonExistentPet;
import static es.uvigo.esei.daa.dataset.PetDataset.pet;
import static es.uvigo.esei.daa.dataset.PetDataset.petWithout;
@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 PetDAOTest {
private PetDAO dao;
@Before
public void setUp() throws Exception {
this.dao = new PetDAO();
}
@Test
public void testList() throws DAOException {
assertThat(this.dao.list(), containsPetInAnyOrder(pet()));
}
@Test
public void testGet() throws DAOException {
final Pet pet = this.dao.get(existentId());
assertThat(pet, is(equalsToPet(existentPet())));
}
@Test(expected = IllegalArgumentException.class)
public void testGetNonExistentId() throws DAOException {
this.dao.get(nonExistentId());
}
@Test
@ExpectedDatabase("/datasets/dataset-delete-pet.xml")
public void testDelete() throws DAOException {
this.dao.delete(existentId());
assertThat(this.dao.list(), containsPetInAnyOrder(petWithout(existentId())));
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteNonExistentId() throws DAOException {
this.dao.delete(nonExistentId());
}
@Test
@ExpectedDatabase("/datasets/dataset-modify-pet.xml")
public void testModify() throws DAOException {
final Pet pet = existentPet();
pet.setName(newName());
pet.setOwner(newOwner());
this.dao.modify(pet);
final Pet persistentPet = this.dao.get(pet.getId());
assertThat(persistentPet, is(equalsToPet(pet)));
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNonExistentId() throws DAOException {
this.dao.modify(nonExistentPet());
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullPet() throws DAOException {
this.dao.modify(null);
}
@Test
@ExpectedDatabase("/datasets/dataset-add-pet.xml")
public void testAdd() throws DAOException {
final Pet pet = this.dao.add(newName(), newOwner());
assertThat(pet, is(equalsToPet(newPet())));
final Pet persistentPet = this.dao.get(pet.getId());
assertThat(persistentPet, is(equalsToPet(newPet())));
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullName() throws DAOException {
this.dao.add(null, newOwner());
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullowner() throws DAOException {
this.dao.add(newName(), null);
}
}
package es.uvigo.esei.daa.dao;
import static org.junit.Assert.*;
import org.junit.Test;
import static es.uvigo.esei.daa.dataset.PetDataset.existentId;
import static es.uvigo.esei.daa.dataset.PetDataset.existentPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newName;
import static es.uvigo.esei.daa.dataset.PetDataset.newPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newOwner;
import static es.uvigo.esei.daa.dataset.PetDataset.pet;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
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.Pet;
import es.uvigo.esei.daa.util.DatabaseQueryUnitTest;
public class PetDAOUnitTest extends DatabaseQueryUnitTest {
@Test
public void testList() throws Exception {
final Pet[] pets = pet();
for (Pet pet : pets) {
expectPetRow(pet);
}
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
assertThat(petDAO.list(), containsPetInAnyOrder(pets));
}
@Test(expected = DAOException.class)
public void testListUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.list();
}
@Test
public void testGet() throws Exception {
final Pet existentPet = existentPet();
expectPetRow(existentPet);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
assertThat(petDAO.get(existentId()), is(equalTo(existentPet)));
}
@Test(expected = IllegalArgumentException.class)
public void testGetMissing() throws Exception {
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.get(existentId());
}
@Test(expected = DAOException.class)
public void testGetUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.get(existentId());
}
@Test
public void testAdd() throws Exception {
final Pet pet = newPet();
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(pet.getId());
connection.close();
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
final Pet newPet = petDAO.add(pet.getName(), pet.getOwner());
assertThat(newPet, is(equalsToPet(pet)));
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullName() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.add(null, newOwner());
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullOwner() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.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 PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newOwner());
}
@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 PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newOwner());
}
@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 PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newOwner());
}
@Test
public void testDelete() throws Exception {
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteInvalidId() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test(expected = DAOException.class)
public void testDeleteUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test
public void testModify() throws Exception {
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullPet() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.modify(null);
}
@Test(expected = IllegalArgumentException.class)
public void testModifyZeroUpdatedRows() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
@Test(expected = DAOException.class)
public void testModifyUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
private void expectPetRow(Pet pet) throws SQLException {
expect(result.next()).andReturn(true);
expect(result.getInt("id")).andReturn(pet.getId());
expect(result.getString("name")).andReturn(pet.getName());
expect(result.getString("owner")).andReturn(pet.getOwner());
}
}
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<Person> 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());
}
}
package es.uvigo.esei.daa.dataset;
import static org.junit.Assert.*;
import org.junit.Test;
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.Pet;
public final class PetDataset {
private PetDataset() {}
public static Pet[] pet() {
return new Pet[] {
new Pet(1, "Antón", "1"),
new Pet(2, "Ana", "2"),
new Pet(3, "Manuel", "3"),
new Pet(4, "María", "4"),
new Pet(5, "Lorenzo", "5"),
new Pet(6, "Laura", "6"),
new Pet(7, "Perico", "7"),
new Pet(8, "Patricia", "8"),
new Pet(9, "Julia", "9"),
new Pet(10, "Juan", "10")
};
}
public static Pet[] petWithout(int ... ids) {
Arrays.sort(ids);
final Predicate<Pet> hasValidId = pet ->
binarySearch(ids, pet.getId()) < 0;
return stream(pet())
.filter(hasValidId)
.toArray(Pet[]::new);
}
public static Pet pet(int id) {
return stream(pet())
.filter(pet -> pet.getId() == id)
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
public static int existentId() {
return 5;
}
public static int nonExistentId() {
return 1234;
}
public static Pet existentPet() {
return pet(existentId());
}
public static Pet nonExistentPet() {
return new Pet(nonExistentId(), "Jane", "13");
}
public static String newName() {
return "John";
}
public static String newOwner() {
return "5";
}
public static Pet newPet() {
return new Pet(pet().length + 1, newName(), newOwner());
}
}
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());
}
}
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();
}
}
package es.uvigo.esei.daa.entities;
import static org.junit.Assert.*;
import org.junit.Test;
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 PetUnitTest {
@Test
public void testPetIntStringString() {
final int id = 1;
final String name = "John";
final String owner = "5";
final Person pet = new Person(id, name, owner);
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getSurname(), is(equalTo(owner)));
}
@Test(expected = NullPointerException.class)
public void testPetIntStringStringNullName() {
new Pet(1, null, "Doe");
}
@Test(expected = NullPointerException.class)
public void testPetIntStringStringNullOwner() {
new Pet(1, "John", null);
}
@Test
public void testSetName() {
final int id = 1;
final String owner = "Doe";
final Pet pet = new Pet(id, "John", owner);
pet.setName("Juan");
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo("Juan")));
assertThat(pet.getOwner(), is(equalTo(owner)));
}
@Test(expected = NullPointerException.class)
public void testSetNullName() {
final Pet pet = new Pet(1, "John", "5");
pet.setName(null);
}
@Test
public void testSetOwner() {
final int id = 1;
final String name = "John";
final Pet pet = new Pet(id, name, "5");
pet.setOwner("Dolores");
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getOwner(), is(equalTo("Dolores")));
}
@Test(expected = NullPointerException.class)
public void testSetNullOwner() {
final Pet pet = new Pet(1, "John", "5");
pet.setOwner(null);
}
@Test
public void testEqualsObject() {
final Pet petA = new Pet(1, "Name A", "Surname A");
final Pet petB = new Pet(1, "Name B", "Surname B");
assertTrue(petA.equals(petB));
}
@Test
public void testEqualsHashcode() {
EqualsVerifier.forClass(Pet.class)
.withIgnoredFields("name", "owner")
.suppress(Warning.STRICT_INHERITANCE)
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
package es.uvigo.esei.daa.filters;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
import java.util.List;
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.PathSegment;
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;
/**
* This performs the Basic HTTP authentication following (almost) the same
* rules as the defined in the web.xml file.
*
* @author Miguel Reboiro Jato
*/
@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]);
if (isPeoplePath(requestContext) && !user.getRole().equals("ADMIN")) {
requestContext.abortWith(createResponse());
} else {
if (isPetPath(requestContext) && !user.getRole().equals("ADMIN")) {
requestContext.abortWith(createResponse());
}
else{requestContext.setSecurityContext(new UserSecurityContext(user));
}
}
} else {
requestContext.abortWith(createResponse());
}
} catch (DAOException e) {
requestContext.abortWith(createResponse());
}
} else {
requestContext.abortWith(createResponse());
}
}
}
private static boolean isPeoplePath(ContainerRequestContext context) {
final List<PathSegment> pathSegments = context.getUriInfo().getPathSegments();
return !pathSegments.isEmpty() && pathSegments.get(0).getPath().equals("people");
}
private static boolean isPetPath(ContainerRequestContext context) {
final List<PathSegment> pathSegments = context.getUriInfo().getPathSegments();
return !pathSegments.isEmpty() && pathSegments.get(0).getPath().equals("pet");
}
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;
}
}
}
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 {}
}
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();
}
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;
}
}
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;
}
package es.uvigo.esei.daa.listeners;
public enum DbManagementAction {
DROP_CREATE_DROP, CREATE_DROP, ONLY_CREATE, ONLY_DROP;
}
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)));
}
}
}
/*
* #%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
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #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<Response> {
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<Response> hasHttpStatus(StatusType expectedStatus) {
return new HasHttpStatus(expectedStatus);
}
@Factory
public static Matcher<Response> hasHttpStatus(int expectedStatus) {
return new HasHttpStatus(expectedStatus);
}
@Factory
public static Matcher<Response> hasOkStatus() {
return new HasHttpStatus(Response.Status.OK);
}
@Factory
public static Matcher<Response> hasBadRequestStatus() {
return new HasHttpStatus(Response.Status.BAD_REQUEST);
}
@Factory
public static Matcher<Response> hasInternalServerErrorStatus() {
return new HasHttpStatus(Response.Status.INTERNAL_SERVER_ERROR);
}
@Factory
public static Matcher<Response> hasUnauthorized() {
return new HasHttpStatus(Response.Status.UNAUTHORIZED);
}
@Factory
public static Matcher<Response> hasForbidden() {
return new HasHttpStatus(Response.Status.FORBIDDEN);
}
}
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 <T> the type of the entities to be matched.
*/
public abstract class IsEqualToEntity<T> extends TypeSafeMatcher<T> {
/**
* The expected entity.
*/
protected final T expected;
private Consumer<Description> 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:
* <p>
* {@code <expected class> entity with value '<expected>' for <attribute>}
* </p>
*
* @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 <R> boolean checkAttribute(
final String attribute,
final Function<T, R> getter, final T actual,
final Function<R, Matcher<R>> 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<R> 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 <R> 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 <R> boolean checkArrayAttribute(
final String attribute,
final Function<T, R[]> getter, final T actual,
final Function<R[], Matcher<Iterable<? extends R>>> 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<Iterable<? extends R>> 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 <R> 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 <R> boolean checkIterableAttribute(
final String attribute,
final Function<T, Iterable<R>> getter, final T actual,
final Function<Iterable<R>, Matcher<Iterable<? extends R>>> matcherFactory
) {
final Iterable<R> expectedValue = getter.apply(this.expected);
final Iterable<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<Iterable<? extends R>> 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 <R> 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 <R> boolean checkAttribute(
final String attribute, final Function<T, R> 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 <R> 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 <R> boolean checkArrayAttribute(
final String attribute, final Function<T, R[]> 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 <R> 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<T, int[]> 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 <T> type of the entity.
* @return a new {@link Matcher} that compares several entities.
*/
@SafeVarargs
protected static <T> Matcher<Iterable<? extends T>> containsEntityInAnyOrder(
final Function<T, Matcher<? super T>> converter, final T ... entities
) {
final Collection<Matcher<? super T>> 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 <T> type of the entity.
* @return a new {@link Matcher} that compares several entities.
*/
protected static <T> Matcher<Iterable<? extends T>> containsEntityInAnyOrder(
final Function<T, Matcher<? super T>> converter, final Iterable<T> entities
) {
final Collection<Matcher<? super T>> 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 <T> The type of the entity.
*
* @return A new {@link Matcher} that compares several entities in the same
* received order.
*/
@SafeVarargs
protected static <T> Matcher<Iterable<? extends T>> containsEntityInOrder(
final Function<T, Matcher<? super T>> 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 <T> The type of the entity.
*
* @return A new {@link Matcher} that compares several entities in the same
* received order.
*/
protected static <T> Matcher<Iterable<? extends T>> containsEntityInOrder(
final Function<T, Matcher<? super T>> converter, final Iterable<T> entities
) {
final List<Matcher<? super T>> matchersList =
StreamSupport.stream(entities.spliterator(), false)
.map(converter)
.collect(toList());
return contains(matchersList);
}
}
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<Person> {
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<Iterable<? extends Person>> containsPeopleInAnyOrder(Person ... persons) {
return containsEntityInAnyOrder(IsEqualToPerson::equalsToPerson, persons);
}
}
package es.uvigo.esei.daa.matchers;
import static org.junit.Assert.*;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import es.uvigo.esei.daa.entities.Pet;
public class IsEqualToPet extends IsEqualToEntity<Pet> {
public IsEqualToPet(Pet entity) {
super(entity);
}
@Override
protected boolean matchesSafely(Pet actual) {
this.clearDescribeTo();
if (actual == null) {
this.addTemplatedDescription("actual", expected.toString());
return false;
} else {
return checkAttribute("id", Pet::getId, actual)
&& checkAttribute("name", Pet::getName, actual)
&& checkAttribute("owner", Pet::getOwner, actual);
}
}
/**
* Factory method that creates a new {@link IsEqualToEntity} matcher with
* the provided {@link Pet} as the expected value.
*
* @param person the expected person.
* @return a new {@link IsEqualToEntity} matcher with the provided
* {@link Pet} as the expected value.
*/
@Factory
public static IsEqualToPet equalsToPet(Pet pet) {
return new IsEqualToPet(pet);
}
/**
* 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<Iterable<? extends Pet>> containsPetInAnyOrder(Pet ... pet) {
return containsEntityInAnyOrder(IsEqualToPet::equalsToPet, pet);
}
}
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<User> {
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<Iterable<? extends User>> containsPeopleInAnyOrder(User ... users) {
return containsEntityInAnyOrder(IsEqualToUser::equalsToUser, users);
}
}
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.dataset.UsersDataset.adminLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.normalLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.userToken;
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.HasHttpStatus.hasUnauthorized;
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.DAAExampleTestApplication;
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 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);
}
@Test
public void testList() throws IOException {
final Response response = target("people").request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final List<Person> people = response.readEntity(new GenericType<List<Person>>(){});
assertThat(people, containsPeopleInAnyOrder(people()));
}
@Test
public void testListUnauthorized() throws IOException {
final Response response = target("people").request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGet() throws IOException {
final Response response = target("people/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final Person person = response.readEntity(Person.class);
assertThat(person, is(equalsToPerson(existentPerson())));
}
@Test
public void testGetUnauthorized() throws IOException {
final Response response = target("people/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGetInvalidId() throws IOException {
final Response response = target("people/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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 testAddUnauthorized() 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)
.header("Authorization", "Basic " + userToken(normalLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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 testModifyUnauthorized() 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)
.header("Authorization", "Basic " + userToken(normalLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasOkStatus());
final Integer deletedId = response.readEntity(Integer.class);
assertThat(deletedId, is(equalTo(existentId())));
}
@Test
public void testDeleteUnauthorized() throws IOException {
final Response response = target("people/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.delete();
assertThat(response, hasUnauthorized());
}
@Test
public void testDeleteInvalidId() throws IOException {
final Response response = target("people/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasBadRequestStatus());
}
}
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<Person> people = asList(people());
expect(daoMock.list()).andReturn(people);
replay(daoMock);
final Response response = resource.list();
assertThat(response, hasOkStatus());
assertThat((List<Person>) 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());
}
}
package es.uvigo.esei.daa.rest;
import static org.junit.Assert.*;
import org.junit.Test;
import static es.uvigo.esei.daa.dataset.PetDataset.existentId;
import static es.uvigo.esei.daa.dataset.PetDataset.existentPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newName;
import static es.uvigo.esei.daa.dataset.PetDataset.newPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newOwner;
import static es.uvigo.esei.daa.dataset.PetDataset.nonExistentId;
import static es.uvigo.esei.daa.dataset.PetDataset.pet;
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.userToken;
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.HasHttpStatus.hasUnauthorized;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
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.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.Pet;
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 PetResourceTest 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);
}
@Test
public void testList() throws IOException {
final Response response = target("pet").request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final List<Pet> pet = response.readEntity(new GenericType<List<Pet>>(){});
assertThat(pet, containsPetInAnyOrder(pet()));
}
@Test
public void testListUnauthorized() throws IOException {
final Response response = target("pet").request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGet() throws IOException {
final Response response = target("pet/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(existentPet())));
}
@Test
public void testGetUnauthorized() throws IOException {
final Response response = target("pet/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGetInvalidId() throws IOException {
final Response response = target("pet/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-add-pet.xml")
public void testAdd() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("owner", newOwner());
final Response response = target("pet").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(newPet())));
}
@Test
public void testAddUnauthorized() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("owner", newOwner());
final Response response = target("pet").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(normalLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@Test
public void testAddMissingName() throws IOException {
final Form form = new Form();
form.param("owner", newOwner());
final Response response = target("pet").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
public void testAddMissingOwner() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("pet").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-modify-pet.xml")
public void testModify() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("owner", newOwner());
final Response response = target("pet/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet modifiedPet = response.readEntity(Pet.class);
final Pet pet = existentPet();
pet.setName(newName());
pet.setOwner(newOwner());
assertThat(modifiedPet, is(equalsToPet(pet)));
}
@Test
public void testModifyUnauthorized() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("owner", newOwner());
final Response response = target("pet/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(normalLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@Test
public void testModifyName() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("pet/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
public void testModifyOwner() throws IOException {
final Form form = new Form();
form.param("owner", newOwner());
final Response response = target("pet/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.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("owner", newOwner());
final Response response = target("pet/" + nonExistentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-delete-pet.xml")
public void testDelete() throws IOException {
final Response response = target("pet/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasOkStatus());
final Integer deletedId = response.readEntity(Integer.class);
assertThat(deletedId, is(equalTo(existentId())));
}
@Test
public void testDeleteUnauthorized() throws IOException {
final Response response = target("pet/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.delete();
assertThat(response, hasUnauthorized());
}
@Test
public void testDeleteInvalidId() throws IOException {
final Response response = target("pet/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasBadRequestStatus());
}
}
package es.uvigo.esei.daa.rest;
import static org.junit.Assert.*;
import org.junit.Test;
import static es.uvigo.esei.daa.dataset.PetDataset.existentId;
import static es.uvigo.esei.daa.dataset.PetDataset.existentPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newName;
import static es.uvigo.esei.daa.dataset.PetDataset.newPet;
import static es.uvigo.esei.daa.dataset.PetDataset.newOwner;
import static es.uvigo.esei.daa.dataset.PetDataset.pet;
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.IsEqualToPet.containsPetInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
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.PetDAO;
import es.uvigo.esei.daa.entities.Pet;
public class PetResourceUnitTest {
private PetDAO daoMock;
private PetResource resource;
@Before
public void setUp() throws Exception {
daoMock = createMock(PetDAO.class);
resource = new PetResource(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<Pet> pet = asList(pet());
expect(daoMock.list()).andReturn(pet);
replay(daoMock);
final Response response = resource.list();
assertThat(response, hasOkStatus());
assertThat((List<Pet>) response.getEntity(), containsPetInAnyOrder(pet()));
}
@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 Pet pet = existentPet();
expect(daoMock.get(pet.getId())).andReturn(pet);
replay(daoMock);
final Response response = resource.get(pet.getId());
assertThat(response, hasOkStatus());
assertThat((Pet) response.getEntity(), is(equalsToPet(pet)));
}
@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 Pet pet = existentPet();
pet.setName(newName());
pet.setOwner(newOwner());
daoMock.modify(pet);
replay(daoMock);
final Response response = resource.modify(
pet.getId(), pet.getName(), pet.getOwner());
assertThat(response, hasOkStatus());
assertEquals(pet, response.getEntity());
}
@Test
public void testModifyDAOException() throws Exception {
daoMock.modify(anyObject());
expectLastCall().andThrow(new DAOException());
replay(daoMock);
final Response response = resource.modify(existentId(), newName(), newOwner());
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(), newOwner());
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(), newOwner());
assertThat(response, hasBadRequestStatus());
}
@Test
public void testAdd() throws Exception {
expect(daoMock.add(newName(), newOwner()))
.andReturn(newPet());
replay(daoMock);
final Response response = resource.add(newName(), newOwner());
assertThat(response, hasOkStatus());
assertThat((Pet) response.getEntity(), is(equalsToPet(newPet())));
}
@Test
public void testAddDAOException() throws Exception {
expect(daoMock.add(anyString(), anyString()))
.andThrow(new DAOException());
replay(daoMock);
final Response response = resource.add(newName(), newOwner());
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(), newOwner());
assertThat(response, hasBadRequestStatus());
}
}
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.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.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);
}
@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());
}
}
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 {
}
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;
import es.uvigo.esei.daa.dao.PetDAOTest;
import es.uvigo.esei.daa.rest.PetResourceTest;
@SuiteClasses({
PeopleDAOTest.class,
PeopleResourceTest.class,
UsersResourceTest.class,
PetDAOTest.class,
PetResourceTest.class
})
@RunWith(Suite.class)
public class IntegrationTestSuite {
}
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;
import es.uvigo.esei.daa.dao.PetDAOUnitTest;
import es.uvigo.esei.daa.entities.PetUnitTest;
import es.uvigo.esei.daa.rest.PetResourceUnitTest;
@SuiteClasses({
PersonUnitTest.class,
PeopleDAOUnitTest.class,
PeopleResourceUnitTest.class,
PetUnitTest.class,
PetDAOUnitTest.class,
PetResourceUnitTest.class
})
@RunWith(Suite.class)
public class UnitTestSuite {
}
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();
}
}
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.
*
* <p>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.</p>
*
* @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;
}
}
}
package es.uvigo.esei.daa.util;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
/**
* Utility class to wait for several JavaScript events to complete.
*
* Code adapted from
* https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
*/
public class JSWaiter {
private final WebDriverWait jsWait;
private final JavascriptExecutor jsExec;
private JSWaiter(WebDriver driver) {
this.jsWait = new WebDriverWait(driver, 10);
this.jsExec = (JavascriptExecutor) driver;
}
public static JSWaiter wait(WebDriver driver) {
return new JSWaiter(driver);
}
public void untilAngular5Ready() {
try {
final Object angular5Check = jsExec.executeScript("return getAllAngularRootElements()[0].attributes['ng-version']");
if (angular5Check != null) {
final Boolean angularPageLoaded = (Boolean) jsExec
.executeScript("return window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1");
if (!angularPageLoaded) {
poll(20);
waitForAngular5Load();
poll(20);
}
}
} catch (WebDriverException ignored) {}
}
private void waitForAngular5Load() {
String angularReadyScript = "return window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1";
try {
final ExpectedCondition<Boolean> angularLoad = driver -> Boolean
.valueOf(((JavascriptExecutor) driver).executeScript(angularReadyScript).toString());
final boolean angularReady = Boolean.valueOf(jsExec.executeScript(angularReadyScript).toString());
if (!angularReady) {
jsWait.until(angularLoad);
}
} catch (WebDriverException ignored) {}
}
private void poll(long milis) {
try {
Thread.sleep(milis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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.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 = 5;
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();
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();
// YWRtaW46YWRtaW5wYXNz
localStorage.setItem("user", "{\"login\":\"admin\",\"password\":\"adminpass\"}");
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()));
}
}
package es.uvigo.esei.daa.web.pages;
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;
import es.uvigo.esei.daa.util.JSWaiter;
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 + "#/people");
this.wait.until(presenceOfElementLocated(By.id(TABLE_ID)));
}
public int countPeople() {
return new PeopleTable(this.driver).countPeople();
}
public List<Person> 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);
JSWaiter.wait(driver).untilAngular5Ready();
}
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<WebElement> 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<Person> listPeople() {
return getRows().stream()
.map(this::rowToPerson)
.collect(toList());
}
private List<WebElement> 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, ""));
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost/daatestdb" />
<property name="username" value="sa" />
<property name="password" value="" />
<property name="maxTotal" value="8" />
<property name="maxIdle" value="4" />
<property name="maxWaitMillis" value="10000" />
</bean>
<bean id="sqlDataTypeFactory" class="org.dbunit.ext.hsqldb.HsqldbDataTypeFactory" />
<bean id="dbUnitDatabaseConfig" class="com.github.springtestdbunit.bean.DatabaseConfigBean">
<property name="datatypeFactory" ref="sqlDataTypeFactory" />
</bean>
<bean id="dbUnitDatabaseConnection"
class="com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean">
<property name="databaseConfig" ref="dbUnitDatabaseConfig" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:mem:daatestdb;create=true" />
<property name="username" value="daatestuser" />
<property name="password" value="daatestpass" />
<property name="maxTotal" value="8" />
<property name="maxIdle" value="4" />
<property name="maxWaitMillis" value="10000" />
</bean>
<bean id="sqlDataTypeFactory" class="org.dbunit.ext.hsqldb.HsqldbDataTypeFactory" />
<bean id="dbUnitDatabaseConfig" class="com.github.springtestdbunit.bean.DatabaseConfigBean">
<property name="datatypeFactory" ref="sqlDataTypeFactory" />
</bean>
<bean id="dbUnitDatabaseConnection"
class="com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean">
<property name="databaseConfig" ref="dbUnitDatabaseConfig" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="5" name="Lorenzo" owner="5" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
<pet id="11" name="John" owner="5" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<people id="11" name="John" surname="Doe" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="5" name="Lorenzo" owner="5" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="5" name="John" owner="5" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="John" surname="Doe" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="5" name="Lorenzo" owner="5" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT dataset (people*, users*,pet*)>
<!ELEMENT people EMPTY>
<!ELEMENT users EMPTY>
<!ELEMENT pet EMPTY>
<!ATTLIST people
id CDATA #IMPLIED
name CDATA #IMPLIED
surname CDATA #IMPLIED
>
<!ATTLIST users
login CDATA #IMPLIED
password CDATA #IMPLIED
role CDATA #IMPLIED
>
<!ATTLIST pet
id CDATA #IMPLIED
name CDATA #IMPLIED
owner CDATA #IMPLIED
>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pet id="1" name="Antón" owner="1" />
<pet id="2" name="Ana" owner="2" />
<pet id="3" name="Manuel" owner="3" />
<pet id="4" name="María" owner="4" />
<pet id="5" name="Lorenzo" owner="5" />
<pet id="6" name="Laura" owner="6" />
<pet id="7" name="Perico" owner="7" />
<pet id="8" name="Patricia" owner="8" />
<pet id="9" name="Julia" owner="9" />
<pet id="10" name="Juan" owner="10" />
</dataset>
\ No newline at end of file
DROP TABLE Pet IF EXISTS;
DROP TABLE People IF EXISTS;
DROP TABLE Users IF EXISTS;
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)
);
CREATE TABLE pet (
id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
name VARCHAR(50) NOT NULL,
owner int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (owner) REFERENCES people(id) ON DELETE CASCADE
);
\ No newline at end of file
<Context>
<!-- maxActive: Maximum number of database connections in pool. Make sure
you configure your mysqld max_connections large enough to handle all of your
db connections. Set to -1 for no limit. -->
<!-- maxIdle: Maximum number of idle database connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis
configuration parameter. -->
<!-- maxWait: Maximum time to wait for a database connection to become available
in ms, in this example 10 seconds. An Exception is thrown if this timeout
is exceeded. Set to -1 to wait indefinitely. -->
<!-- username and password: MySQL username and password for database connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver
- we recommend using Connector/J though. Class name for the official MySQL
Connector/J driver is com.mysql.jdbc.Driver. -->
<!-- url: The JDBC connection url for connecting to your MySQL database. -->
<Resource name="jdbc/daaexample"
auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="daa" password="daa"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/daaexampletest"
/>
</Context>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>add</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">add</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Xián&amp;surname=Ximénez</td>
</tr>
<tr>
<td>click</td>
<td>link=POST</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>200 OK</td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=#response-body-raw &gt; pre</td>
<td></td>
</tr>
<tr>
<td>storeText</td>
<td>css=#response-body-raw &gt; pre</td>
<td>responseBody</td>
</tr>
<tr>
<td>echo</td>
<td>${responseBody}</td>
<td></td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).name</td>
<td>Xián</td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).surname</td>
<td>Ximénez</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>addNoName</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">addNoName</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>surname=Ximénez</td>
</tr>
<tr>
<td>click</td>
<td>link=POST</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>addNoSurname</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">addNoSurname</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Xián</td>
</tr>
<tr>
<td>click</td>
<td>link=POST</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>delete</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">delete</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=DELETE</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/11</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>200 OK</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>deleteInvalidId</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">deleteInvalidId</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=DELETE</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/100</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>rest</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">rest</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=GET</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>200 OK</td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=#response-body-raw &gt; pre</td>
<td></td>
</tr>
<tr>
<td>storeText</td>
<td>css=#response-body-raw &gt; pre</td>
<td>responseBody</td>
</tr>
<tr>
<td>echo</td>
<td>${responseBody}</td>
<td></td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).length</td>
<td>10</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>rest</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">rest</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=GET</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>200 OK</td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=#response-body-raw &gt; pre</td>
<td></td>
</tr>
<tr>
<td>storeText</td>
<td>css=#response-body-raw &gt; pre</td>
<td>responseBody</td>
</tr>
<tr>
<td>echo</td>
<td>${responseBody}</td>
<td></td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).length</td>
<td>10</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>modify</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">modify</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Marta&amp;surname=Martínez</td>
</tr>
<tr>
<td>click</td>
<td>link=PUT</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/4</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>200 OK</td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=#response-body-raw &gt; pre</td>
<td></td>
</tr>
<tr>
<td>storeText</td>
<td>css=#response-body-raw &gt; pre</td>
<td>responseBody</td>
</tr>
<tr>
<td>echo</td>
<td>${responseBody}</td>
<td></td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).name</td>
<td>Marta</td>
</tr>
<tr>
<td>assertEval</td>
<td>JSON.parse(storedVars['responseBody']).surname</td>
<td>Martínez</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>modifyInvalidId</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">modifyInvalidId</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Marta&amp;surname=Martínez</td>
</tr>
<tr>
<td>click</td>
<td>link=PUT</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/100</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>modifyNoId</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">modifyNoId</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Marta&amp;surname=Martínez</td>
</tr>
<tr>
<td>click</td>
<td>link=PUT</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>405 Method Not Allowed</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>modifyNoName</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">modifyNoName</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>surname=Martínez</td>
</tr>
<tr>
<td>click</td>
<td>link=PUT</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/4</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="chrome://restclient/content/restclient.html" />
<title>modifyNoSurname</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">modifyNoSurname</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>chrome://restclient/content/restclient.html</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Cookie</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Headers</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Custom Header</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Content-Type</td>
</tr>
<tr>
<td>type</td>
<td>name=value</td>
<td>application/x-www-form-urlencoded</td>
</tr>
<tr>
<td>click</td>
<td>css=#modal-custom-header &gt; div.modal-footer &gt; input.btn.btn-inverse</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-body</td>
<td>name=Marta</td>
</tr>
<tr>
<td>click</td>
<td>link=PUT</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=request-url</td>
<td>http://localhost:9080/DAAExample/rest/people/4</td>
</tr>
<tr>
<td>click</td>
<td>id=request-button</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=×</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>css=span.header-value</td>
<td></td>
</tr>
<tr>
<td>assertText</td>
<td>css=span.header-value</td>
<td>400 Bad Request</td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="list.html">list</a></td></tr>
<tr><td><a href="add.html">add</a></td></tr>
<tr><td><a href="addNoName.html">addNoName</a></td></tr>
<tr><td><a href="addNoSurname.html">addNoSurname</a></td></tr>
<tr><td><a href="modify.html">modify</a></td></tr>
<tr><td><a href="modifyInvalidId.html">modifyInvalidId</a></td></tr>
<tr><td><a href="modifyNoId.html">modifyNoId</a></td></tr>
<tr><td><a href="modifyNoName.html">modifyNoName</a></td></tr>
<tr><td><a href="modifyNoSurname.html">modifyNoSurname</a></td></tr>
<tr><td><a href="delete.html">delete</a></td></tr>
<tr><td><a href="deleteInvalidId.html">deleteInvalidId</a></td></tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>example</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">example</td></tr>
</thead><tbody>
<tr>
<td>createCookie</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>main.html</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td></td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Hola</td>
</tr>
<tr>
<td>type</td>
<td>name=surname</td>
<td>Mundo</td>
</tr>
<tr>
<td>click</td>
<td>id=btnSubmit</td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>verifyText</td>
<td>css=tr:last-child &gt; td.name</td>
<td>Hola</td>
</tr>
<tr>
<td>verifyText</td>
<td>css=tr:last-child &gt; td.surname</td>
<td>Mundo</td>
</tr>
<tr>
<td>deleteCookie</td>
<td>token</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>delete</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">delete</td></tr>
</thead><tbody>
<tr>
<td>createCookie</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>main.html</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td></td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>storeXpathCount</td>
<td>//tr</td>
<td>rows</td>
</tr>
<tr>
<td>click</td>
<td>xpath=(//a[contains(text(),'Delete')])[last()]</td>
<td></td>
</tr>
<tr>
<td>assertConfirmation</td>
<td>Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?</td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>storeXpathCount</td>
<td>//tr</td>
<td>rowsAfterDeletion</td>
</tr>
<tr>
<td>storeEval</td>
<td>storedVars['rows']-storedVars['rowsAfterDeletion']</td>
<td>rowsDeleted</td>
</tr>
<tr>
<td>verifyExpression</td>
<td>${rowsDeleted}</td>
<td>1</td>
</tr>
<tr>
<td>deleteCookie</td>
<td>token</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>edit</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">edit</td></tr>
</thead><tbody>
<tr>
<td>createCookie</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>main.html</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td></td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>click</td>
<td>xpath=(//a[contains(text(),'Edit')])[last()]</td>
<td></td>
</tr>
<tr>
<td>storeAttribute</td>
<td>//tr[last()]/@id</td>
<td>personId</td>
</tr>
<tr>
<td>type</td>
<td>name=name</td>
<td>Ana</td>
</tr>
<tr>
<td>type</td>
<td>name=surname</td>
<td>María</td>
</tr>
<tr>
<td>click</td>
<td>id=btnSubmit</td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>verifyText</td>
<td>//tr[@id='${personId}']/td[@class = 'name']</td>
<td>Ana</td>
</tr>
<tr>
<td>verifyText</td>
<td>//tr[@id='${personId}']/td[@class = 'surname']</td>
<td>María</td>
</tr>
<tr>
<td>deleteCookie</td>
<td>token</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="list.html">list</a></td></tr>
<tr><td><a href="add.html">add</a></td></tr>
<tr><td><a href="edit.html">edit</a></td></tr>
<tr><td><a href="delete.html">delete</a></td></tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://localhost:9080/DAAExample/" />
<title>list</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">list</td></tr>
</thead><tbody>
<tr>
<td>createCookie</td>
<td>token=bXJqYXRvOm1yamF0bw==</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>main.html</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td></td>
<td></td>
</tr>
<tr>
<td>waitForCondition</td>
<td>selenium.browserbot.getCurrentWindow().jQuery.active == 0</td>
<td>1000</td>
</tr>
<tr>
<td>verifyXpathCount</td>
<td>//tr</td>
<td>11</td>
</tr>
<tr>
<td>deleteCookie</td>
<td>token</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="9205" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector SSLEnabled="false" URIEncoding="ISO-8859-1" connectionTimeout="20000" port="9080" protocol="HTTP/1.1" redirectPort="9443" scheme="http" secure="false"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="9009" protocol="AJP/1.3" redirectPort="9443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="org.hsqldb.jdbc.JDBCDriver"
connectionURL="jdbc:hsqldb:hsql://localhost/daatestdb?user=sa"
userTable="users"
userNameCol="login"
userCredCol="password"
userRoleTable="users"
roleNameCol="role"
digest="SHA-256"
>
<CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler"
algorithm="SHA-256"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
</Host>
</Engine>
</Service>
</Server>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="10205" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector SSLEnabled="false" URIEncoding="ISO-8859-1" connectionTimeout="20000" port="9080" protocol="HTTP/1.1" redirectPort="9443" scheme="http" secure="false"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="9009" protocol="AJP/1.3" redirectPort="9443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/daaexample"
connectionName="daa"
connectionPassword="daa"
userTable="users" userNameCol="login" userCredCol="password"
userRoleTable="users" roleNameCol="role" digest="SHA-256">
<CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler"
algorithm="SHA-256"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
</Host>
</Engine>
</Service>
</Server>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment