Commit 62391120 authored by MvaugustoESEI's avatar MvaugustoESEI

Ejercicio previo terminado, subidos archivos que faltaban

parent 4313de61
{
"plugins": {
"guess-types": {
},
"outline": {
},
"angular": {
}
},
"libs": [
"browser"
]
}
\ No newline at end of file
package es.uvigo.esei.daa.dao;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import es.uvigo.esei.daa.entities.Pet;
public class PetsDAO extends DAO {
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) {
throw new DAOException(e);
}
}
public List<Pet> listByOwnerId(int owner_id) throws DAOException{
try(final Connection conn = this.getConnection()){
final String query = "SELECT * FROM pets WHERE owner_id=?";
try(final PreparedStatement statement = conn.prepareStatement(query)){
statement.setInt(1, owner_id);
try(final ResultSet result = statement.executeQuery()){
final List<Pet> pets = new LinkedList<>();
while(result.next()) {
pets.add(rowToEntity(result));
}
return pets;
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
public Pet add(String name, int idOwner) throws DAOException, IllegalArgumentException{
if(name == null) {
throw new IllegalArgumentException("name can't be null");
}
try(Connection conn = this.getConnection()){
final String query = "INSERT INTO pets VALUES(null, ?, ?);";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)){
statement.setString(1, name);
statement.setInt(2, idOwner);
if(statement.executeUpdate() == 1) {
try(ResultSet resultKeys = statement.getGeneratedKeys()){
if(resultKeys.next()) {
return new Pet(resultKeys.getInt(1), name, new PeopleDAO().get(idOwner));
} else {
throw new SQLException("Error retrieving inserted id");
}
}
} else {
throw new SQLException("Error inserting value");
}
}
} catch (SQLException 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=? WHERE id=?";
try(PreparedStatement statement = conn.prepareStatement(query)){
statement.setString(1, pet.getName());
statement.setInt(2, pet.getId());
if(statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name and owner can't be null");
}
}
} catch(SQLException 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) {
throw new DAOException(e);
}
}
private Pet rowToEntity(ResultSet row) throws SQLException, DAOException {
return new Pet(row.getInt("id"), row.getString("name"), new PeopleDAO().get(row.getInt("owner_id")));
}
}
package es.uvigo.esei.daa.entities;
import static java.util.Objects.requireNonNull;
public class Pet {
private int id;
private String name;
private Person owner;
Pet() {}
public Pet(int id, String name, Person owner) {
this.id = id;
this.setName(name);
this.setOwner(owner);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = requireNonNull(name, "Pet name can't be null");
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = requireNonNull(owner, "Pet owner can't be null");
}
@Override
public int hashCode() {
final int prime = 21;
int result = 1;
result = 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;
}
}
package es.uvigo.esei.daa.rest;
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.dao.PetsDAO;
import es.uvigo.esei.daa.entities.Pet;
@Path("/people/{idOwner}/pets")
@Produces(MediaType.APPLICATION_JSON)
public class PetsResource {
private final PetsDAO dao;
private final PeopleDAO peopleDao;
public PetsResource() {
this(new PetsDAO(), new PeopleDAO());
}
PetsResource(PetsDAO dao, PeopleDAO peopleDao) {
this.dao = dao;
this.peopleDao = peopleDao;
}
@GET
public Response listPets(@PathParam("idOwner") int owner_id) {
try {
return Response.ok(this.dao.listByOwnerId(owner_id)).build();
} catch(DAOException e) {
return Response.serverError().entity(e.getMessage()).build();
}
}
@GET
@Path("/{id}")
public Response get(@PathParam("id") int id) {
try {
final Pet pet = this.dao.get(id);
return Response.ok(pet).build();
} catch(IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch(DAOException e) {
return Response.serverError().entity(e.getMessage()).build();
}
}
@POST
public Response add(@FormParam("name") String name, @PathParam("idOwner") int idOwner) {
try {
final Pet newPet = this.dao.add(name, idOwner);
return Response.ok(newPet).build();
} catch(IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch(DAOException e) {
return Response.serverError().entity(e.getMessage()).build();
}
}
@PUT
@Path("/{id}")
public Response modify(@PathParam("id") int id, @FormParam("name") String name, @PathParam("idOwner") int idOwner) {
try {
final Pet modifiedPet = new Pet(id, name, peopleDao.get(idOwner));
this.dao.modify(modifiedPet);
return Response.ok(modifiedPet).build();
} catch(NullPointerException npe) {
final String message = String.format("Invalid data for pet (name: %s, owner: %d", name, idOwner);
return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
} catch (IllegalArgumentException iae) {
return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();
} catch (DAOException e) {
return Response.serverError().entity(e.getMessage()).build();
}
}
@DELETE
@Path("/{id}")
public Response delete(@PathParam("id") int id) {
try {
this.dao.delete(id);
return Response.ok(id).build();
} catch(IllegalArgumentException iae) {
return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();
} catch (DAOException e) {
return Response.serverError().entity(e.getMessage()).build();
}
}
}
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
var PetsDAO = (function() {
var resourcePath = "rest/people/";
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() {};
let 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(idOwner){
resourcePath = "rest/people/" + idOwner + "/pets/";
this.listPets = function(done, fail, always){
requestByAjax({
url : resourcePath,
type : 'GET'
}, done, fail, always);
};
this.addPet = function(pet, done, fail, always){
requestByAjax({
url : resourcePath,
type : 'POST',
data : pet
}, done, fail, always);
};
this.deletePet = function(id, done, fail, always){
requestByAjax({
url : resourcePath + id,
type : 'DELETE'
}, done, fail, always);
};
this.modifyPet = function(pet, done, fail, always){
requestByAjax({
url : resourcePath + pet.id,
type : 'PUT',
data : pet
}, done, fail, always);
}
}
return PetsDAO;
})();
\ No newline at end of file
var PetsView = (function(){
var dao;
var self;
var formId = 'pets-form';
var listId = 'pets-list';
var formQuery = '#' + formId;
var listQuery = '#' + listId;
function PetsView(petsDao, modalId, title){
dao = petsDao;
self = this;
$('#' + modalId + '-body').empty();
$('#' + modalId + '-title').empty();
insertPetsForm($('#' + modalId + '-body'));
insertPetsList($('#' + modalId + '-body'));
insertModalTitle($('#' + modalId + '-title'), title);
this.init = function(){
dao.listPets(function(pets){
$.each(pets, function(key, pet){
appendToTable(pet);
});
},
function(){
alert("No ha sido posible acceder al listado de mascotas");
});
$(formQuery).submit(function(event){
var pet = self.getPetInForm();
if(self.isEditing()){
dao.modifyPet(pet,
function(pet) {
$('#pet-' + pet.id + ' td.name').text(pet.name);
self.resetForm();
}
);
} else {
dao.addPet(pet,
function(pet){
appendToTable(pet);
self.resetForm();
}
);
}
return false;
});
$('#btnClearPet').click(this.resetForm);
};
this.getPetInForm = function(){
var form = $(formQuery);
return {
'id': form.find('input[name="id"]').val(),
'name': form.find('input[name="name"]').val()
}
};
this.resetForm = function(){
$(formQuery)[0].reset();
$(formQuery + 'input[name="id"').val('');
$('#btnSubmitPet').val('Crear');
};
this.deletePet = function(id){
if(confirm('Está apunto de eliminar una mascoto. ¿Está seguro de que desea continuar?')){
dao.deletePet(id,
function(){
$('tr#pet-' + id).remove();
}
);
}
};
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());
$('input#btnSubmitPet').val('Modificar');
}
};
this.isEditing = function(){
return $(formQuery + ' input[name="id"]').val() != "";
};
};
var getPersonInForm = function(){
var form = $(formQuery);
return {
'id' : form.find('input[name="id"]').val(),
'name' : form.find('input[name="name"]').val(),
};
};
var insertPetsForm = function(parent) {
parent.append(
'<form id="' + formId + '">\
<input name="id" type="hidden" value=""/>\
<div class="row">\
<div>\
<input name="name" type="text" value="" placeholder="Nombre" class="form-control" required/>\
</div>\
<div>\
<input id="btnSubmitPet" type="submit" value="Crear" class="btn btn-primary" />\
<input id="btnClearPet" type="reset" value="Limpiar" class="btn" />\
</div>\
</div>\
</form>'
);
};
var insertPetsList = function(parent){
parent.append(
'<table id="' + listId + '" class="table">\
<thead>\
<tr class="row">\
<th class="col">Nombre</th>\
<th>&nbsp;</th>\
</tr>\
</thead>\
<tbody>\
</tbody>\
</table>'
);
};
var createPetRow = function(pet){
return '<tr id="pet-'+ pet.id +'" class="row">\
<td class="name col">' + pet.name + '</td>\
<td>\
<a class="delete btn btn-warning" href="#">Eliminar</a>\
<a class="edit btn btn-primary" href="#">Editar</a>\
</td>\
</tr>';
};
var addRowListeners = function(pet){
$('#pet-' + pet.id + ' a.delete').click(function(){
self.deletePet(pet.id);
});
$('#pet-' + pet.id + ' a.edit').click(function(){
self.editPet(pet.id);
});
};
var appendToTable = function(pet){
$(listQuery + ' > tbody:last').append(createPetRow(pet));
addRowListeners(pet);
};
var insertModalTitle = function(parent, title){
parent.append(
'Mascotas de ' + title
);
};
return PetsView;
})();
\ No newline at end of file
package es.uvigo.esei.daa.dataset;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.stream;
import java.util.Arrays;
import java.util.function.Predicate;
import es.uvigo.esei.daa.entities.Pet;
public class PetsDataset {
private PetsDataset() {}
public static Pet[] pets() {
return new Pet[] {
new Pet(1, "Micifu", PeopleDataset.people()[0]),
new Pet(2, "Tobi", PeopleDataset.people()[0]),
new Pet(3, "Guantes", PeopleDataset.people()[0]),
new Pet(4, "Pecas", PeopleDataset.people()[0])
};
}
public static Pet[] petsWithout(int ... ids) {
Arrays.sort(ids);
final Predicate<Pet> hasValidId = pet ->
binarySearch(ids, pet.getId()) < 0;
return stream(pets())
.filter(hasValidId)
.toArray(Pet[]::new);
}
public static Pet pet(int id) {
return stream(pets())
.filter(pet -> pet.getId() == id)
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
public static int existentId() {
return 3;
}
public static int nonExistentId() {
return 1234;
}
public static Pet existentPet() {
return pet(existentId());
}
public static Pet nonExistentPet() {
return new Pet(nonExistentId(), "Invisible", PeopleDataset.people()[5]);
}
public static String newName() {
return "Rex";
}
public static Pet newPet() {
return new Pet(pets().length + 1, newName(), PeopleDataset.people()[0]);
}
}
package es.uvigo.esei.daa.entities;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
public class PetUnitTest {
@Test
public void testPetIntStringPerson() {
final int id = 1;
final String name = "Micifu";
final int ownerId = 1;
final String ownerName = "Paco";
final String ownerSurname = "Martinez";
final Person owner = new Person(ownerId, ownerName, ownerSurname);
final Pet pet = new Pet(id, name, owner);
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getOwner(), is(equalTo(owner)));
}
@Test(expected = NullPointerException.class)
public void testPetIntStringPersonNullName() {
final Person owner = new Person(1, "Paco", "Martinez");
new Pet(1, null, owner);
}
@Test(expected = NullPointerException.class)
public void testPetIntStringPersonNullOwner() {
new Pet(1, "Micifu", null);
}
@Test
public void testSetName() {
final int id = 1;
final Person owner = new Person(1, "Paco", "Martinez");
final Pet pet = new Pet(id, "Micifu", owner);
pet.setName("Tobi");
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo("Tobi")));
assertThat(pet.getOwner(), is(equalTo(owner)));
}
@Test(expected = NullPointerException.class)
public void testSetNullName() {
final Pet pet = new Pet(1, "Micifu", new Person(1, "Paco", "Martinez"));
pet.setName(null);
}
@Test(expected = NullPointerException.class)
public void testSetOwner() {
final int id = 1;
final String name = "Micifu";
final Person owner = new Person(1, "Paco", "Martinez");
final Pet pet = new Pet(id, name, new Person(1, "Ana", "Lola"));
pet.setOwner(owner);
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getOwner(), is(equalTo(owner)));
}
@Test(expected = NullPointerException.class)
public void testSetOwnerNull() {
final Pet pet = new Pet(1, "Micifu", new Person(1, "Paco", "Martinez"));
pet.setOwner(null);
}
@Test
public void testEqualsObject() {
final Pet petA = new Pet(1, "Micifu", new Person(1, "Paco", "Martinez"));
final Pet petB = new Pet(1, "Tobi", new Person(2, "Ana", "Ana"));
assertTrue(petA.equals(petB));
}
@Test
public void testEqualsHashcode() {
EqualsVerifier.forClass(Pet.class)
.withIgnoredFields("name", "owner")
.suppress(Warning.STRICT_INHERITANCE)
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
package es.uvigo.esei.daa.matchers;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import es.uvigo.esei.daa.entities.Pet;
public class IsEqualToPet extends IsEqualToEntity<Pet>{
public IsEqualToPet(Pet entity) {
super(entity);
}
@Override
protected boolean matchesSafely(Pet actual) {
this.clearDescribeTo();
if (actual == null) {
this.addTemplatedDescription("actual", expected.toString());
return false;
} else {
return checkAttribute("id", Pet::getId, actual)
&& checkAttribute("name", Pet::getName, actual)
&& checkAttribute("owner", Pet::getOwner, actual);
}
}
@Factory
public static IsEqualToPet equalsToPet(Pet pet) {
return new IsEqualToPet(pet);
}
@Factory
public static Matcher<Iterable<? extends Pet>> containsPetsInAnyOrder(Pet ... pets) {
return containsEntityInAnyOrder(IsEqualToPet::equalsToPet, pets);
}
}
package es.uvigo.esei.daa.rest;
import static es.uvigo.esei.daa.dataset.PetsDataset.existentId;
import static es.uvigo.esei.daa.dataset.PetsDataset.existentPet;
import static es.uvigo.esei.daa.dataset.PetsDataset.newName;
import static es.uvigo.esei.daa.dataset.PetsDataset.newPet;
import static es.uvigo.esei.daa.dataset.PetsDataset.nonExistentId;
import static es.uvigo.esei.daa.dataset.PetsDataset.pets;
import static es.uvigo.esei.daa.dataset.UsersDataset.adminLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.normalLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.userToken;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasBadRequestStatus;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasUnauthorized;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetsInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
import static javax.ws.rs.client.Entity.entity;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import javax.sql.DataSource;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import es.uvigo.esei.daa.DAAExampleTestApplication;
import es.uvigo.esei.daa.entities.Pet;
import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
import es.uvigo.esei.daa.listeners.DbManagement;
import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:contexts/mem-context.xml")
@TestExecutionListeners({
DbUnitTestExecutionListener.class,
DbManagementTestExecutionListener.class,
ApplicationContextJndiBindingTestExecutionListener.class
})
@ApplicationContextBinding(
jndiUrl = "java:/comp/env/jdbc/daaexample",
type = DataSource.class
)
@DbManagement(
create = "classpath:db/hsqldb.sql",
drop = "classpath:db/hsqldb-drop.sql"
)
@DatabaseSetup("/datasets/dataset.xml") // Puede variar
@ExpectedDatabase("/datasets/dataset.xml") // Puede variar
public class PetsResourceTest extends JerseyTest {
@Override
protected Application configure() {
return new DAAExampleTestApplication();
}
@Override
protected void configureClient(ClientConfig config) {
super.configureClient(config);
// Enables JSON transformation in client
config.register(JacksonJsonProvider.class);
config.property("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE);
}
@Test
public void testList() throws IOException {
final Response response = target("people/1/pets").request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final List<Pet> pets = response.readEntity(new GenericType<List<Pet>>(){});
assertThat(pets, containsPetsInAnyOrder(pets()));
}
@Test
public void testListUnauthorized() throws IOException{
final Response response = target("people/1/pets").request().header("Authorization", "Basic " + userToken(normalLogin())).get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGet() throws IOException {
final Response response = target("people/1/pets/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(existentPet())));
}
@Test
public void testGetUnauthorized() throws IOException {
final Response response = target("people/1/pets/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
}
@Test
public void testGetInvalidId() throws IOException {
final Response response = target("people/1/pets/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.get();
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-add-pet.xml")
public void testAdd() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("people/1/pets").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(newPet())));
}
@Test
public void testAddUnauthorized() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("people/1/pets").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(normalLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@Test
public void testAddMissingName() throws IOException {
final Form form = new Form();
final Response response = target("people/1/pets").request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-modify-pet.xml")
public void testModify() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("people/1/pets/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet modifiedPet = response.readEntity(Pet.class);
final Pet pet = existentPet();
pet.setName(newName());
assertThat(modifiedPet, is(equalsToPet(pet)));
}
@Test
public void testModifyUnauthorized() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("people/1/pets/" + existentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(normalLogin()))
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasUnauthorized());
}
@Test
public void testModifyInvalidId() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("people/1/pets/" + nonExistentId()).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + userToken(adminLogin()))
.put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-delete-pet.xml")
public void testDelete() throws IOException {
final Response response = target("people/1/pets/" + existentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasOkStatus());
final Integer deletedId = response.readEntity(Integer.class);
assertThat(deletedId, is(equalTo(existentId())));
}
@Test
public void testDeleteUnauthorized() throws IOException {
final Response response = target("people/1/pets/" + existentId()).request()
.header("Authorization", "Basic " + userToken(normalLogin()))
.delete();
assertThat(response, hasUnauthorized());
}
@Test
public void testDeleteInvalidId() throws IOException {
final Response response = target("people/1/pets/" + nonExistentId()).request()
.header("Authorization", "Basic " + userToken(adminLogin()))
.delete();
assertThat(response, hasBadRequestStatus());
}
}
<?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="Micifu" owner_id="1"/>
<pets id="2" name="Tobi" owner_id="1"/>
<pets id="3" name="Guantes" owner_id="1"/>
<pets id="4" name="Pecas" owner_id="1"/>
<pets id="5" name="Rex" owner_id="1"/>
</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="Micifu" owner_id="1"/>
<pets id="2" name="Tobi" owner_id="1"/>
<pets id="4" name="Pecas" owner_id="1"/>
</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="Micifu" owner_id="1"/>
<pets id="2" name="Tobi" owner_id="1"/>
<pets id="3" name="Rex" owner_id="1"/>
<pets id="4" name="Pecas" owner_id="1"/>
</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