Skip to content
Snippets Groups Projects
Commit 2eb5c629 authored by Hugo Blanquart's avatar Hugo Blanquart
Browse files

to form in ressources

parent 4d9615f3
No related branches found
No related tags found
No related merge requests found
package fr.ulille.iut.pizzaland.beans; package fr.ulille.iut.pizzaland.beans;
import fr.ulille.iut.pizzaland.dto.IngredientDto; import fr.ulille.iut.pizzaland.dto.IngredientDto;
import fr.ulille.iut.pizzaland.dto.IngredientCreateDto;
public class Ingredient { public class Ingredient {
private long id; private long id;
...@@ -69,4 +70,21 @@ public class Ingredient { ...@@ -69,4 +70,21 @@ public class Ingredient {
public String toString() { public String toString() {
return "Ingredient [id=" + id + ", name=" + name + "]"; return "Ingredient [id=" + id + ", name=" + name + "]";
} }
public static IngredientCreateDto toCreateDto(Ingredient ingredient) {
IngredientCreateDto dto = new IngredientCreateDto();
dto.setName(ingredient.getName());
return dto;
}
public static Ingredient fromIngredientCreateDto(IngredientCreateDto dto) {
Ingredient ingredient = new Ingredient();
ingredient.setName(dto.getName());
return ingredient;
}
} }
...@@ -28,4 +28,12 @@ public interface IngredientDao { ...@@ -28,4 +28,12 @@ public interface IngredientDao {
@SqlQuery("SELECT * FROM ingredients WHERE id = :id") @SqlQuery("SELECT * FROM ingredients WHERE id = :id")
@RegisterBeanMapper(Ingredient.class) @RegisterBeanMapper(Ingredient.class)
Ingredient findById(long id); Ingredient findById(long id);
@SqlQuery("SELECT * FROM ingredients WHERE name = :name")
@RegisterBeanMapper(Ingredient.class)
Ingredient findByName(String name);
@SqlUpdate("DELETE FROM ingredients WHERE id = :id")
void remove(long id);
} }
package fr.ulille.iut.pizzaland.dto;
public class IngredientCreateDto {
private String name;
public IngredientCreateDto() {}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package fr.ulille.iut.pizzaland.dto; package fr.ulille.iut.pizzaland.dto;
public class IngredientDto { public class IngredientDto {
private long id; private long id;
private String name; private String name;
public IngredientDto() { public IngredientDto() {}
} public long getId() {
return id;
public long getId() { }
return id;
} public void setId(long id) {
this.id = id;
public void setId(long id) { }
this.id = id;
} public void setName(String name) {
this.name = name;
public String getName() { }
return name;
} public String getName() {
return name;
public void setName(String name) { }
this.name=name;
}
} }
...@@ -11,35 +11,131 @@ import javax.ws.rs.core.Context; ...@@ -11,35 +11,131 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.slf4j.LoggerFactory;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import fr.ulille.iut.pizzaland.beans.Ingredient; import fr.ulille.iut.pizzaland.beans.Ingredient;
import fr.ulille.iut.pizzaland.dto.IngredientDto; import fr.ulille.iut.pizzaland.dto.IngredientDto;
import fr.ulille.iut.pizzaland.BDDFactory;
import fr.ulille.iut.pizzaland.dao.IngredientDao;
import java.util.stream.Collectors;
import javax.ws.rs.POST;
import fr.ulille.iut.pizzaland.dto.IngredientCreateDto;
import javax.ws.rs.WebApplicationException;
@Path("/ingredients") @Path("/ingredients")
public class IngredientResource { public class IngredientResource {
final static Logger LOGGER = Logger.getLogger(IngredientResource.class.getName());
@Context
public UriInfo uriInfo;
private IngredientDao ingredients;
@Context public IngredientResource() {
public UriInfo uriInfo; ingredients = BDDFactory.buildDao(IngredientDao.class);
ingredients.createTable();
}
public IngredientResource() { @GET
} public List<IngredientDto> getAll() {
LOGGER.info("IngredientResource:getAll");
@GET List<IngredientDto> l = ingredients.getAll().stream().map(Ingredient::toDto).collect(Collectors.toList());
public List<IngredientDto> getAll() { return l;
}
return new ArrayList<IngredientDto>(); @GET
} @Path("{id}")
public IngredientDto getOneIngredient(@PathParam("id") long id) {
LOGGER.info("getOneIngredient(" + id + ")");
try {
Ingredient ingredient = ingredients.findById(id);
return Ingredient.toDto(ingredient);
} catch (Exception e) {
// Cette exception générera une réponse avec une erreur 404
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
@GET @POST
@Path("{id}") public Response createIngredient(IngredientCreateDto ingredientCreateDto) {
public IngredientDto getOneIngredient(@PathParam("id") long id) { Ingredient existing = ingredients.findByName(ingredientCreateDto.getName());
Ingredient ingredient = new Ingredient(); if (existing != null) {
ingredient.setId(1); throw new WebApplicationException(Response.Status.CONFLICT);
ingredient.setName("mozzarella"); }
return Ingredient.toDto(ingredient);
} try {
Ingredient ingredient = Ingredient.fromIngredientCreateDto(ingredientCreateDto);
long id = ingredients.insert(ingredient.getName());
ingredient.setId(id);
IngredientDto ingredientDto = Ingredient.toDto(ingredient);
URI uri = uriInfo.getAbsolutePathBuilder().path("" + id).build();
return Response.created(uri).entity(ingredientDto).build();
} catch (Exception e) {
e.printStackTrace();
throw new WebApplicationException(Response.Status.NOT_ACCEPTABLE);
}
}
@DELETE
@Path("{id}")
public Response deleteIngredient(@PathParam("id") long id) {
if ( ingredients.findById(id) == null ) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
} ingredients.remove(id);
\ No newline at end of file
return Response.status(Response.Status.ACCEPTED).build();
}
@GET
@Path("{id}/name")
public String getIngredientName(@PathParam("id") long id) {
Ingredient ingredient = ingredients.findById(id);
if ( ingredient == null ) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return ingredient.getName();
}
@POST
@Consumes("application/x-www-form-urlencoded")
public Response createIngredient(@FormParam("name") String name) {
Ingredient existing = ingredients.findByName(name);
if ( existing != null ) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
try {
Ingredient ingredient = new Ingredient();
ingredient.setName(name);
long id = ingredients.insert(ingredient.getName());
ingredient.setId(id);
IngredientDto ingredientDto = Ingredient.toDto(ingredient);
URI uri = uriInfo.getAbsolutePathBuilder().path("" + id).build();
return Response.created(uri).entity(ingredientDto).build();
}
catch ( Exception e ) {
e.printStackTrace();
throw new WebApplicationException(Response.Status.NOT_ACCEPTABLE);
}
}
}
...@@ -11,7 +11,6 @@ import org.junit.After; ...@@ -11,7 +11,6 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import javax.ws.rs.client.Entity; import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType; import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Application; import javax.ws.rs.core.Application;
...@@ -19,77 +18,160 @@ import javax.ws.rs.core.Response; ...@@ -19,77 +18,160 @@ import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import fr.ulille.iut.pizzaland.dto.IngredientCreateDto;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Form;
import static org.junit.Assert.assertNotNull;
import fr.ulille.iut.pizzaland.dao.IngredientDao;
/* /*
* JerseyTest facilite l'écriture des tests en donnant accès aux * JerseyTest facilite l'écriture des tests en donnant accès aux
* méthodes de l'interface javax.ws.rs.client.Client. * méthodes de l'interface javax.ws.rs.client.Client.
* la méthode configure() permet de démarrer la ressource à tester * la méthode configure() permet de démarrer la ressource à tester
*/ */
public class IngredientResourceTest extends JerseyTest { public class IngredientResourceTest extends JerseyTest {
private IngredientDao dao; private IngredientDao dao;
@Override @Override
protected Application configure() { protected Application configure() {
BDDFactory.setJdbiForTests(); BDDFactory.setJdbiForTests();
return new ApiV1();
} return new ApiV1();
}
// Les méthodes setEnvUp() et tearEnvDown() serviront à terme à initialiser la base de données
// et les DAO @Before
public void setEnvUp() {
// https://stackoverflow.com/questions/25906976/jerseytest-and-junit-throws-nullpointerexception dao = BDDFactory.buildDao(IngredientDao.class);
@Before dao.createTable();
public void setEnvUp() { }
dao = BDDFactory.buildDao(IngredientDao.class);
dao.createTable(); @After
public void tearEnvDown() throws Exception {
} dao.dropTable();
}
@After
public void tearEnvDown() throws Exception { @Test
dao.dropTable(); public void testGetExistingIngredient() {
}
Ingredient ingredient = new Ingredient();
@Test ingredient.setName("mozzarella");
public void testGetEmptyList() {
// La méthode target() permet de préparer une requête sur une URI. long id = dao.insert(ingredient.getName());
// La classe Response permet de traiter la réponse HTTP reçue. ingredient.setId(id);
Response response = target("/ingredients").request().get();
Response response = target("/ingredients/" + id).request().get();
// On vérifie le code de la réponse (200 = OK)
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
Ingredient result = Ingredient.fromDto(response.readEntity(IngredientDto.class));
// On vérifie la valeur retournée (liste vide) assertEquals(ingredient, result);
// L'entité (readEntity() correspond au corps de la réponse HTTP. }
// La classe javax.ws.rs.core.GenericType<T> permet de définir le type
// de la réponse lue quand on a un type complexe (typiquement une liste). @Test
List<IngredientDto> ingredients; public void testGetNotExistingIngredient() {
ingredients = response.readEntity(new GenericType<List<IngredientDto>>(){}); Response response = target("/ingredients/125").request().get();
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
assertEquals(0, ingredients.size()); }
} @Test
public void testCreateIngredient() {
IngredientCreateDto ingredientCreateDto = new IngredientCreateDto();
ingredientCreateDto.setName("mozzarella");
@Test
public void testGetExistingIngredient() { Response response = target("/ingredients").request().post(Entity.json(ingredientCreateDto));
Ingredient ingredient = new Ingredient();
ingredient.setName("mozzarella"); // On vérifie le code de status à 201
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
long id = dao.insert(ingredient.getName());
ingredient.setId(id); IngredientDto returnedEntity = response.readEntity(IngredientDto.class);
Response response = target("/ingredients/" + id).request().get(); // On vérifie que le champ d'entête Location correspond à
// l'URI de la nouvelle entité
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals(target("/ingredients/" + returnedEntity.getId()).getUri(), response.getLocation());
Ingredient result = Ingredient.fromDto(response.readEntity(IngredientDto.class)); // On vérifie que le nom correspond
assertEquals(ingredient, result); assertEquals(returnedEntity.getName(), ingredientCreateDto.getName());
}
}
@Test
public void testCreateSameIngredient() {
IngredientCreateDto ingredientCreateDto = new IngredientCreateDto();
ingredientCreateDto.setName("mozzarella");
dao.insert(ingredientCreateDto.getName());
Response response = target("/ingredients").request().post(Entity.json(ingredientCreateDto));
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());
}
@Test
public void testCreateIngredientWithoutName() {
IngredientCreateDto ingredientCreateDto = new IngredientCreateDto();
Response response = target("/ingredients").request().post(Entity.json(ingredientCreateDto));
assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
}
@Test
public void testDeleteExistingIngredient() {
Ingredient ingredient = new Ingredient();
ingredient.setName("mozzarella");
long id = dao.insert(ingredient.getName());
ingredient.setId(id);
Response response = target("/ingredients/" + id).request().delete();
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
Ingredient result = dao.findById(id);
assertEquals(result, null);
}
@Test
public void testDeleteNotExistingIngredient() {
Response response = target("/ingredients/125").request().delete();
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
public void testGetIngredientName() {
Ingredient ingredient = new Ingredient();
ingredient.setName("mozzarella");
long id = dao.insert(ingredient.getName());
Response response = target("ingredients/" + id + "/name").request().get();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("mozzarella", response.readEntity(String.class));
}
@Test
public void testGetNotExistingIngredientName() {
Response response = target("ingredients/125/name").request().get();
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
public void testCreateWithForm() {
Form form = new Form();
form.param("name", "chorizo");
Entity<Form> formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
Response response = target("ingredients").request().post(formEntity);
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
String location = response.getHeaderString("Location");
long id = Integer.parseInt(location.substring(location.lastIndexOf('/') + 1));
Ingredient result = dao.findById(id);
assertNotNull(result);
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment