Se corrigen errores en test capa rest

También se añade las restricciones en web.xml para pets
parent abf9257a
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-maven-jaxws.rest_2e_config_2e_type>ide</org-netbeans-modules-maven-jaxws.rest_2e_config_2e_type>
</properties>
</project-shared-configuration>
...@@ -14,178 +14,178 @@ import es.uvigo.esei.daa.entities.Person; ...@@ -14,178 +14,178 @@ import es.uvigo.esei.daa.entities.Person;
/** /**
* DAO class for the {@link Person} entities. * DAO class for the {@link Person} entities.
* *
* @author Miguel Reboiro Jato * @author Miguel Reboiro Jato
* *
*/ */
public class PeopleDAO extends DAO { public class PeopleDAO extends DAO {
private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName());
private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName());
/**
* Returns a person stored persisted in the system. /**
* * Returns a person stored persisted in the system.
* @param id identifier of the person. *
* @return a person with the provided identifier. * @param id identifier of the person.
* @throws DAOException if an error happens while retrieving the person. * @return a person with the provided identifier.
* @throws IllegalArgumentException if the provided id does not corresponds * @throws DAOException if an error happens while retrieving the person.
* with any persisted person. * @throws IllegalArgumentException if the provided id does not corresponds
*/ * with any persisted person.
public Person get(int id) */
throws DAOException, IllegalArgumentException { public Person get(int id)
try (final Connection conn = this.getConnection()) { throws DAOException, IllegalArgumentException {
final String query = "SELECT * FROM people WHERE id=?"; 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 PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id);
try (final ResultSet result = statement.executeQuery()) {
if (result.next()) { try (final ResultSet result = statement.executeQuery()) {
return rowToEntity(result); if (result.next()) {
} else { return rowToEntity(result);
throw new IllegalArgumentException("Invalid id"); } else {
} throw new IllegalArgumentException("Invalid id");
} }
} }
} catch (SQLException e) { }
LOG.log(Level.SEVERE, "Error getting a person", e); } catch (SQLException e) {
throw new DAOException(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. /**
* * 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. * @return a list with all the people persisted in the system.
*/ * @throws DAOException if an error happens while retrieving the people.
public List<Person> list() throws DAOException { */
try (final Connection conn = this.getConnection()) { public List<Person> list() throws DAOException {
final String query = "SELECT * FROM people"; 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()) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
final List<Person> people = new LinkedList<>(); try (final ResultSet result = statement.executeQuery()) {
final List<Person> people = new LinkedList<>();
while (result.next()) {
people.add(rowToEntity(result)); while (result.next()) {
} people.add(rowToEntity(result));
}
return people;
} return people;
} }
} catch (SQLException e) { }
LOG.log(Level.SEVERE, "Error listing people", e); } catch (SQLException e) {
throw new DAOException(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. * 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}. * @param name name of the new person. Can't be {@code null}.
* @return a {@link Person} entity representing the persisted person. * @param surname surname of the new person. Can't be {@code null}.
* @throws DAOException if an error happens while persisting the new person. * @return a {@link Person} entity representing the persisted person.
* @throws IllegalArgumentException if the name or surname are {@code null}. * @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 { public Person add(String name, String surname)
if (name == null || surname == null) { throws DAOException, IllegalArgumentException {
throw new IllegalArgumentException("name and surname can't be null"); 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 (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); try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(2, surname); statement.setString(1, name);
statement.setString(2, surname);
if (statement.executeUpdate() == 1) {
try (ResultSet resultKeys = statement.getGeneratedKeys()) { if (statement.executeUpdate() == 1) {
if (resultKeys.next()) { try (ResultSet resultKeys = statement.getGeneratedKeys()) {
return new Person(resultKeys.getInt(1), name, surname); if (resultKeys.next()) {
} else { return new Person(resultKeys.getInt(1), name, surname);
LOG.log(Level.SEVERE, "Error retrieving inserted id"); } else {
throw new SQLException("Error retrieving inserted id"); LOG.log(Level.SEVERE, "Error retrieving inserted id");
} throw new SQLException("Error retrieving inserted id");
} }
} else { }
LOG.log(Level.SEVERE, "Error inserting value"); } else {
throw new SQLException("Error inserting value"); 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); } catch (SQLException e) {
throw new DAOException(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 * Modifies a person previously persisted in the system. The person will be
* replaced with the provided. * 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. * @param person a {@link Person} entity with the new data.
* @throws IllegalArgumentException if the person is {@code null}. * @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 { public void modify(Person person)
if (person == null) { throws DAOException, IllegalArgumentException {
throw new IllegalArgumentException("person can't be null"); 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 (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()); try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(2, person.getSurname()); statement.setString(1, person.getName());
statement.setInt(3, person.getId()); statement.setString(2, person.getSurname());
statement.setInt(3, person.getId());
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name and surname can't be null"); 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); } catch (SQLException e) {
throw new DAOException(); LOG.log(Level.SEVERE, "Error modifying a person", e);
} throw new DAOException();
} }
}
/**
* Removes a persisted person from the system. /**
* * 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. * @param id identifier of the person to be deleted.
* @throws IllegalArgumentException if the provided id does not corresponds * @throws DAOException if an error happens while deleting the person.
* with any persisted person. * @throws IllegalArgumentException if the provided id does not corresponds
*/ * with any persisted person.
public void delete(int id) */
throws DAOException, IllegalArgumentException { public void delete(int id)
try (final Connection conn = this.getConnection()) { throws DAOException, IllegalArgumentException {
final String query = "DELETE FROM people WHERE id=?"; try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM people WHERE id=?";
try (final PreparedStatement statement = conn.prepareStatement(query)) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id); statement.setInt(1, id);
if (statement.executeUpdate() != 1) { if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("Invalid id"); throw new IllegalArgumentException("Invalid id");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
LOG.log(Level.SEVERE, "Error deleting a person", e); LOG.log(Level.SEVERE, "Error deleting a person", e);
throw new DAOException(e); throw new DAOException(e);
} }
} }
private Person rowToEntity(ResultSet row) throws SQLException { private Person rowToEntity(ResultSet row) throws SQLException {
return new Person( return new Person(
row.getInt("id"), row.getInt("id"),
row.getString("name"), row.getString("name"),
row.getString("surname") row.getString("surname")
); );
} }
} }
...@@ -87,8 +87,13 @@ public class PetDAO extends DAO { ...@@ -87,8 +87,13 @@ public class PetDAO extends DAO {
} }
public Pet add(String name, String type, int peopleID) throws DAOException, IllegalArgumentException { public Pet add(String name, String type, int peopleID) throws DAOException, IllegalArgumentException {
if (name == null || type==null) { /*Debido a la forma en la que se generan las PK de people nunca puede
throw new IllegalArgumentException("name and type can't be null"); 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()) { try (Connection conn = this.getConnection()) {
......
...@@ -49,7 +49,7 @@ public class Pet { ...@@ -49,7 +49,7 @@ public class Pet {
} }
public void setPeopleID(int peopleID) { public void setPeopleID(int peopleID) {
this.peopleID = requireNonNull(peopleID, "PeopleID can't be null"); this.peopleID = requireNonNull(peopleID, "PeopleID can't be null");
} }
@Override @Override
......
...@@ -20,155 +20,155 @@ import es.uvigo.esei.daa.entities.Pet; ...@@ -20,155 +20,155 @@ import es.uvigo.esei.daa.entities.Pet;
/** /**
* REST resource for managing people. * REST resource for managing people.
* *
* @author Imanol Cobian Martinez * @author Imanol Cobian Martinez
*/ */
@Path("/pets") @Path("/pets")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public class PetResource { public class PetResource {
private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName()); private final static Logger LOG = Logger.getLogger(PeopleResource.class.getName());
private final PetDAO dao; private final PetDAO dao;
public PetResource() { public PetResource() {
this(new PetDAO()); this(new PetDAO());
} }
PetResource(PetDAO dao) { PetResource(PetDAO dao) {
this.dao = dao; this.dao = dao;
} }
@GET @GET
@Path("/{id}") @Path("/{id}")
public Response get( public Response get(
@PathParam("id") int id @PathParam("id") int id
) { ) {
try { try {
final Pet pet = this.dao.get(id); final Pet pet = this.dao.get(id);
return Response.ok(pet).build(); return Response.ok(pet).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in get method", iae); LOG.log(Level.FINE, "Invalid pet id in get method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()) .entity(iae.getMessage())
.build(); .build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error getting a pet", e); LOG.log(Level.SEVERE, "Error getting a pet", e);
return Response.serverError() return Response.serverError()
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
} }
} }
@GET @GET
public Response listAll() { public Response listAll() {
try { try {
return Response.ok(this.dao.listAll()).build(); return Response.ok(this.dao.listAll()).build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error listing pets", e); LOG.log(Level.SEVERE, "Error listing pets", e);
return Response.serverError().entity(e.getMessage()).build(); return Response.serverError().entity(e.getMessage()).build();
} }
} }
@GET @GET
@Path("/people{peopleID}") @Path("/people{peopleID}")
public Response listByPeopleID( public Response listByPeopleID(
@PathParam("peopleID") int peopleID @PathParam("peopleID") int peopleID
) { ) {
try { try {
return Response.ok(this.dao.listByPeopleID(peopleID)).build(); return Response.ok(this.dao.listByPeopleID(peopleID)).build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error listing pets", e); LOG.log(Level.SEVERE, "Error listing pets", e);
return Response.serverError().entity(e.getMessage()).build(); return Response.serverError().entity(e.getMessage()).build();
} }
} }
@POST @POST
public Response add( public Response add(
@FormParam("name") String name, @FormParam("name") String name,
@FormParam("type") String type, @FormParam("type") String type,
@FormParam("peopleID") int peopleID @FormParam("peopleID") int peopleID
) {
) { try {
try { System.out.println("Esto es el nombre:"+name);
final Pet newPet = this.dao.add(name,type,peopleID); final Pet newPet = this.dao.add(name, type, peopleID);
return Response.ok(newPet).build(); return Response.ok(newPet).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in add method", iae); LOG.log(Level.FINE, "Invalid pet id in add method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()) .entity(iae.getMessage())
.build(); .build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error adding a pet", e); LOG.log(Level.SEVERE, "Error adding a pet", e);
return Response.serverError() return Response.serverError()
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
} }
} }
@PUT @PUT
@Path("/{id}") @Path("/{id}")
public Response modify( public Response modify(
@PathParam("id") int id, @PathParam("id") int id,
@FormParam("name") String name, @FormParam("name") String name,
@FormParam("type") String type, @FormParam("type") String type,
@FormParam("peopleID") int peopleID @FormParam("peopleID") int peopleID
) { ) {
try { try {
final Pet modifiedPet = new Pet(id, name,type,peopleID); final Pet modifiedPet = new Pet(id, name, type, peopleID);
this.dao.modify(modifiedPet); this.dao.modify(modifiedPet);
return Response.ok(modifiedPet).build(); return Response.ok(modifiedPet).build();
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
final String message = String.format("Invalid data for person (name: %s, peopleID: %s)", name, peopleID); final String message = String.format("Invalid data for person (name: %s, peopleID: %s)", name, peopleID);
LOG.log(Level.FINE, message); LOG.log(Level.FINE, message);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(message) .entity(message)
.build(); .build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in modify method", iae); LOG.log(Level.FINE, "Invalid pet id in modify method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()) .entity(iae.getMessage())
.build(); .build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error modifying a pet", e); LOG.log(Level.SEVERE, "Error modifying a pet", e);
return Response.serverError() return Response.serverError()
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
} }
} }
@DELETE @DELETE
@Path("/{id}") @Path("/{id}")
public Response delete( public Response delete(
@PathParam("id") int id @PathParam("id") int id
) { ) {
try { try {
this.dao.delete(id); this.dao.delete(id);
return Response.ok(id).build(); return Response.ok(id).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in delete method", iae); LOG.log(Level.FINE, "Invalid pet id in delete method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()) .entity(iae.getMessage())
.build(); .build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error deleting a pet", e); LOG.log(Level.SEVERE, "Error deleting a pet", e);
return Response.serverError() return Response.serverError()
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
} }
} }
} }
...@@ -59,6 +59,20 @@ ...@@ -59,6 +59,20 @@
<role-name>ADMIN</role-name> <role-name>ADMIN</role-name>
</auth-constraint> </auth-constraint>
</security-constraint> </security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>/rest/pets/*</url-pattern>
<http-method>GET</http-method>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<!-- Security roles referenced by this web application --> <!-- Security roles referenced by this web application -->
<security-role> <security-role>
......
...@@ -22,6 +22,14 @@ var PeopleDAO = (function() { ...@@ -22,6 +22,14 @@ var PeopleDAO = (function() {
type : 'GET' type : 'GET'
}, done, fail, always); }, 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) { this.addPerson = function(person, done, fail, always) {
requestByAjax({ requestByAjax({
......
...@@ -21,7 +21,8 @@ var PetDAO = (function () { ...@@ -21,7 +21,8 @@ var PetDAO = (function () {
this.listPetsByPeopleID = function (peopleID,done, fail, always) { this.listPetsByPeopleID = function (peopleID,done, fail, always) {
requestByAjax({ requestByAjax({
url: resourcePath + 'people' + peopleID, url: resourcePath + 'people' + peopleID,
type: 'GET' type: 'GET',
async:false
}, done, fail, always); }, done, fail, always);
}; };
......
var PeopleView = (function() { var PeopleView = (function () {
var dao; var dao;
// Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self; var self;
var formId = 'people-form'; var formId = 'people-form';
var listId = 'people-list'; var listId = 'people-list';
var formQuery = '#' + formId; var formQuery = '#' + formId;
var listQuery = '#' + listId; var listQuery = '#' + listId;
function PeopleView(peopleDao, formContainerId, listContainerId) { function PeopleView(peopleDao, formContainerId, listContainerId) {
dao = peopleDao; dao = peopleDao;
self = this; self = this;
insertPeopleForm($('#' + formContainerId)); insertPeopleForm($('#' + formContainerId));
insertPeopleList($('#' + listContainerId)); insertPeopleList($('#' + listContainerId));
this.init = function() { this.init = function () {
dao.listPeople(function(people) { dao.listPeople(function (people) {
$.each(people, function(key, person) { $.each(people, function (key, person) {
appendToTable(person); appendToTable(person);
}); });
}, },
function() { function () {
alert('No has sido posible acceder al listado de personas.'); alert('No has sido posible acceder al listado de personas.');
}); });
// La acción por defecto de enviar formulario (submit) se sobreescribe // La acción por defecto de enviar formulario (submit) se sobreescribe
// para que el envío sea a través de AJAX // para que el envío sea a través de AJAX
$(formQuery).submit(function(event) { $(formQuery).submit(function (event) {
var person = self.getPersonInForm(); var person = self.getPersonInForm();
if (self.isEditing()) { if (self.isEditing()) {
dao.modifyPerson(person, dao.modifyPerson(person,
function(person) { function (person) {
$('#person-' + person.id + ' td.name').text(person.name); $('#person-' + person.id + ' td.name').text(person.name);
$('#person-' + person.id + ' td.surname').text(person.surname); $('#person-' + person.id + ' td.surname').text(person.surname);
$('#person-' + person.id + ' td.pet_type').text(person.type); $('#person-' + person.id + ' td.pet_type').text(person.type);
self.resetForm(); self.resetForm();
}, },
showErrorMessage, showErrorMessage,
self.enableForm self.enableForm
); );
} else { } else {
dao.addPerson(person, dao.addPerson(person,
function(person) { function (person) {
appendToTable(person); appendToTable(person);
self.resetForm(); self.resetForm();
}, },
showErrorMessage, showErrorMessage,
self.enableForm self.enableForm
); );
} }
return false; return false;
}); });
$('#btnClear').click(this.resetForm); $('#btnClear').click(this.resetForm);
}; };
this.getPersonInForm = function() { this.getPersonInForm = function () {
var form = $(formQuery); var form = $(formQuery);
return { return {
'id': form.find('input[name="id"]').val(), 'id': form.find('input[name="id"]').val(),
'name': form.find('input[name="name"]').val(), 'name': form.find('input[name="name"]').val(),
'surname': form.find('input[name="surname"]').val() 'surname': form.find('input[name="surname"]').val()
}; };
}; };
this.getPersonInRow = function(id) { this.getPersonInRow = function (id) {
var row = $('#person-' + id); var row = $('#person-' + id);
if (row !== undefined) { if (row !== undefined) {
return { return {
'id': id, 'id': id,
'name': row.find('td.name').text(), 'name': row.find('td.name').text(),
'surname': row.find('td.surname').text() 'surname': row.find('td.surname').text()
}; };
} else { } else {
return undefined; return undefined;
} }
}; };
this.editPerson = function(id) { this.editPerson = function (id) {
var row = $('#person-' + id); var row = $('#person-' + id);
if (row !== undefined) { if (row !== undefined) {
var form = $(formQuery); var form = $(formQuery);
form.find('input[name="id"]').val(id); form.find('input[name="id"]').val(id);
form.find('input[name="name"]').val(row.find('td.name').text()); form.find('input[name="name"]').val(row.find('td.name').text());
form.find('input[name="surname"]').val(row.find('td.surname').text()); form.find('input[name="surname"]').val(row.find('td.surname').text());
$('input#btnSubmit').val('Modificar'); $('input#btnSubmit').val('Modificar');
} }
}; };
this.deletePerson = function(id) { this.deletePerson = function (id) {
if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) { var cont = 0;
dao.deletePerson(id, var daoPet = new PetDAO();
function() { daoPet.listPetsByPeopleID(id, function (people) {
$('tr#person-' + id).remove(); $.each(people, function (key, pet) {
}, cont++;
showErrorMessage });
); }, function () {
} alert('No has sido posible acceder al listado de mascotas.');
}; });
if (cont == 0) {
this.isEditing = function() { if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) {
return $(formQuery + ' input[name="id"]').val() != ""; dao.deletePerson(id,
}; function () {
$('tr#person-' + id).remove();
this.disableForm = function() { },
$(formQuery + ' input').prop('disabled', true); showErrorMessage
}; );
}
this.enableForm = function() { } else {
$(formQuery + ' input').prop('disabled', false); alert('No puedes eliminar esta persona porque tiene mascotas asignadas');
}; }
};
this.resetForm = function() {
$(formQuery)[0].reset(); this.isEditing = function () {
$(formQuery + ' input[name="id"]').val(''); return $(formQuery + ' input[name="id"]').val() != "";
$('#btnSubmit').val('Crear'); };
};
}; this.disableForm = function () {
$(formQuery + ' input').prop('disabled', true);
var insertPeopleList = function(parent) { };
parent.append(
'<table id="' + listId + '" class="table">\ 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(
'<table id="' + listId + '" class="table">\
<thead>\ <thead>\
<tr class="row">\ <tr class="row">\
<th class="col-sm-4">Nombre</th>\ <th class="col-sm-4">Nombre</th>\
...@@ -139,12 +153,12 @@ var PeopleView = (function() { ...@@ -139,12 +153,12 @@ var PeopleView = (function() {
<tbody>\ <tbody>\
</tbody>\ </tbody>\
</table>' </table>'
); );
}; };
var insertPeopleForm = function(parent) { var insertPeopleForm = function (parent) {
parent.append( parent.append(
'<form id="' + formId + '" class="mb-5 mb-10">\ '<form id="' + formId + '" class="mb-5 mb-10">\
<input name="id" type="hidden" value=""/>\ <input name="id" type="hidden" value=""/>\
<div class="row">\ <div class="row">\
<div class="col-sm-4">\ <div class="col-sm-4">\
...@@ -159,11 +173,11 @@ var PeopleView = (function() { ...@@ -159,11 +173,11 @@ var PeopleView = (function() {
</div>\ </div>\
</div>\ </div>\
</form>' </form>'
); );
}; };
var createPersonRow = function(person) { var createPersonRow = function (person) {
return '<tr id="person-'+ person.id +'" class="row">\ return '<tr id="person-' + person.id + '" class="row">\
<td class="name col-sm-4">' + person.name + '</td>\ <td class="name col-sm-4">' + person.name + '</td>\
<td class="surname col-sm-5">' + person.surname + '</td>\ <td class="surname col-sm-5">' + person.surname + '</td>\
<td class="col-sm-3">\ <td class="col-sm-3">\
...@@ -172,35 +186,35 @@ var PeopleView = (function() { ...@@ -172,35 +186,35 @@ var PeopleView = (function() {
<a class="show btn btn-secondary" href="#">Mascotas</a>\ <a class="show btn btn-secondary" href="#">Mascotas</a>\
</td>\ </td>\
</tr>'; </tr>';
}; };
var showErrorMessage = function(jqxhr, textStatus, error) { var showErrorMessage = function (jqxhr, textStatus, error) {
alert(textStatus + ": " + error); alert(textStatus + ": " + error);
}; };
var addRowListeners = function(person) { var addRowListeners = function (person) {
$('#person-' + person.id + ' a.edit').click(function() { $('#person-' + person.id + ' a.edit').click(function () {
self.editPerson(person.id); 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 = "<h1 class=display-5 mt-3 mb-3>Mascotas de "+person.name+" "+person.surname+"</h1>";
var view = new PetView(new PetDAO(),
'people-container', 'people-container',person.id);
view.init();
}); });
};
$('#person-' + person.id + ' a.delete').click(function () {
var appendToTable = function(person) { self.deletePerson(person.id);
$(listQuery + ' > tbody:last') });
.append(createPersonRow(person));
addRowListeners(person); $('#person-' + person.id + ' a.show').click(function () {
}; document.getElementById("people-container").innerHTML = "<h1 class=display-5 mt-3 mb-3>Mascotas de " + person.name + " " + person.surname + "</h1>";
return PeopleView; 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;
})(); })();
var PetView = (function () { var PetView = (function () {
var dao; var dao;
// Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery. // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self; var self;
var peopleID; var peopleID;
var formId = 'people-form'; var formId = 'people-form';
var listId = 'people-list'; var listId = 'people-list';
var formQuery = '#' + formId; var formQuery = '#' + formId;
var listQuery = '#' + listId; 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 = []
var humans_list = [] var humans_list = []
var daoPeople = new PeopleDAO();
function Human(id, name, surname) { function Human(id, name, surname) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.surname = surname; this.surname = surname;
} }
var cont=0; daoPeople.listPeopleSync(function (people) {
var daoPeople = new PeopleDAO();
daoPeople.listPeople(function (people) {
$.each(people, function (key, human) { $.each(people, function (key, human) {
humans[human.id] = new Human(human.id, human.name, human.surname); humans[human.id] = new Human(human.id, human.name, human.surname);
humans_list[cont] = new Human(human.id, human.name, human.surname); humans_list[cont] = new Human(human.id, human.name, human.surname);
cont++; cont++;
}); });
}, },
function () { function () {
alert('No has sido posible acceder al listado de personas.'); alert('No has sido posible acceder al listado de mascotas.');
}); });
insertPetForm($('#' + formContainerId), humans_list, humans);
function PetView(petDao, formContainerId, listContainerId,paramID) {
peopleID=paramID;
dao = petDao;
self = this;
insertPetForm($('#' + formContainerId), humans_list,humans);
insertPetList($('#' + listContainerId)); insertPetList($('#' + listContainerId));
console.log(humans); if (peopleID === "all") {
dao.listAll(function (people) {
this.init = function () { $.each(people, function (key, pet) {
if(peopleID==="all"){ appendToTable(pet, humans);
dao.listAll(function (people) {
$.each(people, function (key, pet) {
appendToTable(pet, humans);
});
},
function () {
alert('No has sido posible acceder al listado de mascotas.');
}); });
}else{ },
dao.listPetsByPeopleID(peopleID,function (people) { function () {
$.each(people, function (key, pet) { alert('No has sido posible acceder al listado de mascotas.');
appendToTable(pet, humans); });
}); } else {
},function () { dao.listPetsByPeopleID(peopleID, function (people) {
alert('No has sido posible acceder al listado de mascotas.'); $.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 // La acción por defecto de enviar formulario (submit) se sobreescribe
// para que el envío sea a través de AJAX // para que el envío sea a través de AJAX
$(formQuery).submit(function (event) { $(formQuery).submit(function (event) {
var pet = self.getPetInForm(); var pet = self.getPetInForm();
if (self.isEditing()) { if (self.isEditing()) {
dao.modifyPet(pet, dao.modifyPet(pet,
function (pet) { function (pet) {
$('#person-' + pet.id + ' td.name').text(pet.name); $('#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); $('#person-' + pet.id + ' td.pet_type').text(pet.type);
self.resetForm(); self.resetForm();
}, },
...@@ -77,7 +71,7 @@ var PetView = (function () { ...@@ -77,7 +71,7 @@ var PetView = (function () {
} else { } else {
dao.addPet(pet, dao.addPet(pet,
function (pet) { function (pet) {
appendToTable(pet,humans); appendToTable(pet, humans);
self.resetForm(); self.resetForm();
}, },
showErrorMessage, showErrorMessage,
...@@ -87,7 +81,6 @@ var PetView = (function () { ...@@ -87,7 +81,6 @@ var PetView = (function () {
return false; return false;
}); });
$('#btnClear').click(this.resetForm); $('#btnClear').click(this.resetForm);
}; };
...@@ -132,7 +125,7 @@ var PetView = (function () { ...@@ -132,7 +125,7 @@ var PetView = (function () {
}; };
this.deletePet = function (id) { 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, dao.deletePet(id,
function () { function () {
$('tr#person-' + id).remove(); $('tr#person-' + id).remove();
...@@ -162,32 +155,31 @@ var PetView = (function () { ...@@ -162,32 +155,31 @@ var PetView = (function () {
} }
; ;
var returnHumansSelect = function (humans) { var returnHumansSelect = function (humans) {
var toret = "<select id=dueno class=form-control>"; var toret = "<select id=dueno class=form-control>";
var cont = 0 var cont = 0
var i=0; var i = 0;
for (i=0;i<humans.length;i++){ for (i = 0; i < humans.length; i++) {
toret+="<option value="+humans[i].id+">"+humans[i].name+" "+humans[i].surname+"</option>"; toret += "<option value=" + humans[i].id + ">" + humans[i].name + " " + humans[i].surname + "</option>";
} }
toret+="</select>"; toret += "</select>";
return toret; return toret;
}; };
var returnHumanTextBox = function (human) { var returnHumanTextBox = function (human) {
var toret ="<input type=hidden id=dueno value=\""+human.id+"\"/><input name=owner type=text value=\""+human.name+" " var toret = "<input type=hidden id=dueno value=\"" + human.id + "\"/><input name=owner type=text value=\"" + human.name + " "
+human.surname+"\" placeholder=Dueño class=form-control readonly/>"; + human.surname + "\" placeholder=Dueño class=form-control readonly/>";
return toret; return toret;
}; };
var insertPetForm = function (parent, humans,humans_map) { var insertPetForm = function (parent, humans, humans_map) {
var txtToAppend=""; var txtToAppend = "";
if(peopleID==='all'){ if (peopleID === 'all') {
txtToAppend=returnHumansSelect(humans); txtToAppend = returnHumansSelect(humans);
}else{ } else {
alert(peopleID); txtToAppend = returnHumanTextBox(humans_map[peopleID]);
txtToAppend=returnHumanTextBox(humans_map[peopleID]);
} }
parent.append( parent.append(
'<form id="' + formId + '" class="mb-5 mb-10">\ '<form id="' + formId + '" class="mb-5 mb-10">\
...@@ -200,7 +192,7 @@ var PetView = (function () { ...@@ -200,7 +192,7 @@ var PetView = (function () {
<input name="type" type="text" value="" placeholder="Tipo" class="form-control" required/>\ <input name="type" type="text" value="" placeholder="Tipo" class="form-control" required/>\
</div>\ </div>\
<div class="col-sm-1">Dueño:</div>\ <div class="col-sm-1">Dueño:</div>\
<div class="col-sm-3">'+ txtToAppend +'</div>\ <div class="col-sm-3">' + txtToAppend + '</div>\
<div class="col-sm-3">\ <div class="col-sm-3">\
<input id="btnSubmit" type="submit" value="Crear" class="btn btn-primary" />\ <input id="btnSubmit" type="submit" value="Crear" class="btn btn-primary" />\
<input id="btnClear" type="reset" value="Limpiar" class="btn" />\ <input id="btnClear" type="reset" value="Limpiar" class="btn" />\
......
...@@ -134,7 +134,7 @@ public class PetResourceTest extends JerseyTest { ...@@ -134,7 +134,7 @@ public class PetResourceTest extends JerseyTest {
} }
@Test @Test
@ExpectedDatabase("/datasets/dataset-add.xml") @ExpectedDatabase("/datasets/dataset-add_pets.xml")
public void testAdd() throws IOException { public void testAdd() throws IOException {
final Form form = new Form(); final Form form = new Form();
form.param("name", newName()); form.param("name", newName());
...@@ -205,7 +205,7 @@ public class PetResourceTest extends JerseyTest { ...@@ -205,7 +205,7 @@ public class PetResourceTest extends JerseyTest {
} }
@Test @Test
@ExpectedDatabase("/datasets/dataset-modify.xml") @ExpectedDatabase("/datasets/dataset-modify_pets.xml")
public void testModify() throws IOException { public void testModify() throws IOException {
final Form form = new Form(); final Form form = new Form();
form.param("name", newName()); form.param("name", newName());
...@@ -292,7 +292,7 @@ public class PetResourceTest extends JerseyTest { ...@@ -292,7 +292,7 @@ public class PetResourceTest extends JerseyTest {
} }
@Test @Test
@ExpectedDatabase("/datasets/dataset-delete.xml") @ExpectedDatabase("/datasets/dataset-delete_pets.xml")
public void testDelete() throws IOException { public void testDelete() throws IOException {
final Response response = target("pets/" + existentId()).request() final Response response = target("pets/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin())) .header("Authorization", "Basic " + userToken(adminLogin()))
......
...@@ -17,9 +17,8 @@ ...@@ -17,9 +17,8 @@
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/> <users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" /> <users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1"/> <pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2"/> <pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1"/> <pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
<pets id="4" name="Jael" type="Perro" peopleID="3"/> <pets id="4" name="Jael" type="Perro" peopleID="3" />
<pets id="5" name="Lucky" type="Anaconda" peopleID="3"/>
</dataset> </dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
<pets id="4" name="Jael" type="Perro" peopleID="3" />
<pets id="5" name="Lucky" type="Anaconda" peopleID="5" />
</dataset>
\ No newline at end of file
...@@ -15,7 +15,8 @@ ...@@ -15,7 +15,8 @@
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/> <users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" /> <users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1"/> <pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2"/> <pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1"/> <pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
<pets id="4" name="Jael" type="Perro" peopleID="3" />
</dataset> </dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
</dataset>
\ No newline at end of file
...@@ -16,8 +16,8 @@ ...@@ -16,8 +16,8 @@
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/> <users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" /> <users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1"/> <pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2"/> <pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1"/> <pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
<pets id="4" name="Lucky" type="Anaconda" peopleID="5"/> <pets id="4" name="Jael" type="Perro" peopleID="3" />
</dataset> </dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
<people id="1" name="Antón" surname="Álvarez" />
<people id="2" name="Ana" surname="Amargo" />
<people id="3" name="Manuel" surname="Martínez" />
<people id="4" name="María" surname="Márquez" />
<people id="5" name="Lorenzo" surname="López" />
<people id="6" name="Laura" surname="Laredo" />
<people id="7" name="Perico" surname="Palotes" />
<people id="8" name="Patricia" surname="Pérez" />
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
<pets id="1" name="Trotsky" type="Perro" peopleID="1" />
<pets id="2" name="Cato" type="Gato" peopleID="2" />
<pets id="3" name="Hiroshi" type="Conejo" peopleID="1" />
<pets id="4" name="Lucky" type="Anaconda" peopleID="5" />
</dataset>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment