Skip to content

Commit

Permalink
Merge pull request #30 from Runi-VN/issue#16
Browse files Browse the repository at this point in the history
Issue#16 - [JOKE] REST-endpoints + testing
  • Loading branch information
Runi-VN authored Sep 10, 2019
2 parents 7309814 + 7aceb9f commit 51711e8
Show file tree
Hide file tree
Showing 5 changed files with 436 additions and 21 deletions.
58 changes: 44 additions & 14 deletions src/main/java/facades/JokeFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,14 @@ private EntityManager getEntityManager() {
public long getJokeCount() {
EntityManager em = getEntityManager();
try {
return (long) em.createQuery("SELECT COUNT(r) FROM Joke r").getSingleResult();
Long result = (long) em.createQuery("SELECT COUNT(r) FROM Joke r").getSingleResult();
if (result == 0) {
throw new IllegalStateException("Database is empty");
}
return result;
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke count" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke count -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -63,10 +67,15 @@ public long getJokeCount() {
public List<Joke> getAllJokes() {
EntityManager em = getEntityManager();
try {
return em.createQuery("SELECT r FROM Joke r", Joke.class).getResultList();
List<Joke> result = em.createQuery("SELECT r FROM Joke r", Joke.class).getResultList();
if (result == null || result.isEmpty()) {
throw new IllegalStateException("Database is empty");
} else {
return result;
}
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get all jokes" + ex.getMessage());
throw new IllegalArgumentException("Could not get all jokes -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -80,10 +89,15 @@ public List<Joke> getAllJokes() {
public List<JokeDTO> getAllJokesAsDTO() {
EntityManager em = getEntityManager();
try {
return em.createQuery("SELECT NEW dto.JokeDTO(j) FROM Joke j", JokeDTO.class).getResultList();
List<JokeDTO> result = em.createQuery("SELECT NEW dto.JokeDTO(j) FROM Joke j", JokeDTO.class).getResultList();
if (result == null || result.isEmpty()) {
throw new IllegalArgumentException("Database is empty. (DTO)");
} else {
return result;
}
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get all jokes (DTO)" + ex.getMessage());
throw new IllegalArgumentException("Could not get all jokes (DTO) -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -101,10 +115,14 @@ public List<JokeDTO> getAllJokesAsDTO() {
public Joke getJokeById(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(Joke.class, id);
Joke result = em.find(Joke.class, id);
if (result == null) {
throw new IllegalStateException("Database is empty or joke doesn't exist.");
}
return result;
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke by ID" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke by ID -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -119,10 +137,16 @@ public Joke getJokeById(Long id) {
public JokeDTO getJokeByIdAsDTO(Long id) {
EntityManager em = getEntityManager();
try {
return new JokeDTO(em.find(Joke.class, id));
Joke result = em.find(Joke.class, id);
if (result == null) {
throw new IllegalStateException("Database is empty or joke doesn't exist.");
} else {
return new JokeDTO(result);
}

} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke by ID" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke (DTO) by ID -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -145,7 +169,7 @@ public Joke getJokeByRandom() {
return em.find(Joke.class, id);
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke by random" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke by random -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -168,7 +192,7 @@ public JokeDTO getJokeByRandomAsDTO() {
return new JokeDTO(em.find(Joke.class, id));
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke by ID" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke by ID (DTO) -> " + ex.getMessage());
} finally {
em.close();
}
Expand All @@ -185,10 +209,16 @@ public JokeDTO getJokeByRandomAsDTO() {
private List<Long> getJokeIds() {
EntityManager em = getEntityManager();
try {
return em.createQuery("SELECT r.id FROM Joke r").getResultList();
List<Long> result = em.createQuery("SELECT r.id FROM Joke r").getResultList();
if (result == null || result.isEmpty())
{
throw new IllegalStateException("Database is empty");
} else{
return result;
}
} catch (Exception ex) {
//em.getTransaction().rollback();
throw new IllegalArgumentException("Could not get joke IDs" + ex.getMessage());
throw new IllegalArgumentException("Could not get joke IDs -> " + ex.getMessage());
} finally {
em.close();
}
Expand Down
1 change: 1 addition & 0 deletions src/main/java/rest/ApplicationConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public Set<Class<?>> getClasses() {
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(org.glassfish.jersey.server.wadl.internal.WadlResource.class);
resources.add(rest.JokeResource.class);
resources.add(rest.RenameMeResource.class);
}

Expand Down
109 changes: 109 additions & 0 deletions src/main/java/rest/JokeResource.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package rest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import utils.EMF_Creator;
import facades.JokeFacade;
import javax.persistence.EntityManagerFactory;
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;

//Todo Remove or change relevant parts before ACTUAL use
@Path("jokes")
public class JokeResource {

private static final EntityManagerFactory EMF = EMF_Creator.createEntityManagerFactory(EMF_Creator.DbSelector.DEV, EMF_Creator.Strategy.DROP_AND_CREATE);
private static final JokeFacade FACADE = JokeFacade.getFacadeExample(EMF);
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

@GET
@Produces({MediaType.APPLICATION_JSON})
public String demo() {
return "{\"msg\":\"ACCESS GRANTED\"}";
}

@Path("/count")
@GET
@Produces({MediaType.APPLICATION_JSON})
public String getJokeCount() {
try {
JsonObject count = new JsonObject();
count.addProperty("count", FACADE.getJokeCount());
return GSON.toJson(count);
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}

@GET
@Path("/all")
@Produces({MediaType.APPLICATION_JSON})
public String getAllJokes() throws Exception {
try {
return GSON.toJson(FACADE.getAllJokes());
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}

@GET
@Path("/all/dto")
@Produces({MediaType.APPLICATION_JSON})
public String getAllJokesAsDTO() throws Exception {
try {
return GSON.toJson(FACADE.getAllJokesAsDTO());
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}


@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_JSON})
public String getJokeByID(@PathParam("id") Long id) throws Exception {
try {
return GSON.toJson(FACADE.getJokeById(id));
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}

@GET
@Path("/{id}/dto")
@Produces({MediaType.APPLICATION_JSON})
public String getJokeDTOByID(@PathParam("id") Long id) throws Exception {
try {
return GSON.toJson(FACADE.getJokeByIdAsDTO(id));
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}

@GET
@Path("/random")
@Produces({MediaType.APPLICATION_JSON})
public String getJokeRandom() throws Exception {
try {
return GSON.toJson(FACADE.getJokeByRandom());
} catch (Exception ex) {
return "{\"error\": \"" + ex.getMessage() + "\"}";
}
}

@GET
@Path("/random/dto")
@Produces({MediaType.APPLICATION_JSON})
public String getJokeRandomAsDTO() throws Exception {
try {
return GSON.toJson(FACADE.getJokeByRandomAsDTO());
} catch (Exception ex) {
return "[\"error\": \"" + ex.getMessage() + "\"}";
}
}

}
24 changes: 17 additions & 7 deletions src/test/java/facades/JokeFacadeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import utils.EMF_Creator;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
Expand Down Expand Up @@ -55,7 +57,9 @@ public void setUp() {

try {
em.getTransaction().begin();
em.createNamedQuery("Joke.deleteAllRows").executeUpdate();
Query query = em.createNativeQuery("truncate table CA1_test.JOKE;");
query.executeUpdate();
//em.createNamedQuery("Joke.deleteAllRows").executeUpdate();
em.getTransaction().commit();
for (Joke j : jokes) {
em.getTransaction().begin();
Expand All @@ -74,7 +78,7 @@ public void tearDown() {

@Test
public void testGetJokeCount() {
assertEquals(jokes.size(), facade.getJokeCount(), "Expects three rows in the database");
assertEquals(jokes.size(), facade.getJokeCount(), "Expects four rows in the database");
}

@Test
Expand Down Expand Up @@ -135,19 +139,25 @@ public void testGetJokeById() {
/**
* em.find in getJokeByID does not actually throw an exception, but returns
* null.
*
*
* I made a guard for that and throw an IllegalStateException.
*/
@Test
public void testGetJokeByIdError() {
//Arrange
Joke expResult = null;
Joke result;
Throwable expResult = new IllegalArgumentException("Could not get joke by ID -> Database is empty or joke doesn't exist.");
Throwable result;
long id = 99L;

//Act
result = facade.getJokeById(99L);
result = assertThrows(IllegalArgumentException.class, () -> {
facade.getJokeById(id);
});

//Assert
Assertions.assertNull(result);
assertEquals(expResult, result); //does the same as above
Assertions.assertNotNull(result);
assertEquals(expResult.getCause(), result.getCause());
}

@Test
Expand Down
Loading

0 comments on commit 51711e8

Please sign in to comment.