diff --git a/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java index 19e804e7e60b515066523633ca18158203cf42dd..4f7eefbabe05e0772811aa6b79672a47c557d74b 100644 --- a/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java +++ b/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java @@ -57,14 +57,14 @@ public class PetsDAO extends DAO { LOG.log(Level.SEVERE, "Error deleting a pet", e); throw new DAOException(e); } - } - public List list() throws DAOException { + public List list(int owner) throws DAOException { try (final Connection conn = this.getConnection()) { - final String query = "SELECT * FROM pet"; + final String query = "SELECT * FROM pet WHERE owner = ?"; try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, owner); try (final ResultSet result = statement.executeQuery()) { final List pets = new LinkedList<>(); diff --git a/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java b/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java index 09b8834c7b71d5176e012bcd6076d36eb275bb29..6b25ec741287f9d87b094c4257e8d68403ccce71 100644 --- a/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java +++ b/src/main/java/es/uvigo/esei/daa/rest/PeopleResource.java @@ -1,211 +1,203 @@ package es.uvigo.esei.daa.rest; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.ws.rs.DELETE; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - import es.uvigo.esei.daa.dao.DAOException; import es.uvigo.esei.daa.dao.PeopleDAO; import es.uvigo.esei.daa.entities.Person; +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 people. - * + * * @author Miguel Reboiro Jato. */ @Path("/people") @Produces(MediaType.APPLICATION_JSON) public class PeopleResource { - private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName()); - - private final PeopleDAO dao; - - /** - * Constructs a new instance of {@link PeopleResource}. - */ - public PeopleResource() { - this(new PeopleDAO()); - } - - // Needed for testing purposes - PeopleResource(PeopleDAO dao) { - this.dao = dao; - } - - /** - * Returns a person with the provided identifier. - * - * @param id the identifier of the person to retrieve. - * @return a 200 OK response with a person that has the provided identifier. - * If the identifier does not corresponds with any user, a 400 Bad Request - * response with an error message will be returned. If an error happens - * while retrieving the list, a 500 Internal Server Error response with an - * error message will be returned. - */ - @GET - @Path("/{id}") - public Response get( - @PathParam("id") int id - ) { - try { - final Person person = this.dao.get(id); - - return Response.ok(person).build(); - } catch (IllegalArgumentException iae) { - LOG.log(Level.FINE, "Invalid person id in get method", iae); - - return Response.status(Response.Status.BAD_REQUEST) - .entity(iae.getMessage()) - .build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error getting a person", e); - - return Response.serverError() - .entity(e.getMessage()) - .build(); - } - } - - /** - * Returns the complete list of people stored in the system. - * - * @return a 200 OK response with the complete list of people stored in the - * system. If an error happens while retrieving the list, a 500 Internal - * Server Error response with an error message will be returned. - */ - @GET - public Response list() { - try { - return Response.ok(this.dao.list()).build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error listing people", e); - return Response.serverError().entity(e.getMessage()).build(); - } - } - - /** - * Creates a new person in the system. - * - * @param name the name of the new person. - * @param surname the surname of the new person. - * @return a 200 OK response with a person that has been created. If the - * name or the surname are not provided, a 400 Bad Request response with an - * error message will be returned. If an error happens while retrieving the - * list, a 500 Internal Server Error response with an error message will be - * returned. - */ - @POST - public Response add( - @FormParam("name") String name, - @FormParam("surname") String surname - ) { - try { - final Person newPerson = this.dao.add(name, surname); - - return Response.ok(newPerson).build(); - } catch (IllegalArgumentException iae) { - LOG.log(Level.FINE, "Invalid person id in add method", iae); - - return Response.status(Response.Status.BAD_REQUEST) - .entity(iae.getMessage()) - .build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error adding a person", e); - - return Response.serverError() - .entity(e.getMessage()) - .build(); - } - } - - /** - * Modifies the data of a person. - * - * @param id identifier of the person to modify. - * @param name the new name of the person. - * @param surname the new surname of the person. - * @return a 200 OK response with a person that has been modified. If the - * identifier does not corresponds with any user or the name or surname are - * not provided, a 400 Bad Request response with an error message will be - * returned. If an error happens while retrieving the list, a 500 Internal - * Server Error response with an error message will be returned. - */ - @PUT - @Path("/{id}") - public Response modify( - @PathParam("id") int id, - @FormParam("name") String name, - @FormParam("surname") String surname - ) { - try { - final Person modifiedPerson = new Person(id, name, surname); - this.dao.modify(modifiedPerson); - - return Response.ok(modifiedPerson).build(); - } catch (NullPointerException npe) { - final String message = String.format("Invalid data for person (name: %s, surname: %s)", name, surname); - - LOG.log(Level.FINE, message); - - return Response.status(Response.Status.BAD_REQUEST) - .entity(message) - .build(); - } catch (IllegalArgumentException iae) { - LOG.log(Level.FINE, "Invalid person id in modify method", iae); - - return Response.status(Response.Status.BAD_REQUEST) - .entity(iae.getMessage()) - .build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error modifying a person", e); - - return Response.serverError() - .entity(e.getMessage()) - .build(); - } - } - - /** - * Deletes a person from the system. - * - * @param id the identifier of the person to be deleted. - * @return a 200 OK response with the identifier of the person that has - * been deleted. If the identifier does not corresponds with any user, a 400 - * Bad Request response with an error message will be returned. If an error - * happens while retrieving the list, a 500 Internal Server Error response - * with an error message will be returned. - */ - @DELETE - @Path("/{id}") - public Response delete( - @PathParam("id") int id - ) { - try { - this.dao.delete(id); - - return Response.ok(id).build(); - } catch (IllegalArgumentException iae) { - LOG.log(Level.FINE, "Invalid person id in delete method", iae); - - return Response.status(Response.Status.BAD_REQUEST) - .entity(iae.getMessage()) - .build(); - } catch (DAOException e) { - LOG.log(Level.SEVERE, "Error deleting a person", e); - - return Response.serverError() - .entity(e.getMessage()) - .build(); - } - } + private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName()); + + private final PeopleDAO dao; + + /** + * Constructs a new instance of {@link PeopleResource}. + */ + public PeopleResource() { + this(new PeopleDAO()); + } + + // Needed for testing purposes + PeopleResource(PeopleDAO dao) { + this.dao = dao; + } + + /** + * Returns a person with the provided identifier. + * + * @param id the identifier of the person to retrieve. + * @return a 200 OK response with a person that has the provided identifier. + * If the identifier does not corresponds with any user, a 400 Bad Request + * response with an error message will be returned. If an error happens + * while retrieving the list, a 500 Internal Server Error response with an + * error message will be returned. + */ + @GET + @Path("/{id}") + public Response get( + @PathParam("id") int id + ) { + try { + final Person person = this.dao.get(id); + + return Response.ok(person).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid person id in get method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error getting a person", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Returns the complete list of people stored in the system. + * + * @return a 200 OK response with the complete list of people stored in the + * system. If an error happens while retrieving the list, a 500 Internal + * Server Error response with an error message will be returned. + */ + @GET + public Response list() { + try { + return Response.ok(this.dao.list()).build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error listing people", e); + return Response.serverError().entity(e.getMessage()).build(); + } + } + + /** + * Creates a new person in the system. + * + * @param name the name of the new person. + * @param surname the surname of the new person. + * @return a 200 OK response with a person that has been created. If the + * name or the surname are not provided, a 400 Bad Request response with an + * error message will be returned. If an error happens while retrieving the + * list, a 500 Internal Server Error response with an error message will be + * returned. + */ + @POST + public Response add( + @FormParam("name") String name, + @FormParam("surname") String surname + ) { + try { + final Person newPerson = this.dao.add(name, surname); + + return Response.ok(newPerson).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid person id in add method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error adding a person", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Modifies the data of a person. + * + * @param id identifier of the person to modify. + * @param name the new name of the person. + * @param surname the new surname of the person. + * @return a 200 OK response with a person that has been modified. If the + * identifier does not corresponds with any user or the name or surname are + * not provided, a 400 Bad Request response with an error message will be + * returned. If an error happens while retrieving the list, a 500 Internal + * Server Error response with an error message will be returned. + */ + @PUT + @Path("/{id}") + public Response modify( + @PathParam("id") int id, + @FormParam("name") String name, + @FormParam("surname") String surname + ) { + try { + final Person modifiedPerson = new Person(id, name, surname); + this.dao.modify(modifiedPerson); + + return Response.ok(modifiedPerson).build(); + } catch (NullPointerException npe) { + final String message = String.format("Invalid data for person (name: %s, surname: %s)", name, surname); + + LOG.log(Level.FINE, message); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(message) + .build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid person id in modify method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error modifying a person", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } + + /** + * Deletes a person from the system. + * + * @param id the identifier of the person to be deleted. + * @return a 200 OK response with the identifier of the person that has + * been deleted. If the identifier does not corresponds with any user, a 400 + * Bad Request response with an error message will be returned. If an error + * happens while retrieving the list, a 500 Internal Server Error response + * with an error message will be returned. + */ + @DELETE + @Path("/{id}") + public Response delete( + @PathParam("id") int id + ) { + try { + this.dao.delete(id); + + return Response.ok(id).build(); + } catch (IllegalArgumentException iae) { + LOG.log(Level.FINE, "Invalid person id in delete method", iae); + + return Response.status(Response.Status.BAD_REQUEST) + .entity(iae.getMessage()) + .build(); + } catch (DAOException e) { + LOG.log(Level.SEVERE, "Error deleting a person", e); + + return Response.serverError() + .entity(e.getMessage()) + .build(); + } + } } diff --git a/src/main/java/es/uvigo/esei/daa/rest/PetsResource.java b/src/main/java/es/uvigo/esei/daa/rest/PetsResource.java index c7f2c278138d15eac06716f4f67e3a96dcd5cf55..123f84cb242b58ea823ee0a5140528c1b56cf440 100644 --- a/src/main/java/es/uvigo/esei/daa/rest/PetsResource.java +++ b/src/main/java/es/uvigo/esei/daa/rest/PetsResource.java @@ -22,21 +22,15 @@ public class PetsResource { private final PetsDAO dao; + + public PetsResource() { + this(new PetsDAO()); + } + PetsResource(PetsDAO dao) { this.dao = dao; } - - /** - * Returns a person with the provided identifier. - * - * @param id the identifier of the person to retrieve. - * @return a 200 OK response with a person that has the provided identifier. - * If the identifier does not corresponds with any user, a 400 Bad Request - * response with an error message will be returned. If an error happens - * while retrieving the list, a 500 Internal Server Error response with an - * error message will be returned. - */ @GET @Path("/{id}") public Response get( @@ -88,9 +82,10 @@ public class PetsResource { @GET - public Response list() { + @Path("/owner/{owner}") + public Response list(@PathParam("owner") int owner) { try { - return Response.ok(this.dao.list()).build(); + return Response.ok(this.dao.list(owner)).build(); } catch (DAOException e) { LOG.log(Level.SEVERE, "Error listing pets", e); return Response.serverError().entity(e.getMessage()).build(); diff --git a/src/main/webapp/js/dao/people.js b/src/main/webapp/js/dao/people.js index 29618ee5eafbab06acb34bd0320c8c9e5604ac40..e21cd60bd235ae748c33e9cb7af485bbb25459c9 100644 --- a/src/main/webapp/js/dao/people.js +++ b/src/main/webapp/js/dao/people.js @@ -5,7 +5,7 @@ var PeopleDAO = (function() { fail = typeof fail !== 'undefined' ? fail : function() {}; always = typeof always !== 'undefined' ? always : function() {}; - let authToken = localStorage.getItem('authorization-token'); + var authToken = localStorage.getItem('authorization-token'); if (authToken !== null) { data.beforeSend = function(xhr) { xhr.setRequestHeader('Authorization', 'Basic ' + authToken); @@ -23,7 +23,7 @@ var PeopleDAO = (function() { }, done, fail, always); }; - this.addPerson = function(person, done, fail, always) { + this.addPet = function (person, done, fail, always) { requestByAjax({ url : resourcePath, type : 'POST', @@ -31,7 +31,7 @@ var PeopleDAO = (function() { }, done, fail, always); }; - this.modifyPerson = function(person, done, fail, always) { + this.modifyPet = function (person, done, fail, always) { requestByAjax({ url : resourcePath + person.id, type : 'PUT', diff --git a/src/main/webapp/js/dao/pets.js b/src/main/webapp/js/dao/pets.js new file mode 100644 index 0000000000000000000000000000000000000000..f390b5f94c8eda05862cb769b5fe92f409323feb --- /dev/null +++ b/src/main/webapp/js/dao/pets.js @@ -0,0 +1,54 @@ +var PetsDAO = (function () { + var resourcePath = "rest/pets/"; + 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 () { + }; + + var authToken = localStorage.getItem('authorization-token'); + if (authToken !== null) { + data.beforeSend = function (xhr) { + xhr.setRequestHeader('Authorization', 'Basic ' + authToken); + }; + } + + $.ajax(data).done(done).fail(fail).always(always); + }; + + function PetsDAO() { + this.listPets = function (owner, done, fail, always) { + requestByAjax({ + url: resourcePath + "owner/" + owner, + type: 'GET' + }, done, fail, always); + }; + + this.addPet = function (pet, done, fail, always) { + requestByAjax({ + url: resourcePath, + 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 PetsDAO; +})(); \ 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 802d6b228a27a98d921ff39604f82e616f79a735..2476de3db112fa06c548a5ce61bcbc116961f49f 100644 --- a/src/main/webapp/js/view/people.js +++ b/src/main/webapp/js/view/people.js @@ -1,133 +1,145 @@ -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); - 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.modifyPet(person, + function (person) { + $('#person-' + person.id + ' td.name').text(person.name); + $('#person-' + person.id + ' td.surname').text(person.surname); + self.resetForm(); + }, + showErrorMessage, + self.enableForm + ); + } else { + dao.addPet(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.deletePet(id, + function () { + $('tr#person-' + id).remove(); + }, + showErrorMessage + ); + } + }; + + this.showPets = function (id) { + document.getElementById('people-container').style.display = 'none'; + document.getElementById('pet-container').style.display = 'block'; + + var view = new PetsView(id, new PetsDAO(), + 'pet-container', 'pet-container' + ); + + view.init(); + + } + + 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( + '
\ \ \ \ @@ -138,12 +150,12 @@ var PeopleView = (function() { \ \
Nombre
' - ); - }; + ); + }; - var insertPeopleForm = function(parent) { - parent.append( - '
\ + var insertPeopleForm = function (parent) { + parent.append( + '\ \
\
\ @@ -158,39 +170,46 @@ var PeopleView = (function() {
\
\
' - ); - }; - - var createPersonRow = function(person) { - return '\ - ' + person.name + '\ - ' + person.surname + '\ - \ - Editar\ - Eliminar\ + ); + }; + + var createPersonRow = function (person) { + return '\ + ' + person.name + '\ + ' + person.surname + '\ + \ + Mascotas\ + Editar\ + Eliminar\ \ '; - }; - - 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); - }); - }; - - var appendToTable = function(person) { - $(listQuery + ' > tbody:last') - .append(createPersonRow(person)); - addRowListeners(person); - }; - - return PeopleView; + }; + + 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-pets').click(function () { + self.showPets(person.id); + }); + + + }; + + 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 new file mode 100644 index 0000000000000000000000000000000000000000..05a209ffeac0871c8e27a0cddabf9a4b4541c00f --- /dev/null +++ b/src/main/webapp/js/view/pets.js @@ -0,0 +1,201 @@ +var PetsView = (function () { + var dao; + + // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. + var self; + + var formId = 'pets-form'; + var listId = 'pets-list'; + var formQuery = '#' + formId; + var listQuery = '#' + listId; + + function PetsView(owner, petsDao, formContainerId, listContainerId) { + dao = petsDao; + self = this; + + insertPetsForm($('#' + formContainerId)); + insertPetsList($('#' + listContainerId)); + + this.init = function () { + dao.listPets(owner, function (pets) { + $.each(pets, function (key, pet) { + appendToTable(pet); + }); + }, + 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) { + $('#pet-' + pet.id + ' td.name').text(pet.name); + $('#pet-' + pet.id + ' td.owner').text(pet.owner); + 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(), + 'name': form.find('input[name="name"]').val(), + 'owner': form.find('input[name="owner"]').val() + }; + }; + + this.getPetInRow = function (id) { + var row = $('#pet-' + id); + + if (row !== undefined) { + return { + 'id': id, + 'name': row.find('td.name').text(), + 'owner': row.find('td.owner').text() + }; + } else { + return undefined; + } + }; + + this.editPet = function (id) { + var row = $('#pet-' + 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="owner"]').val(row.find('td.owner').text()); + + $('input#btnSubmit').val('Modificar'); + } + }; + + this.deletePet = function (id) { + if (confirm('Está a punto de eliminar a una mascota. ¿Está seguro de que desea continuar?')) { + dao.deletePet(id, + function () { + $('tr#pet-' + id).remove(); + }, + showErrorMessage + ); + } + }; + + this.showPets = function (id) { + + + } + + 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 insertPetsList = function (parent) { + parent.append( + '\ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
NombrePropietario 
' + ); + }; + + var insertPetsForm = function (parent) { + parent.append( + '
\ + \ +
\ +
\ + \ +
\ +
\ + \ +
\ +
\ + \ + \ +
\ +
\ +
' + ); + }; + + var createPetRow = function (pet) { + return '\ + ' + pet.name + '\ + ' + pet.owner + '\ + \ + Editar\ + Eliminar\ + \ + '; + }; + + var showErrorMessage = function (jqxhr, textStatus, error) { + alert(textStatus + ": " + error); + }; + + var addRowListeners = function (pet) { + $('#pet-' + pet.id + ' a.edit').click(function () { + self.editPet(pet.id); + }); + + $('#pet-' + pet.id + ' a.delete').click(function () { + self.deletePet(pet.id); + }); + }; + + var appendToTable = function (pet) { + $(listQuery + ' > tbody:last') + .append(createPetRow(pet)); + addRowListeners(pet); + }; + + return PetsView; +})(); diff --git a/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java b/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java index 764a44f32ca073bfff43697da7e915ab6c0b4d9b..00f296d5d07beca3b79e5bccc4c36887b9943510 100644 --- a/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java +++ b/src/test/java/es/uvigo/esei/daa/dataset/PeopleDataset.java @@ -1,12 +1,12 @@ package es.uvigo.esei.daa.dataset; -import static java.util.Arrays.binarySearch; -import static java.util.Arrays.stream; +import es.uvigo.esei.daa.entities.Person; import java.util.Arrays; import java.util.function.Predicate; -import es.uvigo.esei.daa.entities.Person; +import static java.util.Arrays.binarySearch; +import static java.util.Arrays.stream; public final class PeopleDataset { private PeopleDataset() {} @@ -45,7 +45,7 @@ public final class PeopleDataset { } public static int existentId() { - return 5; + return 1; } public static int nonExistentId() { diff --git a/src/test/java/es/uvigo/esei/daa/rest/PetsResourceUnitTest.java b/src/test/java/es/uvigo/esei/daa/rest/PetsResourceUnitTest.java index 1219e9bcb1a5d5cfebe01637f0a491cc0693e15f..f3efaa6d7987ba9ac59f64ee84bf4fe25c2ab1d7 100644 --- a/src/test/java/es/uvigo/esei/daa/rest/PetsResourceUnitTest.java +++ b/src/test/java/es/uvigo/esei/daa/rest/PetsResourceUnitTest.java @@ -11,6 +11,7 @@ import org.junit.Test; import javax.ws.rs.core.Response; import java.util.List; +import static es.uvigo.esei.daa.dataset.PeopleDataset.existentPerson; import static es.uvigo.esei.daa.dataset.PeopleDataset.newName; import static es.uvigo.esei.daa.dataset.PetsDataset.*; import static es.uvigo.esei.daa.matchers.HasHttpStatus.*; @@ -61,13 +62,13 @@ public class PetsResourceUnitTest { @Test @SuppressWarnings("unchecked") public void testList() throws Exception { - final List people = asList(pets()); + final List pets = asList(pets()); - expect(daoMock.list()).andReturn(people); + expect(daoMock.list(existentPerson().getId())).andReturn(pets); replay(daoMock); - final Response response = resource.list(); + final Response response = resource.list(existentPet().getId()); assertThat(response, hasOkStatus()); assertThat((List) response.getEntity(), containsPetsInAnyOrder(pets())); @@ -76,11 +77,11 @@ public class PetsResourceUnitTest { @Test public void testListDAOException() throws Exception { - expect(daoMock.list()).andThrow(new DAOException()); + expect(daoMock.list(existentPerson().getId())).andThrow(new DAOException()); replay(daoMock); - final Response response = resource.list(); + final Response response = resource.list(existentPerson().getId()); assertThat(response, hasInternalServerErrorStatus()); }