|
| 1 | +package com.baeldung.akkahttp; |
| 2 | + |
| 3 | +import java.util.Optional; |
| 4 | +import java.util.concurrent.CompletionStage; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | + |
| 7 | +import akka.actor.ActorRef; |
| 8 | +import akka.http.javadsl.marshallers.jackson.Jackson; |
| 9 | +import akka.http.javadsl.model.StatusCodes; |
| 10 | +import akka.http.javadsl.server.AllDirectives; |
| 11 | +import akka.http.javadsl.server.Route; |
| 12 | +import akka.pattern.PatternsCS; |
| 13 | +import akka.util.Timeout; |
| 14 | +import com.baeldung.akkahttp.UserMessages.ActionPerformed; |
| 15 | +import com.baeldung.akkahttp.UserMessages.CreateUser; |
| 16 | +import scala.concurrent.duration.Duration; |
| 17 | +import static akka.http.javadsl.server.PathMatchers.*; |
| 18 | + |
| 19 | +class UserRoutes extends AllDirectives { |
| 20 | + |
| 21 | + private final ActorRef userActor; |
| 22 | + |
| 23 | + Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS)); |
| 24 | + |
| 25 | + UserRoutes(ActorRef userActor) { |
| 26 | + this.userActor = userActor; |
| 27 | + } |
| 28 | + |
| 29 | + Route routes() { |
| 30 | + return path("users", this::postUser) |
| 31 | + .orElse(path(segment("users").slash(longSegment()), id -> |
| 32 | + route(getUser(id), |
| 33 | + deleteUser(id)))); |
| 34 | + } |
| 35 | + |
| 36 | + private Route getUser(Long id) { |
| 37 | + return get(() -> { |
| 38 | + CompletionStage<Optional<User>> user = PatternsCS.ask(userActor, new UserMessages.GetUser(id), timeout) |
| 39 | + .thenApply(obj -> (Optional<User>) obj); |
| 40 | + |
| 41 | + return onSuccess(() -> user, performed -> { |
| 42 | + if (performed.isPresent()) |
| 43 | + return complete(StatusCodes.OK, performed.get(), Jackson.marshaller()); |
| 44 | + else |
| 45 | + return complete(StatusCodes.NOT_FOUND); |
| 46 | + }); |
| 47 | + }); |
| 48 | + } |
| 49 | + |
| 50 | + private Route deleteUser(Long id) { |
| 51 | + return delete(() -> { |
| 52 | + CompletionStage<ActionPerformed> userDeleted = PatternsCS.ask(userActor, new UserMessages.DeleteUser(id), timeout) |
| 53 | + .thenApply(obj -> (ActionPerformed) obj); |
| 54 | + |
| 55 | + return onSuccess(() -> userDeleted, performed -> { |
| 56 | + return complete(StatusCodes.OK, performed, Jackson.marshaller()); |
| 57 | + }); |
| 58 | + }); |
| 59 | + } |
| 60 | + |
| 61 | + private Route postUser() { |
| 62 | + return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> { |
| 63 | + CompletionStage<ActionPerformed> userCreated = PatternsCS.ask(userActor, new CreateUser(user), timeout) |
| 64 | + .thenApply(obj -> (ActionPerformed) obj); |
| 65 | + |
| 66 | + return onSuccess(() -> userCreated, performed -> { |
| 67 | + return complete(StatusCodes.CREATED, performed, Jackson.marshaller()); |
| 68 | + }); |
| 69 | + }))); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments