Add pet entitie, DAO, Resource

parent d86860fc
# General
/bak
# Eclipse
.project
.classpath
.settings
WebContent
# Maven
/bin
/target
/assembly
# Testing
/servers
C:\\nppdf32Log\\debuglog.txt
......@@ -13,8 +13,18 @@ CREATE TABLE `daaexample`.`users` (
PRIMARY KEY (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `daaexample`.`pets` (
`idPet` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`idOwner` int NOT NULL,
PRIMARY KEY (`idPet`),
FOREING KEY (`idOwner`) REFERENCES people(id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
-- INSERTS IN PEOPLE --
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Antón','Pérez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Manuel','Martínez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Laura','Reboredo');
......@@ -24,6 +34,14 @@ INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'María','Nu
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fernández');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez');
-- INSERTS IN PETS --
INSERT INTO `daaexample`.`pets` (`idPet`,`name`,`id`) VALUES (0,'Perro',0);
INSERT INTO `daaexample`.`pets` (`idPet`,`name`,`id`) VALUES (0,'Gato',1);
INSERT INTO `daaexample`.`pets` (`idPet`,`name`,`id`) VALUES (0,'Loro',2);
INSERT INTO `daaexample`.`pets` (`idPet`,`name`,`id`) VALUES (0,'Serpiente',3);
INSERT INTO `daaexample`.`pets` (`idPet`,`name`,`id`) VALUES (0,'Rata',0);
-- The password for each user is its login suffixed with "pass". For example, user "admin" has the password "adminpass".
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('admin', '43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70');
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('normal', '688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336');
......@@ -11,6 +11,7 @@ import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import es.uvigo.esei.daa.rest.PeopleResource;
import es.uvigo.esei.daa.rest.PetResource;
import es.uvigo.esei.daa.rest.UsersResource;
/**
......@@ -26,7 +27,8 @@ public class DAAExampleApplication extends Application {
public Set<Class<?>> getClasses() {
return Stream.of(
PeopleResource.class,
UsersResource.class
UsersResource.class,
PetResource.class
).collect(toSet());
}
......
package es.uvigo.esei.daa.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import es.uvigo.esei.daa.entities.Person;
import es.uvigo.esei.daa.entities.Pet;
public class PetsDAO extends DAO{
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 idPet=?";
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> pet = new LinkedList<>();
while (result.next()) {
pet.add(rowToEntity(result));
}
return pet;
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error listing people", e);
throw new DAOException(e);
}
}
public Person add(String name, String surname)
throws DAOException, IllegalArgumentException {
if (name == null || surname == null) {
throw new IllegalArgumentException("name and surname can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "INSERT INTO people VALUES(null, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, name);
statement.setString(2, surname);
if (statement.executeUpdate() == 1) {
try (ResultSet resultKeys = statement.getGeneratedKeys()) {
if (resultKeys.next()) {
return new Person(resultKeys.getInt(1), name, surname);
} else {
LOG.log(Level.SEVERE, "Error retrieving inserted id");
throw new SQLException("Error retrieving inserted id");
}
}
} else {
LOG.log(Level.SEVERE, "Error inserting value");
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error adding a person", e);
throw new DAOException(e);
}
}
public void modify(Person person)
throws DAOException, IllegalArgumentException {
if (person == null) {
throw new IllegalArgumentException("person can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "UPDATE people SET name=?, surname=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, person.getName());
statement.setString(2, person.getSurname());
statement.setInt(3, person.getId());
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name and surname can't be null");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error modifying a person", e);
throw new DAOException();
}
}
public void delete(int id)
throws DAOException, IllegalArgumentException {
try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM people WHERE id=?";
try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id);
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("Invalid id");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error deleting a person", e);
throw new DAOException(e);
}
}
private Pet rowToEntity(ResultSet row) throws SQLException {
return new Pet(
row.getInt("id"),
row.getString("name"),
row.getInt("idOwner")
);
}
}
package es.uvigo.esei.daa.entities;
import static java.util.Objects.requireNonNull;
public class Pet {
private int id;
private String name;
private int idOwner;
Pet() {}
public Pet(int id, String name, int idOwner) {
this.id = id;
this.setName(name);
this.setOwner(idOwner);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getIdOwner() {
return idOwner;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setOwner(int idOwner) {
this.idOwner = idOwner;
}
@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;
}
}
package es.uvigo.esei.daa.rest;
import java.util.logging.Level;
import javax.ws.rs.GET;
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.entities.Person;
@Path("/pets")
@Produces(MediaType.APPLICATION_JSON)
public class PetResource {
@GET
@Path("/{idPet}")
public Response get(@PathParam("idPet") int idPet) {
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();
}
}
}
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