diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000000000000000000000000000000000000..2c55e21aa9928ca9cda5910f0118dd3f9e341da4 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000000000000000000000000000000000..211fc4dc20b27d6ce593f6bd656533fcfd594488 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000000000000000000000000000000000000..ba5acda262640244da36fdc58ecc518a37363cc7 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,1353 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Edit + peop + people + person + addp + nam + modify + addPe + listP + dele + appendToTable + createpetRow + Create + btnSubmit + addpet + create + delete + list + td + input + editpet + error + logout + lis + add + get + getPetInForm + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + project + + + + + + + + + + + + + + + + project + + + true + + + + DIRECTORY + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1487695444459 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Web + + + + + + + + + + + + + + + 1.8 + + + + + + + + main + + + + + + + + 1.8 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/db/daaexample.sql b/db/daaexample.sql new file mode 100644 index 0000000000000000000000000000000000000000..a40c629f47374968bc2db7abc98f62fe95a143ea --- /dev/null +++ b/db/daaexample.sql @@ -0,0 +1,138 @@ +-- phpMyAdmin SQL Dump +-- version 4.6.5.2 +-- https://www.phpmyadmin.net/ +-- +-- Servidor: 127.0.0.1 +-- Tiempo de generación: 26-02-2017 a las 19:38:32 +-- Versión del servidor: 10.1.21-MariaDB +-- Versión de PHP: 5.6.30 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Base de datos: `daaexample` +-- + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `people` +-- + +CREATE TABLE `people` ( + `id` int(11) NOT NULL, + `name` varchar(50) NOT NULL, + `surname` varchar(100) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +-- +-- Volcado de datos para la tabla `people` +-- + +INSERT INTO `people` (`id`, `name`, `surname`) VALUES +(1, 'Antón', 'Pérez'), +(2, 'Manuel', 'Martínez'), +(3, 'Laura', 'Reboredo'), +(4, 'Perico', 'Palotes'), +(5, 'Ana', 'María'), +(6, 'María', 'Nuevo'), +(7, 'Alba', 'Fernández'), +(8, 'Asunción', 'Jiménez'); + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `pet` +-- + +CREATE TABLE `pet` ( + `id` int(11) NOT NULL, + `personId` int(50) NOT NULL, + `nombre` varchar(50) NOT NULL, + `especie` varchar(50) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +-- +-- Volcado de datos para la tabla `pet` +-- + +INSERT INTO `pet` (`id`, `personId`, `nombre`, `especie`) VALUES +(14, 1, 'Dog', 'Dog'), +(15, 2, 'Cat', 'Cat'); + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `users` +-- + +CREATE TABLE `users` ( + `login` varchar(100) NOT NULL, + `password` varchar(64) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +-- +-- Volcado de datos para la tabla `users` +-- + +INSERT INTO `users` (`login`, `password`) VALUES +('admin', '43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70'), +('normal', '688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336'); + +-- +-- Índices para tablas volcadas +-- + +-- +-- Indices de la tabla `people` +-- +ALTER TABLE `people` + ADD PRIMARY KEY (`id`); + +-- +-- Indices de la tabla `pet` +-- +ALTER TABLE `pet` + ADD PRIMARY KEY (`id`), + ADD KEY `pet_ibfk_1` (`personId`); + +-- +-- Indices de la tabla `users` +-- +ALTER TABLE `users` + ADD PRIMARY KEY (`login`); + +-- +-- AUTO_INCREMENT de las tablas volcadas +-- + +-- +-- AUTO_INCREMENT de la tabla `people` +-- +ALTER TABLE `people` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; +-- +-- AUTO_INCREMENT de la tabla `pet` +-- +ALTER TABLE `pet` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; +-- +-- Restricciones para tablas volcadas +-- + +-- +-- Filtros para la tabla `pet` +-- +ALTER TABLE `pet` + ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`personId`) REFERENCES `people` (`id`) ON DELETE CASCADE; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/pom.xml b/pom.xml index 1388a8259f3937118c082f3b4e3999ad885eff82..6aa85915cfe351709c1c753d9281ee75800ae97e 100644 --- a/pom.xml +++ b/pom.xml @@ -581,7 +581,7 @@ https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz - ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator} + ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator} ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz ${geckodriver.basepath}${file.separator}geckodriver @@ -620,7 +620,7 @@ https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip - ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator} + ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator} ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip ${geckodriver.basepath}${file.separator}geckodriver.exe @@ -714,7 +714,7 @@ mac https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz - ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator} + ${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator} ${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz ${geckodriver.basepath}${file.separator}geckodriver diff --git a/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java b/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java index 2a67f22f93bf402148426fd8becb0ce7c8f37dfc..0df167d323a016d756027fdfaabc42e7c66eace8 100644 --- a/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java +++ b/src/main/java/es/uvigo/esei/daa/DAAExampleApplication.java @@ -11,6 +11,7 @@ import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import es.uvigo.esei.daa.rest.PeopleResource; +import es.uvigo.esei.daa.rest.PetResource; import es.uvigo.esei.daa.rest.UsersResource; /** @@ -26,7 +27,8 @@ public class DAAExampleApplication extends Application { public Set> getClasses() { return Stream.of( PeopleResource.class, - UsersResource.class + UsersResource.class, + PetResource.class ).collect(toSet()); } diff --git a/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java new file mode 100644 index 0000000000000000000000000000000000000000..51b546939d2d96ecaa082a8eb23396e365fdda6c --- /dev/null +++ b/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java @@ -0,0 +1,211 @@ +package es.uvigo.esei.daa.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import es.uvigo.esei.daa.entities.Pet; + +/** + * DAO class for the {@link Pet} entities. + * + * Created by LuisF on 23/02/2017. + */ +public class PetDAO extends DAO +{ + private final static Logger LOG = Logger.getLogger(PetDAO.class.getName()); + + /** + * Returns a pet stored persisted in the system. + * + * @param id identifier of the pet. + * @return a pet with the provided identifier. + * @throws DAOException if an error happens while retrieving the pet. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted pet. + */ + public Pet get(int id) + throws DAOException, IllegalArgumentException + { + try (final Connection conn = this.getConnection()) + { + final String query = "SELECT * FROM pet WHERE id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) + { + statement.setInt(1, id); + + try (final ResultSet resultado = statement.executeQuery()) + { + if (resultado.next()) + { + return rowToEntity(resultado); + } else + { + throw new IllegalArgumentException("Invalid id"); + } + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error getting a pet", e); + throw new DAOException(e); + } + } + + /** + * Returns a list with all the pet persisted in the system. + * + * @return a list with all the pet persisted in the system. + * @throws DAOException if an error happens while retrieving the pet. + */ + public List list() throws DAOException + { + try (final Connection conn = this.getConnection()) + { + final String query = "SELECT * FROM pet"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) + { + try (final ResultSet result = statement.executeQuery()) { + final List pet = new LinkedList<>(); + + while (result.next()) { + pet.add(rowToEntity(result)); + } + + return pet; + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error listing pet", e); + throw new DAOException(e); + } + } + + /** + * Persists a new pet in the system. An identifier will be assigned + * automatically to tte new pet. + * + * @param nombre name of the new pet. Can't be {@code null}. + * @param especie surname of the new pet. Can't be {@code null}. + * @param personID surname of the new pet. Can't be {@code null}. + * @return a {@link Pet} entity representing the persisted pet. + * @throws DAOException if an error happens while persisting the new person. + * @throws IllegalArgumentException if the name or specie are {@code null}. + */ + public Pet add(int personID, String nombre, String especie) + throws DAOException, IllegalArgumentException { + if (nombre == null || especie == null) { + throw new IllegalArgumentException("name and specie can't be null"); + } + + try (Connection conn = this.getConnection()) { + final String query = "INSERT INTO pet VALUES(null, ?, ?, ?)"; + + try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + statement.setInt(1, personID); + statement.setString(2, nombre); + statement.setString(3, especie); + + + if (statement.executeUpdate() == 1) { + try (ResultSet resultKeys = statement.getGeneratedKeys()) { + if (resultKeys.next()) { + return new Pet(resultKeys.getInt(1),personID, nombre, especie); + } else { + LOG.log(Level.SEVERE, "Error retrieving inserted id"); + throw new SQLException("Error retrieving inserted id"); + } + } + } else { + LOG.log(Level.SEVERE, "Error inserting value"); + throw new SQLException("Error inserting value"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error adding a pet", e); + throw new DAOException(e); + } + } + + /** + * Modifies a pet previously persisted in the system. The pet will be + * retrieved by the provided id and its current name and specie will be + * replaced with the provided. + * + * @param pet a {@link Pet} entity with the new data. + * @throws DAOException if an error happens while modifying the new pet. + * @throws IllegalArgumentException if the pet is {@code null}. + */ + public void modify(Pet pet) + throws DAOException, IllegalArgumentException + { + if (pet == null) + { + throw new IllegalArgumentException("pet can't be null"); + } + + try (Connection conn = this.getConnection()) + { + final String query = "UPDATE pet SET nombre=?, especie=? WHERE id=?"; + + try (PreparedStatement statement = conn.prepareStatement(query)) { + statement.setString(1, pet.getNombre()); + statement.setString(2, pet.getEspecie()); + statement.setInt(3, pet.getId()); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("name and specie can't be null"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error modifying a pet", e); + throw new DAOException(); + } + } + + /** + * Removes a persisted pet from the system. + * + * @param id identifier of the pet to be deleted. + * @throws DAOException if an error happens while deleting the pet. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted pet. + */ + public void delete(int id) + throws DAOException, IllegalArgumentException + { + try (final Connection conn = this.getConnection()) { + final String query = "DELETE FROM pet WHERE id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) + { + statement.setInt(1, id); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("Invalid id"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error deleting a pet", e); + throw new DAOException(e); + } + } + + private Pet rowToEntity(ResultSet row) throws SQLException { + return new Pet( + row.getInt("id"), + row.getInt("personId"), + row.getString("nombre"), + row.getString("especie") + ); + } + + +} diff --git a/src/main/java/es/uvigo/esei/daa/entities/Pet.java b/src/main/java/es/uvigo/esei/daa/entities/Pet.java new file mode 100644 index 0000000000000000000000000000000000000000..5120014db8e5b6f2ebbb04a4c4bb758e9e0d6038 --- /dev/null +++ b/src/main/java/es/uvigo/esei/daa/entities/Pet.java @@ -0,0 +1,99 @@ +package es.uvigo.esei.daa.entities; + +import static java.util.Objects.requireNonNull; + +/** + * Entidad que representa Mascota + * + * Created by Luis Francisco on 23/02/2017. + */ +public class Pet +{ + private int id; + private int personId; + private String nombre; + private String especie; + + // Constructor needed for the JSON conversion + Pet() {} + + /** + * Constructs a new instance of {@link Pet}. + * + * @param id identificador de la mascota. + * @param nombre nombre de la mascota. + * @param especie tipo de especie de la mascota. + */ + public Pet(int id, int personId, String nombre, String especie) + { + this.personId = personId; + this.id = id; + this.setNombre(nombre); + this.setEspecie(especie); + } + + /** + * Devuelve el identificador de la mascota. + * + * @return identificador de la mascota. + */ + public int getId() + { + return id; + } + + /** + * Devuelve el identificador del dueño de la mascota. + * + * @return identificador del dueño de la mascota. + */ + public int getPersonId() + { + return personId; + } + + /** + * Devuelve el nombre de la mascota. + * + * @return nombre de la mascota. + */ + public String getNombre() + { + return nombre; + } + + /** + * Modifica el nombre de la mascota. + * + * @param nombre nuevo nombre de la mascota. + * @throws NullPointerException if the {@code name} is {@code null}. + */ + public void setNombre(String nombre) + { + this.nombre = requireNonNull(nombre, "Name can't be null"); + } + + /** + * Devuelve el especie de la mascota. + * + * @return especie de la mascota. + */ + public String getEspecie() + { + return especie; + } + + /** + * Modifica la especie de la mascota. + * + * @param especie especie de la mascota. + * @throws NullPointerException if the {@code name} is {@code null}. + */ + public void setEspecie(String especie) + { + this.especie = requireNonNull(especie, "Specie can't be null"); + } + + //Faltan los override, preguntarle a Martín + +} diff --git a/src/main/java/es/uvigo/esei/daa/rest/PetResource.java b/src/main/java/es/uvigo/esei/daa/rest/PetResource.java new file mode 100644 index 0000000000000000000000000000000000000000..80be36cb7386fb4cdf62cee5095ae54d6eab4c8b --- /dev/null +++ b/src/main/java/es/uvigo/esei/daa/rest/PetResource.java @@ -0,0 +1,207 @@ +package es.uvigo.esei.daa.rest; + +import es.uvigo.esei.daa.dao.DAOException; +import es.uvigo.esei.daa.dao.PetDAO; +import es.uvigo.esei.daa.entities.Pet; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * REST resource for managing pet. + * + * @author Miguel Reboiro Jato. + */ +@Path("/pet") +@Produces(MediaType.APPLICATION_JSON) +public class PetResource { + private final static Logger LOG = Logger.getLogger(PetResource.class.getName()); + + private final PetDAO dao; + + /** + * Constructs a new instance of {@link PetResource}. + */ + public PetResource() { + this(new PetDAO()); + } + + // Needed for testing purposes + PetResource(PetDAO dao) { + this.dao = dao; + } + + /** + * Returns a pet with the provided identifier. + * + * @param id the identifier of the pet to retrieve. + * @return a 200 OK response with a pet that has the provided identifier. + * If the identifier does not corresponds with any user, a 400 Bad Request + * response with an error message will be returned. If an error happens + * while retrieving the list, a 500 Internal Server Error response with an + * error message will be returned. + */ + @GET + @Path("/{id}") + public Response get( + @PathParam("id") int id + ) { + try { + final Pet pet = this.dao.get(id); + + return Response.ok(pet).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid pet id in get method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error getting a pet", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Returns the complete list of pet stored in the system. + * + * @return a 200 OK response with the complete list of pet stored in the + * system. If an error happens while retrieving the list, a 500 Internal + * Server Error response with an error message will be returned. + */ + @GET + public Response list( + ) { + try { + return Response.ok(this.dao.list()).build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error listing pet", e); + return Response.serverError().entity(e.getMessage()).build(); + } + } + + /** + * Creates a new pet in the system. + * + * @param name the name of the new pet. + * @param surname the surname of the new pet. + * @return a 200 OK response with a pet that has been created. If the + * name or the surname are not provided, a 400 Bad Request response with an + * error message will be returned. If an error happens while retrieving the + * list, a 500 Internal Server Error response with an error message will be + * returned. + */ + @POST + @Path("/{personId}") + public Response add( + @PathParam("personId") int id, + @FormParam("nombre") String nombre, + @FormParam("especie") String especie + ) { + try { + + final Pet newpet = this.dao.add(id, nombre, especie); + + return Response.ok(newpet).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid pet id in add method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error adding a pet", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Modifies the data of a pet. + * + * @param id identifier of the pet to modify. + * @param name the new name of the pet. + * @param surname the new surname of the pet. + * @return a 200 OK response with a pet that has been modified. If the + * identifier does not corresponds with any user or the name or surname are + * not provided, a 400 Bad Request response with an error message will be + * returned. If an error happens while retrieving the list, a 500 Internal + * Server Error response with an error message will be returned. + */ + @PUT + @Path("/{id}") + public Response modify( + @PathParam("id") int id, + @FormParam("nombre") String name, + @FormParam("especie") String surname + ) { + try { + final Pet modifiedpet = new Pet(id, 0, name, surname); + this.dao.modify(modifiedpet); + + return Response.ok(modifiedpet).build(); + } catch (NullPointerException npe) { + final String message = String.format("Invalid data for pet (name: %s, surname: %s)", name, surname); + + LOG.log(Level.FINE, message); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(message) + .build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid pet id in modify method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error modifying a pet", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Deletes a pet from the system. + * + * @param id the identifier of the pet to be deleted. + * @return a 200 OK response with the identifier of the pet that has + * been deleted. If the identifier does not corresponds with any user, a 400 + * Bad Request response with an error message will be returned. If an error + * happens while retrieving the list, a 500 Internal Server Error response + * with an error message will be returned. + */ + @DELETE + @Path("/{id}") + public Response delete( + @PathParam("id") int id + ) { + try { + this.dao.delete(id); + + return Response.ok(id).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid pet id in delete method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error deleting a pet", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } +} diff --git a/src/main/main.iml b/src/main/main.iml new file mode 100644 index 0000000000000000000000000000000000000000..80f236980f889d055114e9a26c5228bbd80d9c4f --- /dev/null +++ b/src/main/main.iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/js/dao/pet.js b/src/main/webapp/js/dao/pet.js new file mode 100644 index 0000000000000000000000000000000000000000..10e55fa8c3ae68b95455b50819d0572d05a9eff1 --- /dev/null +++ b/src/main/webapp/js/dao/pet.js @@ -0,0 +1,54 @@ +var PetDAO = (function() { + var resourcePath = "rest/pet/"; + var requestByAjax = function(data, done, fail, always) { + done = typeof done !== 'undefined' ? done : function() {}; + fail = typeof fail !== 'undefined' ? fail : function() {}; + always = typeof always !== 'undefined' ? always : function() {}; + + $.ajax(data) + .done(done) + .fail(fail) + .always(always); + }; + + function PetDAO() { + this.listPet = function(done, fail, always) { + requestByAjax({ + url: resourcePath, + type: 'GET' + }, done, fail, always); + }; + + this.getUser = function(done, fail, always) { + requestByAjax({ + url: resourcePath, + type: 'GET' + }, done, fail, always); + }; + + this.addPet = function(pet, done, fail, always) { + requestByAjax({ + url: resourcePath + pet.personId, + type: 'POST', + data: pet + }, done, fail, always); + }; + + this.modifyPet = function(pet, done, fail, always) { + requestByAjax({ + url: resourcePath + pet.id, + type: 'PUT', + data: pet + }, done, fail, always); + }; + + this.deletePet = function(id, done, fail, always) { + requestByAjax({ + url: resourcePath + id, + type: 'DELETE', + }, done, fail, always); + }; + } + + return PetDAO; +})(); \ No newline at end of file diff --git a/src/main/webapp/js/view/people.js b/src/main/webapp/js/view/people.js index 1f7bc5ec03d301065334b27dd3cbee15c881a8ad..0b521dc7fed5686978d61f877a774eb410ce14a5 100644 --- a/src/main/webapp/js/view/people.js +++ b/src/main/webapp/js/view/people.js @@ -148,6 +148,9 @@ var PeopleView = (function() { \ Delete\ \ + \ + Pet\ + \ '; } @@ -171,6 +174,12 @@ var PeopleView = (function() { ); } }); + + //pasamos la id de persona + $('#person-' + person.id + ' a.pet').click(function() { + + location.href="pet.html?"+person.id; + }); } var appendToTable = function(person) { diff --git a/src/main/webapp/js/view/pet.js b/src/main/webapp/js/view/pet.js new file mode 100644 index 0000000000000000000000000000000000000000..6aa2e937b7364f8200d6e3936c13e0dde2033cc6 --- /dev/null +++ b/src/main/webapp/js/view/pet.js @@ -0,0 +1,194 @@ +var PetView = (function() { + var dao; + + // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. + var self; + var url = window.location.href; + var personId; + + var formId = 'pet-form'; + var listId = 'pet-list'; + var formQuery = '#' + formId; + var listQuery = '#' + listId; + + function PetView(petDao, formContainerId, listContainerId) { + dao = petDao; + self = this; + personId= url.substring(url.lastIndexOf('?') + 1); + + insertPetForm($('#' + formContainerId)); + insertPetList($('#' + listContainerId)); + + this.init = function() { + var pet = self.getPetInForm(); + + dao.listPet(function(pet) + { + $.each(pet, function(key, pet) { + appendToTable(pet); + }); + }); + + // La acción por defecto de enviar formulario (submit) se sobreescribe + // para que el envío sea a través de AJAX + $(formQuery).submit(function(event) { + var pet = self.getPetInForm(); + + if (self.isEditing()) { + dao.modifyPet(pet, + function(pet) { + $('#pet-' + pet.id + ' td.personId').text(pet.personId); + $('#pet-' + pet.id + ' td.nombre').text(pet.nombre); + $('#pet-' + pet.id + ' td.especie').text(pet.especie); + self.resetForm(); + }, + showErrorMessage, + self.enableForm + ); + } else { + dao.addPet(pet, + function(pet) { + appendToTable(pet); + self.resetForm(); + }, + showErrorMessage, + self.enableForm + ); + } + + return false; + }); + + $('#btnClear').click(this.resetForm); + }; + + this.getPetInForm = function() { + var form = $(formQuery); + return { + 'id': form.find('input[name="id"]').val(), + 'personId': form.find('input[name="personId"]').val(), + 'nombre': form.find('input[name="nombre"]').val(), + 'especie': form.find('input[name="especie"]').val() + }; + }; + + this.getPetInRow = function(id) { + var row = $('#pet-' + id); + + if (row !== undefined) { + return { + 'id': id, + 'nombre': row.find('td.nombre').text(), + 'especie': row.find('td.especie').text() + }; + } else { + return undefined; + } + }; + + this.editpet = function(id) { + var row = $('#pet-' + id); + + console.log(row); + if (row !== undefined) { + var form = $(formQuery); + console.log(form); + console.log(row.find('td.nombre').text()); + console.log(row.find('td.especie').text()); + + form.find('input[name="id"]').val(id); + form.find('input[name="nombre"]').val(row.find('td.nombre').text()); + form.find('input[name="especie"]').val(row.find('td.especie').text()); + } + } + + this.isEditing = function() { + return $(formQuery + ' input[name="id"]').val() != ""; + }; + + this.disableForm = function() { + $(formQuery + ' input').prop('disabled', true); + }; + + this.enableForm = function() { + $(formQuery + ' input').prop('disabled', false); + }; + + this.resetForm = function() { + $(formQuery)[0].reset(); + $(formQuery + ' input[name="id"]').val(''); + $('#btnSubmit').val('Crear'); + }; + } + + var insertPetList = function(parent) { + parent.append( + '\ + \ + \ + \ + \ + \ + \ +
NombreEspecie
' + ); + } + + var insertPetForm = function(parent) { + parent.append( + '
\ + \ + \ + \ + \ + \ + \ +
' + ); + } + + var createpetRow = function(pet) { + if(pet.personId == personId) { + return '\ + ' + pet.nombre + '\ + ' + pet.especie + '\ + \ + Edit\ + \ + \ + Delete\ + \ + '; + } + } + + var showErrorMessage = function(jqxhr, textStatus, error) { + alert(textStatus + ": " + error); + } + + var addRowListeners = function(pet) { + $('#pet-' + pet.id + ' a.edit').click(function() { + self.editpet(pet.id); + $('input#btnSubmit').val('Modificar'); + }); + + $('#pet-' + pet.id + ' a.delete').click(function() { + if (confirm('Está a punto de eliminar a una mascota. ¿Está seguro de que desea continuar?')) { + dao.deletePet(pet.id, + function() { + $('tr#pet-' + pet.id).remove(); + }, + showErrorMessage + ); + } + }); + } + + var appendToTable = function(pet) { + $(listQuery + ' > tbody:last') + .append(createpetRow(pet)); + addRowListeners(pet); + } + + return PetView; +})(); diff --git a/src/main/webapp/pet.html b/src/main/webapp/pet.html new file mode 100644 index 0000000000000000000000000000000000000000..79e98a60a4d3f1a18ec238d99436ddb43b89b710 --- /dev/null +++ b/src/main/webapp/pet.html @@ -0,0 +1,25 @@ + + + + +DAA Example + + +
+

Pet

+ Logout + Home +
+ + + + + + + \ No newline at end of file diff --git a/src/test/test.iml b/src/test/test.iml new file mode 100644 index 0000000000000000000000000000000000000000..5ebc6f48ecbe7e78271fcbb44057f6682d802638 --- /dev/null +++ b/src/test/test.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file