-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
gsmet
merged 2 commits into
quarkusio:development
from
mkouba:hibernate-reactive-routes-improvements
Jul 28, 2020
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
156 changes: 73 additions & 83 deletions
156
...te-reactive-routes-quickstart/src/main/java/org/acme/hibernate/reactive/FruitsRoutes.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.")); | ||
} | ||
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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...