[JAVA-22519] Move articles from generic libraries module to specific library modules (#15416)
This commit is contained in:
@@ -8,12 +8,8 @@ The code examples related to different libraries are each in their own module.
|
||||
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
|
||||
|
||||
### Relevant articles
|
||||
- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine)
|
||||
- [A Docker Guide for Java](https://www.baeldung.com/docker-java-api)
|
||||
- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java)
|
||||
- [Introduction to jOOL](https://www.baeldung.com/jool)
|
||||
- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts)
|
||||
- [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue)
|
||||
- [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client)
|
||||
- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools)
|
||||
- More articles [[<-- prev]](/libraries-4) [[next -->]](/libraries-6)
|
||||
|
||||
+2
-76
@@ -6,49 +6,17 @@
|
||||
<artifactId>libraries-5</artifactId>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>${jool.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>au.com.dius</groupId>
|
||||
<artifactId>pact-jvm-provider-junit5_2.12</artifactId>
|
||||
<version>${pact.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>au.com.dius</groupId>
|
||||
<artifactId>pact-jvm-consumer-junit5_2.12</artifactId>
|
||||
<version>${pact.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.typesafe.akka/akka-actor -->
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-actor_${scala.version}</artifactId>
|
||||
<version>${typesafe-akka.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-testkit_${scala.version}</artifactId>
|
||||
<version>${typesafe-akka.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!--Java Docker API Client -->
|
||||
<dependency>
|
||||
<groupId>com.github.docker-java</groupId>
|
||||
@@ -69,18 +37,6 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!--Java Docker API Client -->
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
<version>${caffeine.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
<version>${findbugs.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Atlassian Fugue -->
|
||||
<dependency>
|
||||
<groupId>io.atlassian.fugue</groupId>
|
||||
@@ -92,44 +48,14 @@
|
||||
<artifactId>jnats</artifactId>
|
||||
<version>${jnats.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jctools</groupId>
|
||||
<artifactId>jctools-core</artifactId>
|
||||
<version>${jctools.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<pact.rootDir>target/mypacts</pact.rootDir>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<pact.version>3.6.3</pact.version>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
<spring.version>4.3.8.RELEASE</spring.version>
|
||||
<scala.version>2.12</scala.version>
|
||||
<typesafe-akka.version>2.5.11</typesafe-akka.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
<caffeine.version>3.1.8</caffeine.version>
|
||||
<findbugs.version>3.0.2</findbugs.version>
|
||||
<fugue.version>4.5.1</fugue.version>
|
||||
<jnats.version>1.0</jnats.version>
|
||||
<jctools.version>2.1.2</jctools.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.actor.Props;
|
||||
import akka.event.Logging;
|
||||
import akka.event.LoggingAdapter;
|
||||
|
||||
public class FirstActor extends AbstractActor {
|
||||
|
||||
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
|
||||
|
||||
public static Props props() {
|
||||
return Props.create(FirstActor.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preStart() {
|
||||
log.info("Actor started");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStop() {
|
||||
log.info("Actor stopped");
|
||||
}
|
||||
|
||||
// Messages will not be handled
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.event.Logging;
|
||||
import akka.event.LoggingAdapter;
|
||||
|
||||
public class MyActor extends AbstractActor {
|
||||
|
||||
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
|
||||
|
||||
@Override
|
||||
public void postStop() {
|
||||
log.info("Stopping actor {}", this);
|
||||
}
|
||||
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.matchEquals("printit", p -> {
|
||||
System.out.println("The address of this actor is: " + getSelf());
|
||||
getSender().tell("Got Message", getSelf());
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.actor.Props;
|
||||
import akka.event.Logging;
|
||||
import akka.event.LoggingAdapter;
|
||||
|
||||
public class PrinterActor extends AbstractActor {
|
||||
|
||||
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
|
||||
|
||||
public static Props props(String text) {
|
||||
return Props.create(PrinterActor.class, text);
|
||||
}
|
||||
|
||||
public static final class PrintFinalResult {
|
||||
Integer totalNumberOfWords;
|
||||
|
||||
public PrintFinalResult(Integer totalNumberOfWords) {
|
||||
this.totalNumberOfWords = totalNumberOfWords;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preStart() {
|
||||
log.info("Starting PrinterActor {}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStop() {
|
||||
log.info("Stopping PrinterActor {}", this);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(PrinterActor.PrintFinalResult.class,
|
||||
r -> {
|
||||
log.info("Received PrintFinalResult message from " + getSender());
|
||||
log.info("The text has a total number of {} words", r.totalNumberOfWords);
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.Props;
|
||||
import akka.event.Logging;
|
||||
import akka.event.LoggingAdapter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static akka.pattern.PatternsCS.ask;
|
||||
|
||||
public class ReadingActor extends AbstractActor {
|
||||
|
||||
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
|
||||
|
||||
private String text;
|
||||
|
||||
public ReadingActor(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public static Props props(String text) {
|
||||
return Props.create(ReadingActor.class, text);
|
||||
}
|
||||
|
||||
public static final class ReadLines {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preStart() {
|
||||
log.info("Starting ReadingActor {}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStop() {
|
||||
log.info("Stopping ReadingActor {}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(ReadLines.class, r -> {
|
||||
|
||||
log.info("Received ReadLines message from " + getSender());
|
||||
|
||||
String[] lines = text.split("\n");
|
||||
List<CompletableFuture> futures = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
String line = lines[i];
|
||||
ActorRef wordCounterActorRef = getContext().actorOf(Props.create(WordCounterActor.class), "word-counter-" + i);
|
||||
|
||||
CompletableFuture<Object> future =
|
||||
ask(wordCounterActorRef, new WordCounterActor.CountWords(line), 1000).toCompletableFuture();
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
Integer totalNumberOfWords = futures.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.mapToInt(n -> (Integer) n)
|
||||
.sum();
|
||||
|
||||
ActorRef printerActorRef = getContext().actorOf(Props.create(PrinterActor.class), "Printer-Actor");
|
||||
printerActorRef.forward(new PrinterActor.PrintFinalResult(totalNumberOfWords), getContext());
|
||||
// printerActorRef.tell(new PrinterActor.PrintFinalResult(totalNumberOfWords), getSelf());
|
||||
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.event.Logging;
|
||||
import akka.event.LoggingAdapter;
|
||||
|
||||
public class WordCounterActor extends AbstractActor {
|
||||
|
||||
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
|
||||
|
||||
public static final class CountWords {
|
||||
String line;
|
||||
|
||||
public CountWords(String line) {
|
||||
this.line = line;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preStart() {
|
||||
log.info("Starting WordCounterActor {}", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(CountWords.class, r -> {
|
||||
try {
|
||||
log.info("Received CountWords message from " + getSender());
|
||||
int numberOfWords = countWordsFromLine(r.line);
|
||||
getSender().tell(numberOfWords, getSelf());
|
||||
} catch (Exception ex) {
|
||||
getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
|
||||
throw ex;
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
private int countWordsFromLine(String line) throws Exception {
|
||||
|
||||
if (line == null) {
|
||||
throw new IllegalArgumentException("The text to process can't be null!");
|
||||
}
|
||||
|
||||
int numberOfWords = 0;
|
||||
String[] words = line.split(" ");
|
||||
for (String possibleWord : words) {
|
||||
if (possibleWord.trim().length() > 0) {
|
||||
numberOfWords++;
|
||||
}
|
||||
}
|
||||
return numberOfWords;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.caffeine;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
final class DataObject {
|
||||
private final String data;
|
||||
|
||||
private static int objectCounter = 0;
|
||||
private static final Logger log = LoggerFactory.getLogger(DataObject.class);
|
||||
|
||||
private DataObject(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DataObject{" + "data='" + data + '\'' + '}';
|
||||
}
|
||||
|
||||
public static DataObject get(String data) {
|
||||
objectCounter++;
|
||||
log.info("Init DataObject#{} with '{}'", objectCounter, data);
|
||||
return new DataObject(data);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.baeldung.jctools;
|
||||
|
||||
import org.jctools.queues.MpmcArrayQueue;
|
||||
import org.jctools.queues.atomic.MpmcAtomicArrayQueue;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Control;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.SampleTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Fork(1)
|
||||
@Warmup(iterations = 1)
|
||||
@Measurement(iterations = 3)
|
||||
@State(Scope.Group)
|
||||
public class MpmcBenchmark {
|
||||
|
||||
public static final String PARAM_UNSAFE = "MpmcArrayQueue";
|
||||
public static final String PARAM_AFU = "MpmcAtomicArrayQueue";
|
||||
public static final String PARAM_JDK = "ArrayBlockingQueue";
|
||||
|
||||
public static final int PRODUCER_THREADS_NUMBER = 32;
|
||||
public static final int CONSUMER_THREADS_NUMBER = 32;
|
||||
|
||||
public static final String GROUP_NAME = "MyGroup";
|
||||
|
||||
public static final int CAPACITY = 128;
|
||||
|
||||
@Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK})
|
||||
public volatile String implementation;
|
||||
|
||||
public volatile Queue<Long> queue;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
switch (implementation) {
|
||||
case PARAM_UNSAFE:
|
||||
queue = new MpmcArrayQueue<>(CAPACITY);
|
||||
break;
|
||||
case PARAM_AFU:
|
||||
queue = new MpmcAtomicArrayQueue<>(CAPACITY);
|
||||
break;
|
||||
case PARAM_JDK:
|
||||
queue = new ArrayBlockingQueue<>(CAPACITY);
|
||||
break;
|
||||
default:
|
||||
throw new UnsupportedOperationException("Unsupported implementation " + implementation);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@Group(GROUP_NAME)
|
||||
@GroupThreads(PRODUCER_THREADS_NUMBER)
|
||||
public void write(Control control) {
|
||||
//noinspection StatementWithEmptyBody
|
||||
while (!control.stopMeasurement && !queue.offer(1L)) {
|
||||
// Is intentionally left blank
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@Group(GROUP_NAME)
|
||||
@GroupThreads(CONSUMER_THREADS_NUMBER)
|
||||
public void read(Control control) {
|
||||
//noinspection StatementWithEmptyBody
|
||||
while (!control.stopMeasurement && queue.poll() == null) {
|
||||
// Is intentionally left blank
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
## How to build and run the JMH benchmark
|
||||
|
||||
Execute the following from the project's root:
|
||||
```bash
|
||||
mvn clean install
|
||||
java -jar ./target/benchmarks.jar MpmcBenchmark -si true
|
||||
```
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.pact.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.pact")
|
||||
public class MainApplication implements WebMvcConfigurer {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(MainApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.pact.web.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.pact.web.dto.PactDto;
|
||||
|
||||
@RestController
|
||||
public class PactController {
|
||||
|
||||
List<PactDto> pacts = new ArrayList<>();
|
||||
|
||||
@GetMapping(value = "/pact", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public PactDto getPact() {
|
||||
return new PactDto(true, "tom");
|
||||
}
|
||||
|
||||
@PostMapping("/pact")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void createPact(PactDto pact) {
|
||||
pacts.add(pact);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.pact.web.dto;
|
||||
|
||||
public class PactDto {
|
||||
|
||||
private boolean condition;
|
||||
private String name;
|
||||
|
||||
public PactDto() {
|
||||
}
|
||||
|
||||
public PactDto(boolean condition, String name) {
|
||||
super();
|
||||
this.condition = condition;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isCondition() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
public void setCondition(boolean condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.baeldung.akka;
|
||||
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.actor.Props;
|
||||
import akka.testkit.TestKit;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import scala.concurrent.duration.Duration;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static akka.pattern.PatternsCS.ask;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class AkkaActorsUnitTest {
|
||||
|
||||
private static ActorSystem system = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
system = ActorSystem.create("test-system");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void teardown() {
|
||||
TestKit.shutdownActorSystem(system, Duration.apply(1000, TimeUnit.MILLISECONDS), true);
|
||||
system = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnActor_sendHimAMessageUsingTell() {
|
||||
|
||||
final TestKit probe = new TestKit(system);
|
||||
ActorRef myActorRef = probe.childActorOf(Props.create(MyActor.class));
|
||||
myActorRef.tell("printit", probe.testActor());
|
||||
|
||||
probe.expectMsg("Got Message");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnActor_sendHimAMessageUsingAsk() throws ExecutionException, InterruptedException {
|
||||
|
||||
final TestKit probe = new TestKit(system);
|
||||
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
|
||||
|
||||
CompletableFuture<Object> future =
|
||||
ask(wordCounterActorRef, new WordCounterActor.CountWords("this is a text"), 1000).toCompletableFuture();
|
||||
|
||||
Integer numberOfWords = (Integer) future.get();
|
||||
assertTrue("The actor should count 4 words", 4 == numberOfWords);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnActor_whenTheMessageIsNull_respondWithException() {
|
||||
final TestKit probe = new TestKit(system);
|
||||
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
|
||||
|
||||
CompletableFuture<Object> future =
|
||||
ask(wordCounterActorRef, new WordCounterActor.CountWords(null), 1000).toCompletableFuture();
|
||||
|
||||
try {
|
||||
future.get(1000, TimeUnit.MILLISECONDS);
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue("Invalid error message", e.getMessage().contains("The text to process can't be null!"));
|
||||
} catch (InterruptedException | TimeoutException e) {
|
||||
fail("Actor should respond with an exception instead of timing out !");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnAkkaSystem_countTheWordsInAText() {
|
||||
ActorSystem system = ActorSystem.create("test-system");
|
||||
ActorRef myActorRef = system.actorOf(Props.create(MyActor.class), "my-actor");
|
||||
myActorRef.tell("printit", null);
|
||||
// system.stop(myActorRef);
|
||||
// myActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
|
||||
// myActorRef.tell(Kill.getInstance(), ActorRef.noSender());
|
||||
|
||||
ActorRef readingActorRef = system.actorOf(ReadingActor.props(TEXT), "readingActor");
|
||||
readingActorRef.tell(new ReadingActor.ReadLines(), ActorRef.noSender()); //ActorRef.noSender() means the sender ref is akka://test-system/deadLetters
|
||||
|
||||
// Future<Terminated> terminateResponse = system.terminate();
|
||||
}
|
||||
|
||||
private static String TEXT = "Lorem Ipsum is simply dummy text\n" +
|
||||
"of the printing and typesetting industry.\n" +
|
||||
"Lorem Ipsum has been the industry's standard dummy text\n" +
|
||||
"ever since the 1500s, when an unknown printer took a galley\n" +
|
||||
"of type and scrambled it to make a type specimen book.\n" +
|
||||
" It has survived not only five centuries, but also the leap\n" +
|
||||
"into electronic typesetting, remaining essentially unchanged.\n" +
|
||||
" It was popularised in the 1960s with the release of Letraset\n" +
|
||||
" sheets containing Lorem Ipsum passages, and more recently with\n" +
|
||||
" desktop publishing software like Aldus PageMaker including\n" +
|
||||
"versions of Lorem Ipsum.";
|
||||
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package com.baeldung.caffeine;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.*;
|
||||
|
||||
public class CaffeineUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCache_whenPopulate_thenValueStored() {
|
||||
Cache<String, DataObject> cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build();
|
||||
|
||||
String key = "A";
|
||||
DataObject dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNull(dataObject);
|
||||
|
||||
dataObject = cache.get(key, k -> DataObject.get("Data for A"));
|
||||
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for A", dataObject.getData());
|
||||
|
||||
cache.put(key, dataObject);
|
||||
dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNotNull(dataObject);
|
||||
|
||||
cache.invalidate(key);
|
||||
dataObject = cache.getIfPresent(key);
|
||||
|
||||
assertNull(dataObject);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCache_whenGet_thenValuePopulated() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
|
||||
String key = "A";
|
||||
|
||||
DataObject dataObject = cache.get(key);
|
||||
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for " + key, dataObject.getData());
|
||||
|
||||
Map<String, DataObject> dataObjectMap = cache.getAll(Arrays.asList("A", "B", "C"));
|
||||
|
||||
assertEquals(3, dataObjectMap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
|
||||
|
||||
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k));
|
||||
String key = "A";
|
||||
|
||||
cache.get(key).thenAccept(dataObject -> {
|
||||
assertNotNull(dataObject);
|
||||
assertEquals("Data for " + key, dataObject.getData());
|
||||
});
|
||||
|
||||
cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> Assert.assertEquals(3, dataObjectMap.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
Assert.assertEquals(0, cache.estimatedSize());
|
||||
|
||||
cache.get("A");
|
||||
|
||||
Assert.assertEquals(1, cache.estimatedSize());
|
||||
|
||||
cache.get("B");
|
||||
cache.cleanUp();
|
||||
|
||||
Assert.assertEquals(1, cache.estimatedSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
Assert.assertEquals(0, cache.estimatedSize());
|
||||
|
||||
cache.get("A");
|
||||
|
||||
Assert.assertEquals(1, cache.estimatedSize());
|
||||
|
||||
cache.get("B");
|
||||
|
||||
Assert.assertEquals(2, cache.estimatedSize());
|
||||
|
||||
cache.get("C");
|
||||
cache.cleanUp();
|
||||
|
||||
Assert.assertEquals(2, cache.estimatedSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
|
||||
@Override
|
||||
public long expireAfterCreate(@Nonnull String key, @Nonnull DataObject value, long currentTime) {
|
||||
return value.getData().length() * 1000;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterUpdate(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterRead(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
}).build(k -> DataObject.get("Data for " + k));
|
||||
|
||||
cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
|
||||
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k));
|
||||
cache.get("A");
|
||||
cache.get("A");
|
||||
|
||||
Assert.assertEquals(1, cache.stats().hitCount());
|
||||
Assert.assertEquals(1, cache.stats().missCount());
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package com.baeldung.jctools;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.jctools.queues.SpscArrayQueue;
|
||||
import org.jctools.queues.SpscChunkedArrayQueue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
public class JCToolsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleProducers_whenSpscQueueUsed_thenNoWarningOccurs() throws InterruptedException {
|
||||
SpscArrayQueue<Integer> queue = new SpscArrayQueue<Integer>(2);
|
||||
|
||||
Thread producer1 = new Thread(() -> {
|
||||
queue.offer(1);
|
||||
});
|
||||
producer1.start();
|
||||
producer1.join();
|
||||
|
||||
Thread producer2 = new Thread(() -> {
|
||||
queue.offer(2);
|
||||
});
|
||||
producer2.start();
|
||||
producer2.join();
|
||||
|
||||
Set<Integer> fromQueue = new HashSet<>();
|
||||
Thread consumer = new Thread(() -> queue.drain(fromQueue::add));
|
||||
consumer.start();
|
||||
consumer.join();
|
||||
|
||||
assertThat(fromQueue).containsOnly(1, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException {
|
||||
SpscChunkedArrayQueue<Integer> queue = new SpscChunkedArrayQueue<>(8, 16);
|
||||
Assertions.assertThat(queue.capacity()).isEqualTo(16);
|
||||
|
||||
CountDownLatch startConsuming = new CountDownLatch(1);
|
||||
CountDownLatch awakeProducer = new CountDownLatch(1);
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
Thread producer = new Thread(() -> {
|
||||
IntStream.range(0, queue.capacity()).forEach(i -> {
|
||||
Assertions.assertThat(queue.offer(i)).isTrue();
|
||||
});
|
||||
Assertions.assertThat(queue.offer(queue.capacity())).isFalse();
|
||||
startConsuming.countDown();
|
||||
try {
|
||||
awakeProducer.await();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Assertions.assertThat(queue.offer(queue.capacity())).isTrue();
|
||||
});
|
||||
producer.setUncaughtExceptionHandler((t, e) -> {
|
||||
error.set(e);
|
||||
startConsuming.countDown();
|
||||
});
|
||||
producer.start();
|
||||
|
||||
startConsuming.await();
|
||||
|
||||
if (error.get() != null) {
|
||||
fail("Producer's assertion failed", error.get());
|
||||
}
|
||||
|
||||
Set<Integer> fromQueue = new HashSet<>();
|
||||
queue.drain(fromQueue::add);
|
||||
awakeProducer.countDown();
|
||||
producer.join();
|
||||
queue.drain(fromQueue::add);
|
||||
|
||||
assertThat(fromQueue).containsAll(IntStream.range(0, 17).boxed().collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package com.baeldung.pact;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import au.com.dius.pact.consumer.MockServer;
|
||||
import au.com.dius.pact.consumer.Pact;
|
||||
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
|
||||
import au.com.dius.pact.consumer.junit5.PactTestFor;
|
||||
import au.com.dius.pact.model.RequestResponsePact;
|
||||
|
||||
@ExtendWith(PactConsumerTestExt.class)
|
||||
@PactTestFor(providerName = "test_provider", hostInterface="localhost")
|
||||
public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
@Pact(provider="test_provider", consumer = "test_consumer")
|
||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Content-Type", "application/json");
|
||||
|
||||
return builder
|
||||
.given("test GET")
|
||||
.uponReceiving("GET REQUEST")
|
||||
.path("/pact")
|
||||
.method("GET")
|
||||
.willRespondWith()
|
||||
.status(200)
|
||||
.headers(headers)
|
||||
.body("{\"condition\": true, \"name\": \"tom\"}")
|
||||
.given("test POST")
|
||||
.uponReceiving("POST REQUEST")
|
||||
.method("POST")
|
||||
.headers(headers)
|
||||
.body("{\"name\": \"Michael\"}")
|
||||
.path("/pact")
|
||||
.willRespondWith()
|
||||
.status(201)
|
||||
.toPact();
|
||||
}
|
||||
|
||||
@Test
|
||||
@PactTestFor
|
||||
void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody(MockServer mockServer) {
|
||||
// when
|
||||
ResponseEntity<String> response = new RestTemplate().getForEntity(mockServer.getUrl() + "/pact", String.class);
|
||||
|
||||
// then
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
|
||||
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
|
||||
|
||||
// and
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
String jsonBody = "{\"name\": \"Michael\"}";
|
||||
|
||||
// when
|
||||
ResponseEntity<String> postResponse = new RestTemplate().exchange(mockServer.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class);
|
||||
|
||||
// then
|
||||
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.pact;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.TestTemplate;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
|
||||
import com.baeldung.pact.config.MainApplication;
|
||||
|
||||
import au.com.dius.pact.provider.junit.Provider;
|
||||
import au.com.dius.pact.provider.junit.State;
|
||||
import au.com.dius.pact.provider.junit.loader.PactFolder;
|
||||
import au.com.dius.pact.provider.junit5.HttpTestTarget;
|
||||
import au.com.dius.pact.provider.junit5.PactVerificationContext;
|
||||
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
|
||||
|
||||
@Provider("test_provider")
|
||||
@PactFolder("target/mypacts")
|
||||
public class PactProviderLiveTest {
|
||||
|
||||
private static ConfigurableWebApplicationContext application;
|
||||
|
||||
@BeforeAll
|
||||
public static void start() {
|
||||
application = (ConfigurableWebApplicationContext) SpringApplication.run(MainApplication.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void before(PactVerificationContext context) {
|
||||
context.setTarget(new HttpTestTarget("localhost", 8082, "/spring-rest"));
|
||||
}
|
||||
|
||||
@TestTemplate
|
||||
@ExtendWith(PactVerificationInvocationContextProvider.class)
|
||||
void pactVerificationTestTemplate(PactVerificationContext context) {
|
||||
context.verifyInteraction();
|
||||
}
|
||||
|
||||
@State("test GET")
|
||||
public void toGetState() {
|
||||
}
|
||||
|
||||
@State("test POST")
|
||||
public void toPostState() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user