Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hibernate reactive routes quickstart improvements #626

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,123 +1,113 @@
package org.acme.hibernate.reactive;

import javax.enterprise.context.ApplicationScoped;
import static io.quarkus.vertx.web.Route.HandlerType.FAILURE;
import static io.vertx.core.http.HttpMethod.DELETE;
import static io.vertx.core.http.HttpMethod.GET;
import static io.vertx.core.http.HttpMethod.POST;
import static io.vertx.core.http.HttpMethod.PUT;

import java.util.List;
import java.util.NoSuchElementException;

import javax.inject.Inject;

import org.hibernate.reactive.mutiny.Mutiny;
import org.jboss.logging.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.vertx.web.Body;
import io.quarkus.vertx.web.Param;
import io.quarkus.vertx.web.Route;
import io.quarkus.vertx.web.RouteBase;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

import static io.vertx.core.http.HttpMethod.DELETE;
import static io.vertx.core.http.HttpMethod.GET;
import static io.vertx.core.http.HttpMethod.POST;
import static io.vertx.core.http.HttpMethod.PUT;

/**
* An example using Vert.x Web, Hibernate Reactive and Mutiny.
*/
@ApplicationScoped
@RouteBase(path = "/fruits", produces = "application/json")
public class FruitsRoutes {

@Inject
ObjectMapper mapper;
private static final Logger LOGGER = Logger.getLogger(FruitsRoutes.class.getName());

@Inject
Mutiny.Session session;

/**
* Convert an object into a JSON string.
*/
private String toJSON(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}

@Route(methods = GET, path = "/")
public Multi<Fruit> getAll(RoutingContext rc) throws Exception {
return session.createNamedQuery(Fruit.FIND_ALL, Fruit.class).getResults();
public Uni<List<Fruit>> getAll() throws Exception {
// In this case, it makes sense to return a Uni<List<Fruit>> because we return a reasonable amount of results
// Consider returning a Multi<Fruit> for result streams
return session.createNamedQuery(Fruit.FIND_ALL, Fruit.class).getResultList();
}

@Route(methods = GET, path = "/:id")
public Uni<Fruit> getSingle(RoutingContext rc) {
final Integer id = Integer.valueOf(rc.request().getParam("id"));

return session.find(Fruit.class, id);
public Uni<Fruit> getSingle(@Param String id) {
return session.find(Fruit.class, Integer.valueOf(id));
}

@Route(methods = POST, path = "/")
public Uni<HttpServerResponse> create(RoutingContext rc) {
final String name = rc.getBodyAsJson().getString("name");
final Fruit entity = new Fruit(name);

return session.persist(entity)
.onItem().produceUni(s -> session.flush())
.onItem().apply(ignore -> httpResponse(rc, 201, entity));
public Uni<Fruit> create(@Body Fruit fruit, HttpServerResponse response) {
if (fruit == null || fruit.getId() != null) {
return Uni.createFrom().failure(new IllegalArgumentException("Fruit id invalidly set on request."));
}
return session.persist(fruit)
.onItem().transformToUni(session -> session.flush())
.onItem().transform(ignore -> {
response.setStatusCode(201);
return fruit;
});
}

@Route(methods = PUT, path = "/:id")
public Uni<HttpServerResponse> update(RoutingContext rc) {
final Integer id = Integer.valueOf(rc.request().getParam("id"));
final String name = rc.getBodyAsJson().getString("name");

return session.find(Fruit.class, id)
// if entity exists
.onItem().ifNotNull()
.produceUni(entity -> {
// Update the entity
entity.setName(name);
return session.flush()
.onItem().apply(ignore -> httpResponse(rc, 200, entity));
})
// if entity doesn't exist
.onItem().ifNull()
// Not found response code
.continueWith(httpResponse(rc, 404));
public Uni<Fruit> update(@Body Fruit fruit, @Param String id) {
if (fruit == null || fruit.getName() == null) {
return Uni.createFrom().failure(new IllegalArgumentException("Fruit name was not set on request."));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A curiosity, does it have to be a Uni in this case? Can't we just throw the exception?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can. But I think that it's better to avoid throwing an exception unless we have to...

}
return session.find(Fruit.class, Integer.valueOf(id))
// If entity exists then update
.onItem().ifNotNull().transformToUni(entity -> {
entity.setName(fruit.getName());
return session.flush()
.onItem().transform(ignore -> entity);
})
// else
.onItem().ifNull().fail();
}

@Route(methods = DELETE, path = "/:id")
public Uni<HttpServerResponse> delete(RoutingContext rc) {
final Integer id = Integer.valueOf(rc.request().getParam("id"));

return session.find(Fruit.class, id)
// if entity exists
.onItem().ifNotNull()
.produceUni(entity ->
// Remove the entity
session.remove(entity)
.onItem().produceUni(ignore -> session.flush())
.onItem().apply(ignore -> httpResponse(rc, 204))
)
// if entity doesn't exist
.onItem().ifNull()
// Not found response code
.continueWith(httpResponse(rc, 404));
public Uni<Fruit> delete(@Param String id, HttpServerResponse response) {
return session.find(Fruit.class, Integer.valueOf(id))
// If entity exists then delete
.onItem().ifNotNull().transformToUni(entity -> session.remove(entity)
.onItem().transformToUni(ignore -> session.flush())
.onItem().transform(ignore -> {
response.setStatusCode(204).end();
return entity;
}))
// else
.onItem().ifNull().fail();
}

protected static HttpServerResponse httpResponse(RoutingContext rc, int statusCode) {
return rc.response()
.setStatusCode(statusCode)
.putHeader("Content-Type", "application/json");
@Route(path = "/*", type = FAILURE)
public void error(RoutingContext context) {
Throwable t = context.failure();
if (t != null) {
LOGGER.error("Failed to handle request", t);
int status = context.statusCode();
String chunk = "";
if (t instanceof NoSuchElementException) {
status = 404;
} else if (t instanceof IllegalArgumentException) {
status = 422;
chunk = new JsonObject().put("code", status)
.put("exceptionType", t.getClass().getName()).put("error", t.getMessage()).encode();
}
context.response().setStatusCode(status).end(chunk);
} else {
// Continue with the default error handler
context.next();
}
}

/**
* Generate the response with the specified status code and add the object to the body as JSON.
*/
protected HttpServerResponse httpResponse(RoutingContext rc, int statusCode, Object object) {
String asJson = toJSON(object);
return httpResponse(rc, statusCode)
// Content-Length header is required when using .write
.putHeader("Content-Length", Long.toString(asJson.length()))
.write(asJson);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,101 +16,115 @@ public class FruitsEndpointTest {
public void testListAllFruits() {
//List all, should have all 3 fruits the database has initially:
given()
.when()
.when()
.get("/fruits/")
.then()
.then()
.statusCode(200)
.body(
containsString("Cherry"),
containsString("Apple"),
containsString("Banana"));
.body(
containsString("Cherry"),
containsString("Apple"),
containsString("Banana"));

// Update Cherry to Pineapple
given()
.when()
.when()
.body("{\"name\" : \"Pineapple\"}")
.contentType("application/json")
.put("/fruits/1")
.then()
.then()
.statusCode(200)
.body(
containsString("\"id\":"),
containsString("\"name\":\"Pineapple\""));
.body(
containsString("\"id\":"),
containsString("\"name\":\"Pineapple\""));

//List all, Pineapple should've replaced Cherry:
given()
.when()
.when()
.get("/fruits/")
.then()
.then()
.statusCode(200)
.body(
not(containsString( "Cherry" )),
containsString("Pineapple"),
containsString("Apple"),
containsString("Banana"));
.body(
not(containsString("Cherry")),
containsString("Pineapple"),
containsString("Apple"),
containsString("Banana"));

//Delete Pineapple:
given()
.when()
.when()
.delete("/fruits/1")
.then()
.then()
.statusCode(204);

//List all, Pineapple should be missing now:
given()
.when()
.when()
.get("/fruits/")
.then()
.then()
.statusCode(200)
.body(
not(containsString( "Pineapple")),
containsString("Apple"),
containsString("Banana"));
not(containsString("Pineapple")),
containsString("Apple"),
containsString("Banana"));

//Create the Pear:
given()
.when()
.when()
.body("{\"name\" : \"Pear\"}")
.contentType("application/json")
.post("/fruits/")
.then()
.then()
.statusCode(201)
.body(
containsString("\"id\":"),
containsString("\"name\":\"Pear\""));
containsString("\"id\":"),
containsString("\"name\":\"Pear\""));

//List all, Pineapple should be still missing now:
given()
.when()
.when()
.get("/fruits/")
.then()
.then()
.statusCode(200)
.body(
not(containsString("Pineapple")),
containsString("Apple"),
containsString("Banana"),
containsString("Pear"));
not(containsString("Pineapple")),
containsString("Apple"),
containsString("Banana"),
containsString("Pear"));
}

@Test
public void testEntityNotFoundForDelete() {
given()
.when()
.when()
.delete("/fruits/9236")
.then()
.then()
.statusCode(404)
.body(containsString("{\"statusMessage\":\"Not Found\",\"statusCode\":404,\"chunked\":false}"));
.body(emptyString());
}

@Test
public void testEntityNotFoundForUpdate() {
given()
.when()
.when()
.body("{\"name\" : \"Watermelon\"}")
.contentType("application/json")
.put("/fruits/32432")
.then()
.then()
.statusCode(404)
.body(containsString("{\"statusMessage\":\"Not Found\",\"statusCode\":404,\"chunked\":false}"));
.body(emptyString());
}

@Test
public void testMissingNameForUpdate() {
given()
.when()
.contentType("application/json")
.put("/fruits/3")
.then()
.statusCode(422)
.body(
containsString("\"code\":422"),
containsString("\"error\":\"Fruit name was not set on request.\""),
containsString("\"exceptionType\":\"java.lang.IllegalArgumentException\""));
}
}