Skip to content

Commit ac9651c

Browse files
authored
Merge pull request eugenp#3812 from tamasradu/radutamas/BAEL-1435
Radutamas/bael 1435
2 parents d602f66 + 46e4113 commit ac9651c

9 files changed

Lines changed: 352 additions & 0 deletions

File tree

‎libraries/pom.xml‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,20 @@
1111
</parent>
1212

1313
<dependencies>
14+
<!-- https://mvnrepository.com/artifact/com.typesafe.akka/akka-actor -->
15+
<dependency>
16+
<groupId>com.typesafe.akka</groupId>
17+
<artifactId>akka-actor_2.12</artifactId>
18+
<version>2.5.11</version>
19+
</dependency>
20+
21+
<dependency>
22+
<groupId>com.typesafe.akka</groupId>
23+
<artifactId>akka-testkit_2.12</artifactId>
24+
<version>2.5.11</version>
25+
<scope>test</scope>
26+
</dependency>
27+
1428
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
1529
<dependency>
1630
<groupId>org.asynchttpclient</groupId>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.AbstractActor;
4+
import akka.actor.Props;
5+
import akka.event.Logging;
6+
import akka.event.LoggingAdapter;
7+
8+
public class FirstActor extends AbstractActor {
9+
10+
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
11+
12+
public static Props props() {
13+
return Props.create(FirstActor.class);
14+
}
15+
16+
@Override
17+
public void preStart() {
18+
log.info("Actor started");
19+
}
20+
21+
@Override
22+
public void postStop() {
23+
log.info("Actor stopped");
24+
}
25+
26+
// Messages will not be handled
27+
@Override
28+
public Receive createReceive() {
29+
return receiveBuilder()
30+
.build();
31+
}
32+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.AbstractActor;
4+
import akka.event.Logging;
5+
import akka.event.LoggingAdapter;
6+
7+
public class MyActor extends AbstractActor {
8+
9+
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
10+
11+
@Override
12+
public void postStop() {
13+
log.info("Stopping actor {}", this);
14+
}
15+
16+
public Receive createReceive() {
17+
return receiveBuilder()
18+
.matchEquals("printit", p -> {
19+
System.out.println("The address of this actor is: " + getSelf());
20+
getSender().tell("Got Message", getSelf());
21+
})
22+
.build();
23+
}
24+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.AbstractActor;
4+
import akka.actor.Props;
5+
import akka.event.Logging;
6+
import akka.event.LoggingAdapter;
7+
8+
public class PrinterActor extends AbstractActor {
9+
10+
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
11+
12+
public static Props props(String text) {
13+
return Props.create(PrinterActor.class, text);
14+
}
15+
16+
public static final class PrintFinalResult {
17+
Integer totalNumberOfWords;
18+
19+
public PrintFinalResult(Integer totalNumberOfWords) {
20+
this.totalNumberOfWords = totalNumberOfWords;
21+
}
22+
}
23+
24+
@Override
25+
public void preStart() {
26+
log.info("Starting PrinterActor {}", this);
27+
}
28+
29+
@Override
30+
public void postStop() {
31+
log.info("Stopping PrinterActor {}", this);
32+
}
33+
34+
35+
@Override
36+
public Receive createReceive() {
37+
return receiveBuilder()
38+
.match(PrinterActor.PrintFinalResult.class,
39+
r -> {
40+
log.info("Received PrintFinalResult message from " + getSender());
41+
log.info("The text has a total number of {} words", r.totalNumberOfWords);
42+
})
43+
.build();
44+
}
45+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.AbstractActor;
4+
import akka.actor.ActorRef;
5+
import akka.actor.Props;
6+
import akka.event.Logging;
7+
import akka.event.LoggingAdapter;
8+
9+
import java.util.ArrayList;
10+
import java.util.List;
11+
import java.util.concurrent.CompletableFuture;
12+
13+
import static akka.pattern.PatternsCS.ask;
14+
15+
public class ReadingActor extends AbstractActor {
16+
17+
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
18+
19+
private String text;
20+
21+
public ReadingActor(String text) {
22+
this.text = text;
23+
}
24+
25+
public static Props props(String text) {
26+
return Props.create(ReadingActor.class, text);
27+
}
28+
29+
public static final class ReadLines {
30+
}
31+
32+
@Override
33+
public void preStart() {
34+
log.info("Starting ReadingActor {}", this);
35+
}
36+
37+
@Override
38+
public void postStop() {
39+
log.info("Stopping ReadingActor {}", this);
40+
}
41+
42+
@Override
43+
public Receive createReceive() {
44+
return receiveBuilder()
45+
.match(ReadLines.class, r -> {
46+
47+
log.info("Received ReadLines message from " + getSender());
48+
49+
String[] lines = text.split("\n");
50+
List<CompletableFuture> futures = new ArrayList<>();
51+
52+
for (int i = 0; i < lines.length; i++) {
53+
String line = lines[i];
54+
ActorRef wordCounterActorRef = getContext().actorOf(Props.create(WordCounterActor.class), "word-counter-" + i);
55+
56+
CompletableFuture<Object> future =
57+
ask(wordCounterActorRef, new WordCounterActor.CountWords(line), 1000).toCompletableFuture();
58+
futures.add(future);
59+
}
60+
61+
Integer totalNumberOfWords = futures.stream()
62+
.map(CompletableFuture::join)
63+
.mapToInt(n -> (Integer) n)
64+
.sum();
65+
66+
ActorRef printerActorRef = getContext().actorOf(Props.create(PrinterActor.class), "Printer-Actor");
67+
printerActorRef.forward(new PrinterActor.PrintFinalResult(totalNumberOfWords), getContext());
68+
// printerActorRef.tell(new PrinterActor.PrintFinalResult(totalNumberOfWords), getSelf());
69+
70+
})
71+
.build();
72+
}
73+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.AbstractActor;
4+
import akka.event.Logging;
5+
import akka.event.LoggingAdapter;
6+
7+
public class WordCounterActor extends AbstractActor {
8+
9+
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
10+
11+
public static final class CountWords {
12+
String line;
13+
14+
public CountWords(String line) {
15+
this.line = line;
16+
}
17+
}
18+
19+
@Override
20+
public void preStart() {
21+
log.info("Starting WordCounterActor {}", this);
22+
}
23+
24+
@Override
25+
public Receive createReceive() {
26+
return receiveBuilder()
27+
.match(CountWords.class, r -> {
28+
try {
29+
log.info("Received CountWords message from " + getSender());
30+
int numberOfWords = countWordsFromLine(r.line);
31+
getSender().tell(numberOfWords, getSelf());
32+
} catch (Exception ex) {
33+
getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
34+
throw ex;
35+
}
36+
})
37+
.build();
38+
}
39+
40+
private int countWordsFromLine(String line) throws Exception {
41+
42+
if (line == null) {
43+
throw new IllegalArgumentException("The text to process can't be null!");
44+
}
45+
46+
int numberOfWords = 0;
47+
String[] words = line.split(" ");
48+
for (String possibleWord : words) {
49+
if (possibleWord.trim().length() > 0) {
50+
numberOfWords++;
51+
}
52+
}
53+
return numberOfWords;
54+
}
55+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package com.baeldung.akka;
2+
3+
import akka.actor.ActorRef;
4+
import akka.actor.ActorSystem;
5+
import akka.actor.Props;
6+
import akka.testkit.TestKit;
7+
import org.junit.AfterClass;
8+
import org.junit.BeforeClass;
9+
import org.junit.Test;
10+
11+
import scala.concurrent.duration.Duration;
12+
13+
import java.util.concurrent.CompletableFuture;
14+
import java.util.concurrent.ExecutionException;
15+
import java.util.concurrent.TimeUnit;
16+
import java.util.concurrent.TimeoutException;
17+
18+
import static akka.pattern.PatternsCS.ask;
19+
import static org.junit.Assert.assertTrue;
20+
import static org.junit.Assert.fail;
21+
22+
public class AkkaActorsUnitTest {
23+
24+
private static ActorSystem system = null;
25+
26+
@BeforeClass
27+
public static void setup() {
28+
system = ActorSystem.create("test-system");
29+
}
30+
31+
@AfterClass
32+
public static void teardown() {
33+
TestKit.shutdownActorSystem(system, Duration.apply(1000, TimeUnit.MILLISECONDS), true);
34+
system = null;
35+
}
36+
37+
@Test
38+
public void givenAnActor_sendHimAMessageUsingTell() {
39+
40+
final TestKit probe = new TestKit(system);
41+
ActorRef myActorRef = probe.childActorOf(Props.create(MyActor.class));
42+
myActorRef.tell("printit", probe.testActor());
43+
44+
probe.expectMsg("Got Message");
45+
}
46+
47+
@Test
48+
public void givenAnActor_sendHimAMessageUsingAsk() throws ExecutionException, InterruptedException {
49+
50+
final TestKit probe = new TestKit(system);
51+
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
52+
53+
CompletableFuture<Object> future =
54+
ask(wordCounterActorRef, new WordCounterActor.CountWords("this is a text"), 1000).toCompletableFuture();
55+
56+
Integer numberOfWords = (Integer) future.get();
57+
assertTrue("The actor should count 4 words", 4 == numberOfWords);
58+
}
59+
60+
@Test
61+
public void givenAnActor_whenTheMessageIsNull_respondWithException() {
62+
final TestKit probe = new TestKit(system);
63+
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
64+
65+
CompletableFuture<Object> future =
66+
ask(wordCounterActorRef, new WordCounterActor.CountWords(null), 1000).toCompletableFuture();
67+
68+
try {
69+
future.get(1000, TimeUnit.MILLISECONDS);
70+
} catch (ExecutionException e) {
71+
assertTrue("Invalid error message", e.getMessage().contains("The text to process can't be null!"));
72+
} catch (InterruptedException | TimeoutException e) {
73+
fail("Actor should respond with an exception instead of timing out !");
74+
}
75+
}
76+
77+
@Test
78+
public void givenAnAkkaSystem_countTheWordsInAText() {
79+
ActorSystem system = ActorSystem.create("test-system");
80+
ActorRef myActorRef = system.actorOf(Props.create(MyActor.class), "my-actor");
81+
myActorRef.tell("printit", null);
82+
// system.stop(myActorRef);
83+
// myActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
84+
// myActorRef.tell(Kill.getInstance(), ActorRef.noSender());
85+
86+
ActorRef readingActorRef = system.actorOf(ReadingActor.props(TEXT), "readingActor");
87+
readingActorRef.tell(new ReadingActor.ReadLines(), ActorRef.noSender()); //ActorRef.noSender() means the sender ref is akka://test-system/deadLetters
88+
89+
// Future<Terminated> terminateResponse = system.terminate();
90+
}
91+
92+
private static String TEXT = "Lorem Ipsum is simply dummy text\n" +
93+
"of the printing and typesetting industry.\n" +
94+
"Lorem Ipsum has been the industry's standard dummy text\n" +
95+
"ever since the 1500s, when an unknown printer took a galley\n" +
96+
"of type and scrambled it to make a type specimen book.\n" +
97+
" It has survived not only five centuries, but also the leap\n" +
98+
"into electronic typesetting, remaining essentially unchanged.\n" +
99+
" It was popularised in the 1960s with the release of Letraset\n" +
100+
" sheets containing Lorem Ipsum passages, and more recently with\n" +
101+
" desktop publishing software like Aldus PageMaker including\n" +
102+
"versions of Lorem Ipsum.";
103+
104+
}

‎libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import au.com.dius.pact.consumer.PactVerification;
66
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
77
import au.com.dius.pact.model.RequestResponsePact;
8+
9+
import org.junit.Ignore;
810
import org.junit.Rule;
911
import org.junit.Test;
1012
import org.springframework.http.HttpEntity;
@@ -34,6 +36,7 @@ public RequestResponsePact createPact(PactDslWithProvider builder) {
3436
}
3537

3638
@Test
39+
@Ignore
3740
@PactVerification()
3841
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
3942
// when

‎libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.apache.http.entity.ContentType;
1616
import org.junit.AfterClass;
1717
import org.junit.BeforeClass;
18+
import org.junit.Ignore;
1819
import org.junit.Test;
1920

2021
import com.baeldung.unirest.Article;
@@ -104,6 +105,7 @@ public void givenRequestBodyWhenCreatedThenCorrect() throws UnirestException {
104105
}
105106

106107
@Test
108+
@Ignore
107109
public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException {
108110
Future<HttpResponse<JsonNode>> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms")
109111
.header("accept", "application/json")

0 commit comments

Comments
 (0)