Skip to content

Commit 8696022

Browse files
KotharuKotharu
authored andcommitted
BAEL-1724 Akka HTTP Initial Commit
1 parent 01b9b56 commit 8696022

8 files changed

Lines changed: 371 additions & 0 deletions

File tree

‎akka-http/pom.xml‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?xml version="1.0"?>
2+
<project
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
4+
xmlns="http://maven.apache.org/POM/4.0.0"
5+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
6+
7+
<modelVersion>4.0.0</modelVersion>
8+
<artifactId>akka-http</artifactId>
9+
<name>akka-http</name>
10+
11+
<parent>
12+
<artifactId>parent-modules</artifactId>
13+
<groupId>com.baeldung</groupId>
14+
<version>1.0.0-SNAPSHOT</version>
15+
</parent>
16+
17+
<dependencies>
18+
<dependency>
19+
<groupId>com.typesafe.akka</groupId>
20+
<artifactId>akka-http_2.12</artifactId>
21+
<version>${akka.http.version}</version>
22+
</dependency>
23+
<dependency>
24+
<groupId>com.typesafe.akka</groupId>
25+
<artifactId>akka-stream_2.12</artifactId>
26+
<version>${akka.stream.version}</version>
27+
</dependency>
28+
<dependency>
29+
<groupId>com.typesafe.akka</groupId>
30+
<artifactId>akka-http-jackson_2.12</artifactId>
31+
<version>${akka.http.version}</version>
32+
</dependency>
33+
<dependency>
34+
<groupId>com.typesafe.akka</groupId>
35+
<artifactId>akka-http-testkit_2.12</artifactId>
36+
<version>${akka.http.version}</version>
37+
<scope>test</scope>
38+
</dependency>
39+
</dependencies>
40+
41+
<properties>
42+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
43+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
44+
<java.version>1.8</java.version>
45+
<akka.http.version>10.0.11</akka.http.version>
46+
<akka.stream.version>2.5.11</akka.stream.version>
47+
</properties>
48+
</project>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.akkahttp;
2+
3+
import java.util.concurrent.CompletionStage;
4+
5+
import akka.NotUsed;
6+
import akka.actor.ActorRef;
7+
import akka.actor.ActorSystem;
8+
import akka.http.javadsl.ConnectHttp;
9+
import akka.http.javadsl.Http;
10+
import akka.http.javadsl.ServerBinding;
11+
import akka.http.javadsl.model.HttpRequest;
12+
import akka.http.javadsl.model.HttpResponse;
13+
import akka.http.javadsl.server.AllDirectives;
14+
import akka.stream.ActorMaterializer;
15+
import akka.stream.javadsl.Flow;
16+
17+
public class AkkaHttpServer extends AllDirectives {
18+
19+
private final UserRoutes userRoutes;
20+
21+
public AkkaHttpServer(ActorSystem system, ActorRef userRegistryActor) {
22+
userRoutes = new UserRoutes(system, userRegistryActor);
23+
}
24+
25+
public static void main(String[] args) throws Exception {
26+
ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
27+
final ActorMaterializer materializer = ActorMaterializer.create(system);
28+
29+
ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor");
30+
31+
AkkaHttpServer app = new AkkaHttpServer(system, userActorRef);
32+
33+
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = app.userRoutes.routes().flow(system, materializer);
34+
35+
final CompletionStage<ServerBinding> binding = Http.get(system).bindAndHandle(routeFlow,
36+
ConnectHttp.toHost("localhost", 8080), materializer);
37+
38+
System.out.println("Server is online at http://localhost:8080/");
39+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.akkahttp;
2+
3+
/**
4+
* User Entity
5+
*
6+
*/
7+
public class User {
8+
9+
private final String name;
10+
private final String address;
11+
12+
public User() {
13+
this.name = "";
14+
this.address = "";
15+
}
16+
17+
public User(String name, String address) {
18+
this.name = name;
19+
this.address = address;
20+
}
21+
22+
public String getName() {
23+
return name;
24+
}
25+
26+
public String getAddress() {
27+
return address;
28+
}
29+
30+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.akkahttp;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import akka.actor.AbstractActor;
7+
import akka.actor.Props;
8+
import akka.event.Logging;
9+
import akka.event.LoggingAdapter;
10+
11+
/**
12+
* User Actor
13+
*
14+
*/
15+
public class UserActor extends AbstractActor {
16+
17+
LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
18+
19+
/**
20+
* In memory List to hold the users added via POST operation.
21+
*/
22+
private final List<User> users = new ArrayList<>();
23+
24+
/**
25+
* To define UserActor Props.
26+
*
27+
* @return Props
28+
*/
29+
static Props props() {
30+
return Props.create(UserActor.class);
31+
}
32+
33+
/**
34+
* createReveive() implementation
35+
*/
36+
@Override
37+
public Receive createReceive() {
38+
return receiveBuilder().match(UserRegistryMessages.GetUsers.class, getUsers -> getSender().tell(new Users(users), getSelf()))
39+
.match(UserRegistryMessages.CreateUser.class, createUser -> {
40+
users.add(createUser.getUser());
41+
getSender().tell(new UserRegistryMessages.ActionPerformed(String.format("User %s created.", createUser.getUser()
42+
.getName())), getSelf());
43+
})
44+
.match(UserRegistryMessages.GetUser.class, getUser -> {
45+
getSender().tell(users.stream()
46+
.filter(user -> user.getName()
47+
.equals(getUser.getName()))
48+
.findFirst(), getSelf());
49+
})
50+
.match(UserRegistryMessages.DeleteUser.class, deleteUser -> {
51+
users.removeIf(user -> user.getName()
52+
.equals(deleteUser.getName()));
53+
getSender().tell(new UserRegistryMessages.ActionPerformed(String.format("User %s deleted.", deleteUser.getName())), getSelf());
54+
55+
})
56+
.matchAny(o -> log.info("received unknown message"))
57+
.build();
58+
}
59+
60+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.baeldung.akkahttp;
2+
3+
/**
4+
* Defines all messages related to User Actor
5+
*
6+
*/
7+
public interface UserRegistryMessages {
8+
9+
class GetUsers implements Serializable {
10+
11+
private static final long serialVersionUID = 1L;
12+
}
13+
14+
class ActionPerformed implements Serializable {
15+
16+
private static final long serialVersionUID = 1L;
17+
18+
private final String description;
19+
20+
public ActionPerformed(String description) {
21+
this.description = description;
22+
}
23+
24+
public String getDescription() {
25+
return description;
26+
}
27+
}
28+
29+
class CreateUser implements Serializable {
30+
31+
private static final long serialVersionUID = 1L;
32+
private final User user;
33+
34+
public CreateUser(User user) {
35+
this.user = user;
36+
}
37+
38+
public User getUser() {
39+
return user;
40+
}
41+
}
42+
43+
class GetUser implements Serializable {
44+
45+
private static final long serialVersionUID = 1L;
46+
private final String name;
47+
48+
public GetUser(String name) {
49+
this.name = name;
50+
}
51+
52+
public String getName() {
53+
return name;
54+
}
55+
}
56+
57+
class DeleteUser implements Serializable {
58+
59+
private static final long serialVersionUID = 1L;
60+
private final String name;
61+
62+
public DeleteUser(String name) {
63+
this.name = name;
64+
}
65+
66+
public String getName() {
67+
return name;
68+
}
69+
}
70+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package com.baeldung.akkahttp;
2+
3+
import java.time.Duration;
4+
import java.util.Optional;
5+
import java.util.concurrent.CompletionStage;
6+
import java.util.concurrent.TimeUnit;
7+
8+
import akka.actor.ActorRef;
9+
import akka.actor.ActorSystem;
10+
import akka.event.Logging;
11+
import akka.event.LoggingAdapter;
12+
import akka.http.javadsl.marshallers.jackson.Jackson;
13+
import akka.http.javadsl.model.StatusCodes;
14+
import akka.http.javadsl.server.AllDirectives;
15+
import akka.http.javadsl.server.PathMatchers;
16+
import akka.http.javadsl.server.Route;
17+
import akka.pattern.PatternsCS;
18+
import akka.util.Timeout;
19+
20+
public class UserRoutes extends AllDirectives {
21+
22+
private final ActorRef userActorRef;
23+
private final LoggingAdapter log;
24+
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
25+
26+
public UserRoutes(ActorSystem system, ActorRef userActorRef) {
27+
this.userActorRef = userActorRef;
28+
log = Logging.getLogger(system, this);
29+
}
30+
31+
public Route routes() {
32+
return pathPrefix("users", () -> route(getOrPostUsers(), path(PathMatchers.segment(), name -> route(getUser(name), deleteUser(name)))));
33+
}
34+
35+
/**
36+
* Defines and returns a route to get the user by name
37+
*
38+
* @param name
39+
* @return Route
40+
*/
41+
private Route getUser(String name) {
42+
43+
Route getRoute = get(() -> {
44+
CompletionStage<Optional<User>> user = PatternsCS.ask(userActorRef, new UserRegistryMessages.GetUser(name), timeout)
45+
.thenApply(obj -> (Optional<User>) obj);
46+
47+
return onSuccess(() -> user, performed -> {
48+
if (performed.isPresent())
49+
return complete(StatusCodes.OK, performed.get(), Jackson.marshaller());
50+
else
51+
return complete(StatusCodes.NOT_FOUND);
52+
});
53+
});
54+
return getRoute;
55+
}
56+
57+
/**
58+
* Defines and returns a Route to delete the user by name.
59+
*
60+
* @param name
61+
* @return Route
62+
*/
63+
private Route deleteUser(String name) {
64+
65+
Route deleteRoute = delete(() -> {
66+
CompletionStage<ActionPerformed> userDeleted = PatternsCS.ask(userActorRef, new UserRegistryMessages.DeleteUser(name), timeout)
67+
.thenApply(obj -> (ActionPerformed) obj);
68+
69+
return onSuccess(() -> userDeleted, performed -> {
70+
log.info("Deleted user [{}]: {}", name, performed.getDescription());
71+
return complete(StatusCodes.OK, performed, Jackson.marshaller());
72+
});
73+
});
74+
75+
return deleteRoute;
76+
}
77+
78+
/**
79+
* Defines two routes, one to get all users and the other is to post users.
80+
*
81+
* @return
82+
*/
83+
private Route getOrPostUsers() {
84+
return pathEnd(() -> route(get(() -> {
85+
CompletionStage<Users> futureUsers = PatternsCS.ask(userActorRef, new UserRegistryMessages.GetUsers(), timeout)
86+
.thenApply(obj -> (Users) obj);
87+
return onSuccess(() -> futureUsers, users -> complete(StatusCodes.OK, users, Jackson.marshaller()));
88+
}), post(() -> entity(Jackson.unmarshaller(User.class), user -> {
89+
CompletionStage<ActionPerformed> userCreated = PatternsCS.ask(userActorRef, new CreateUser(user), timeout)
90+
.thenApply(obj -> (ActionPerformed) obj);
91+
return onSuccess(() -> userCreated, performed -> {
92+
log.info("Created user [{}]: {}", user.getName(), performed.getDescription());
93+
return complete(StatusCodes.CREATED, performed, Jackson.marshaller());
94+
});
95+
}))));
96+
}
97+
98+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.akkahttp;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* This class is used to send the response enclosed by Users.
8+
*
9+
*/
10+
public class Users {
11+
12+
private final List<User> users;
13+
14+
public Users() {
15+
this.users = new ArrayList<>();
16+
}
17+
18+
public Users(List<User> users) {
19+
this.users = users;
20+
}
21+
22+
public List<User> getUsers() {
23+
return users;
24+
}
25+
}

‎pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1254,6 +1254,7 @@
12541254
<module>aws</module>
12551255
<module>aws-lambda</module>
12561256
<module>akka-streams</module>
1257+
<module>akka-http</module>
12571258
<module>algorithms</module>
12581259
<module>annotations</module>
12591260
<module>apache-cxf</module>

0 commit comments

Comments
 (0)