Commit 9bdbb995 authored by Miguel Reboiro Jato's avatar Miguel Reboiro Jato

Initial commit

Initial commit with the basic project configuration and information.
parents
#Eclipse
.settings
.project
.classpath
#Maven
target
#General
bak
*.tar.gz
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
\ No newline at end of file
# Servidor Híbrido de Documentos Estructurados
## Objetivo
El objetivo principal de esta práctica es el desarrollo de un proyecto en el cual se apliquen las herramientas y tecnologías vistas en la asignatura.
Este proyecto consistirá en el desarrollo de un sistema híbrido cliente/servidor y P2P para la gestión de documentos estructurados (HTML y XML). Este proyecto se desarrollará en dos partes que coincidirán con las dos entregas a realizar.
Como primera parte del proyecto se desarrollará un sistema similar a un servidor Web, con la diferencia de que las páginas servidas se solicitarán mediante un identificador y que estas estarán almacenadas en una base de datos relacional. En esta primera parte el sistema solo tendrá soporte para páginas HTML.
En la segunda parte del proyecto se desarrollará el sistema P2P y se añadirá soporte para XML. El sistema P2P permitirá que cada servidor pueda servir cualquier página almacenada en cualquier servidor de la red P2P. Por lo tanto, si un servidor recibe un identificador de página desconocido deberá consultar al resto de los servidores de la red si lo conocen y, en tal caso, solicitar el documento y servirlo al cliente.
## Entorno
En el desarrollo de este proyecto debe utilizarse:
* Java 11
* MySQL 8+
* Maven 3.6+
* Git 2+ (en el caso de querer hacer commits, lo cual es recomendable)
Es importante que antes de empezar a trabajar se edite el fichero `pom.xml` para:
* Poner en la propiedad `group.name` el nombre del grupo en Moovi.
* Descomentar y completar la sección `developers` con los datos de los miembros del grupo.
### Comandos útiles
Algunos comandos Maven que te serán útiles son:
* `mvn test`: ejecuta los tests y genera un informe en `target/site/surefire-report.html`.
* `mvn exec:java`: ejecuta la aplicación (es decir, ejecuta `Launcher`).
* `mvn exec:java -Dexec.args="arg1 arg2 arg3"`: ejecuta la aplicación con los parámetos `arg1 arg2 arg3`. Por ejemplo, `mvn exec:java -Dexec.args="config.props"` ejecuta `Launcher` pasándole el parámetro `config.props`.
* `mvn package`: empaqueta la aplicación. Generará un fichero `hybrid-server-<nombre del grupo>.r1.tar.gz` en la raíz del proyecto que es el que habrá que entregar en Moovi en la primera entrega.
## Arquitectura
La Figura 1 muestra la arquitectura general del sistema. Como se puede observar, la parte Cliente/Servidor (C/S) está claramente diferenciada de la parte P2P. Una importante diferencia entre ambas es que en la parte C/S los clientes interactuarán con los servidores, mientras que la parte P2P está reservada a la comunicación entre servidores.
![Figura 1. Arquitectura general del sistema](images/Arquitectura.png)
*Figura 1. Arquitectura general del sistema*
### Gestión de contenidos
El sistema final deberá tener soporte para servir páginas HTML y XML. Mientras que las páginas HTML serán servidas sin modificación desde la base de datos, las páginas XML podrán solicitarse con una plantilla XSLT asociada, debiéndose aplicar dicha plantilla antes de ser servida. Además, las plantillas XSLT tendrán un esquema XSD asociado, por lo que antes de aplicar dicha plantilla habrá que validar el documento XML contra dicho esquema.
Todos los contenidos se alojarán en una base de datos en cada servidor y tendrán asociado un identificador único para todo el sistema, que podrá ser generado utilizando la clase `java.util.UUID`. Cuando se solicite un contenido se hará haciendo uso de este identificador.
### Comunicación
La comunicación entre cliente y servidor se realizará utilizando el protocolo HTTP, de tal modo que cualquier navegador web actual (p.ej. Mozilla Firefox, Chrome/Chromium, Safari, etc.) pueda ser utilizado como cliente. No es necesario un soporte completo del protocolo, tan solo el suficiente como para cubrir los requisitos indicados en la siguiente sección.
Algunas de las simplificaciones sobre este protocolo que se tendrán en cuenta son que no será necesario soportar el modo de conexión “keep-alive” y que siempre se utilizará la codificación de caracteres UTF-8.
La comunicación entre servidores se realizará utilizando servicios Web, de tal modo que cada servidor podrá invocar comandos en cualquier otro servidor de la red P2P. Este será el medio por el cual se obtendrá información de las páginas alojadas en otros servidores.
## Requisitos
En esta sección se detallan los requisitos que debe cumplir la aplicación en forma de funcionalidades. Dependiendo de si dichas funcionalidades deben ser implementadas para la primera o segunda entrega, se identifican con AX o BX, respectivamente.
En cada requisito se indica la puntuación asociada, que en cada entrega será sobre un máximo de 10 puntos. La documentación y el formato de entrega también se tendrán en cuenta en la puntuación, restando hasta un máximo de 1 punto en el caso de que existan errores o incumplimientos.
De forma adicional a lo descrito en estos puntos, también debe tenerse en cuenta que no respetar las buenas prácticas descritas en los distintos temas de teoría supondrá una penalización en la puntuación. Así, por ejemplo, no cerrar flujos o conexiones cuando ya no son utilizadas.
Adicionalmente, debe tenerse en cuenta que los tests incluidos en el proyecto base y los que se entregarán para la segunda entrega incluyen detalles de implementación que son obligatorios (p.ej. evalúan el `Content-Type` devuelto por algunas respuestas), por lo que no superar los tests puede suponer una penalización en la nota final.
Como norma general, no se podrá modificar el nombre, paquete o firma de los métodos de las clases entregadas. Solo se podrá modificar el código de aquellos métodos en los que se indique. Tampoco se podrán utilizar bibliotecas externas adicionales a las incluidas inicialmenten en el proyecto.
En Moovi se detallarán las normas de evaluación, realización, entrega y defensa del proyecto.
## A. Primera entrega
El objetivo de esta primera entrega es desarrollar un servidor capaz de servir páginas HTML a clientes HTTP (normalmente, un navegador web).
Las páginas deberán estar almacenadas en una base de datos. Sin embargo, durante el paso 2 del desarrollo se almacenarán en memoria. Por ello, en esta primera entrega será obligatorio que el servidor soporte el trabajo con las páginas HTML almacenadas en memoria y en la base de datos.
### A1. Servir una página HTML [GET] (3 puntos)
El sistema debe ser capaz de servir una página Web alojada en su base de datos. La petición HTTP deberá hacerse con el método `GET` sobre el recurso `html` y con el parámetro `uuid` al que se le asignará el identificador de la página Web que se desea recuperar.
Así, por ejemplo, para solicitar a un servidor local escuchando en el puerto 2000 la página con identificador “12345678-1234-1234-1234-123456789012” (este es el formato de identificador proporcionado por `java.util.UUID`), el cliente deberá introducir la siguiente URL en su navegador:
http://localhost:2000/htm?uuid=12345678-1234-1234-1234-123456789012
#### Página de Bienvenida
Cuando un usuario acceda a la dirección raíz (p.ej. http://localhost:2000) se le servirá una **página de bienvenida donde aparecerá, al menos, el nombre “Hybrid Server” y los autores del proyecto**. También puede haber, por ejemplo, un enlace al listado de páginas del servidor (ver siguiente punto) o la descripción de la configuración del mismo, pero esto no es obligatorio.
Es importante tener en cuenta que esta página siempre debe funcionar, independientemente de que exista conexión con la base de datos o no. Por lo tanto, establecer conexión con la base de datos para servir este página será un error.
#### Listado de páginas
Si un cliente hace una petición sobre el recurso `html` sin ningún parámetro se listarán los enlaces a todas las páginas HTML almacenadas en el servidor con una página similar a la mostrada en la Figura 2.
![Figura 2. Lista de documentos HTML de un servidor](images/Listado.png)
*Figura 2. Lista de documentos HTML de un servidor*
#### A2. Añadir una nueva página HTML [POST] (2 puntos)
El sistema debe ser capaz de añadir nuevas páginas Web a su base de datos, asignándoles un nuevo identificador único. Estas páginas se recibirán en el parámetro `html` de una petición con el método `POST` sobre el recurso `html`.
Un formulario HTML adaptado a este tipo de petición podría ser el siguiente:
```html
<form action=”http://localhost:2000/html” method=”POST”>
<textarea name=”html”></textarea>
<button type=”submit”>Submit</button>
</form>
```
La respuesta a esta petición debe ser una página HTML con un hiperenlace a la página recién añadida, cuyo texto sea el identificador asignado.
También es posible utilizar alguna herramienta tipo [Postman](https://www.postman.com/), [RESTClient](https://addons.mozilla.org/es/firefox/addon/restclient/) o [Talend API Tester](https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm) para hacer peticiones POST de una forma sencilla.
#### A3. Eliminar una página HTML [DELETE] (2 puntos)
El sistema debe ser capaz de eliminar una página Web alojada en su base de datos. Para ello se deberá hacer una petición HTTP al servidor sobre el recurso `html` utilizando el método `DELETE` e incluyendo el parámetro `uuid` con el identificador de la página a eliminar. Solo se debe eliminar dicho contenido de la base de datos si se corresponde con una página HTML.
Este tipo de peticiones puede realizarse, por ejemplo, utilizando el comando `curl` de los sistemas Linux. Así, por ejemplo, si se desea eliminar la página con identificador “12345678-1234-1234-1234-123456789012” de un servidor local activo en el puerto 2000, se podrá utilizar el siguiente comando:
```bash
curl -X DELETE http://localhost:2000/html?uuid=12345678-1234-1234-1234-123456789012
```
La respuesta a esta petición deberá ser una página web con un mensaje que indique se se ha eliminado dicha página.
También es posible utilizar alguna herramienta tipo [Postman](https://www.postman.com/), [RESTClient](https://addons.mozilla.org/es/firefox/addon/restclient/) o [Talend API Tester](https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm) para hacer peticiones `DELETE` de una forma sencilla.
#### A4. Manejo de errores (1 punto)
El sistema deberá manejar correctamente los errores, evitando que finalice la ejecución de un servidor bruscamente y comunicándose debidamente con los clientes. Para ello, en el caso de que en alguna las tres peticiones anteriores (y en las descritas posteriormente) se produzca un error en el servidor (normalmente, por el lanzamiento de una excepción), este deberá responder al cliente con un mensaje con código 500 (*Internal server error*) y continuar su ejecución. Además, si el cliente solicita una página que no existe el servidor deberá responder con un código 404 (*Not found*) y, si la solicitud es incorrecta, deberá responder con un código 400 (*Bad Request*).
Como parte del manejo de errores es importante tener en cuenta que, en el caso de que se pierda o no se pueda establecer conexión con la base de datos el servidor debe seguir funcionando correctamente, devolviendo un código 500 en el caso de que la petición requiera conexión con la base de datos. Además, en el momento en el que la base de datos vuelva a funcionar correctamente, el servidor debe continuar funcionando de forma normal.
#### A5. Servicio a Múltiples Usuarios (1 punto)
El servidor deberá ser capaz de atender a varios clientes simultáneamente evitando, en cualquier caso, descartar clientes por exceso de peticiones. El número de clientes al que se dará servicio de forma simultánea será un parámetro de la configuración del sistema (ver siguiente punto). Las peticiones de aquellos clientes en exceso de este parámetro quedarán suspendidas hasta que se liberen los recursos necesarios.
#### A6. Configuración y Ejecución (1 punto)
Toda la configuración del servidor deberá alojarse en un fichero externo, cuya ubicación será el único parámetro que recibirá el sistema al ejecutarse. Por lo tanto, la ejecución de un servidor se realizará de la siguiente forma:
```bash
java es.uvigo.esei.dai.hybridserver.Launch config.conf
```
Este fichero debe incluir, los siguientes elementos de configuración:
* Puerto de servicio de HTTP. Para la comunicación con los clientes.
* Número de clientes a los que se les podrá dar servicio de forma simultánea.
* Datos de configuración de la conexión con la base de datos (URL, usuario y password).
Es recomendable utilizar, para la primera parte, un fichero de propiedades de Java, gestionado mediante la clase java.util.Properties.
En concreto, en la primera entrega, el fichero de configuración debe contener los siguientes campos (debe respetarse mayúsculas y minúsculas):
```
numClients=
port=
db.url=
db.user=
db.password=
```
**En el caso de que no se le pase un fichero de configuración, se utilizarán los siguientes parámetros como parámetros por defecto**:
```
numClients=50
port=8888
db.url=jdbc:mysql://localhost:3306/hstestdb
db.user=hsdb
db.password=hsdbpass
```
**En el caso de que se reciba más de un parámetro deberá mostrarse un mensaje de error explicando cómo ejecutar correctamente la aplicación.**
## B. Segunda Entrega
La segunda entrega está centrada en la inclusión de XML y en el servicio P2P.
#### B1. Soporte para XML (2 puntos)
El sistema deberá soportar ficheros XML de la misma forma que soporta HTML, es decir, permitiendo solicitar, crear y eliminar documentos XML. Existirán dos diferencias principales:
1. Las peticiones deberán dirigirse al recurso `xml` en lugar de `html` y en la creación de un nuevo documento (petición `POST`) el documento estará asignado al parámetro `xml` en lugar de al parámetro `html`.
2. En las solicitudes `GET`, el cliente podrá incluir el parámetro `xslt` con el identificador de una plantilla XSLT alojada en el sistema. En tal caso, el sistema deberá recuperar dicha plantilla y el esquema asociados (ver siguiente punto), validar el XML con el esquema y, en el caso de que se supere la validación, devolver el resultado de transformar el documento XML con la plantilla XSLT.
#### B2. Soporte para XSLT y XSD (2 puntos)
El sistema deberá soportar ficheros XSD y XSLT de la misma forma que soporta HTML y XML, es decir, permitiendo solicitar, crear y eliminar documentos XSD y XSLT. En este caso existen las siguientes particularidades:
1. Cuando se sube un fichero de plantilla XSLT (petición `POST`) deberá incluirse el parámetro `xsd` con el identificador de un esquema asociado. Este será el esquema que se utilizará para validar un XML cuando se solicite con un XSLT asociado.
2. En el caso de que no se proporcione el parámetro `xsd` en la petición se dará una respuesta 400 (*Bad Request*).
3. En el caso de que el XSD que se quiera asociar a un XSLT no exista, deberá devolverse un 404 (*Not Found*).
#### B3. Sistema P2P (5 puntos; mínimo 2 puntos)
Deberá crearse un sistema P2P para la comunicación entre servidores, te tal forma que cuando un cliente solicite un recurso los servidores lo busquen en todos los *hosts* del sistema P2P. De este modo, cuando un cliente solicite un documento HTML o XML, si el servidor al que hace la solicitud no lo contiene lo buscará en otros servidores. Esto incluye los documentos XSD y XSLT.
En el caso de las páginas de listados de contenido (peticiones `GET` sin `uuid`), se mostrará el contenido de todos los servidores de la red, con una página similar a la mostrada en la Figura 3.
![Figura 3. Listado de documentos de la red P2P](images/Listado remotos.png)
*Figura 3. Listado de documentos de la red P2P*
Debe tenerse en cuenta que los enlaces de los servidores remotos deben llevar a esos servidores y no al servidor que está mostrando el listado.
<span style="color: red">**Importante**</span>: no conseguir el mínimo de 2 puntos en este apartado supondrá no superar esta segunda parte. En tal caso, se asignará una nota máxima de 3,9 en esta segunda parte.
#### B4. Configuración en XML (1 punto)
El fichero de configuración descrito en el punto A6 deberá convertirse en un fichero XML. Para ello, deberá definirse un esquema XSD (`configuration.xsd`) que lo valide y un fichero XSLT (`configuration.xslt`) que lo presente en formato HTML cuando sea abierto. Cuando el sistema cargue el fichero deberá validarlo contra el esquema definido, anulando la ejecución en el caso de que no se supere la validación.
La validación del fichero recibido debe hacerse con la clase `XMLConfigurationLoader`. Por otro lado, los ficheros `configuration.xsd` y `configuration.xslt` deben estar en la raíz del proyecto.
En el caso de no recibir parámetros o de recibir más de uno el comportamiento debe ser el mismo que el descrito en el punto A6.
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>hybrid-server</artifactId>
<groupId>es.uvigo.esei.dai</groupId>
<version>1.0.0-SNAPSHOT</version>
<name>Hybrid Server</name>
<description>Servidor Híbrido de Documentos Estructurados</description>
<url>https://sing-group.org/dt/gitlab/dai-2526/hybrid-server</url>
<contributors>
<contributor>
<name>Miguel Reboiro Jato</name>
<email>mrjato@uvigo.gal</email>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<roles>
<role>professor</role>
</roles>
</contributor>
</contributors>
<!-- developers>
<developer>
<id>[Login el email de la ESEI (p.ej. student@esei.uvigo.es => student)]</id>
<email>[xxx@esei.uvigo.es]</email>
<name>[Nombre completo]</name>
<organization>Escola Superior de Enxeñaría Informática - Universidade de
Vigo</organization>
<roles>
<role>student</role>
</roles>
</developer>
<developer>
<id>[Login el email de la ESEI (p.ej. student@esei.uvigo.es => student)]</id>
<email>[xxx@esei.uvigo.es]</email>
<name>[Nombre completo]</name>
<organization>Escola Superior de Enxeñaría Informática - Universidade de
Vigo</organization>
<roles>
<role>student</role>
</roles>
</developer>
</developers -->
<properties>
<group.name>[nombre_del_grupo]</group.name>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<main.class>es.uvigo.esei.dai.hybridserver.Launcher</main.class>
<!-- Dependencies versions -->
<jakarta.xml.ws-api.version>4.0.0</jakarta.xml.ws-api.version>
<jaxws-rt.version>4.0.3</jaxws-rt.version>
<mysql-connector-j.version>8.4.0</mysql-connector-j.version>
<!-- Test dependencies versions -->
<junit.jupiter.version>5.13.4</junit.jupiter.version>
<hamcrest.version>2.2</hamcrest.version>
<dbunit.version>2.7.3</dbunit.version>
<fluent-hc.version>4.5.14</fluent-hc.version>
<slf4j.version>2.0.7</slf4j.version>
<!-- Plugin versions -->
<exec-maven-plugin.version>3.1.0</exec-maven-plugin.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<maven-jxr-plugin.version>3.3.0</maven-jxr-plugin.version>
<maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.jupiter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>jakarta.xml.ws</groupId>
<artifactId>jakarta.xml.ws-api</artifactId>
<version>${jakarta.xml.ws-api.version}</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>${mysql-connector-j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>${jaxws-rt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>${dbunit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${fluent-hc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<mainClass>es.uvigo.esei.dai.hybridserver.Launcher</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<includes>
<include>
es/uvigo/esei/dai/hybridserver/HybridServerFirstReleaseTestSuite.java
</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>report-only</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<finalName>hybrid-server-${group.name}.r1</finalName>
<outputDirectory>${project.basedir}</outputDirectory>
<descriptors>
<descriptor>
src/main/assembly/assembly-first-release.xml
</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>${maven-jxr-plugin.version}</version>
</plugin>
</plugins>
</reporting>
</project>
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.2.0 http://maven.apache.org/xsd/assembly-2.2.0.xsd">
<id>first-release</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${project.build.sourceDirectory}</directory>
<outputDirectory>src/main/java</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.basedir}/src/main/resources</directory>
<outputDirectory>src/main/resources</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.build.directory}/site</directory>
<outputDirectory>site</outputDirectory>
</fileSet>
</fileSets>
<files>
<file>
<source>pom.xml</source>
<outputDirectory>/</outputDirectory>
</file>
<file>
<source>ENTREGA1.md</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
</assembly>
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Properties;
public class HybridServer implements AutoCloseable {
private static final int SERVICE_PORT = 8888;
private Thread serverThread;
private boolean stop;
public HybridServer() {
// TODO Inicializar con los parámetros por defecto
}
public HybridServer(Map<String, String> pages) {
// TODO Inicializar con la base de datos en memoria conteniendo "pages"
}
public HybridServer(Properties properties) {
// TODO Inicializar con los parámetros recibidos
}
public int getPort() {
return SERVICE_PORT;
}
public void start() {
this.serverThread = new Thread() {
@Override
public void run() {
try (final ServerSocket serverSocket = new ServerSocket(SERVICE_PORT)) {
while (true) {
try (Socket socket = serverSocket.accept()) {
if (stop)
break;
// TODO Responder al cliente
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
this.stop = false;
this.serverThread.start();
}
@Override
public void close() {
// TODO Si es necesario, añadir el código para liberar otros recursos.
this.stop = true;
try (Socket socket = new Socket("localhost", SERVICE_PORT)) {
// Esta conexión se hace, simplemente, para "despertar" el hilo servidor
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
this.serverThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.serverThread = null;
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
public class Launcher {
public static void main(String[] args) {
// TODO Ejecutar el servidor
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
public enum HTTPHeaders {
CONTENT_LENGTH("Content-Length"),
CONTENT_TYPE("Content-Type"),
HTTP_1_1("HTTP/1.1"),
CONNECTION("Connection");
private final String header;
private HTTPHeaders(String header) {
this.header = header;
}
public String getHeader() {
return this.header;
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
public class HTTPParseException extends Exception {
private static final long serialVersionUID = 1L;
public HTTPParseException() {
}
public HTTPParseException(String message) {
super(message);
}
public HTTPParseException(Throwable cause) {
super(cause);
}
public HTTPParseException(String message, Throwable cause) {
super(message, cause);
}
public HTTPParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
public class HTTPRequest {
public HTTPRequest(Reader reader) throws IOException, HTTPParseException {
// TODO Completar. Cualquier error en el procesado debe lanzar una HTTPParseException
}
public HTTPRequestMethod getMethod() {
// TODO Completar
return null;
}
public String getResourceChain() {
// TODO Completar
return null;
}
public String[] getResourcePath() {
// TODO Completar
return null;
}
public String getResourceName() {
// TODO Completar
return null;
}
public Map<String, String> getResourceParameters() {
// TODO Completar
return null;
}
public String getHttpVersion() {
// TODO Completar
return null;
}
public Map<String, String> getHeaderParameters() {
// TODO Completar
return null;
}
public String getContent() {
// TODO Completar
return null;
}
public int getContentLength() {
// TODO Completar
return -1;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder().append(this.getMethod().name()).append(' ')
.append(this.getResourceChain()).append(' ').append(this.getHttpVersion()).append("\r\n");
for (Map.Entry<String, String> param : this.getHeaderParameters().entrySet()) {
sb.append(param.getKey()).append(": ").append(param.getValue()).append("\r\n");
}
if (this.getContentLength() > 0) {
sb.append("\r\n").append(this.getContent());
}
return sb.toString();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
public enum HTTPRequestMethod {
HEAD,
GET,
POST,
PUT,
DELETE,
TRACE,
OPTIONS,
CONNECT;
}
\ No newline at end of file
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
public class HTTPResponse {
public HTTPResponse() {
// TODO Completar
}
public HTTPResponseStatus getStatus() {
// TODO Completar
return null;
}
public void setStatus(HTTPResponseStatus status) {
// TODO Completar
}
public String getVersion() {
// TODO Completar
return null;
}
public void setVersion(String version) {
// TODO Completar
}
public String getContent() {
// TODO Completar
return null;
}
public void setContent(String content) {
// TODO Completar
}
public Map<String, String> getParameters() {
// TODO Completar
return null;
}
public String putParameter(String name, String value) {
// TODO Completar
return null;
}
public boolean containsParameter(String name) {
// TODO Completar
return false;
}
public String removeParameter(String name) {
// TODO Completar
return null;
}
public void clearParameters() {
// TODO Completar
}
public List<String> listParameters() {
// TODO Completar
return null;
}
public void print(Writer writer) throws IOException {
// TODO Completar
}
@Override
public String toString() {
try (final StringWriter writer = new StringWriter()) {
this.print(writer);
return writer.toString();
} catch (IOException e) {
throw new RuntimeException("Unexpected I/O exception", e);
}
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
public enum HTTPResponseStatus {
S100("Continue"),
S101("Switching Protocols"),
S200("OK"),
S201("Created"),
S202("Accepted"),
S203("Non-Authoritative Information"),
S204("No Content"),
S205("Reset Content"),
S206("Partial Content"),
S300("Multiple Choices"),
S301("Moved Permanently"),
S302("Found"),
S303("See Other"),
S304("Not Modified"),
S305("Use Proxy"),
S307("Temporary Redirect"),
S400("Bad Request"),
S401("Unauthorized"),
S402("Payment Required"),
S403("Forbidden"),
S404("Not Found"),
S405("Method Not Allowed"),
S406("Not Acceptable"),
S407("Proxy Authentication Required"),
S408("Request Time-out"),
S409("Conflict"),
S410("Gone"),
S411("Length Required"),
S412("Precondition Failed"),
S413("Request Entity Too Large"),
S414("Request-URI Too Large"),
S415("Unsupported Media Type"),
S416("Requested range not satisfiable"),
S417("Expectation Failed"),
S500("Internal Server Error"),
S501("Not Implemented"),
S502("Bad Gateway"),
S503("Service Unavailable"),
S504("Gateway Time-out"),
S505("HTTP Version not supported");
private final int code;
private final String status;
private HTTPResponseStatus(String status) {
this.code = Integer.parseInt(this.name().substring(1));
this.status = status;
}
public int getCode() {
return this.code;
}
public String getStatus() {
return this.status;
}
public static HTTPResponseStatus forCode(int code) {
return HTTPResponseStatus.valueOf("S" + code);
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.http;
public enum MIME {
APPLICATION_XML("application/xml"),
FORM("application/x-www-form-urlencoded"),
TEXT_HTML("text/html");
private String mime;
private MIME(String mime) {
this.mime = mime;
}
public String getMime() {
return this.mime;
}
}
\ No newline at end of file
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectClasses({
Step1TestSuite.class,
Step2TestSuite.class,
Step3TestSuite.class
})
public class HybridServerFirstReleaseTestSuite {
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
import es.uvigo.esei.dai.hybridserver.step1.HTTPRequestResponseSuite;
import es.uvigo.esei.dai.hybridserver.step1.WelcomePageTest;
@Suite
@SelectClasses({
WelcomePageTest.class,
HTTPRequestResponseSuite.class
})
public class Step1TestSuite {
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
import es.uvigo.esei.dai.hybridserver.step1.HTTPRequestResponseSuite;
import es.uvigo.esei.dai.hybridserver.step2.ClientRequetsTest;
@Suite
@SelectClasses({
ClientRequetsTest.class,
HTTPRequestResponseSuite.class
})
public class Step2TestSuite {
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
import es.uvigo.esei.dai.hybridserver.step3.ClientRequestsWithDatabaseTest;
import es.uvigo.esei.dai.hybridserver.step3.CustomPortTest;
@Suite
@SelectClasses({
CustomPortTest.class,
ClientRequestsWithDatabaseTest.class
})
public class Step3TestSuite {
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step1;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Named.named;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.StringReader;
import java.util.stream.Stream;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import es.uvigo.esei.dai.hybridserver.http.HTTPParseException;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
@Tag("request")
public class HTTPBadRequestsTest {
public static Stream<Arguments> badRequests() {
return Stream
.of(
arguments(
named(
"Missing method",
"/hello HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
),
arguments(
named(
"Missing resource",
"GET HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
),
arguments(
named(
"Missing version",
"GET /hello\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
),
arguments(
named(
"Missing first line",
"Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
),
arguments(
named(
"Invalid header",
"GET /hello/world.html?country=Spain&province=Ourense&city=Ourense HTTP/1.1\r\n"
+ "Host\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
),
arguments(
named(
"Missing new line after header",
"GET /hello/world.html?country=Spain&province=Ourense&city=Ourense HTTP/1.1"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n"
)
)
);
}
@ParameterizedTest
@MethodSource("badRequests")
public void testThatThrowsHTTPParseException(final String requestText) {
assertThrows(HTTPParseException.class, () -> new HTTPRequest(new StringReader(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.ArrayMatching.arrayContaining;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestGETParametersTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
requestText =
"GET /hello/world.html?country=Spain&province=Ourense&city=Ourense HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n";
request = new HTTPRequest(new StringReader(requestText + "\r\n"));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.GET)));
}
@Test
public final void testGetResourceChain() {
assertThat(
request.getResourceChain(), is(equalTo("/hello/world.html?country=Spain&province=Ourense&city=Ourense"))
);
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(arrayContaining("hello", "world.html")));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(equalTo("hello/world.html")));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(
request.getResourceParameters(),
allOf(hasEntry("country", "Spain"), hasEntry("province", "Ourense"), hasEntry("city", "Ourense"))
);
assertThat(request.getResourceParameters(), is(aMapWithSize(3)));
}
@Test
public final void testGetHeaderParameters() {
assertThat(
request.getHeaderParameters(),
allOf(hasEntry("Host", "localhost"), hasEntry("Accept", "text/html"), hasEntry("Accept-Encoding", "gzip,deflate"))
);
assertThat(request.getHeaderParameters(), is(aMapWithSize(3)));
}
@Test
public final void testGetContent() {
assertThat(request.getContent(), is(nullValue()));
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(0)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.ArrayMatching.arrayContaining;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestGETResourceTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"GET /hello HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n";
this.request = new HTTPRequest(new StringReader(this.requestText + "\r\n"));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.GET)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/hello")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(arrayContaining("hello")));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(equalTo("hello")));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(this.request.getResourceParameters(), is(anEmptyMap()));
}
@Test
public final void testGetHeaderParameters() {
assertThat(
request.getHeaderParameters(),
allOf(hasEntry("Host", "localhost"), hasEntry("Accept", "text/html"), hasEntry("Accept-Encoding", "gzip,deflate"))
);
assertThat(request.getHeaderParameters(), is(aMapWithSize(3)));
}
@Test
public final void testGetContent() {
assertThat(request.getContent(), is(nullValue()));
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(0)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.ArrayMatching.arrayContaining;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestGETResourcesTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"GET /hello/world.html HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Accept: text/html\r\n"
+ "Accept-Encoding: gzip,deflate\r\n";
this.request = new HTTPRequest(new StringReader(this.requestText + "\r\n"));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.GET)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/hello/world.html")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(arrayContaining("hello", "world.html")));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(equalTo("hello/world.html")));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(this.request.getResourceParameters(), is(anEmptyMap()));
}
@Test
public final void testGetHeaderParameters() {
assertThat(
request.getHeaderParameters(),
allOf(hasEntry("Host", "localhost"), hasEntry("Accept", "text/html"), hasEntry("Accept-Encoding", "gzip,deflate"))
);
assertThat(request.getHeaderParameters(), is(aMapWithSize(3)));
}
@Test
public final void testGetContent() {
assertThat(request.getContent(), is(nullValue()));
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(0)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsArrayWithSize.emptyArray;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
import static org.hamcrest.text.IsEmptyString.emptyString;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestGETRootTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"GET / HTTP/1.1\r\n"
+ "Host: localhost\r\n";
this.request = new HTTPRequest(new StringReader(this.requestText + "\r\n"));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.GET)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(emptyArray()));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(emptyString()));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(this.request.getResourceParameters(), is(anEmptyMap()));
}
@Test
public final void testGetHeaderParameters() {
assertThat(request.getHeaderParameters(), hasEntry("Host", "localhost"));
assertThat(request.getHeaderParameters(), is(aMapWithSize(1)));
}
@Test
public final void testGetContent() {
assertThat(request.getContent(), is(nullValue()));
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(0)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsArrayWithSize.emptyArray;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.text.IsEmptyString.emptyString;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestPOSTEncodedTest {
private String requestText;
private String encodedRequestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"POST / HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: 116\r\n"
+ "\r\n"
+ "message=Hello world!!&mensaje=¡¡Hola mundo!!&mensaxe=Ola mundo!!&mensagem=Olá mundo!!";
this.encodedRequestText =
"POST / HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: 116\r\n"
+ "\r\n"
+ "message=Hello+world%21%21&mensaje=%C2%A1%C2%A1Hola+mundo%21%21&mensaxe=Ola+mundo%21%21&mensagem=Ol%C3%A1+mundo%21%21";
this.request = new HTTPRequest(new StringReader(this.encodedRequestText));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.POST)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(emptyArray()));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(emptyString()));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(
request.getResourceParameters(),
allOf(
hasEntry("message", "Hello world!!"), hasEntry("mensaje", "¡¡Hola mundo!!"), hasEntry("mensaxe", "Ola mundo!!"),
hasEntry("mensagem", "Olá mundo!!")
)
);
assertThat(request.getResourceParameters(), is(aMapWithSize(4)));
}
@Test
public final void testGetHeaderParameters() {
assertThat(
request.getHeaderParameters(),
allOf(
hasEntry("Host", "localhost"), hasEntry("Content-Type", "application/x-www-form-urlencoded"),
hasEntry("Content-Length", "116")
)
);
assertThat(request.getHeaderParameters(), is(aMapWithSize(3)));
}
@Test
public final void testGetContent() {
assertThat(
request.getContent(),
is(equalTo("message=Hello world!!&mensaje=¡¡Hola mundo!!&mensaxe=Ola mundo!!&mensagem=Olá mundo!!"))
);
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(116)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.ArrayMatching.arrayContaining;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestPOSTMultipleParametersTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"POST /resource HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Length: 85\r\n"
+ "\r\n"
+ "message=Hello world!!&mensaje=¡¡Hola mundo!!&mensaxe=Ola mundo!!&mensagem=Olá mundo!!";
this.request = new HTTPRequest(new StringReader(this.requestText));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.POST)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/resource")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(arrayContaining("resource")));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(equalTo("resource")));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(
request.getResourceParameters(),
allOf(
hasEntry("message", "Hello world!!"), hasEntry("mensaje", "¡¡Hola mundo!!"), hasEntry("mensaxe", "Ola mundo!!"),
hasEntry("mensagem", "Olá mundo!!")
)
);
assertThat(request.getResourceParameters(), is(aMapWithSize(4)));
}
@Test
public final void testGetHeaderParameters() {
assertThat(request.getHeaderParameters(), allOf(hasEntry("Host", "localhost"), hasEntry("Content-Length", "85")));
assertThat(request.getHeaderParameters(), is(aMapWithSize(2)));
}
@Test
public final void testGetContent() {
assertThat(
request.getContent(),
is(equalTo("message=Hello world!!&mensaje=¡¡Hola mundo!!&mensaxe=Ola mundo!!&mensagem=Olá mundo!!"))
);
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(85)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsArrayWithSize.emptyArray;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.text.IsEmptyString.emptyString;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequest;
import es.uvigo.esei.dai.hybridserver.http.HTTPRequestMethod;
@Tag("request")
public class HTTPRequestPOSTOneParameterTest {
private String requestText;
private HTTPRequest request;
@BeforeEach
public void setUp() throws Exception {
this.requestText =
"POST / HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Length: 21\r\n"
+ "\r\n"
+ "message=Hello world!!";
this.request = new HTTPRequest(new StringReader(this.requestText));
}
@Test
public final void testGetMethod() {
assertThat(request.getMethod(), is(equalTo(HTTPRequestMethod.POST)));
}
@Test
public final void testGetResourceChain() {
assertThat(request.getResourceChain(), is(equalTo("/")));
}
@Test
public final void testGetResourcePath() {
assertThat(request.getResourcePath(), is(emptyArray()));
}
@Test
public final void testGetResourceName() {
assertThat(request.getResourceName(), is(emptyString()));
}
@Test
public final void testGetHttpVersion() {
assertThat(request.getHttpVersion(), is(equalTo(HTTPHeaders.HTTP_1_1.getHeader())));
}
@Test
public final void testGetResourceParameters() {
assertThat(request.getResourceParameters(), hasEntry("message", "Hello world!!"));
assertThat(request.getResourceParameters(), is(aMapWithSize(1)));
}
@Test
public final void testGetHeaderParameters() {
assertThat(request.getHeaderParameters(), allOf(hasEntry("Host", "localhost"), hasEntry("Content-Length", "21")));
assertThat(request.getHeaderParameters(), is(aMapWithSize(2)));
}
@Test
public final void testGetContent() {
assertThat(request.getContent(), is(equalTo("message=Hello world!!")));
}
@Test
public final void testGetContentLength() {
assertThat(request.getContentLength(), is(equalTo(21)));
}
@Test
public final void testToString() {
assertThat(request.toString(), is(equalTo(requestText)));
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step1;
import org.junit.platform.suite.api.IncludeTags;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectPackages("es.uvigo.esei.dai.hybridserver.step1")
@IncludeTags({ "request", "response" })
public class HTTPRequestResponseSuite {
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step1;
import org.junit.platform.suite.api.IncludeTags;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectPackages("es.uvigo.esei.dai.hybridserver.step1")
@IncludeTags("response")
public class HTTPRequestSuite {
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponse;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponseStatus;
@Tag("response")
public class HTTPResponseNoContentTest {
private HTTPResponse response;
@BeforeEach
public void setUp() throws Exception {
this.response = new HTTPResponse();
this.response.setStatus(HTTPResponseStatus.S200);
this.response.setVersion(HTTPHeaders.HTTP_1_1.getHeader());
}
@Test
public final void testPrint() throws IOException {
try (final StringWriter writer = new StringWriter()) {
this.response.print(writer);
assertThat(writer.toString(), is(equalTo("HTTP/1.1 200 OK\r\n\r\n")));
}
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponse;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponseStatus;
@Tag("response")
public class HTTPResponseNoContentWithHeadersTest {
private HTTPResponse response;
@BeforeEach
public void setUp() throws Exception {
this.response = new HTTPResponse();
this.response.setStatus(HTTPResponseStatus.S200);
this.response.setVersion(HTTPHeaders.HTTP_1_1.getHeader());
this.response.putParameter("Content-Type", "text/html");
this.response.putParameter("Content-Encoding", "deflate");
this.response.putParameter("Content-Language", "en");
}
@Test
public final void testPrint() throws IOException {
try (final StringWriter writer = new StringWriter()) {
this.response.print(writer);
final String responseText = writer.toString();
assertThat(responseText, startsWith("HTTP/1.1 200 OK"));
assertThat(responseText, containsString("Content-Type: text/html"));
assertThat(responseText, containsString("Content-Encoding: deflate"));
assertThat(responseText, containsString("Content-Language: en"));
assertThat(responseText, endsWith("\r\n\r\n"));
}
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step1;
import org.junit.platform.suite.api.IncludeTags;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectPackages("es.uvigo.esei.dai.hybridserver.step1")
@IncludeTags("request")
public class HTTPResponseSuite {
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponse;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponseStatus;
@Tag("response")
public class HTTPResponseTest {
private HTTPResponse response;
@BeforeEach
public void setUp() throws Exception {
this.response = new HTTPResponse();
this.response.setContent("Hello World");
this.response.setStatus(HTTPResponseStatus.S200);
this.response.setVersion(HTTPHeaders.HTTP_1_1.getHeader());
}
@Test
public final void testPrint() throws IOException {
try (final StringWriter writer = new StringWriter()) {
this.response.print(writer);
assertThat(writer.toString(), is(equalTo("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello World")));
}
}
}
package es.uvigo.esei.dai.hybridserver.step1;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.io.StringWriter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.http.HTTPHeaders;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponse;
import es.uvigo.esei.dai.hybridserver.http.HTTPResponseStatus;
@Tag("response")
public class HTTPResponseWithHeadersTest {
private HTTPResponse response;
@BeforeEach
public void setUp() throws Exception {
this.response = new HTTPResponse();
this.response.setContent("Hello World");
this.response.setStatus(HTTPResponseStatus.S200);
this.response.setVersion(HTTPHeaders.HTTP_1_1.getHeader());
this.response.putParameter("Content-Type", "text/html");
this.response.putParameter("Content-Encoding", "deflate");
this.response.putParameter("Content-Language", "en");
}
@Test
public final void testPrint() throws IOException {
try (final StringWriter writer = new StringWriter()) {
this.response.print(writer);
final String responseText = writer.toString();
assertThat(responseText, startsWith("HTTP/1.1 200 OK"));
assertThat(responseText, containsString("Content-Length: 11"));
assertThat(responseText, containsString("Content-Type: text/html"));
assertThat(responseText, containsString("Content-Encoding: deflate"));
assertThat(responseText, containsString("Content-Language: en"));
assertThat(responseText, endsWith("\r\n\r\nHello World"));
}
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step1;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContentWithType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.utils.HybridServerTestCase;
public class WelcomePageTest extends HybridServerTestCase {
@Test
public void testWelcome() throws IOException {
for (int i = 0; i < 10; i++) {
assertThat(getContentWithType(url, "text/html"), containsString("Hybrid Server"));
}
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step2;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.deleteStatus;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.extractUUIDFromText;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContent;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContentWithType;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getStatus;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.postContent;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.postStatus;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toMap;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.HybridServer;
import es.uvigo.esei.dai.hybridserver.utils.HybridServerTestCase;
public class ClientRequetsTest extends HybridServerTestCase {
private String invalidUUID;
private String[][] pages;
@BeforeEach
public void setup() {
this.invalidUUID = "12345678-abcd-1234-ab12-9876543210ab";
}
@Override
protected HybridServer createHybridServer() {
// El servidor debe tener las siguientes páginas en memoria
this.pages = new String[][] {
// { "uuid", "texto contenido por la página" }
{ "6df1047e-cf19-4a83-8cf3-38f5e53f7725", "This is the html page 6df1047e-cf19-4a83-8cf3-38f5e53f7725." },
{ "79e01232-5ea4-41c8-9331-1c1880a1d3c2", "This is the html page 79e01232-5ea4-41c8-9331-1c1880a1d3c2." },
{ "a35b6c5e-22d6-4707-98b4-462482e26c9e", "This is the html page a35b6c5e-22d6-4707-98b4-462482e26c9e." },
{ "3aff2f9c-0c7f-4630-99ad-27a0cf1af137", "This is the html page 3aff2f9c-0c7f-4630-99ad-27a0cf1af137." },
{ "77ec1d68-84e1-40f4-be8e-066e02f4e373", "This is the html page 77ec1d68-84e1-40f4-be8e-066e02f4e373." },
{ "8f824126-0bd1-4074-b88e-c0b59d3e67a3", "This is the html page 8f824126-0bd1-4074-b88e-c0b59d3e67a3." },
{ "c6c80c75-b335-4f68-b7a7-59434413ce6c", "This is the html page c6c80c75-b335-4f68-b7a7-59434413ce6c." },
{ "f959ecb3-6382-4ae5-9325-8fcbc068e446", "This is the html page f959ecb3-6382-4ae5-9325-8fcbc068e446." },
{ "2471caa8-e8df-44d6-94f2-7752a74f6819", "This is the html page 2471caa8-e8df-44d6-94f2-7752a74f6819." },
{ "fa0979ca-2734-41f7-84c5-e40e0886e408", "This is the html page fa0979ca-2734-41f7-84c5-e40e0886e408." } };
// Creación del servidor con las páginas ya en memoria.
final Map<String, String> pages = Stream.of(this.pages).collect(toMap(entry -> entry[0], entry -> entry[1]));
return new HybridServer(pages);
}
// Ejercicio 2
@Test
public void testGetHtmlPage() throws IOException {
for (String[] page : pages) {
final String uuid = page[0];
final String content = page[1];
final String pageURL = url + "html?uuid=" + uuid;
assertThat(getContentWithType(pageURL, "text/html"), containsString(content));
}
}
// Ejercicio 3
@Test
public void testGetHtmlList() throws IOException {
final String pageURL = url + "html";
final String content = getContentWithType(pageURL, "text/html");
for (String[] page : pages) {
final String uuid = page[0];
assertThat(content, containsString(uuid));
}
}
// Ejercicio 4
@Test
public void testPost() throws IOException {
final String content = "<html><body>Testing POST</body></html>";
// Envío de la página y extracción del uuid de la nueva página
final String responseContent = postContent(url + "html", singletonMap("html", content));
final String uuid = extractUUIDFromText(responseContent);
assertThat(uuid, is(notNullValue()));
// Verificación de que la página de respuesta contiene un enlace a la nueva página
final String uuidHyperlink = "<a href=\"html?uuid=" + uuid + "\">" + uuid + "</a>";
assertThat(responseContent, containsString(uuidHyperlink));
// Recuperación de la nueva página
final String url = this.url + "html?uuid=" + uuid;
assertThat("The new page couldn't be retrieved", getContent(url), is(equalTo(content)));
}
@Test
public void testDelete() throws IOException {
final String uuid = pages[4][0];
final String url = this.url + "html?uuid=" + uuid;
assertThat("The page couldn't be deleted", deleteStatus(url), is(equalTo(200)));
assertThat("The page already exists", getStatus(url), is(equalTo(404)));
}
// Ejercicio 5
@Test
public void testGetInvalidHtmlPage() throws IOException {
final String pageURL = url + "html?uuid=" + invalidUUID;
assertThat(getStatus(pageURL), is(equalTo(404)));
}
@Test
public void testGetInvalidResource() throws IOException {
final String pageURL = url + "xxx?uuid=" + pages[0];
assertThat(getStatus(pageURL), is(equalTo(400)));
}
@Test
public void testDeleteNonexistentPage() throws IOException {
final String pageURL = this.url + "html?uuid=" + invalidUUID;
assertThat(deleteStatus(pageURL), is(equalTo(404)));
}
@Test
public void testPostInvalidContent() throws IOException {
final String content = "<html><body>Testing POST</body></html>";
assertThat(postStatus(url + "html", singletonMap("xxx", content)), is(equalTo(400)));
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step3;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.deleteStatus;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.extractUUIDFromText;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContent;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContentWithType;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getStatus;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.postContent;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.postStatus;
import static es.uvigo.esei.dai.hybridserver.utils.matchers.TableMatcher.hasTable;
import static java.util.Collections.singletonMap;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.util.Properties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import es.uvigo.esei.dai.hybridserver.HybridServer;
import es.uvigo.esei.dai.hybridserver.utils.JdbcTestCase;
public class ClientRequestsWithDatabaseTest extends JdbcTestCase {
private HybridServer server;
private String url;
private String invalidUUID;
private String[][] pages;
@BeforeEach
public void initAttributes() {
this.invalidUUID = "12345678-abcd-1234-ab12-9876543210ab";
// Estas páginas se insertan en la base de datos al inicio del test.
this.pages = new String[][] {
// { "uuid", "texto contenido por la página" }
{ "6df1047e-cf19-4a83-8cf3-38f5e53f7725", "This is the html page 6df1047e-cf19-4a83-8cf3-38f5e53f7725." },
{ "79e01232-5ea4-41c8-9331-1c1880a1d3c2", "This is the html page 79e01232-5ea4-41c8-9331-1c1880a1d3c2." },
{ "a35b6c5e-22d6-4707-98b4-462482e26c9e", "This is the html page a35b6c5e-22d6-4707-98b4-462482e26c9e." },
{ "3aff2f9c-0c7f-4630-99ad-27a0cf1af137", "This is the html page 3aff2f9c-0c7f-4630-99ad-27a0cf1af137." },
{ "77ec1d68-84e1-40f4-be8e-066e02f4e373", "This is the html page 77ec1d68-84e1-40f4-be8e-066e02f4e373." },
{ "8f824126-0bd1-4074-b88e-c0b59d3e67a3", "This is the html page 8f824126-0bd1-4074-b88e-c0b59d3e67a3." },
{ "c6c80c75-b335-4f68-b7a7-59434413ce6c", "This is the html page c6c80c75-b335-4f68-b7a7-59434413ce6c." },
{ "f959ecb3-6382-4ae5-9325-8fcbc068e446", "This is the html page f959ecb3-6382-4ae5-9325-8fcbc068e446." },
{ "2471caa8-e8df-44d6-94f2-7752a74f6819", "This is the html page 2471caa8-e8df-44d6-94f2-7752a74f6819." },
{ "fa0979ca-2734-41f7-84c5-e40e0886e408", "This is the html page fa0979ca-2734-41f7-84c5-e40e0886e408." } };
}
@BeforeEach
public void startServer() throws Exception {
final Properties properties = new Properties();
properties.setProperty("port", Integer.toString(8888));
properties.setProperty("numClients", "50");
properties.setProperty("db.url", getConnectionUrl());
properties.setProperty("db.user", getUsername());
properties.setProperty("db.password", getPassword());
this.server = new HybridServer(properties);
this.url = String.format("http://localhost:%d/", this.server.getPort());
this.server.start();
}
@AfterEach
public void stopServer() {
this.server.close();
}
@Test
public void testGetHtmlList() throws IOException {
final String pageURL = url + "html";
final String content = getContentWithType(pageURL, "text/html");
for (String[] page : pages) {
final String uuid = page[0];
assertThat(content, containsString(uuid));
}
}
@Test
public void testPost() throws Exception {
final String content = "<html><body>Testing POST</body></html>";
// Envío de la página y extracción del uuid de la nueva página
final String responseContent = postContent(url + "html", singletonMap("html", content));
final String uuid = extractUUIDFromText(responseContent);
assertThat(uuid, is(notNullValue()));
// Verificación de que la página de respuesta contiene un enlace a la nueva página
final String uuidHyperlink = "<a href=\"html?uuid=" + uuid + "\">" + uuid + "</a>";
assertThat(responseContent, containsString(uuidHyperlink));
// Recuperación de la nueva página
final String url = this.url + "html?uuid=" + uuid;
assertThat("The new page couldn't be retrieved", getContent(url), is(equalTo(content)));
// Comprobación de la inserción en la base de datos
assertThat(getConnection(), hasTable(getSchema(), "HTML").withColumn("uuid").withValue(uuid));
}
@Test
public void testDelete() throws Exception {
final String uuid = pages[4][0];
final String url = this.url + "html?uuid=" + uuid;
// Eliminación de la página
assertThat("The page couldn't be deleted", deleteStatus(url), is(equalTo(200)));
// Comprobación de la eliminación en la base de datos
assertThat(getConnection(), hasTable(getSchema(), "HTML").withColumn("uuid").withoutValue(uuid));
// Comprobación de la eliminación vía web
assertThat("The page already exists", getStatus(url), is(equalTo(404)));
}
// Ejercicio 5
@Test
public void testGetInvalidHtmlPage() throws IOException {
final String pageURL = url + "html?uuid=" + invalidUUID;
assertThat(getStatus(pageURL), is(equalTo(404)));
}
@Test
public void testGetInvalidResource() throws IOException {
final String pageURL = url + "xxx?uuid=" + pages[0];
assertThat(getStatus(pageURL), is(equalTo(400)));
}
@Test
public void testDeleteNonexistentPage() throws IOException {
final String pageURL = this.url + "html?uuid=" + invalidUUID;
assertThat(deleteStatus(pageURL), is(equalTo(404)));
}
@Test
public void testPostInvalidContent() throws IOException {
final String content = "<html><body>Testing POST</body></html>";
assertThat(postStatus(url + "html", singletonMap("xxx", content)), is(equalTo(400)));
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.step3;
import static es.uvigo.esei.dai.hybridserver.utils.TestUtils.getContentWithType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import es.uvigo.esei.dai.hybridserver.HybridServer;
@Timeout(5L)
public class CustomPortTest {
public HybridServer startServer() {
final HybridServer server = new HybridServer();
server.start();
return server;
}
public HybridServer startServer(int port) {
final Properties properties = new Properties();
properties.setProperty("port", Integer.toString(port));
properties.setProperty("numClients", "50");
properties.setProperty("db.url", "jdbc:mysql://localhost/hstestdb");
properties.setProperty("db.user", "dai");
properties.setProperty("db.password", "daipassword");
final HybridServer server = new HybridServer(properties);
server.start();
return server;
}
@Test
public void testWelcome() throws IOException {
try (HybridServer server = startServer()) {
final String url = getUrlForHome(server);
for (int i = 0; i < 10; i++) {
assertThat(getContentWithType(url, "text/html"), containsString("Hybrid Server"));
}
}
}
@ParameterizedTest
@ValueSource(ints = { 1234, 4242, 7315, 8833, 10201, 21386, 33217, 45450, 55881, 60000 })
public void testMultipleWelcome(int port) throws IOException {
try (HybridServer server = startServer(port)) {
final String url = getUrlForHome(server);
for (int i = 0; i < 10; i++) {
assertThat(getContentWithType(url, "text/html"), containsString("Hybrid Server"));
}
}
}
private String getUrlForHome(HybridServer server) {
return String.format("http://localhost:%d/", server.getPort());
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Timeout;
import es.uvigo.esei.dai.hybridserver.HybridServer;
@Timeout(5L)
public abstract class HybridServerTestCase {
protected HybridServer server;
protected String url;
@BeforeEach
public void startServer() {
this.server = createHybridServer();
this.url = String.format("http://localhost:%d/", this.server.getPort());
this.server.start();
}
@AfterEach
public void stopServer() {
this.server.close();
}
protected HybridServer createHybridServer() {
return new HybridServer();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils;
import java.sql.Connection;
import org.dbunit.IDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
public abstract class JdbcTestCase {
private IDatabaseTester tester;
private IDatabaseConnection connection;
@BeforeEach
public void setUpJdbc() throws Exception {
this.tester = this.createDatabaseTester();
this.connection = this.tester.getConnection();
this.tester.setDataSet(getDataSet());
this.tester.onSetup();
}
@AfterEach
public void tearDownJdbc() throws Exception {
try {
this.tester.onTearDown();
this.connection.close();
} finally {
this.connection = null;
}
}
protected IDatabaseTester createDatabaseTester() throws ClassNotFoundException {
return new MySqlJdbcDatabaseTester(getConnectionUrl(), getUsername(), getPassword());
}
protected String getSchema() {
return "hstestdb";
}
protected String getConnectionUrl() {
// Esta base de datos debe existir con las tablas creadas
// y el usuario debe tener acceso.
return "jdbc:mysql://localhost/" + this.getSchema();
}
protected String getUsername() {
return "hsdb";
}
protected String getPassword() {
return "hsdbpass";
}
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder()
.setMetaDataSetFromDtd(getClass().getResourceAsStream("dataset.dtd"))
.setCaseSensitiveTableNames(false)
.setColumnSensing(true).build(getClass().getResourceAsStream("dataset.xml"));
}
protected Connection getConnection() throws Exception {
return this.connection.getConnection();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;
import org.dbunit.ext.mysql.MySqlMetadataHandler;
public class MySqlJdbcDatabaseTester extends JdbcDatabaseTester {
private final static String MYSQL_DRIVER = "com.mysql.cj.jdbc.Driver";
public MySqlJdbcDatabaseTester(String connectionUrl) throws ClassNotFoundException {
super(MYSQL_DRIVER, connectionUrl);
}
public MySqlJdbcDatabaseTester(String connectionUrl, String username, String password) throws ClassNotFoundException {
super(MYSQL_DRIVER, connectionUrl, username, password);
}
public MySqlJdbcDatabaseTester(String connectionUrl, String username, String password, String schema)
throws ClassNotFoundException {
super(MYSQL_DRIVER, connectionUrl, username, password, schema);
}
@Override
public IDatabaseConnection getConnection() throws Exception {
final IDatabaseConnection connection = super.getConnection();
connection.getConfig().setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
return connection;
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
public final class TestUtils {
private TestUtils() {
}
/**
* Devuelve un <i>reader</i> a un fichero en el classpath.
*
* @param filePath
* ruta absoluta del fichero, que debe estar en el classpath del sistema.
* @return <i>reader</i> asociado al fichero o {@code null} si el fichero no existe.
*/
public static final Reader openReaderToFile(String filePath) {
return new InputStreamReader(TestUtils.class.getResourceAsStream(filePath));
}
/**
* Realiza una petición por GET y devuelve el contenido de la respuesta.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @return contenido de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static String getContent(String url) throws IOException {
final HttpResponse response = Request.Get(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.execute()
.returnResponse();
assertEquals(200, response.getStatusLine().getStatusCode());
return EntityUtils.toString(response.getEntity());
}
/**
* Realiza una petición por GET y devuelve el contenido de la respuesta.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @return contenido de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static String getContentWithType(String url, String contentType) throws IOException {
final HttpResponse response = Request.Get(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.execute()
.returnResponse();
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals(contentType, response.getEntity().getContentType().getValue());
return EntityUtils.toString(response.getEntity());
}
/**
* Realiza una petición por GET y devuelve el código de la respuesta HTTP.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @return código de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static int getStatus(String url) throws IOException {
return Request.Get(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.execute()
.returnResponse().getStatusLine().getStatusCode();
}
/**
* Realiza una petición por POST y devuelve el contenido de la respuesta.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @param content
* parámetros que se incluirán en la petición HTTP.
* @return contenido de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static String postContent(String url, Map<String, String> content) throws IOException {
final HttpResponse response = Request.Post(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.bodyForm(mapToNameValuePair(content))
.execute().returnResponse();
assertEquals(200, response.getStatusLine().getStatusCode());
return EntityUtils.toString(response.getEntity());
}
/**
* Realiza una petición por POST y devuelve el código de la respuesta.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @param content
* parámetros que se incluirán en la petición HTTP.
* @return código de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static int postStatus(String url, Map<String, String> content) throws IOException {
return Request.Post(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.bodyForm(mapToNameValuePair(content))
.execute().returnResponse().getStatusLine().getStatusCode();
}
/**
* Realiza una petición por DELETE y devuelve el código de la respuesta HTTP.
*
* La petición se hace en UTF-8 y solicitando el cierre de la conexión.
*
* Este método comprueba que el código de respuesta HTTP sea 200 OK.
*
* @param url
* URL de la página solicitada.
* @return código de la respuesta HTTP.
* @throws IOException
* en el caso de que se produzca un error de conexión.
*/
public static int deleteStatus(String url) throws IOException {
return Request.Delete(url)
.addHeader("Connection", "close")
.addHeader("Content-encoding", "UTF-8")
.execute().returnResponse().getStatusLine().getStatusCode();
}
/**
* Extrae un UUID de un texto. En el caso de que existan varios UUID en el texto se devolverá, únicamente, el primero
* de ellos.
*
* @param text
* texto del cual se quiere extraer el UUID.
* @return UUID encontrado en el texto o <code>null</code> en el caso de que no exista ninguno.
*/
public static String extractUUIDFromText(String text) {
final String patternString = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
final Pattern pattern = Pattern.compile(patternString);
final Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group() : null;
}
/**
* Lee por completo un recurso en el classpath, cuya ruta es relativa a una clase.
*
* @param clazz
* clase de referencia para obtener el recurso.
* @param resourcePath
* ruta al recurso relativa a la clase.
* @return contenido del flujo de entrada.
*/
public static String readResourceToString(Class<?> clazz, String resourcePath) {
return readToString(clazz.getResourceAsStream(resourcePath));
}
/**
* Lee por completo un InputStream y devuelve su contenido en forma de cadena de texto.
*
* @param is
* flujo de entrada del que se va a leer.
* @return contenido del flujo de entrada.
*/
public static String readToString(InputStream is) {
try (final Reader reader = new InputStreamReader(is)) {
final char[] buffer = new char[4096];
final StringBuilder sb = new StringBuilder();
int read;
while ((read = reader.read(buffer, 0, buffer.length)) != -1) {
sb.append(buffer, 0, read);
}
return sb.toString();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
private static List<NameValuePair> mapToNameValuePair(Map<String, String> map) {
final Form form = Form.form();
for (Map.Entry<String, String> entry : map.entrySet()) {
form.add(entry.getKey(), entry.getValue());
}
return form.build();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
public class Column {
private final Table table;
private final String name;
private String value;
Column(Table table, String name) {
this.table = table;
this.name = name;
}
public TableHas withValue(String value) {
this.value = value;
this.table.addColumn(this);
return new TableHas(table);
}
public TableHasNot withoutValue(String value) {
this.value = value;
this.table.addColumn(this);
return new TableHasNot(table);
}
String getName() {
return name;
}
String getValue() {
return value;
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
/**
* Comprueba que dos cadenas de texto son iguales ignorando los espacios en blanco y las mayúsculas y minúsculas.
*/
public class EqualsToIgnoringSpacesAndCaseMatcher extends BaseMatcher<String> {
private final String expected;
public EqualsToIgnoringSpacesAndCaseMatcher(String expected) {
this.expected = expected;
}
@Override
public boolean matches(Object item) {
if (item instanceof String) {
final String text = (String) item;
return expected.replaceAll("\\s", "").equalsIgnoreCase(text.replaceAll("\\s", ""));
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("Strings are not equal ignoring whitespaces and case");
}
public static EqualsToIgnoringSpacesAndCaseMatcher equalsToIgnoringSpacesAndCase(String expected) {
return new EqualsToIgnoringSpacesAndCaseMatcher(expected);
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
/**
* Comprueba que dos cadenas de texto son iguales ignorando los espacios en blanco.
*/
public class EqualsToIgnoringSpacesMatcher extends BaseMatcher<String> {
private final String expected;
public EqualsToIgnoringSpacesMatcher(String expected) {
this.expected = expected;
}
@Override
public boolean matches(Object item) {
if (item instanceof String) {
final String text = (String) item;
return expected.replaceAll("\\s", "").equals(text.replaceAll("\\s", ""));
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("Strings are not equal ignoring whitespaces");
}
public static EqualsToIgnoringSpacesMatcher equalsToIgnoringSpaces(String expected) {
return new EqualsToIgnoringSpacesMatcher(expected);
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import java.util.LinkedList;
import java.util.List;
public class Table {
private final String schema;
private final String name;
private final List<Column> columns;
Table(String schema, String name) {
this.schema = schema;
this.name = name;
this.columns = new LinkedList<>();
}
public Column withColumn(String name) {
return new Column(this, name);
}
void addColumn(Column column) {
this.columns.add(column);
}
String getSchema() {
return schema;
}
String getName() {
return name;
}
String getQualifiedName() {
return this.schema + "." + this.getName();
}
List<Column> getColumns() {
return columns;
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.hamcrest.Description;
public class TableHas extends TableMatcher {
TableHas(Table table) {
super(table);
}
@Override
public void describeTo(Description description) {
description.appendText("No row matching query: " + this.toSQL());
}
@Override
protected String toSQL() {
final StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ").append(table.getQualifiedName());
final List<Column> columns = table.getColumns();
if (!columns.isEmpty()) {
sb.append(" WHERE 1=1");
for (Column column : columns) {
sb.append(" AND ").append(column.getName()).append(" = \"").append(column.getValue()).append('"');
}
}
return sb.toString();
}
@Override
protected boolean checkResults(ResultSet results) throws SQLException {
return results.next();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.hamcrest.Description;
public class TableHasNot extends TableMatcher {
TableHasNot(Table table) {
super(table);
}
@Override
public void describeTo(Description description) {
description.appendText("There is a row matching query: " + this.toSQL());
}
@Override
protected String toSQL() {
final StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ").append(table.getQualifiedName());
final List<Column> columns = table.getColumns();
if (!columns.isEmpty()) {
sb.append(" WHERE 1=1");
for (Column column : columns) {
sb.append(" AND ").append(column.getName()).append(" = \"").append(column.getValue()).append('"');
}
}
return sb.toString();
}
@Override
protected boolean checkResults(ResultSet results) throws SQLException {
return !results.next();
}
}
/**
* HybridServer
* Copyright (C) 2025 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/>.
*/
package es.uvigo.esei.dai.hybridserver.utils.matchers;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.hamcrest.TypeSafeMatcher;
public abstract class TableMatcher extends TypeSafeMatcher<Connection> {
protected final Table table;
TableMatcher(Table table) {
this.table = table;
}
@Override
protected boolean matchesSafely(Connection connection) {
try (Statement statement = connection.createStatement()) {
try (ResultSet results = statement.executeQuery(this.toSQL())) {
return checkResults(results);
}
} catch (SQLException e) {
return false;
}
}
protected abstract String toSQL();
protected abstract boolean checkResults(ResultSet results) throws SQLException;
public static Table hasTable(String schema, String name) {
return new Table(schema, name);
}
public Column andColumn(String name) {
return new Column(this.table, name);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT dataset (hstestdb.HTML+)>
<!ELEMENT hstestdb.HTML EMPTY>
<!ATTLIST hstestdb.HTML
uuid CDATA #REQUIRED
content CDATA #REQUIRED
>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd" >
<dataset>
<hstestdb.HTML uuid="6df1047e-cf19-4a83-8cf3-38f5e53f7725"
content="&lt;html&gt;&lt;body&gt;This is the html page 6df1047e-cf19-4a83-8cf3-38f5e53f7725.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="79e01232-5ea4-41c8-9331-1c1880a1d3c2"
content="&lt;html&gt;&lt;body&gt;This is the html page 79e01232-5ea4-41c8-9331-1c1880a1d3c2.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="a35b6c5e-22d6-4707-98b4-462482e26c9e"
content="&lt;html&gt;&lt;body&gt;This is the html page a35b6c5e-22d6-4707-98b4-462482e26c9e.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="3aff2f9c-0c7f-4630-99ad-27a0cf1af137"
content="&lt;html&gt;&lt;body&gt;This is the html page 3aff2f9c-0c7f-4630-99ad-27a0cf1af137.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="77ec1d68-84e1-40f4-be8e-066e02f4e373"
content="&lt;html&gt;&lt;body&gt;This is the html page 77ec1d68-84e1-40f4-be8e-066e02f4e373.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="8f824126-0bd1-4074-b88e-c0b59d3e67a3"
content="&lt;html&gt;&lt;body&gt;This is the html page 8f824126-0bd1-4074-b88e-c0b59d3e67a3.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="c6c80c75-b335-4f68-b7a7-59434413ce6c"
content="&lt;html&gt;&lt;body&gt;This is the html page c6c80c75-b335-4f68-b7a7-59434413ce6c.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="f959ecb3-6382-4ae5-9325-8fcbc068e446"
content="&lt;html&gt;&lt;body&gt;This is the html page f959ecb3-6382-4ae5-9325-8fcbc068e446.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="2471caa8-e8df-44d6-94f2-7752a74f6819"
content="&lt;html&gt;&lt;body&gt;This is the html page 2471caa8-e8df-44d6-94f2-7752a74f6819.&lt;/body&gt;&lt;/html&gt;" />
<hstestdb.HTML uuid="fa0979ca-2734-41f7-84c5-e40e0886e408"
content="&lt;html&gt;&lt;body&gt;This is the html page fa0979ca-2734-41f7-84c5-e40e0886e408.&lt;/body&gt;&lt;/html&gt;" />
</dataset>
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