Java-1470 Split libraries module
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
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.";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.bytebuddy;
|
||||
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.agent.ByteBuddyAgent;
|
||||
import net.bytebuddy.dynamic.DynamicType;
|
||||
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
|
||||
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
|
||||
import net.bytebuddy.implementation.FixedValue;
|
||||
import net.bytebuddy.implementation.MethodDelegation;
|
||||
import net.bytebuddy.matcher.ElementMatchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
|
||||
import static net.bytebuddy.matcher.ElementMatchers.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class ByteBuddyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
|
||||
DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
|
||||
|
||||
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
|
||||
|
||||
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
|
||||
ByteBuddyAgent.install();
|
||||
new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
|
||||
Foo f = new Foo();
|
||||
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
|
||||
|
||||
String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
|
||||
.sayHelloFoo();
|
||||
|
||||
assertEquals(r, Bar.sayHelloBar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
|
||||
Class<?> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
|
||||
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
|
||||
|
||||
Method m = type.getDeclaredMethod("custom", null);
|
||||
|
||||
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
|
||||
assertNotNull(type.getDeclaredField("x"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.PortBinding;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.hamcrest.core.Is;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class ContainerLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingRunningContainers_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Container> containers = dockerClient.listContainersCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(containers.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingExitedContainers_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Container> containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec();
|
||||
|
||||
// then
|
||||
assertThat(containers.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingContainer_thenMustReturnContainerId() {
|
||||
|
||||
// when
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();
|
||||
|
||||
// then
|
||||
MatcherAssert.assertThat(container.getId(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHavingContainer_thenRunContainer() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
// then
|
||||
dockerClient.startContainerCmd(container.getId()).exec();
|
||||
|
||||
dockerClient.stopContainerCmd(container.getId()).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningContainer_thenStopContainer() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
dockerClient.startContainerCmd(container.getId()).exec();
|
||||
|
||||
// then
|
||||
dockerClient.stopContainerCmd(container.getId()).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningContainer_thenKillContainer() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
|
||||
|
||||
dockerClient.startContainerCmd(container.getId()).exec();
|
||||
|
||||
Thread.sleep(3000);
|
||||
dockerClient.stopContainerCmd(container.getId()).exec();
|
||||
|
||||
// then
|
||||
dockerClient.killContainerCmd(container.getId()).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHavingContainer_thenInspectContainer() {
|
||||
|
||||
// when
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
|
||||
|
||||
// then
|
||||
InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
|
||||
|
||||
MatcherAssert.assertThat(containerResponse.getId(), Is.is(container.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
|
||||
|
||||
// given
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
|
||||
|
||||
// when
|
||||
String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec();
|
||||
|
||||
// then
|
||||
assertThat(imageId, is(not(null)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class DockerClientLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClient_thenReturnDefaultInstance() {
|
||||
|
||||
// when
|
||||
DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder();
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
// then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
|
||||
// when
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build();
|
||||
|
||||
// then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
|
||||
|
||||
// when
|
||||
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung")
|
||||
.withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build();
|
||||
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
// then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingDockerClientWithProperties_thenReturnInstance() {
|
||||
|
||||
// when
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("registry.email", "info@bealdung.com");
|
||||
properties.setProperty("registry.url", "register.bealdung.io/v2/");
|
||||
properties.setProperty("registry.password", "strongpassword");
|
||||
properties.setProperty("registry.username", "bealdung");
|
||||
properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs");
|
||||
properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/");
|
||||
properties.setProperty("DOCKER_TLS_VERIFY", "1");
|
||||
properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
|
||||
|
||||
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build();
|
||||
|
||||
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
|
||||
|
||||
// then
|
||||
assertNotNull(dockerClient);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectImageResponse;
|
||||
import com.github.dockerjava.api.model.Image;
|
||||
import com.github.dockerjava.api.model.SearchItem;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import com.github.dockerjava.core.command.BuildImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PullImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PushImageResultCallback;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.hamcrest.core.Is;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class ImageLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImages_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
|
||||
|
||||
// then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingDanglingImages_thenReturnNonNullList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().withDanglingFilter(true).exec();
|
||||
|
||||
// then
|
||||
assertThat(images, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuildingImage_thenMustReturnImageId() {
|
||||
|
||||
// when
|
||||
String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId();
|
||||
|
||||
// then
|
||||
assertThat(imageId, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
|
||||
|
||||
// given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
// when
|
||||
InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
|
||||
|
||||
// then
|
||||
MatcherAssert.assertThat(imageResponse.getId(), Is.is(image.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenTagImage_thenListMustIncrement() {
|
||||
|
||||
// given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
// when
|
||||
dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();
|
||||
|
||||
// then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(greaterThan(images.size())));
|
||||
}
|
||||
|
||||
public void pushingAnImage() throws InterruptedException {
|
||||
|
||||
dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
|
||||
|
||||
// when
|
||||
dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);
|
||||
|
||||
// then
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingImage_thenImageListDecrease() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
dockerClient.removeImageCmd(image.getId()).exec();
|
||||
|
||||
// then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(lessThan(images.size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSearchingImage_thenMustReturn25Items() {
|
||||
|
||||
// when
|
||||
List<SearchItem> items = dockerClient.searchImagesCmd("Java").exec();
|
||||
|
||||
// then
|
||||
assertThat(items.size(), is(25));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateNetworkResponse;
|
||||
import com.github.dockerjava.api.model.Network;
|
||||
import com.github.dockerjava.api.model.Network.Ipam;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class NetworkLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("temporarily")
|
||||
public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
List<Network> networks = dockerClient.listNetworksCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(networks.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRetrieveResponse() {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
String networkName = "bridge";
|
||||
Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
|
||||
|
||||
// then
|
||||
MatcherAssert.assertThat(network.getName(), is(networkName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRemove() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeNetworkCmd(networkResponse.getId()).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateVolumeResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesResponse;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class VolumeLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingVolumes_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
|
||||
// then
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
assertThat(volumes.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() {
|
||||
|
||||
// given
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
InspectVolumeResponse volume = volumes.get(0);
|
||||
|
||||
// when
|
||||
InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec();
|
||||
|
||||
// then
|
||||
assertThat(volumeResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingUnnamedVolume_thenGetVolumeId() {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
|
||||
|
||||
// then
|
||||
MatcherAssert.assertThat(unnamedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNamedVolume_thenGetVolumeId() {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
|
||||
|
||||
// then
|
||||
MatcherAssert.assertThat(namedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
|
||||
|
||||
// then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeVolumeCmd(namedVolume.getName()).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.baeldung.fugue;
|
||||
|
||||
import io.atlassian.fugue.*;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static io.atlassian.fugue.Unit.Unit;
|
||||
|
||||
public class FugueUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSome_thenDefined() {
|
||||
Option<String> some = Option.some("value");
|
||||
|
||||
assertTrue(some.isDefined());
|
||||
assertEquals("value", some.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNone_thenNotDefined() {
|
||||
Option<Object> none = Option.none();
|
||||
|
||||
assertFalse(none.isDefined());
|
||||
assertEquals(1, none.getOrElse(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSomeNull_thenException() {
|
||||
try {
|
||||
Option.some(null);
|
||||
|
||||
fail("some(null) should throw");
|
||||
} catch (NullPointerException e) {
|
||||
//Expected
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullOption_thenSome() {
|
||||
Option<String> some = Option.some("value") .map(String::toUpperCase);
|
||||
|
||||
assertEquals("VALUE", some.get());
|
||||
|
||||
some = some.map(x -> null);
|
||||
|
||||
assertNull(some.get());
|
||||
some.forEach(Assert::assertNull);
|
||||
for(Object value : some) {
|
||||
assertNull(value);
|
||||
}
|
||||
assertEquals(1, some.toStream().count());
|
||||
|
||||
Option<Object> none = Option.some("value").flatMap(x -> Option.none());
|
||||
|
||||
assertFalse(none.isDefined());
|
||||
|
||||
none = Option.some("value").flatMap(Options.nullSafe(x -> null));
|
||||
|
||||
assertFalse(none.isDefined());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNone_thenEmptyOptional() {
|
||||
Optional<Object> optional = Option.none().toOptional();
|
||||
|
||||
assertFalse(optional.isPresent());
|
||||
assertTrue(Option.fromOptional(optional).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOption_thenIterable() {
|
||||
Option<String> some = Option.some("value");
|
||||
Iterable<String> strings = Iterables.concat(some, Arrays.asList("a", "b", "c"));
|
||||
List<String> stringList = new ArrayList<>();
|
||||
Iterables.addAll(stringList, strings);
|
||||
|
||||
assertEquals(4, stringList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOption_thenStream() {
|
||||
assertEquals(0, Option.none().toStream().count());
|
||||
assertEquals(1, Option.some("value").toStream().count());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLift_thenPartialFunction() {
|
||||
Function<Integer, Integer> f = (Integer x) -> x > 0 ? x + 1 : null;
|
||||
Function<Option<Integer>, Option<Integer>> lifted = Options.lift(f);
|
||||
|
||||
assertEquals(2, (long) lifted.apply(Option.some(1)).get());
|
||||
assertTrue(lifted.apply(Option.none()).isEmpty());
|
||||
assertEquals(null, lifted.apply(Option.some(0)).get());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
public void whenLeft_thenEither() {
|
||||
Either<Integer, String> right = Either.right("value");
|
||||
Either<Integer, String> left = Either.left(-1);
|
||||
if(right.isLeft()) {
|
||||
fail();
|
||||
}
|
||||
if(left.isRight()) {
|
||||
fail();
|
||||
}
|
||||
|
||||
String s = right.map(String::toUpperCase).getOrNull();
|
||||
|
||||
assertEquals("VALUE", s);
|
||||
|
||||
Either<String, String> either = right.left().map(x -> decodeSQLErrorCode(x));
|
||||
|
||||
assertTrue(either.isRight());
|
||||
assertEquals("value", either.right().get());
|
||||
|
||||
either.right().forEach(x -> assertEquals("value", x));
|
||||
}
|
||||
|
||||
private static String decodeSQLErrorCode(Integer x) {
|
||||
return "error";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryIsFailure_thenIsFailureReturnsTrue() {
|
||||
assertTrue(Try.failure(new Exception("Fail!")).isFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryIsSuccess_thenIsSuccessReturnsTrue() {
|
||||
assertTrue(Try.successful("OK").isSuccess());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunctionReturning_whenCheckedOf_thenSuccess() {
|
||||
assertTrue(Checked.of(() -> "ok").isSuccess());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunctionThrowing_whenCheckedOf_thenFailure() {
|
||||
assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunctionThrowing_whenCheckedLift_thenFailure() {
|
||||
Checked.Function<String, Object, Exception> throwException = (String x) -> {
|
||||
throw new Exception(x);
|
||||
};
|
||||
|
||||
assertTrue(Checked.lift(throwException).apply("ko").isFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecover_thenSuccessfulTry() {
|
||||
Try<Object> recover = Try.
|
||||
failure(new Exception("boo!")).
|
||||
recover((Exception e) -> e.getMessage() + " recovered.");
|
||||
|
||||
assertTrue(recover.isSuccess());
|
||||
assertEquals("boo! recovered.", recover.getOrElse(() -> null));
|
||||
|
||||
recover = Try.
|
||||
failure(new Exception("boo!")).
|
||||
recoverWith((Exception e) -> Try.successful("recovered again!"));
|
||||
|
||||
assertTrue(recover.isSuccess());
|
||||
assertEquals("recovered again!", recover.getOrElse(() -> null));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenFailure_thenMapNotCalled() {
|
||||
Try<Object> recover = Try.failure(new Exception("boo!")).map(x -> {
|
||||
fail("Oh, no!");
|
||||
return null;
|
||||
}).recover(Function.identity());
|
||||
Exception exception = (Exception) recover.toOption().get();
|
||||
|
||||
assertTrue(recover.isSuccess());
|
||||
assertEquals("boo!", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenException_thenTryThrows() {
|
||||
Try<Object> checked = Checked.of(() -> {
|
||||
throw new Exception("Aaargh!");
|
||||
});
|
||||
Either<Exception, Object> either = checked.toEither();
|
||||
|
||||
assertTrue(checked.isFailure());
|
||||
assertTrue(either.isLeft());
|
||||
assertEquals(42, checked.getOrElse(() -> 42));
|
||||
|
||||
try {
|
||||
checked.getOrElse(() -> {
|
||||
throw new NoSuchElementException("fail");
|
||||
});
|
||||
|
||||
fail("Was expecting exception");
|
||||
} catch (Exception e) {
|
||||
assertEquals("fail", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecoverThrows_thenFailure() {
|
||||
Try<Object> failure = Try.failure(new Exception("boo!")).recover(x -> {
|
||||
throw new RuntimeException(x);
|
||||
});
|
||||
|
||||
assertTrue(failure.isFailure());
|
||||
}
|
||||
|
||||
Unit doSomething() {
|
||||
System.out.println("Hello! Side effect");
|
||||
return Unit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPair_thenLeftAndRight() {
|
||||
Pair<Integer, String> pair = Pair.pair(1, "a");
|
||||
|
||||
assertEquals(1, (int) pair.left());
|
||||
assertEquals("a", pair.right());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.jnats;
|
||||
|
||||
import io.nats.client.Message;
|
||||
import io.nats.client.SyncSubscription;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class NatsClientLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenMessageExchange_MessagesReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.bar");
|
||||
SyncSubscription barSubscription = client.subscribeSync("bar.foo");
|
||||
client.publishMessage("foo.bar", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
|
||||
client.publishMessage(message.getReplyTo(), message.getSubject(), "hello back");
|
||||
|
||||
message = barSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello back", new String(message.getData()));
|
||||
}
|
||||
|
||||
|
||||
private NatsClient connectClient() {
|
||||
return new NatsClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWildCardSubscription_andMatchTopic_MessageReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
|
||||
|
||||
client.publishMessage("foo.bar", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWildCardSubscription_andNotMatchTopic_NoMessageReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
|
||||
|
||||
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNull("Got message!", message);
|
||||
|
||||
|
||||
SyncSubscription barSubscription = client.subscribeSync("foo.>");
|
||||
|
||||
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
|
||||
|
||||
message = barSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRequest_ReplyReceived() {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
client.installReply("salary.requests", "denied!");
|
||||
|
||||
Message reply = client.makeRequest("salary.requests", "I need a raise.");
|
||||
assertNotNull("No message!", reply);
|
||||
assertEquals("denied!", new String(reply.getData()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueueMessage_OnlyOneReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription queue1 = client.joinQueueGroup("foo.bar.requests", "queue1");
|
||||
SyncSubscription queue2 = client.joinQueueGroup("foo.bar.requests", "queue1");
|
||||
|
||||
client.publishMessage("foo.bar.requests", "queuerequestor", "foobar");
|
||||
|
||||
List<Message> messages = new ArrayList<>();
|
||||
|
||||
Message message = queue1.nextMessage(200);
|
||||
|
||||
if (message != null) messages.add(message);
|
||||
message = queue2.nextMessage(200);
|
||||
|
||||
if (message != null) messages.add(message);
|
||||
assertEquals(1, messages.size());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.baeldung.jool;
|
||||
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.jooq.lambda.Unchecked;
|
||||
import org.jooq.lambda.function.Function1;
|
||||
import org.jooq.lambda.function.Function2;
|
||||
import org.jooq.lambda.tuple.Tuple2;
|
||||
import org.jooq.lambda.tuple.Tuple3;
|
||||
import org.jooq.lambda.tuple.Tuple4;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.jooq.lambda.tuple.Tuple.tuple;
|
||||
|
||||
public class JOOLUnitTest {
|
||||
@Test
|
||||
public void givenSeq_whenCheckContains_shouldReturnTrue() {
|
||||
List<Integer> concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList();
|
||||
|
||||
assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).contains(2));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() {
|
||||
// given
|
||||
Stream<Integer> left = Stream.of(1, 2, 4);
|
||||
Stream<Integer> right = Stream.of(1, 2, 3);
|
||||
|
||||
// when
|
||||
List<Integer> rightCollected = right.collect(Collectors.toList());
|
||||
List<Integer> collect = left.filter(rightCollected::contains).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() {
|
||||
assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)));
|
||||
|
||||
assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() {
|
||||
assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5);
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2))
|
||||
|
||||
);
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() {
|
||||
|
||||
Map<Integer, List<Integer>> expectedAfterGroupBy = new HashMap<>();
|
||||
expectedAfterGroupBy.put(1, Arrays.asList(1, 3));
|
||||
expectedAfterGroupBy.put(0, Arrays.asList(2, 4));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy);
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc");
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() {
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenZip_shouldHaveZippedSeq() {
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c"));
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)));
|
||||
}
|
||||
|
||||
public Integer methodThatThrowsChecked(String arg) throws Exception {
|
||||
return arg.length();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() {
|
||||
// when
|
||||
List<Integer> collect = Stream.of("a", "b", "c").map(elem -> {
|
||||
try {
|
||||
return methodThatThrowsChecked(elem);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 1, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
|
||||
// when
|
||||
List<Integer> collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 1, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() {
|
||||
// given
|
||||
Function2<Integer, Integer, Integer> addTwoNumbers = (v1, v2) -> v1 + v2;
|
||||
addTwoNumbers.toBiFunction();
|
||||
Function1<Integer, Integer> addToTwo = addTwoNumbers.applyPartially(2);
|
||||
|
||||
// when
|
||||
Integer result = addToTwo.apply(5);
|
||||
|
||||
// then
|
||||
assertEquals(result, (Integer) 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() {
|
||||
// given
|
||||
Seq<Tuple3<String, String, Integer>> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43));
|
||||
Tuple2<String, String> tuple = tuple("winter", "summer");
|
||||
|
||||
// when
|
||||
List<Tuple4<String, String, String, String>> result = personDetails.map(t -> t.limit2().concat(tuple)).toList();
|
||||
|
||||
// then
|
||||
assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.pact;
|
||||
|
||||
import au.com.dius.pact.consumer.Pact;
|
||||
import au.com.dius.pact.consumer.PactProviderRuleMk2;
|
||||
import au.com.dius.pact.consumer.PactVerification;
|
||||
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||
import au.com.dius.pact.model.RequestResponsePact;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
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 java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
@Rule
|
||||
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
||||
|
||||
@Pact(consumer = "test_consumer")
|
||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||
Map<String, String> headers = new HashMap<String, String>();
|
||||
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
|
||||
@Ignore
|
||||
@PactVerification()
|
||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||
// when
|
||||
ResponseEntity<String> response = new RestTemplate().getForEntity(mockProvider.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(mockProvider.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class);
|
||||
|
||||
// then
|
||||
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
import one.util.streamex.StreamEx;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamExMergeStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
Stream<Integer> stream3 = Stream.of(18, 15, 36);
|
||||
Stream<Integer> stream4 = Stream.of(99);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<String> stream1 = Stream.of("foo", "bar");
|
||||
Stream<String> openingBracketStream = Stream.of("[");
|
||||
Stream<String> closingBracketStream = Stream.of("]");
|
||||
|
||||
Stream<String> resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream);
|
||||
|
||||
assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user