From 2059c6451bb0bfb84b31ba4fc1903c8d5a7caff9 Mon Sep 17 00:00:00 2001 From: aggonzalez Date: Thu, 1 Apr 2021 13:01:48 +0200 Subject: [PATCH] Se corrigen errores en test capa rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit También se añade las restricciones en web.xml para pets --- nb-configuration.xml | 18 + .../java/es/uvigo/esei/daa/dao/PeopleDAO.java | 340 ++++++++--------- .../java/es/uvigo/esei/daa/dao/PetDAO.java | 9 +- .../java/es/uvigo/esei/daa/entities/Pet.java | 2 +- .../es/uvigo/esei/daa/rest/PetResource.java | 290 +++++++------- src/main/webapp/WEB-INF/web.xml | 14 + src/main/webapp/js/dao/people.js | 8 + src/main/webapp/js/dao/pets.js | 3 +- src/main/webapp/js/view/people.js | 354 +++++++++--------- src/main/webapp/js/view/pets.js | 102 +++-- .../uvigo/esei/daa/rest/PetResourceTest.java | 6 +- src/test/resources/datasets/dataset-add.xml | 9 +- .../resources/datasets/dataset-add_pets.xml | 24 ++ .../resources/datasets/dataset-delete.xml | 7 +- .../datasets/dataset-delete_pets.xml | 22 ++ .../resources/datasets/dataset-modify.xml | 8 +- .../datasets/dataset-modify_pets.xml | 23 ++ 17 files changed, 680 insertions(+), 559 deletions(-) create mode 100644 nb-configuration.xml create mode 100644 src/test/resources/datasets/dataset-add_pets.xml create mode 100644 src/test/resources/datasets/dataset-delete_pets.xml create mode 100644 src/test/resources/datasets/dataset-modify_pets.xml diff --git a/nb-configuration.xml b/nb-configuration.xml new file mode 100644 index 0000000..4da1f6c --- /dev/null +++ b/nb-configuration.xml @@ -0,0 +1,18 @@ + + + + + + ide + + diff --git a/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java index 1d99edb..abc2690 100644 --- a/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java +++ b/src/main/java/es/uvigo/esei/daa/dao/PeopleDAO.java @@ -14,178 +14,178 @@ import es.uvigo.esei.daa.entities.Person; /** * DAO class for the {@link Person} entities. - * + * * @author Miguel Reboiro Jato * */ public class PeopleDAO extends DAO { - private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName()); - - /** - * Returns a person stored persisted in the system. - * - * @param id identifier of the person. - * @return a person with the provided identifier. - * @throws DAOException if an error happens while retrieving the person. - * @throws IllegalArgumentException if the provided id does not corresponds - * with any persisted person. - */ - public Person get(int id) - throws DAOException, IllegalArgumentException { - try (final Connection conn = this.getConnection()) { - final String query = "SELECT * FROM people WHERE id=?"; - - try (final PreparedStatement statement = conn.prepareStatement(query)) { - statement.setInt(1, id); - - try (final ResultSet result = statement.executeQuery()) { - if (result.next()) { - return rowToEntity(result); - } else { - throw new IllegalArgumentException("Invalid id"); - } - } - } - } catch (SQLException e) { - LOG.log(Level.SEVERE, "Error getting a person", e); - throw new DAOException(e); - } - } - - /** - * Returns a list with all the people persisted in the system. - * - * @return a list with all the people persisted in the system. - * @throws DAOException if an error happens while retrieving the people. - */ - public List list() throws DAOException { - try (final Connection conn = this.getConnection()) { - final String query = "SELECT * FROM people"; - - try (final PreparedStatement statement = conn.prepareStatement(query)) { - try (final ResultSet result = statement.executeQuery()) { - final List people = new LinkedList<>(); - - while (result.next()) { - people.add(rowToEntity(result)); - } - - return people; - } - } - } catch (SQLException e) { - LOG.log(Level.SEVERE, "Error listing people", e); - throw new DAOException(e); - } - } - - /** - * Persists a new person in the system. An identifier will be assigned - * automatically to the new person. - * - * @param name name of the new person. Can't be {@code null}. - * @param surname surname of the new person. Can't be {@code null}. - * @return a {@link Person} entity representing the persisted person. - * @throws DAOException if an error happens while persisting the new person. - * @throws IllegalArgumentException if the name or surname are {@code null}. - */ - public Person add(String name, String surname) - throws DAOException, IllegalArgumentException { - if (name == null || surname == null) { - throw new IllegalArgumentException("name and surname can't be null"); - } - - try (Connection conn = this.getConnection()) { - final String query = "INSERT INTO people VALUES(null, ?, ?)"; - - try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { - statement.setString(1, name); - statement.setString(2, surname); - - if (statement.executeUpdate() == 1) { - try (ResultSet resultKeys = statement.getGeneratedKeys()) { - if (resultKeys.next()) { - return new Person(resultKeys.getInt(1), name, surname); - } else { - LOG.log(Level.SEVERE, "Error retrieving inserted id"); - throw new SQLException("Error retrieving inserted id"); - } - } - } else { - LOG.log(Level.SEVERE, "Error inserting value"); - throw new SQLException("Error inserting value"); - } - } - } catch (SQLException e) { - LOG.log(Level.SEVERE, "Error adding a person", e); - throw new DAOException(e); - } - } - - /** - * Modifies a person previously persisted in the system. The person will be - * retrieved by the provided id and its current name and surname will be - * replaced with the provided. - * - * @param person a {@link Person} entity with the new data. - * @throws DAOException if an error happens while modifying the new person. - * @throws IllegalArgumentException if the person is {@code null}. - */ - public void modify(Person person) - throws DAOException, IllegalArgumentException { - if (person == null) { - throw new IllegalArgumentException("person can't be null"); - } - - try (Connection conn = this.getConnection()) { - final String query = "UPDATE people SET name=?, surname=? WHERE id=?"; - - try (PreparedStatement statement = conn.prepareStatement(query)) { - statement.setString(1, person.getName()); - statement.setString(2, person.getSurname()); - statement.setInt(3, person.getId()); - - if (statement.executeUpdate() != 1) { - throw new IllegalArgumentException("name and surname can't be null"); - } - } - } catch (SQLException e) { - LOG.log(Level.SEVERE, "Error modifying a person", e); - throw new DAOException(); - } - } - - /** - * Removes a persisted person from the system. - * - * @param id identifier of the person to be deleted. - * @throws DAOException if an error happens while deleting the person. - * @throws IllegalArgumentException if the provided id does not corresponds - * with any persisted person. - */ - public void delete(int id) - throws DAOException, IllegalArgumentException { - try (final Connection conn = this.getConnection()) { - final String query = "DELETE FROM people WHERE id=?"; - - try (final PreparedStatement statement = conn.prepareStatement(query)) { - statement.setInt(1, id); - - if (statement.executeUpdate() != 1) { - throw new IllegalArgumentException("Invalid id"); - } - } - } catch (SQLException e) { - LOG.log(Level.SEVERE, "Error deleting a person", e); - throw new DAOException(e); - } - } - - private Person rowToEntity(ResultSet row) throws SQLException { - return new Person( - row.getInt("id"), - row.getString("name"), - row.getString("surname") - ); - } + + private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName()); + + /** + * Returns a person stored persisted in the system. + * + * @param id identifier of the person. + * @return a person with the provided identifier. + * @throws DAOException if an error happens while retrieving the person. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted person. + */ + public Person get(int id) + throws DAOException, IllegalArgumentException { + try (final Connection conn = this.getConnection()) { + final String query = "SELECT * FROM people WHERE id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, id); + + try (final ResultSet result = statement.executeQuery()) { + if (result.next()) { + return rowToEntity(result); + } else { + throw new IllegalArgumentException("Invalid id"); + } + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error getting a person", e); + throw new DAOException(e); + } + } + + /** + * Returns a list with all the people persisted in the system. + * + * @return a list with all the people persisted in the system. + * @throws DAOException if an error happens while retrieving the people. + */ + public List list() throws DAOException { + try (final Connection conn = this.getConnection()) { + final String query = "SELECT * FROM people"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + try (final ResultSet result = statement.executeQuery()) { + final List people = new LinkedList<>(); + + while (result.next()) { + people.add(rowToEntity(result)); + } + + return people; + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error listing people", e); + throw new DAOException(e); + } + } + + /** + * Persists a new person in the system. An identifier will be assigned + * automatically to the new person. + * + * @param name name of the new person. Can't be {@code null}. + * @param surname surname of the new person. Can't be {@code null}. + * @return a {@link Person} entity representing the persisted person. + * @throws DAOException if an error happens while persisting the new person. + * @throws IllegalArgumentException if the name or surname are {@code null}. + */ + public Person add(String name, String surname) + throws DAOException, IllegalArgumentException { + if (name == null || surname == null) { + throw new IllegalArgumentException("name and surname can't be null"); + } + + try (Connection conn = this.getConnection()) { + final String query = "INSERT INTO people VALUES(null, ?, ?)"; + + try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + statement.setString(1, name); + statement.setString(2, surname); + + if (statement.executeUpdate() == 1) { + try (ResultSet resultKeys = statement.getGeneratedKeys()) { + if (resultKeys.next()) { + return new Person(resultKeys.getInt(1), name, surname); + } else { + LOG.log(Level.SEVERE, "Error retrieving inserted id"); + throw new SQLException("Error retrieving inserted id"); + } + } + } else { + LOG.log(Level.SEVERE, "Error inserting value"); + throw new SQLException("Error inserting value"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error adding a person", e); + throw new DAOException(e); + } + } + + /** + * Modifies a person previously persisted in the system. The person will be + * retrieved by the provided id and its current name and surname will be + * replaced with the provided. + * + * @param person a {@link Person} entity with the new data. + * @throws DAOException if an error happens while modifying the new person. + * @throws IllegalArgumentException if the person is {@code null}. + */ + public void modify(Person person) + throws DAOException, IllegalArgumentException { + if (person == null) { + throw new IllegalArgumentException("person can't be null"); + } + + try (Connection conn = this.getConnection()) { + final String query = "UPDATE people SET name=?, surname=? WHERE id=?"; + + try (PreparedStatement statement = conn.prepareStatement(query)) { + statement.setString(1, person.getName()); + statement.setString(2, person.getSurname()); + statement.setInt(3, person.getId()); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("name and surname can't be null"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error modifying a person", e); + throw new DAOException(); + } + } + + /** + * Removes a persisted person from the system. + * + * @param id identifier of the person to be deleted. + * @throws DAOException if an error happens while deleting the person. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted person. + */ + public void delete(int id) + throws DAOException, IllegalArgumentException { + try (final Connection conn = this.getConnection()) { + final String query = "DELETE FROM people WHERE id=?"; + try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, id); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("Invalid id"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error deleting a person", e); + throw new DAOException(e); + } + } + + private Person rowToEntity(ResultSet row) throws SQLException { + return new Person( + row.getInt("id"), + row.getString("name"), + row.getString("surname") + ); + } } diff --git a/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java index 0bc99e2..b6084a3 100644 --- a/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java +++ b/src/main/java/es/uvigo/esei/daa/dao/PetDAO.java @@ -87,8 +87,13 @@ public class PetDAO extends DAO { } public Pet add(String name, String type, int peopleID) throws DAOException, IllegalArgumentException { - if (name == null || type==null) { - throw new IllegalArgumentException("name and type can't be null"); + /*Debido a la forma en la que se generan las PK de people nunca puede + existir una persona con ID igual a 0 que es el caso de si faltase el + valor peopleID en el formulario de añadir de pets + */ + + if (name == null || type==null || peopleID==0) { + throw new IllegalArgumentException("name, type or peopleID can't be null"); } try (Connection conn = this.getConnection()) { diff --git a/src/main/java/es/uvigo/esei/daa/entities/Pet.java b/src/main/java/es/uvigo/esei/daa/entities/Pet.java index 4a19369..c51f68a 100644 --- a/src/main/java/es/uvigo/esei/daa/entities/Pet.java +++ b/src/main/java/es/uvigo/esei/daa/entities/Pet.java @@ -49,7 +49,7 @@ public class Pet { } public void setPeopleID(int peopleID) { - this.peopleID = requireNonNull(peopleID, "PeopleID can't be null"); + this.peopleID = requireNonNull(peopleID, "PeopleID can't be null"); } @Override diff --git a/src/main/java/es/uvigo/esei/daa/rest/PetResource.java b/src/main/java/es/uvigo/esei/daa/rest/PetResource.java index bfa6ed3..5d0ce2e 100644 --- a/src/main/java/es/uvigo/esei/daa/rest/PetResource.java +++ b/src/main/java/es/uvigo/esei/daa/rest/PetResource.java @@ -20,155 +20,155 @@ import es.uvigo.esei.daa.entities.Pet; /** * REST resource for managing people. - * + * * @author Imanol Cobian Martinez */ @Path("/pets") @Produces(MediaType.APPLICATION_JSON) public class PetResource { - private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName()); - - private final PetDAO dao; - - public PetResource() { - this(new PetDAO()); - } - - PetResource(PetDAO dao) { - this.dao = dao; - } - - @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(); - } - } - - @GET - public Response listAll() { - try { - return Response.ok(this.dao.listAll()).build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error listing pets", e); - return Response.serverError().entity(e.getMessage()).build(); - } - } - - @GET - @Path("/people{peopleID}") - public Response listByPeopleID( - @PathParam("peopleID") int peopleID - ) { - try { - return Response.ok(this.dao.listByPeopleID(peopleID)).build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error listing pets", e); - return Response.serverError().entity(e.getMessage()).build(); - } - } - - @POST - public Response add( - @FormParam("name") String name, - @FormParam("type") String type, - @FormParam("peopleID") int peopleID - - ) { - try { - final Pet newPet = this.dao.add(name,type,peopleID); - - 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(); - } - } - - @PUT - @Path("/{id}") - public Response modify( - @PathParam("id") int id, - @FormParam("name") String name, - @FormParam("type") String type, - @FormParam("peopleID") int peopleID - ) { - try { - final Pet modifiedPet = new Pet(id, name,type,peopleID); - this.dao.modify(modifiedPet); - - return Response.ok(modifiedPet).build(); - } catch (NullPointerException npe) { - final String message = String.format("Invalid data for person (name: %s, peopleID: %s)", name, peopleID); - - 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(); - } - } - - @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(); - } - } + private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName()); + + private final PetDAO dao; + + public PetResource() { + this(new PetDAO()); + } + + PetResource(PetDAO dao) { + this.dao = dao; + } + + @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(); + } + } + + @GET + public Response listAll() { + try { + return Response.ok(this.dao.listAll()).build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error listing pets", e); + return Response.serverError().entity(e.getMessage()).build(); + } + } + + @GET + @Path("/people{peopleID}") + public Response listByPeopleID( + @PathParam("peopleID") int peopleID + ) { + try { + return Response.ok(this.dao.listByPeopleID(peopleID)).build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error listing pets", e); + return Response.serverError().entity(e.getMessage()).build(); + } + } + + @POST + public Response add( + @FormParam("name") String name, + @FormParam("type") String type, + @FormParam("peopleID") int peopleID + ) { + try { + System.out.println("Esto es el nombre:"+name); + final Pet newPet = this.dao.add(name, type, peopleID); + + 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(); + } + } + + @PUT + @Path("/{id}") + public Response modify( + @PathParam("id") int id, + @FormParam("name") String name, + @FormParam("type") String type, + @FormParam("peopleID") int peopleID + ) { + try { + final Pet modifiedPet = new Pet(id, name, type, peopleID); + this.dao.modify(modifiedPet); + + return Response.ok(modifiedPet).build(); + } catch (NullPointerException npe) { + final String message = String.format("Invalid data for person (name: %s, peopleID: %s)", name, peopleID); + + 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(); + } + } + + @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/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index f748eff..9a54339 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -59,6 +59,20 @@ ADMIN + + + + Admin Area + /rest/pets/* + GET + PUT + DELETE + POST + + + ADMIN + + diff --git a/src/main/webapp/js/dao/people.js b/src/main/webapp/js/dao/people.js index 29618ee..b697319 100644 --- a/src/main/webapp/js/dao/people.js +++ b/src/main/webapp/js/dao/people.js @@ -22,6 +22,14 @@ var PeopleDAO = (function() { type : 'GET' }, done, fail, always); }; + + this.listPeopleSync = function(done, fail, always) { + requestByAjax({ + url : resourcePath, + type : 'GET', + async:false + }, done, fail, always); + }; this.addPerson = function(person, done, fail, always) { requestByAjax({ diff --git a/src/main/webapp/js/dao/pets.js b/src/main/webapp/js/dao/pets.js index bd80be6..6d0daea 100644 --- a/src/main/webapp/js/dao/pets.js +++ b/src/main/webapp/js/dao/pets.js @@ -21,7 +21,8 @@ var PetDAO = (function () { this.listPetsByPeopleID = function (peopleID,done, fail, always) { requestByAjax({ url: resourcePath + 'people' + peopleID, - type: 'GET' + type: 'GET', + async:false }, done, fail, always); }; diff --git a/src/main/webapp/js/view/people.js b/src/main/webapp/js/view/people.js index cac09d4..8805b83 100644 --- a/src/main/webapp/js/view/people.js +++ b/src/main/webapp/js/view/people.js @@ -1,134 +1,148 @@ -var PeopleView = (function() { - var dao; - - // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. - var self; - - var formId = 'people-form'; - var listId = 'people-list'; - var formQuery = '#' + formId; - var listQuery = '#' + listId; - - function PeopleView(peopleDao, formContainerId, listContainerId) { - dao = peopleDao; - self = this; - - insertPeopleForm($('#' + formContainerId)); - insertPeopleList($('#' + listContainerId)); - - this.init = function() { - dao.listPeople(function(people) { - $.each(people, function(key, person) { - appendToTable(person); - }); - }, - function() { - alert('No has sido posible acceder al listado de personas.'); - }); - - // La acción por defecto de enviar formulario (submit) se sobreescribe - // para que el envío sea a través de AJAX - $(formQuery).submit(function(event) { - var person = self.getPersonInForm(); - - if (self.isEditing()) { - dao.modifyPerson(person, - function(person) { - $('#person-' + person.id + ' td.name').text(person.name); - $('#person-' + person.id + ' td.surname').text(person.surname); - $('#person-' + person.id + ' td.pet_type').text(person.type); - self.resetForm(); - }, - showErrorMessage, - self.enableForm - ); - } else { - dao.addPerson(person, - function(person) { - appendToTable(person); - self.resetForm(); - }, - showErrorMessage, - self.enableForm - ); - } - - return false; - }); - - $('#btnClear').click(this.resetForm); - }; - - this.getPersonInForm = function() { - var form = $(formQuery); - return { - 'id': form.find('input[name="id"]').val(), - 'name': form.find('input[name="name"]').val(), - 'surname': form.find('input[name="surname"]').val() - }; - }; - - this.getPersonInRow = function(id) { - var row = $('#person-' + id); - - if (row !== undefined) { - return { - 'id': id, - 'name': row.find('td.name').text(), - 'surname': row.find('td.surname').text() - }; - } else { - return undefined; - } - }; - - this.editPerson = function(id) { - var row = $('#person-' + id); - - if (row !== undefined) { - var form = $(formQuery); - - form.find('input[name="id"]').val(id); - form.find('input[name="name"]').val(row.find('td.name').text()); - form.find('input[name="surname"]').val(row.find('td.surname').text()); - - $('input#btnSubmit').val('Modificar'); - } - }; - - this.deletePerson = function(id) { - if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) { - dao.deletePerson(id, - function() { - $('tr#person-' + id).remove(); - }, - showErrorMessage - ); - } - }; - - this.isEditing = function() { - return $(formQuery + ' input[name="id"]').val() != ""; - }; - - this.disableForm = function() { - $(formQuery + ' input').prop('disabled', true); - }; - - this.enableForm = function() { - $(formQuery + ' input').prop('disabled', false); - }; - - this.resetForm = function() { - $(formQuery)[0].reset(); - $(formQuery + ' input[name="id"]').val(''); - $('#btnSubmit').val('Crear'); - }; - }; - - var insertPeopleList = function(parent) { - parent.append( - '\ +var PeopleView = (function () { + var dao; + + // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. + var self; + + var formId = 'people-form'; + var listId = 'people-list'; + var formQuery = '#' + formId; + var listQuery = '#' + listId; + + function PeopleView(peopleDao, formContainerId, listContainerId) { + dao = peopleDao; + self = this; + + insertPeopleForm($('#' + formContainerId)); + insertPeopleList($('#' + listContainerId)); + + this.init = function () { + dao.listPeople(function (people) { + $.each(people, function (key, person) { + appendToTable(person); + }); + }, + function () { + alert('No has sido posible acceder al listado de personas.'); + }); + + // La acción por defecto de enviar formulario (submit) se sobreescribe + // para que el envío sea a través de AJAX + $(formQuery).submit(function (event) { + var person = self.getPersonInForm(); + + if (self.isEditing()) { + dao.modifyPerson(person, + function (person) { + $('#person-' + person.id + ' td.name').text(person.name); + $('#person-' + person.id + ' td.surname').text(person.surname); + $('#person-' + person.id + ' td.pet_type').text(person.type); + self.resetForm(); + }, + showErrorMessage, + self.enableForm + ); + } else { + dao.addPerson(person, + function (person) { + appendToTable(person); + self.resetForm(); + }, + showErrorMessage, + self.enableForm + ); + } + + return false; + }); + + $('#btnClear').click(this.resetForm); + }; + + this.getPersonInForm = function () { + var form = $(formQuery); + return { + 'id': form.find('input[name="id"]').val(), + 'name': form.find('input[name="name"]').val(), + 'surname': form.find('input[name="surname"]').val() + }; + }; + + this.getPersonInRow = function (id) { + var row = $('#person-' + id); + + if (row !== undefined) { + return { + 'id': id, + 'name': row.find('td.name').text(), + 'surname': row.find('td.surname').text() + }; + } else { + return undefined; + } + }; + + this.editPerson = function (id) { + var row = $('#person-' + id); + + if (row !== undefined) { + var form = $(formQuery); + + form.find('input[name="id"]').val(id); + form.find('input[name="name"]').val(row.find('td.name').text()); + form.find('input[name="surname"]').val(row.find('td.surname').text()); + + $('input#btnSubmit').val('Modificar'); + } + }; + + this.deletePerson = function (id) { + var cont = 0; + var daoPet = new PetDAO(); + daoPet.listPetsByPeopleID(id, function (people) { + $.each(people, function (key, pet) { + cont++; + }); + }, function () { + alert('No has sido posible acceder al listado de mascotas.'); + }); + if (cont == 0) { + if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) { + dao.deletePerson(id, + function () { + $('tr#person-' + id).remove(); + }, + showErrorMessage + ); + } + } else { + alert('No puedes eliminar esta persona porque tiene mascotas asignadas'); + } + }; + + this.isEditing = function () { + return $(formQuery + ' input[name="id"]').val() != ""; + }; + + this.disableForm = function () { + $(formQuery + ' input').prop('disabled', true); + }; + + this.enableForm = function () { + $(formQuery + ' input').prop('disabled', false); + }; + + this.resetForm = function () { + $(formQuery)[0].reset(); + $(formQuery + ' input[name="id"]').val(''); + $('#btnSubmit').val('Crear'); + }; + } + ; + + var insertPeopleList = function (parent) { + parent.append( + '
\ \ \ \ @@ -139,12 +153,12 @@ var PeopleView = (function() { \ \
Nombre
' - ); - }; + ); + }; - var insertPeopleForm = function(parent) { - parent.append( - '
\ + var insertPeopleForm = function (parent) { + parent.append( + '\ \
\
\ @@ -159,11 +173,11 @@ var PeopleView = (function() {
\
\
' - ); - }; + ); + }; - var createPersonRow = function(person) { - return '\ + var createPersonRow = function (person) { + return '\ ' + person.name + '\ ' + person.surname + '\ \ @@ -172,35 +186,35 @@ var PeopleView = (function() { Mascotas\ \ '; - }; - - var showErrorMessage = function(jqxhr, textStatus, error) { - alert(textStatus + ": " + error); - }; - - var addRowListeners = function(person) { - $('#person-' + person.id + ' a.edit').click(function() { - self.editPerson(person.id); - }); - - $('#person-' + person.id + ' a.delete').click(function() { - self.deletePerson(person.id); - }); - - $('#person-' + person.id + ' a.show').click(function () { - document.getElementById("people-container").innerHTML = "

Mascotas de "+person.name+" "+person.surname+"

"; - - var view = new PetView(new PetDAO(), - 'people-container', 'people-container',person.id); - view.init(); + }; + + var showErrorMessage = function (jqxhr, textStatus, error) { + alert(textStatus + ": " + error); + }; + + var addRowListeners = function (person) { + $('#person-' + person.id + ' a.edit').click(function () { + self.editPerson(person.id); }); - }; - - var appendToTable = function(person) { - $(listQuery + ' > tbody:last') - .append(createPersonRow(person)); - addRowListeners(person); - }; - - return PeopleView; + + $('#person-' + person.id + ' a.delete').click(function () { + self.deletePerson(person.id); + }); + + $('#person-' + person.id + ' a.show').click(function () { + document.getElementById("people-container").innerHTML = "

Mascotas de " + person.name + " " + person.surname + "

"; + + var view = new PetView(new PetDAO(), + 'people-container', 'people-container', person.id); + view.init(); + }); + }; + + var appendToTable = function (person) { + $(listQuery + ' > tbody:last') + .append(createPersonRow(person)); + addRowListeners(person); + }; + + return PeopleView; })(); diff --git a/src/main/webapp/js/view/pets.js b/src/main/webapp/js/view/pets.js index 8d30df9..7d94780 100644 --- a/src/main/webapp/js/view/pets.js +++ b/src/main/webapp/js/view/pets.js @@ -1,73 +1,67 @@ var PetView = (function () { var dao; - // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. var self; var peopleID; - var formId = 'people-form'; var listId = 'people-list'; var formQuery = '#' + formId; var listQuery = '#' + listId; + function PetView(petDao, formContainerId, listContainerId, paramID) { + peopleID = paramID; + dao = petDao; + self = this; + + this.init = function () { + var cont = 0; var humans = [] - var humans_list = [] + var humans_list = [] + var daoPeople = new PeopleDAO(); function Human(id, name, surname) { this.id = id; this.name = name; this.surname = surname; } - var cont=0; - var daoPeople = new PeopleDAO(); - daoPeople.listPeople(function (people) { + daoPeople.listPeopleSync(function (people) { $.each(people, function (key, human) { humans[human.id] = new Human(human.id, human.name, human.surname); humans_list[cont] = new Human(human.id, human.name, human.surname); - cont++; + cont++; }); }, function () { - alert('No has sido posible acceder al listado de personas.'); + alert('No has sido posible acceder al listado de mascotas.'); }); - - - function PetView(petDao, formContainerId, listContainerId,paramID) { - peopleID=paramID; - dao = petDao; - self = this; - insertPetForm($('#' + formContainerId), humans_list,humans); + insertPetForm($('#' + formContainerId), humans_list, humans); insertPetList($('#' + listContainerId)); - console.log(humans); - - this.init = function () { - if(peopleID==="all"){ - dao.listAll(function (people) { - $.each(people, function (key, pet) { - appendToTable(pet, humans); - }); - }, - function () { - alert('No has sido posible acceder al listado de mascotas.'); + if (peopleID === "all") { + dao.listAll(function (people) { + $.each(people, function (key, pet) { + appendToTable(pet, humans); }); - }else{ - dao.listPetsByPeopleID(peopleID,function (people) { - $.each(people, function (key, pet) { - appendToTable(pet, humans); - }); - },function () { - alert('No has sido posible acceder al listado de mascotas.'); + }, + function () { + alert('No has sido posible acceder al listado de mascotas.'); + }); + } else { + dao.listPetsByPeopleID(peopleID, function (people) { + $.each(people, function (key, pet) { + appendToTable(pet, humans); }); - } + }, function () { + alert('No has sido posible acceder al listado de mascotas.'); + }); + } // 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) { $('#person-' + pet.id + ' td.name').text(pet.name); - $('#person-' + pet.id + ' td.surname').text(humans[pet.peopleID].name+" "+humans[pet.peopleID].surname); + $('#person-' + pet.id + ' td.surname').text(humans[pet.peopleID].name + " " + humans[pet.peopleID].surname); $('#person-' + pet.id + ' td.pet_type').text(pet.type); self.resetForm(); }, @@ -77,7 +71,7 @@ var PetView = (function () { } else { dao.addPet(pet, function (pet) { - appendToTable(pet,humans); + appendToTable(pet, humans); self.resetForm(); }, showErrorMessage, @@ -87,7 +81,6 @@ var PetView = (function () { return false; }); - $('#btnClear').click(this.resetForm); }; @@ -132,7 +125,7 @@ var PetView = (function () { }; this.deletePet = function (id) { - if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) { + if (confirm('Está a punto de eliminar a una mascota. ¿Está seguro de que desea continuar?')) { dao.deletePet(id, function () { $('tr#person-' + id).remove(); @@ -162,32 +155,31 @@ var PetView = (function () { } ; - + var returnHumansSelect = function (humans) { var toret = ""; + toret += ""; return toret; }; - + var returnHumanTextBox = function (human) { - var toret =""; + var toret = ""; return toret; }; - var insertPetForm = function (parent, humans,humans_map) { - var txtToAppend=""; - if(peopleID==='all'){ - txtToAppend=returnHumansSelect(humans); - }else{ - alert(peopleID); - txtToAppend=returnHumanTextBox(humans_map[peopleID]); + var insertPetForm = function (parent, humans, humans_map) { + var txtToAppend = ""; + if (peopleID === 'all') { + txtToAppend = returnHumansSelect(humans); + } else { + txtToAppend = returnHumanTextBox(humans_map[peopleID]); } parent.append( '
\ @@ -200,7 +192,7 @@ var PetView = (function () { \ \
Dueño:
\ -
'+ txtToAppend +'
\ +
' + txtToAppend + '
\
\ \ \ diff --git a/src/test/java/es/uvigo/esei/daa/rest/PetResourceTest.java b/src/test/java/es/uvigo/esei/daa/rest/PetResourceTest.java index cc7ae97..1252e9b 100644 --- a/src/test/java/es/uvigo/esei/daa/rest/PetResourceTest.java +++ b/src/test/java/es/uvigo/esei/daa/rest/PetResourceTest.java @@ -134,7 +134,7 @@ public class PetResourceTest extends JerseyTest { } @Test - @ExpectedDatabase("/datasets/dataset-add.xml") + @ExpectedDatabase("/datasets/dataset-add_pets.xml") public void testAdd() throws IOException { final Form form = new Form(); form.param("name", newName()); @@ -205,7 +205,7 @@ public class PetResourceTest extends JerseyTest { } @Test - @ExpectedDatabase("/datasets/dataset-modify.xml") + @ExpectedDatabase("/datasets/dataset-modify_pets.xml") public void testModify() throws IOException { final Form form = new Form(); form.param("name", newName()); @@ -292,7 +292,7 @@ public class PetResourceTest extends JerseyTest { } @Test - @ExpectedDatabase("/datasets/dataset-delete.xml") + @ExpectedDatabase("/datasets/dataset-delete_pets.xml") public void testDelete() throws IOException { final Response response = target("pets/" + existentId()).request() .header("Authorization", "Basic " + userToken(adminLogin())) diff --git a/src/test/resources/datasets/dataset-add.xml b/src/test/resources/datasets/dataset-add.xml index ab1b90f..9002d5c 100644 --- a/src/test/resources/datasets/dataset-add.xml +++ b/src/test/resources/datasets/dataset-add.xml @@ -17,9 +17,8 @@ - - - - - + + + + \ No newline at end of file diff --git a/src/test/resources/datasets/dataset-add_pets.xml b/src/test/resources/datasets/dataset-add_pets.xml new file mode 100644 index 0000000..f0cdb78 --- /dev/null +++ b/src/test/resources/datasets/dataset-add_pets.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/datasets/dataset-delete.xml b/src/test/resources/datasets/dataset-delete.xml index 711d3a8..dadc5ca 100644 --- a/src/test/resources/datasets/dataset-delete.xml +++ b/src/test/resources/datasets/dataset-delete.xml @@ -15,7 +15,8 @@ - - - + + + + \ No newline at end of file diff --git a/src/test/resources/datasets/dataset-delete_pets.xml b/src/test/resources/datasets/dataset-delete_pets.xml new file mode 100644 index 0000000..975e4c5 --- /dev/null +++ b/src/test/resources/datasets/dataset-delete_pets.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/datasets/dataset-modify.xml b/src/test/resources/datasets/dataset-modify.xml index fdb534e..e7c25ee 100644 --- a/src/test/resources/datasets/dataset-modify.xml +++ b/src/test/resources/datasets/dataset-modify.xml @@ -16,8 +16,8 @@ - - - - + + + + \ No newline at end of file diff --git a/src/test/resources/datasets/dataset-modify_pets.xml b/src/test/resources/datasets/dataset-modify_pets.xml new file mode 100644 index 0000000..9318d54 --- /dev/null +++ b/src/test/resources/datasets/dataset-modify_pets.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- 2.18.1