...
 
Commits (1)
package es.uvigo.esei.daa.dao;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
protected EntityManagerFactory emf;
protected EntityManager em;
protected Class<T> entityClass;
public GenericDAO() {
this.emf = Persistence.createEntityManagerFactory("DAA");
this.em = emf.createEntityManager();
}
private void setEntityClass() {
this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public T create(T entity) {
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
return entity;
}
public T update(T entity) {
em.getTransaction().begin();
T result = em.merge(entity);
em.getTransaction().commit();
return result;
}
public void delete(T entity) {
em.getTransaction().begin();
em.remove(em.merge(entity));
em.getTransaction().commit();
}
public T findById(Object id) {
if (this.entityClass == null) {
setEntityClass();
}
T result = em.find(this.entityClass, id);
return result;
}
/*
public List<T> findAll() {
if (this.entityClass == null) {
setEntityClass();
}
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<T> query = builder.createQuery(this.entityClass);
query.select(query.from(this.entityClass));
em.getTransaction().begin();
List<T> result = em.createQuery(query).getResultList();
em.getTransaction().commit();
return result;
}
*/
}
package es.uvigo.esei.daa.dao; package es.uvigo.esei.daa.dao;
import java.util.logging.Logger; import javax.persistence.EntityManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import es.uvigo.esei.daa.entities.Pet; import es.uvigo.esei.daa.entities.Pet;
public class PetsDAO extends DAO { public class PetsDAO extends GenericDAO<Pet> {
private final static Logger LOG = Logger.getLogger(PetsDAO.class.getName());
public Pet get(int id)
throws DAOException, IllegalArgumentException {
try (final Connection conn = this.getConnection()) {
final String query = "SELECT * FROM pets 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 pet", e);
throw new DAOException(e);
}
}
public List<Pet> list() throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "SELECT * FROM pets";
try (final PreparedStatement statement = conn.prepareStatement(query)) {
try (final ResultSet result = statement.executeQuery()) {
final List<Pet> pets = new LinkedList<>();
while (result.next()) {
pets.add(rowToEntity(result));
}
return pets;
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error listing pets", e);
throw new DAOException(e);
}
}
public List<Pet> peoplePets(int peopleId) throws DAOException {
try(final Connection conn = this.getConnection()){
final String query = "SELECT * FROM pets WHERE owner= ?";
try(final PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1,peopleId);
try(final ResultSet result = stmt.executeQuery()) {
final List<Pet> pets = new LinkedList<>();
while (result.next()) {
pets.add(rowToEntity(result));
}
return pets;
}
}
} catch (SQLException e){
LOG.log(Level.SEVERE, "Error peoplePets", e);
throw new DAOException(e);
}
}
public Pet add(Pet pet)
throws DAOException, IllegalArgumentException {
if (pet==null) {
throw new IllegalArgumentException("Pet is null!");
}
try (Connection conn = this.getConnection()) {
final String query = "INSERT INTO pets(name, kind, breed, owner) VALUES (?,?,?,?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, pet.getName());
statement.setString(2, pet.getKind());
statement.setString(3, pet.getBreed());
statement.setInt(4, pet.getOwner());
if (statement.executeUpdate() == 1) {
return pet;
} else {
LOG.log(Level.SEVERE, "Error inserting value");
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error adding a pet", e);
throw new DAOException(e);
}
}
public void modify(Pet pet)
throws DAOException, IllegalArgumentException {
if (pet == null) {
throw new IllegalArgumentException("pet can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "UPDATE pets SET name=?, kind=?, breed=?, owner=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { public PetsDAO() {
statement.setString(1, pet.getName()); super();
statement.setString(2, pet.getKind());
statement.setString(3, pet.getBreed());
statement.setInt(4,pet.getOwner());
statement.setInt(5,pet.getId());
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name, kind and breed can't be null");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error modifying a pet", e);
throw new DAOException();
}
} }
public void delete(int id)
throws DAOException, IllegalArgumentException {
try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM pets 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 pet: "+ id, e);
throw new DAOException(e);
}
}
private Pet rowToEntity(ResultSet row) throws SQLException {
return new Pet(
row.getInt("id"),
row.getString("name"),
row.getString("kind"),
row.getString("breed"),
row.getInt("owner")
);
}
} }
\ No newline at end of file
package es.uvigo.esei.daa.entities; package es.uvigo.esei.daa.entities;
public class Pet { import java.io.Serializable;
import javax.persistence.Column;
private int id; import javax.persistence.Entity;
private String name; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Size;
@Entity
public class Pet implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Size(min = 0, max = 30)
@Column(length = 30, nullable = false)
String name;
@Size(min = 0, max = 30)
@Column(length = 30, nullable = false)
private String kind; private String kind;
@Size(min = 0, max = 30)
@Column(length = 30, nullable = false)
private String breed; private String breed;
private int owner;
@ManyToOne
Person owner;
Pet(){} Pet(){}
public Pet(int id, String name, String kind, String breed, int owner) { public Pet(int id, String name, String kind, String breed, Person owner) {
this.setId(id);
this.setName(name); this.setName(name);
this.setKind(kind); this.setKind(kind);
this.setBreed(breed); this.setBreed(breed);
this.setOwner(owner); this.setOwner(owner);
} }
public int getId() { public Long getId() {
return id; return id;
} }
public void setId(int id) {
this.id = id;
}
public String getName() { public String getName() {
return name; return name;
} }
...@@ -50,34 +68,11 @@ public class Pet { ...@@ -50,34 +68,11 @@ public class Pet {
this.breed = breed; this.breed = breed;
} }
public int getOwner() { public Person getOwner() {
return owner; return owner;
} }
public void setOwner(int owner) { public void setOwner(Person owner) {
this.owner = owner; this.owner = owner;
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (int) (prime * result + id);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Pet))
return false;
Pet other = (Pet) obj;
if (id != other.id)
return false;
return true;
}
} }
...@@ -205,29 +205,6 @@ public class PeopleResource { ...@@ -205,29 +205,6 @@ public class PeopleResource {
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error deleting a person", e); LOG.log(Level.SEVERE, "Error deleting a person", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
@GET
@Path("/{id}/pets/")
public Response personsPets(
@PathParam("id") int id
) {
this.pets = new PetsDAO();
try {
return Response.ok(this.pets.peoplePets(id)).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() return Response.serverError()
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
......
package es.uvigo.esei.daa.rest; package es.uvigo.esei.daa.rest;
import java.util.logging.Level; import javax.ws.rs.Consumes;
import java.util.logging.Logger;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import es.uvigo.esei.daa.dao.DAOException;
import java.util.List;
import es.uvigo.esei.daa.dao.PetsDAO; import es.uvigo.esei.daa.dao.PetsDAO;
import es.uvigo.esei.daa.entities.Pet; import es.uvigo.esei.daa.entities.Pet;
@Path("/pets") @Path("/pets")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public class PetsResource { public class PetsResource {
private final static Logger LOG = Logger.getLogger(PetsResource.class.getName());
private final PetsDAO dao; private final PetsDAO dao;
/**
* Constructs a new instance of {@link PeopleResource}.
*/
public PetsResource() { public PetsResource() {
this(new PetsDAO()); this(new PetsDAO());
} }
...@@ -35,126 +35,60 @@ public class PetsResource { ...@@ -35,126 +35,60 @@ public class PetsResource {
this.dao = dao; this.dao = dao;
} }
/*
@GET @GET
@Path("/{id}") @Produces({MediaType.APPLICATION_JSON})
public Response get( public Response searchPets() {
@PathParam("id") int id List<Pet> pets = dao.findAll();
) { GenericEntity<List<Pet>> entidadJSON = new GenericEntity<List<Pet>>(pets) {};
try { return Response.ok(entidadJSON).build();
final Pet pet = this.dao.get(id); }*/
return Response.ok(pet).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();
}
}
@GET @GET
public Response list() { @Produces({MediaType.APPLICATION_JSON})
try { @Path("{id:[0­9]+}")
return Response.ok(this.dao.list()).build(); public Response buscarAutor(@PathParam("id") Long id) {
} catch (DAOException e) { Pet pet = dao.findById(id);
LOG.log(Level.SEVERE, "Error listing pets", e); if (pet != null) {
return Response.serverError().entity(e.getMessage()).build(); return Response.ok(pet).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
} }
} }
@POST @POST
public Response add( @Consumes({MediaType.APPLICATION_JSON})
@FormParam("name") String name, public Response createPet(Pet pet) {
@FormParam("kind") String kind,
@FormParam("breed") String breed,
@FormParam("owner") int owner
) {
try { try {
Pet newPet = new Pet(0, name, kind, breed, owner); Pet newPet = dao.create(pet);
newPet = this.dao.add(newPet);
return Response.ok(newPet).build(); return Response.ok(newPet).build();
} catch (IllegalArgumentException | NullPointerException iae) { } catch (Exception e) {
LOG.log(Level.FINE, "Invalid pet id in add method", iae); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage())
.build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error adding this pet " + name +" breed: "+ breed, e);
return Response.serverError()
.entity(e.getMessage())
.build();
} }
} }
@PUT @PUT
@Path("/{id}") @Consumes({MediaType.APPLICATION_JSON})
public Response modify( @Path("{id:[0­9]+}")
@PathParam("id") int id, public Response updatePet(Pet pet) {
@FormParam("name") String name,
@FormParam("kind") String kind,
@FormParam("breed") String breed,
@FormParam("owner") int owner
) {
try { try {
final Pet pet = new Pet(id, name, kind, breed, owner); dao.update(pet);
this.dao.modify(pet); return Response.noContent().build();
} catch (Exception e) {
return Response.ok(pet).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (NullPointerException npe) {
final String message = "Invalid data for pet" + " id: " + id + " name: " + name + " kind: "
+ kind + " breed: " + breed + " owner: " + owner;
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 @DELETE
@Path("/{id}") @Path("{id:[0­9]+}")
public Response delete( public Response deletePet(@PathParam("id") Long id) {
@PathParam("id") int id Pet pet = dao.findById(id);
) { if (pet != null) {
try { dao.delete(pet);
this.dao.delete(id); return Response.noContent().build();
} else {
return Response.ok(id).build(); return Response.status(Response.Status.NOT_FOUND).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();
} }
} }
} }
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DAA">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/daaexample" />
<property name="javax.persistence.jdbc.user" value="daa" />
<property name="javax.persistence.jdbc.password" value="daa" />
</properties>
</persistence-unit>
</persistence>
\ No newline at end of file