Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -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,231 @@
package com.baeldung.atlassian.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,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,144 @@
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.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 -> 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));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
cache.cleanUp();
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));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
assertEquals(2, cache.estimatedSize());
cache.get("C");
cache.cleanUp();
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");
assertEquals(1, cache.stats().hitCount());
assertEquals(1, cache.stats().missCount());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.cglib.proxy;
import net.sf.cglib.beans.BeanGenerator;
import org.junit.Test;
import java.lang.reflect.Method;
import static junit.framework.TestCase.assertEquals;
public class BeanGeneratorIntegrationTest {
@Test
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
// given
BeanGenerator beanGenerator = new BeanGenerator();
// when
beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create();
Method setter = myBean.getClass().getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib");
// then
Method getter = myBean.getClass().getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.cglib.proxy;
import com.baeldung.cglib.mixin.Class1;
import com.baeldung.cglib.mixin.Class2;
import com.baeldung.cglib.mixin.Interface1;
import com.baeldung.cglib.mixin.Interface2;
import com.baeldung.cglib.mixin.MixinInterface;
import net.sf.cglib.proxy.Mixin;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class MixinUnitTest {
@Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
// when
Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
MixinInterface mixinDelegate = (MixinInterface) mixin;
// then
assertEquals("first behaviour", mixinDelegate.first());
assertEquals("second behaviour", mixinDelegate.second());
}
}
@@ -0,0 +1,60 @@
package com.baeldung.cglib.proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ProxyIntegrationTest {
@Test
public void givenPersonService_whenSayHello_thenReturnResult() {
// given
PersonService personService = new PersonService();
// when
String res = personService.sayHello("Tom");
// then
assertEquals(res, "Hello Tom");
}
@Test
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((FixedValue) () -> "Hello Tom!");
PersonService proxy = (PersonService) enhancer.create();
// when
String res = proxy.sayHello(null);
// then
assertEquals("Hello Tom!", res);
}
@Test
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
return "Hello Tom!";
} else {
return proxy.invokeSuper(obj, args);
}
});
// when
PersonService proxy = (PersonService) enhancer.create();
// then
assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary");
assertEquals(4, lengthOfName);
}
}
@@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to cglib](http://www.baeldung.com/cglib)
@@ -0,0 +1,43 @@
package com.baeldung.chronicle.queue;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.Test;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueIntegrationTest {
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
ChronicleTools.deleteOnExit(queueDir.getPath());
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
String stringVal = "Hello World";
int intVal = 101;
long longVal = System.currentTimeMillis();
double doubleVal = 90.00192091d;
ChronicleQueue.writeToQueue(chronicle, stringVal, intVal, longVal, doubleVal);
ExcerptTailer tailer = chronicle.createTailer();
while (tailer.nextIndex()) {
assertEquals(stringVal, tailer.readUTF());
assertEquals(intVal, tailer.readInt());
assertEquals(longVal, tailer.readLong());
assertEquals((Double) doubleVal, (Double) tailer.readDouble());
}
tailer.finish();
tailer.close();
chronicle.close();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.eclipse.collections.impl.block.factory.HashingStrategies;
import org.eclipse.collections.impl.utility.ListIterate;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithEclipseCollectionsUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithJavaFunctionUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2);
}
@Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import one.util.streamex.StreamEx;
public class DistinctWithStreamexUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithVavrUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.distinct;
import java.util.Arrays;
import java.util.List;
public class PersonDataGenerator {
public static List<Person> getPersonListWithFakeValues() {
// @formatter:off
return Arrays.asList(
new Person(20, "Jhon", "jhon@test.com"),
new Person(20, "Jhon", "jhon1@test.com"),
new Person(20, "Jhon", "jhon2@test.com"),
new Person(21, "Tom", "Tom@test.com"),
new Person(21, "Mark", "Mark@test.com"),
new Person(20, "Julia", "jhon@test.com"));
// @formatter:on
}
}
@@ -0,0 +1,123 @@
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.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
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();
assertThat(containerResponse.getId(), 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,140 @@
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.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
assertThat(imageResponse.getId(), 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,80 @@
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.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
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,83 @@
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.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
assertThat(unnamedVolume.getName(), is(not(null)));
}
@Test
public void whenCreatingNamedVolume_thenGetVolumeId() {
// when
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
// then
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,26 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class AllSatisfyPatternUnitTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
boolean result = list.allSatisfy(Predicates.greaterThan(0));
assertTrue(result);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class AnySatisfyPatternUnitTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
boolean result = list.anySatisfy(Predicates.greaterThan(30));
assertTrue(result);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class CollectPatternUnitTest {
@Test
public void whenCollect_thenCorrect() {
Student student1 = new Student("John", "Hopkins");
Student student2 = new Student("George", "Adams");
MutableList<Student> students = FastList.newListWith(student1, student2);
MutableList<String> lastNames = students.collect(Student::getLastName);
Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams");
}
}
@@ -0,0 +1,17 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Test;
public class ConvertContainerToAnotherUnitTest {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void whenConvertContainerToAnother_thenCorrect() {
MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList();
Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class DetectPatternUnitTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void whenDetect_thenCorrect() {
Integer result = list.detect(Predicates.greaterThan(30));
Assertions.assertThat(result).isEqualTo(41);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class FlatCollectUnitTest {
MutableList<String> addresses1;
MutableList<String> addresses2;
MutableList<String> addresses3;
MutableList<String> addresses4;
List<String> expectedAddresses;
MutableList<Student> students;
@Before
public void setup() {
String address1 = "73 Pacific St., Forest Hills, NY 11375";
String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419";
String address3 = "548 Market St, San Francisco, CA 94104";
String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069";
this.addresses1 = FastList.newListWith(address1, address2);
this.addresses2 = FastList.newListWith(address3, address4);
Student student1 = new Student("John", "Hopkins", addresses1);
Student student2 = new Student("George", "Adams", addresses2);
this.addresses2 = FastList.newListWith(address3, address4);
this.students = FastList.newListWith(student1, student2);
this.expectedAddresses = new ArrayList<>();
this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375");
this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419");
this.expectedAddresses.add("548 Market St, San Francisco, CA 94104");
this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069");
}
@Test
public void whenFlatCollect_thenCorrect() {
MutableList<String> addresses = students.flatCollect(Student::getAddresses);
Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses);
}
}
@@ -0,0 +1,29 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertEquals;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.tuple.Tuples;
import org.junit.Test;
public class ForEachPatternUnitTest {
@SuppressWarnings("unchecked")
@Test
public void whenInstantiateAndChangeValues_thenCorrect() {
Pair<Integer, String> pair1 = Tuples.pair(1, "One");
Pair<Integer, String> pair2 = Tuples.pair(2, "Two");
Pair<Integer, String> pair3 = Tuples.pair(3, "Three");
UnifiedMap<Integer, String> map = UnifiedMap.newMapWith(pair1, pair2, pair3);
for (int i = 0; i < map.size(); i++) {
map.put(i + 1, "New Value");
}
for (int i = 0; i < map.size(); i++) {
assertEquals("New Value", map.get(i + 1));
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.eclipse.collections.impl.factory.Lists;
import org.junit.Test;
public class InjectIntoPatternUnitTest {
@Test
public void whenInjectInto_thenCorrect() {
List<Integer> list = Lists.mutable.of(1, 2, 3, 4);
int result = 5;
for (int i = 0; i < list.size(); i++) {
Integer v = list.get(i);
result = result + v.intValue();
}
assertEquals(15, result);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.LazyIterable;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.factory.Lists;
import org.junit.Test;
public class LazyIterationUnitTest {
@Test
public void whenLazyIteration_thenCorrect() {
Student student1 = new Student("John", "Hopkins");
Student student2 = new Student("George", "Adams");
Student student3 = new Student("Jennifer", "Rodriguez");
MutableList<Student> students = Lists.mutable.with(student1, student2, student3);
LazyIterable<Student> lazyStudents = students.asLazy();
LazyIterable<String> lastNames = lazyStudents.collect(Student::getLastName);
Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
}
}
@@ -0,0 +1,40 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.partition.list.PartitionMutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class PartitionPatternUnitTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
MutableList<Integer> numbers = list;
PartitionMutableList<Integer> partitionedFolks = numbers.partition(new Predicate<Integer>() {
/**
*
*/
private static final long serialVersionUID = -1551138743683678406L;
public boolean accept(Integer each) {
return each > 30;
}
});
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected().sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected().sortThis();
Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class RejectPatternUnitTest {
MutableList<Integer> list;
MutableList<Integer> expectedList;
@Before
public void setup() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
this.expectedList = FastList.newListWith(1, 5, 8, 17, 23);
}
@Test
public void whenReject_thenCorrect() {
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class SelectPatternUnitTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void givenListwhenSelect_thenCorrect() {
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
@SuppressWarnings("rawtypes")
public MutableList selectUsingLambda() {
return list.select(each -> each > 30).sortThis();
}
@SuppressWarnings("unchecked")
@Test
public void givenListwhenSelectUsingLambda_thenCorrect() {
MutableList<Integer> greaterThanThirty = selectUsingLambda();
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.tuple.Tuples;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
public class ZipUnitTest {
MutableList<Pair<String, String>> expectedPairs;
@SuppressWarnings("unchecked")
@Before
public void setup() {
Pair<String, String> pair1 = Tuples.pair("1", "Porsche");
Pair<String, String> pair2 = Tuples.pair("2", "Volvo");
Pair<String, String> pair3 = Tuples.pair("3", "Toyota");
expectedPairs = Lists.mutable.of(pair1, pair2, pair3);
}
@Test
public void whenZip_thenCorrect() {
MutableList<String> numbers = Lists.mutable.with("1", "2", "3", "Ignored");
MutableList<String> cars = Lists.mutable.with("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, String>> pairs = numbers.zip(cars);
Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.eclipse.collections.impl.tuple.Tuples;
import org.junit.Before;
import org.junit.Test;
public class ZipWithIndexUnitTest {
MutableList<Pair<String, Integer>> expectedPairs;
@SuppressWarnings("unchecked")
@Before
public void setup() {
Pair<String, Integer> pair1 = Tuples.pair("Porsche", 0);
Pair<String, Integer> pair2 = Tuples.pair("Volvo", 1);
Pair<String, Integer> pair3 = Tuples.pair("Toyota", 2);
expectedPairs = Lists.mutable.of(pair1, pair2, pair3);
}
@Test
public void whenZip_thenCorrect() {
MutableList<String> cars = FastList.newListWith("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, Integer>> pairs = cars.zipWithIndex();
Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs);
}
}
@@ -0,0 +1,116 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaUnitTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static final Integer timesTwoRegular(Integer i) {
return i * 2;
}
public static final F<Integer, Integer> timesTwo = i -> i * 2;
public static final F<Integer, Integer> plusOne = i -> i + 1;
@Test
public void multiplyNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo);
List<Integer> fList2 = fList.map(i -> i * 2);
assertTrue(fList1.equals(fList2));
}
@Test
public void applyMultipleFunctions_givenIntList_returnFalse() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo).map(plusOne);
Show.listShow(Show.intShow).println(fList1);
List<Integer> fList2 = fList.map(plusOne).map(timesTwo);
Show.listShow(Show.intShow).println(fList2);
assertFalse(fList1.equals(fList2));
}
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
assertTrue(evenList.equals(evenListTrueResult));
}
@Test
public void mapList_givenIntList_returnResult() {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
assertTrue(fList.equals(resultList));
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(isEven);
Array<Integer> result = Array.array(4, 6);
assertTrue(filteredArray.equals(result));
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)));
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
Option<Integer> n3 = Option.none();
F<Integer, Option<Integer>> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(function);
Option<Integer> result2 = n2.bind(function);
Option<Integer> result3 = n3.bind(function);
assertEquals(Option.none(), result1);
assertEquals(Option.some(102), result2);
assertEquals(Option.none(), result3);
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sumAll = intArray.foldLeft(Integers.add, 0);
assertEquals(260, sumAll);
int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
assertEquals(148, sumEven);
}
}
@@ -0,0 +1,73 @@
package com.baeldung.ftp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;
import org.mockftpserver.fake.filesystem.DirectoryEntry;
import org.mockftpserver.fake.filesystem.FileEntry;
import org.mockftpserver.fake.filesystem.FileSystem;
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
public class FtpClientIntegrationTest {
private FakeFtpServer fakeFtpServer;
private FtpClient ftpClient;
@Before
public void setup() throws IOException {
fakeFtpServer = new FakeFtpServer();
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
FileSystem fileSystem = new UnixFakeFileSystem();
fileSystem.add(new DirectoryEntry("/data"));
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
fakeFtpServer.setFileSystem(fileSystem);
fakeFtpServer.setServerControlPort(0);
fakeFtpServer.start();
ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password");
ftpClient.open();
}
@After
public void teardown() throws IOException {
ftpClient.close();
fakeFtpServer.stop();
}
@Test
public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException {
Collection<String> files = ftpClient.listFiles("");
assertThat(files).contains("foobar.txt");
}
@Test
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt");
assertThat(new File("downloaded_buz.txt")).exists();
new File("downloaded_buz.txt").delete(); // cleanup
}
@Test
public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException {
File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI());
ftpClient.putFileToPath(file, "/buz.txt");
assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue();
}
}
@@ -0,0 +1,63 @@
package com.baeldung.ftp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;
import org.mockftpserver.fake.filesystem.DirectoryEntry;
import org.mockftpserver.fake.filesystem.FileEntry;
import org.mockftpserver.fake.filesystem.FileSystem;
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
public class JdkFtpClientIntegrationTest {
private FakeFtpServer fakeFtpServer;
@Before
public void setup() throws IOException {
fakeFtpServer = new FakeFtpServer();
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
FileSystem fileSystem = new UnixFakeFileSystem();
fileSystem.add(new DirectoryEntry("/data"));
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
fakeFtpServer.setFileSystem(fileSystem);
fakeFtpServer.setServerControlPort(0);
fakeFtpServer.start();
}
@After
public void teardown() throws IOException {
fakeFtpServer.stop();
}
@Test
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort());
URLConnection urlConnection = new URL(ftpUrl).openConnection();
InputStream inputStream = urlConnection.getInputStream();
Files.copy(inputStream, new File("downloaded_buz.txt").toPath());
inputStream.close();
assertThat(new File("downloaded_buz.txt")).exists();
new File("downloaded_buz.txt").delete(); // cleanup
}
}
@@ -0,0 +1,138 @@
package com.baeldung.java.io;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.FileSystemUtils;
public class JavaDirectoryDeleteUnitTest {
private static Path TEMP_DIRECTORY;
private static final String DIRECTORY_NAME = "toBeDeleted";
private static final List<String> ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6");
@BeforeClass
public static void initializeTempDirectory() throws IOException {
TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit");
}
@AfterClass
public static void cleanTempDirectory() throws IOException {
FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile());
}
@Before
public void setupDirectory() throws IOException {
Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME));
// Create a directory structure
Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2));
Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4));
Files.createDirectories(tempPathForEachTest.resolve("Empty"));
Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty"));
Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5));
Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3));
aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory"));
Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5));
Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2));
}
@After
public void checkAndCleanupIfRequired() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
if (Files.exists(pathToBeDeleted)) {
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
@Test
public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = deleteDirectory(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
}
@@ -0,0 +1,99 @@
package com.baeldung.javapoet.test;
import com.baeldung.javapoet.PersonGenerator;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class PersonGeneratorUnitTest {
private PersonGenerator generator;
private Path generatedFolderPath;
private Path expectedFolderPath;
@Before
public void setUp() {
String packagePath = this
.getClass()
.getPackage()
.getName()
.replace(".", "/") + "/person";
generator = new PersonGenerator();
generatedFolderPath = generator
.getOutputPath()
.resolve(packagePath);
expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath);
}
@After
public void tearDown() throws Exception {
FileUtils.deleteDirectory(new File(generator
.getOutputPath()
.toUri()));
}
@Test
public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException {
generator.generateGenderEnum();
String fileName = "Gender.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
@Test
public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException {
generator.generatePersonInterface();
String fileName = "Person.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
@Test
public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException {
generator.generateStudentClass();
String fileName = "Student.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException {
String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName));
String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName));
assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent)));
}
private void deleteGeneratedFile(String fileName) throws IOException {
Path generatedFilePath = generatedFolderPath.resolve(fileName);
Files.delete(generatedFilePath);
}
private String extractFileContent(Path filePath) throws IOException {
byte[] fileContentAsBytes = Files.readAllBytes(filePath);
String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8);
if (!fileContentAsString.contains("\r\n")) {
// file is not in DOS format
// convert it first, so that the content comparison will be relevant
return fileContentAsString.replaceAll("\n", "\r\n");
}
return fileContentAsString;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.javapoet.test.person;
public enum Gender {
MALE,
FEMALE,
UNSPECIFIED
}
@@ -0,0 +1,13 @@
package com.baeldung.javapoet.test.person;
import java.lang.String;
public interface Person {
String DEFAULT_NAME = "Alice";
String getName();
default String getDefaultName() {
return DEFAULT_NAME;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.javapoet.test.person;
import java.lang.Override;
import java.lang.String;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
public class Student implements Person {
private String name;
@Override
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void printNameMultipleTimes() {
List<String> names = new ArrayList<>();
IntStream.range(0, 10).forEach(i -> names.add(name));
names.forEach(System.out::println);
}
public static void sortByLength(List<String> strings) {
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
}
}
@@ -0,0 +1,122 @@
package com.baeldung.javassist;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.NotFoundException;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.Bytecode;
import javassist.bytecode.ClassFile;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.FieldInfo;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Mnemonic;
import org.junit.Test;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JavasisstUnitTest {
@Test
public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
// given
String classNameWithPackage = "com.baeldung.JavassistGeneratedClass";
ClassFile cf = new ClassFile(false, classNameWithPackage, null);
cf.setInterfaces(new String[] { "java.lang.Cloneable" });
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
// when
String className = "JavassistGeneratedClass.class";
cf.write(new DataOutputStream(new FileOutputStream(className)));
// then
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
assertEquals(fields[0].getName(), "id");
String classContent = new String(Files.readAllBytes(Paths.get(className)));
assertTrue(classContent.contains("java/lang/Cloneable"));
}
@Test
public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode {
// given
ClassPool cp = ClassPool.getDefault();
ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile();
MethodInfo minfo = cf.getMethod("move");
CodeAttribute ca = minfo.getCodeAttribute();
CodeIterator ci = ca.iterator();
// when
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
int index = ci.next();
int op = ci.byteAt(index);
operations.add(Mnemonic.OPCODE[op]);
}
// then
assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
}
@Test
public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException {
// given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile();
// when
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
List<String> fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList());
assertTrue(fieldsList.contains("id"));
}
@Test
public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode {
// given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile();
Bytecode code = new Bytecode(cf.getConstPool());
code.addAload(0);
code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
code.addReturn(null);
// when
MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V");
minfo.setCodeAttribute(code.toCodeAttribute());
cf.addMethod(minfo);
// then
CodeIterator ci = code.toCodeAttribute().iterator();
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
int index = ci.next();
int op = ci.byteAt(index);
operations.add(Mnemonic.OPCODE[op]);
}
assertEquals(operations, Arrays.asList("aload_0", "invokespecial", "return"));
}
}
@@ -0,0 +1,118 @@
package com.baeldung.javatuples;
import org.javatuples.KeyValue;
import org.javatuples.LabelValue;
import org.javatuples.Pair;
import org.javatuples.Quartet;
import org.javatuples.Triplet;
import org.javatuples.Unit;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaTuplesUnitTest {
@SuppressWarnings("unused")
@Test
public void whenCreatingTuples_thenCreateTuples() {
Pair<String, Integer> pair = new Pair<String, Integer>("This is a pair", 55);
Triplet<String, Integer, Double> triplet = Triplet.with("hello", 23, 33.2);
List<String> collectionOfNames = Arrays.asList("john", "doe", "anne", "alex");
Quartet<String, String, String, String> quartet = Quartet.fromCollection(collectionOfNames);
Pair<String, String> pairFromList = Pair.fromIterable(collectionOfNames, 2);
String[] names = new String[] { "john", "doe", "anne" };
Triplet<String, String, String> triplet2 = Triplet.fromArray(names);
}
@Test
public void whenGetValuexFromTuples_thenRetriveValueWithType() {
Quartet<String, Double, Integer, String> quartet = Quartet.with("john", 72.5, 32, "1051 SW");
String name = quartet.getValue0();
Integer age = quartet.getValue2();
assertThat(name).isEqualTo("john");
assertThat(age).isEqualTo(32);
}
@Test
public void whenGetKeyValue_thenGetKeyValue() {
KeyValue<Integer, String> keyValue = KeyValue.with(5, "F");
Integer key = keyValue.getKey();
String value = keyValue.getValue();
assertThat(key).isEqualTo(5);
assertThat(value).isEqualTo("F");
}
@Test
public void whenGetLabelValue_thenGetLabelValue() {
LabelValue<Integer, String> labelValue = LabelValue.with(5, "F");
Integer key = labelValue.getLabel();
String value = labelValue.getValue();
assertThat(key).isEqualTo(5);
assertThat(value).isEqualTo("F");
}
@Test
public void whenGetValueFromTuples_thenRetriveValueWithoutType() {
Quartet<String, Double, Integer, String> quartet = Quartet.with("john", 72.5, 32, "1051 SW");
String name = (String) quartet.getValue(0);
Integer age = (Integer) quartet.getValue(2);
assertThat(name).isEqualTo("john");
assertThat(age).isEqualTo(32);
}
@Test
public void whenSetValueInTuple_thenGetANewTuple() {
Pair<String, Integer> john = Pair.with("john", 32);
Pair<String, Integer> alex = john.setAt0("alex");
assertThat(john.toString()).isNotEqualTo(alex.toString());
}
@Test
public void whenAddNewElement_thenCreateNewTuple() {
Pair<String, Integer> pair1 = Pair.with("john", 32);
Triplet<String, Integer, String> triplet1 = pair1.add("1051 SW");
assertThat(triplet1.contains("john"));
assertThat(triplet1.contains(32));
assertThat(triplet1.contains("1051 SW"));
Pair<String, Integer> pair2 = Pair.with("alex", 45);
Quartet<String, Integer, String, Integer> quartet2 = pair1.add(pair2);
assertThat(quartet2.containsAll(pair1));
assertThat(quartet2.containsAll(pair2));
Quartet<String, Integer, String, Integer> quartet1 = pair1.add("alex", 45);
assertThat(quartet1.containsAll("alex", "john", 32, 45));
Triplet<String, String, Integer> triplet2 = pair1.addAt1("1051 SW");
assertThat(triplet2.indexOf("john")).isEqualTo(0);
assertThat(triplet2.indexOf("1051 SW")).isEqualTo(1);
assertThat(triplet2.indexOf(32)).isEqualTo(2);
Unit<Integer> unit = pair1.removeFrom0();
assertThat(unit.contains(32));
}
@Test
public void whenCallingToList_thenReturnList() {
Quartet<String, Double, Integer, String> quartet = Quartet.with("john", 72.5, 32, "1051 SW");
List<Object> list = quartet.toList();
assertThat(list.size()).isEqualTo(4);
}
@Test
public void whenCallingToArray_thenReturnArray() {
Quartet<String, Double, Integer, String> quartet = Quartet.with("john", 72.5, 32, "1051 SW");
Object[] array = quartet.toArray();
assertThat(array.length).isEqualTo(4);
}
}
@@ -0,0 +1,103 @@
package com.baeldung.javers;
import org.javers.common.collections.Lists;
import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
import org.javers.core.diff.Diff;
import org.javers.core.diff.changetype.NewObject;
import org.javers.core.diff.changetype.ObjectRemoved;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.diff.changetype.container.ListChange;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class JaversUnitTest {
@Test
public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() {
// given
Javers javers = JaversBuilder.javers().build();
Person person = new Person(1, "Michael Program");
Person personAfterModification = new Person(1, "Michael Java");
// when
Diff diff = javers.compare(person, personAfterModification);
// then
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
assertThat(diff.getChanges()).hasSize(1);
assertThat(change.getPropertyName()).isEqualTo("name");
assertThat(change.getLeft()).isEqualTo("Michael Program");
assertThat(change.getRight()).isEqualTo("Michael Java");
}
@Test
public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() {
// given
Javers javers = JaversBuilder.javers().build();
Person personThatWillBeRemoved = new Person(2, "Thomas Link");
List<Person> oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved);
List<Person> newList = Lists.asList(new Person(1, "Michael Not Program"));
// when
Diff diff = javers.compareCollections(oldList, newList, Person.class);
// then
assertThat(diff.getChanges()).hasSize(3);
ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0);
assertThat(valueChange.getPropertyName()).isEqualTo("name");
assertThat(valueChange.getLeft()).isEqualTo("Michael Program");
assertThat(valueChange.getRight()).isEqualTo("Michael Not Program");
ObjectRemoved objectRemoved = diff.getChangesByType(ObjectRemoved.class).get(0);
assertThat(objectRemoved.getAffectedObject().get().equals(personThatWillBeRemoved)).isTrue();
ListChange listChange = diff.getChangesByType(ListChange.class).get(0);
assertThat(listChange.getValueRemovedChanges().size()).isEqualTo(1);
}
@Test
public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() {
// given
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA")));
// when
Diff diff = javers.compare(person, personWithNewAddress);
List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class);
// then
assertThat(objectsByChangeType).hasSize(1);
assertThat(objectsByChangeType.get(0).equals(new Address("USA")));
}
@Test
public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() {
// given
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList());
// when
Diff diff = javers.compare(person, personWithNewAddress);
List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class);
// then
assertThat(objectsByChangeType).hasSize(1);
assertThat(objectsByChangeType.get(0).equals(new Address("England")));
}
}
@@ -0,0 +1,86 @@
package com.baeldung.jctools;
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);
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 -> {
assertThat(queue.offer(i)).isTrue();
});
assertThat(queue.offer(queue.capacity())).isFalse();
startConsuming.countDown();
try {
awakeProducer.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
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,26 @@
package com.baeldung.jdeffered;
import com.baeldung.jdeffered.PipeDemo.Result;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JDeferredUnitTest {
@Test
public void givenJob_expectPromise() {
PromiseDemo.startJob("Baeldung Job");
}
@Test
public void givenMsg_expectModifiedMsg() {
String msg = FilterDemo.filter("Baeldung");
assertEquals("Hello Baeldung", msg);
}
@Test
public void givenNum_validateNum_expectStatus() {
Result result = PipeDemo.validate(80);
assertEquals(result, Result.SUCCESS);
}
}
@@ -0,0 +1,351 @@
package com.baeldung.jets3t;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.S3Service;
import org.jets3t.service.ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JetS3tLiveTest {
private Log log = LogFactory.getLog(JetS3tLiveTest.class);
private static final String BucketName = "baeldung-barfoo";
private static final String TestString = "test string";
private static final String TestStringName = "string object";
private static final String TgtBucket = "baeldung-tgtbucket";
private static S3Service s3Service;
@BeforeClass
public static void connectS3() throws Exception {
// Replace with your keys
String awsAccessKey = "your access key";
String awsSecretKey = "your secret key";
// Create credentials
AWSCredentials awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey);
// Create service
s3Service = new RestS3Service(awsCredentials);
}
@Test
public void givenCreate_AndDeleteBucket_CountGoesUpThenDown() throws Exception {
// List buckets, get a count
S3Bucket[] myBuckets = s3Service.listAllBuckets();
int count = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
// Create a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// List again
myBuckets = s3Service.listAllBuckets();
int newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
// We should have one more
assertEquals((count + 1), newCount);
// Delete so next test doesn't fail
deleteBucket();
// Check the count again, just for laughs
myBuckets = s3Service.listAllBuckets();
newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
assertEquals(count, newCount);
}
private S3Bucket createBucket() throws Exception {
S3Bucket bucket = s3Service.createBucket(BucketName);
log.info(bucket);
return bucket;
}
private void deleteBucket() throws ServiceException {
s3Service.deleteBucket(BucketName);
}
@Test
public void givenString_Uploaded_StringInfoIsAvailable() throws Exception {
// Create a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Upload a string
uploadStringData();
// Get the details
StorageObject objectDetailsOnly = s3Service.getObjectDetails(BucketName, TestStringName);
log.info("Content type: " + objectDetailsOnly.getContentType() + " length: " + objectDetailsOnly.getContentLength());
// Delete it
deleteObject(TestStringName);
// For next test
deleteBucket();
}
private void uploadStringData() throws Exception {
S3Object stringObject = new S3Object(TestStringName, TestString);
s3Service.putObject(BucketName, stringObject);
log.info("Content type:" + stringObject.getContentType());
}
private void deleteObject(String objectName) throws ServiceException {
s3Service.deleteObject(BucketName, objectName);
}
@Test
public void givenStringUploaded_StringIsDownloaded() throws Exception {
// Get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
uploadStringData();
// Download
S3Object stringObject = s3Service.getObject(BucketName, TestStringName);
// Process stream into a string
String downloadedString = new BufferedReader(new InputStreamReader(stringObject.getDataInputStream())).lines().collect(Collectors.joining("\n"));
// Verify
assertTrue(TestString.equals(downloadedString));
// Clean up for next test
deleteObject(TestStringName);
deleteBucket();
}
@Test
public void givenBinaryFileUploaded_FileIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Print info about type and name
log.info("Content type:" + fileObject.getContentType());
log.info("File object name is " + fileObject.getName());
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "test.jpg");
// Save to a different name
File newFile = new File("src/test/resources/newtest.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/newtest.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteBucket();
}
// Get MD5 hash for a file
private String getFileMD5(String filename) throws IOException {
try (FileInputStream fis = new FileInputStream(new File(filename))) {
return DigestUtils.md5Hex(fis);
}
}
@Test
public void givenStreamDataUploaded_StreamDataIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(3);
numbers.add(5);
numbers.add(7);
// Serialize ArrayList
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytes);
objectOutputStream.writeObject(numbers);
// Wrap bytes
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes.toByteArray());
// Create and populate object
S3Object streamObject = new S3Object("stream");
streamObject.setDataInputStream(byteArrayInputStream);
streamObject.setContentLength(byteArrayInputStream.available());
streamObject.setContentType("binary/octet-stream");
// Put it
s3Service.putObject(BucketName, streamObject);
// Get it
S3Object newStreamObject = s3Service.getObject(BucketName, "stream");
// Convert back to ArrayList
ObjectInputStream objectInputStream = new ObjectInputStream(newStreamObject.getDataInputStream());
ArrayList<Integer> newNumbers = (ArrayList<Integer>)objectInputStream.readObject();
assertEquals(2, (int)newNumbers.get(0));
assertEquals(3, (int)newNumbers.get(1));
assertEquals(5, (int)newNumbers.get(2));
assertEquals(7, (int)newNumbers.get(3));
// Clean up
deleteObject("stream");
deleteBucket();
}
@Test
public void whenFileCopied_CopyIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
S3Object targetObject = new S3Object("testcopy.jpg");
s3Service.copyObject(BucketName, "test.jpg", BucketName, targetObject, false);
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "testcopy.jpg");
// Save to a different name
File newFile = new File("src/test/resources/testcopy.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/testcopy.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteObject("testcopy.jpg");
deleteBucket();
}
@Test
public void whenFileRenamed_NewNameIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
s3Service.renameObject(BucketName, "test.jpg", new S3Object("spidey.jpg"));
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "spidey.jpg");
// Save to a different name
File newFile = new File("src/test/resources/spidey.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteObject("spidey.jpg");
deleteBucket();
}
@Test
public void whenFileMoved_NewInstanceIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// create another bucket
S3Bucket tgtBucket = s3Service.createBucket(TgtBucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
s3Service.moveObject(BucketName, "test.jpg", TgtBucket,
new S3Object("spidey.jpg"), false);
// Download
S3Object newFileObject = s3Service.getObject(TgtBucket, "spidey.jpg");
// Save to a different name
File newFile = new File("src/test/resources/spidey.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteBucket();
s3Service.deleteObject(TgtBucket, "spidey.jpg");
s3Service.deleteBucket(TgtBucket);
}
}
@@ -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,54 @@
package com.baeldung.junitparams;
import junitparams.FileParameters;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class SafeAdditionUtilUnitTest {
private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil();
@Test
@Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" })
public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@Parameters(method = "parametersToTestAdd")
public void whenCalledWithNamedMethod_thendSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersToTestAdd() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@Parameters
public void whenCalledWithnoParam_thenLoadByNameSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@Parameters(source = TestDataProvider.class)
public void whenCalledWithNamedClass_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@FileParameters("src/test/resources/JunitParamsTestParameters.csv")
public void whenCalledWithCsvFile_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.junitparams;
public class TestDataProvider {
public static Object[] provideBasicData() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } };
}
public static Object[] provideEdgeCaseData() {
return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, };
}
}
@@ -0,0 +1,61 @@
package com.baeldung.kafkastreams;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.test.TestUtils;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import java.util.Properties;
import java.util.regex.Pattern;
public class KafkaStreamsLiveTest {
private String bootstrapServers = "localhost:9092";
@Test
@Ignore("it needs to have kafka broker running on local")
public void shouldTestKafkaStreams() throws InterruptedException {
// given
String inputTopic = "inputTopic";
Properties streamsConfiguration = new Properties();
streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-live-test");
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000);
streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Use a temporary directory for storing state, which will be automatically removed after the test.
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());
// when
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream(inputTopic);
Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS);
KTable<String, Long> wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count();
textLines.foreach((word, count) -> System.out.println("word: " + word + " -> " + count));
String outputTopic = "outputTopic";
final Serde<String> stringSerde = Serdes.String();
final Serde<String> longSerde = Serdes.String();
textLines.to(outputTopic, Produced.with(stringSerde,longSerde));
KafkaStreams streams = new KafkaStreams(new Topology(), streamsConfiguration);
streams.start();
// then
Thread.sleep(30000);
streams.close();
}
}
@@ -0,0 +1,46 @@
package com.baeldung.lsh;
import info.debatty.java.lsh.LSHMinHash;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalSensitiveHashingUnitTest {
@Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results")
@Test()
public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() {
// given
boolean[] vector1 = new boolean[] { true, true, true, true, true };
boolean[] vector2 = new boolean[] { false, false, false, true, false };
boolean[] vector3 = new boolean[] { false, false, true, true, false };
int sizeOfVectors = 5;
int numberOfBuckets = 10;
int stages = 4;
LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors);
// when
int[] firstHash = lsh.hash(vector1);
int[] secondHash = lsh.hash(vector2);
int[] thirdHash = lsh.hash(vector3);
System.out.println(Arrays.toString(firstHash));
System.out.println(Arrays.toString(secondHash));
System.out.println(Arrays.toString(thirdHash));
// then
int lastIndexOfResult = stages - 1;
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]);
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]);
assertThat(isCloseOrEqual(secondHash[lastIndexOfResult], thirdHash[lastIndexOfResult], numberOfBuckets)).isTrue();
}
private boolean isCloseOrEqual(int secondHash, int thirdHash, int numberOfBuckets) {
return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
public class MBassadorAsyncDispatchUnitTest {
private MBassador dispatcher = new MBassador<String>();
private String testString;
private AtomicBoolean ready = new AtomicBoolean(false);
@Before
public void prepareTests() {
dispatcher.subscribe(this);
}
@Test
public void whenAsyncDispatched_thenMessageReceived() {
dispatcher.post("foobar").asynchronously();
await().untilAtomic(ready, equalTo(true));
assertNotNull(testString);
}
@Handler
public void handleStringMessage(String message) {
this.testString = message;
ready.set(true);
}
}
@@ -0,0 +1,45 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import net.engio.mbassy.listener.Invoke;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
public class MBassadorAsyncInvocationUnitTest {
private MBassador dispatcher = new MBassador<Integer>();
private Integer testInteger;
private String invocationThreadName;
private AtomicBoolean ready = new AtomicBoolean(false);
@Before
public void prepareTests() {
dispatcher.subscribe(this);
}
@Test
public void whenHandlerAsync_thenHandled() {
dispatcher.post(42).now();
await().untilAtomic(ready, equalTo(true));
assertNotNull(testInteger);
assertFalse(Thread.currentThread().getName().equals(invocationThreadName));
}
@Handler(delivery = Invoke.Asynchronously)
public void handleIntegerMessage(Integer message) {
this.invocationThreadName = Thread.currentThread().getName();
this.testInteger = message;
ready.set(true);
}
}
@@ -0,0 +1,69 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.bus.common.DeadMessage;
import net.engio.mbassy.listener.Handler;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class MBassadorBasicUnitTest {
private MBassador dispatcher = new MBassador();
private String messageString;
private Integer messageInteger;
private Object deadEvent;
@Before
public void prepareTests() {
dispatcher.subscribe(this);
}
@Test
public void whenStringDispatched_thenHandleString() {
dispatcher.post("TestString").now();
assertNotNull(messageString);
assertEquals("TestString", messageString);
}
@Test
public void whenIntegerDispatched_thenHandleInteger() {
dispatcher.post(42).now();
assertNull(messageString);
assertNotNull(messageInteger);
assertTrue(42 == messageInteger);
}
@Test
public void whenLongDispatched_thenDeadEvent() {
dispatcher.post(42L).now();
assertNull(messageString);
assertNull(messageInteger);
assertNotNull(deadEvent);
assertTrue(deadEvent instanceof Long);
assertTrue(42L == (Long) deadEvent);
}
@Handler
public void handleString(String message) {
messageString = message;
}
@Handler
public void handleInteger(Integer message) {
messageInteger = message;
}
@Handler
public void handleDeadEvent(DeadMessage message) {
deadEvent = message.getMessage();
}
}
@@ -0,0 +1,89 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.bus.error.IPublicationErrorHandler;
import net.engio.mbassy.bus.error.PublicationError;
import net.engio.mbassy.listener.Handler;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.*;
public class MBassadorConfigurationUnitTest implements IPublicationErrorHandler {
private MBassador dispatcher;
private String messageString;
private Throwable errorCause;
private LinkedList<Integer> list = new LinkedList<>();
@Before
public void prepareTests() {
dispatcher = new MBassador<String>(this);
dispatcher.subscribe(this);
}
@Test
public void whenErrorOccurs_thenErrorHandler() {
dispatcher.post("Error").now();
assertNull(messageString);
assertNotNull(errorCause);
}
@Test
public void whenNoErrorOccurs_thenStringHandler() {
dispatcher.post("Errol").now();
assertNull(errorCause);
assertNotNull(messageString);
}
@Test
public void whenRejectDispatched_thenPriorityHandled() {
dispatcher.post(new RejectMessage()).now();
// Items should pop() off in reverse priority order
assertTrue(1 == list.pop());
assertTrue(3 == list.pop());
assertTrue(5 == list.pop());
}
@Handler
public void handleString(String message) {
if ("Error".equals(message)) {
throw new Error("BOOM");
}
messageString = message;
}
@Override
public void handleError(PublicationError error) {
errorCause = error.getCause().getCause();
}
@Handler(priority = 5)
public void handleRejectMessage5(RejectMessage rejectMessage) {
list.push(5);
}
@Handler(priority = 3)
public void handleRejectMessage3(RejectMessage rejectMessage) {
list.push(3);
}
@Handler(priority = 2, rejectSubtypes = true)
public void handleMessage(Message rejectMessage) {
list.push(3);
}
@Handler(priority = 0)
public void handleRejectMessage0(RejectMessage rejectMessage) {
list.push(1);
}
}
@@ -0,0 +1,103 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.bus.common.DeadMessage;
import net.engio.mbassy.bus.common.FilteredMessage;
import net.engio.mbassy.listener.Filter;
import net.engio.mbassy.listener.Filters;
import net.engio.mbassy.listener.Handler;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class MBassadorFilterUnitTest {
private MBassador dispatcher = new MBassador();
private Message baseMessage;
private Message subMessage;
private String testString;
private FilteredMessage filteredMessage;
private RejectMessage rejectMessage;
private DeadMessage deadMessage;
@Before
public void prepareTests() {
dispatcher.subscribe(this);
}
@Test
public void whenMessageDispatched_thenMessageFiltered() {
dispatcher.post(new Message()).now();
assertNotNull(baseMessage);
assertNull(subMessage);
}
@Test
public void whenRejectDispatched_thenRejectFiltered() {
dispatcher.post(new RejectMessage()).now();
assertNotNull(subMessage);
assertNull(baseMessage);
}
@Test
public void whenShortStringDispatched_thenStringHandled() {
dispatcher.post("foobar").now();
assertNotNull(testString);
}
@Test
public void whenLongStringDispatched_thenStringFiltered() {
dispatcher.post("foobar!").now();
assertNull(testString);
// filtered only populated when messages does not pass any filters
assertNotNull(filteredMessage);
assertTrue(filteredMessage.getMessage() instanceof String);
assertNull(deadMessage);
}
@Test
public void whenWrongRejectDispatched_thenRejectFiltered() {
RejectMessage testReject = new RejectMessage();
testReject.setCode(-1);
dispatcher.post(testReject).now();
assertNull(rejectMessage);
assertNotNull(subMessage);
assertEquals(-1, ((RejectMessage) subMessage).getCode());
}
@Handler(filters = { @Filter(Filters.RejectSubtypes.class) })
public void handleBaseMessage(Message message) {
this.baseMessage = message;
}
@Handler(filters = { @Filter(Filters.SubtypesOnly.class) })
public void handleSubMessage(Message message) {
this.subMessage = message;
}
@Handler(condition = "msg.length() < 7")
public void handleStringMessage(String message) {
this.testString = message;
}
@Handler(condition = "msg.getCode() != -1")
public void handleRejectMessage(RejectMessage rejectMessage) {
this.rejectMessage = rejectMessage;
}
@Handler
public void handleFilterMessage(FilteredMessage message) {
this.filteredMessage = message;
}
@Handler
public void handleDeadMessage(DeadMessage deadMessage) {
this.deadMessage = deadMessage;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.mbassador;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class MBassadorHierarchyUnitTest {
private MBassador dispatcher = new MBassador<Message>();
private Message message;
private AckMessage ackMessage;
private RejectMessage rejectMessage;
@Before
public void prepareTests() {
dispatcher.subscribe(this);
}
@Test
public void whenMessageDispatched_thenMessageHandled() {
dispatcher.post(new Message()).now();
assertNotNull(message);
assertNull(ackMessage);
assertNull(rejectMessage);
}
@Test
public void whenRejectDispatched_thenMessageAndRejectHandled() {
dispatcher.post(new RejectMessage()).now();
assertNotNull(message);
assertNotNull(rejectMessage);
assertNull(ackMessage);
}
@Test
public void whenAckDispatched_thenMessageAndAckHandled() {
dispatcher.post(new AckMessage()).now();
assertNotNull(message);
assertNotNull(ackMessage);
assertNull(rejectMessage);
}
@Handler
public void handleMessage(Message message) {
this.message = message;
}
@Handler
public void handleRejectMessage(RejectMessage message) {
rejectMessage = message;
}
@Handler
public void handleAckMessage(AckMessage message) {
ackMessage = message;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.neuroph;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neuroph.core.NeuralNetwork;
import static org.junit.Assert.*;
public class XORIntegrationTest {
private NeuralNetwork ann = null;
private void print(String input, double output, double actual) {
System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
}
@Before
public void annInit() {
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
}
@Test
public void leftDisjunctTest() {
ann.setInput(0, 1);
ann.calculate();
print("0, 1", ann.getOutput()[0], 1.0);
assertEquals(ann.getOutput()[0], 1.0, 0.0);
}
@Test
public void rightDisjunctTest() {
ann.setInput(1, 0);
ann.calculate();
print("1, 0", ann.getOutput()[0], 1.0);
assertEquals(ann.getOutput()[0], 1.0, 0.0);
}
@Test
public void bothFalseConjunctTest() {
ann.setInput(0, 0);
ann.calculate();
print("0, 0", ann.getOutput()[0], 0.0);
assertEquals(ann.getOutput()[0], 0.0, 0.0);
}
@Test
public void bothTrueConjunctTest() {
ann.setInput(1, 1);
ann.calculate();
print("1, 1", ann.getOutput()[0], 0.0);
assertEquals(ann.getOutput()[0], 0.0, 0.0);
}
@After
public void annClose() {
ann = null;
}
}
@@ -0,0 +1,62 @@
package com.baeldung.noexception;
import com.machinezoo.noexception.Exceptions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NoExceptionUnitTest {
private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class);
@Test
public void whenStdExceptionHandling_thenCatchAndLog() {
try {
System.out.println("Result is " + Integer.parseInt("foobar"));
} catch (Throwable exception) {
logger.error("Caught exception:", exception);
}
}
@Test
public void whenDefaultNoException_thenCatchAndLog() {
Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() {
Exceptions.log(logger).run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithMessage() {
Exceptions.log(logger, "Something went wrong:").run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() {
System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> Integer.parseInt("foobar")).orElse(-1));
}
@Test(expected = Error.class)
public void givenCustomHandler_whenError_thenRethrowError() {
CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler();
customExceptionHandler.run(() -> throwError());
}
@Test
public void givenCustomHandler_whenException_thenCatchAndLog() {
CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler();
customExceptionHandler.run(() -> throwException());
}
private static void throwError() {
throw new Error("This is very bad.");
}
private static void throwException() {
String testString = "foo";
testString.charAt(5);
}
}
@@ -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,49 @@
package com.baeldung.pairs;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.junit.Assert;
import org.junit.Test;
public class ApacheCommonsPairUnitTest {
@Test
public void givenMutablePair_whenGetValue_shouldPass() {
int key = 5;
String value = "Five";
MutablePair<Integer, String> mutablePair = new MutablePair<>(key, value);
Assert.assertTrue(mutablePair.getKey() == key);
Assert.assertEquals(mutablePair.getValue(), value);
}
@Test
public void givenMutablePair_whenSetValue_shouldPass() {
int key = 6;
String value = "Six";
String newValue = "New Six";
MutablePair<Integer, String> mutablePair = new MutablePair<>(key, value);
Assert.assertTrue(mutablePair.getKey() == key);
Assert.assertEquals(mutablePair.getValue(), value);
mutablePair.setValue(newValue);
Assert.assertEquals(mutablePair.getValue(), newValue);
}
@Test
public void givenImmutablePair_whenGetValue_shouldPass() {
int key = 2;
String value = "Two";
ImmutablePair<Integer, String> immutablePair = new ImmutablePair<>(key, value);
Assert.assertTrue(immutablePair.getKey() == key);
Assert.assertEquals(immutablePair.getValue(), value);
}
@Test(expected = UnsupportedOperationException.class)
public void givenImmutablePair_whenSetValue_shouldFail() {
ImmutablePair<Integer, String> immutablePair = new ImmutablePair<>(1, "One");
immutablePair.setValue("Another One");
}
}
@@ -0,0 +1,17 @@
package com.baeldung.pairs;
import javafx.util.Pair;
import org.junit.Assert;
import org.junit.Test;
public class CoreJavaPairUnitTest {
@Test
public void givenPair_whenGetValue_shouldSucceed() {
String key = "Good Day";
boolean value = true;
Pair<String, Boolean> pair = new Pair<>(key, value);
Assert.assertEquals(key, pair.getKey());
Assert.assertEquals(value, pair.getValue());
}
}
@@ -0,0 +1,39 @@
package com.baeldung.pairs;
import static org.junit.Assert.*;
import java.util.AbstractMap;
import org.junit.Test;
public class CoreJavaSimpleEntryUnitTest {
@Test
public void givenSimpleEntry_whenGetValue_thenOk() {
AbstractMap.SimpleEntry<Integer, String> entry = new AbstractMap.SimpleEntry<Integer, String>(1, "one");
Integer key = entry.getKey();
String value = entry.getValue();
assertEquals(key.intValue(), 1);
assertEquals(value, "one");
}
@Test(expected = UnsupportedOperationException.class)
public void givenSimpleImmutableEntry_whenSetValue_thenException() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
entry.setValue("two");
}
@Test
public void givenSimpleImmutableEntry_whenGetValue_thenOk() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
Integer key = entry.getKey();
String value = entry.getValue();
assertEquals(key.intValue(), 1);
assertEquals(value, "one");
}
}
@@ -0,0 +1,29 @@
package com.baeldung.pairs;
import io.vavr.Tuple2;
import org.junit.Assert;
import org.junit.Test;
public class VavrPairsUnitTest {
@Test
public void givenTuple_whenSetValue_shouldSucceed() {
String key = "Eleven";
double value = 11.0;
double newValue = 11.1;
Tuple2<String, Double> pair = new Tuple2<>(key, value);
pair = pair.update2(newValue);
Assert.assertTrue(newValue == pair._2());
}
@Test
public void givenPair_whenGetValue_shouldSucceed() {
String key = "Twelve";
double value = 12.0;
Tuple2<String, Double> pair = new Tuple2<>(key, value);
Assert.assertTrue(value == pair._2());
}
}
@@ -0,0 +1,96 @@
package com.baeldung.pcollections;
import org.junit.Test;
import org.pcollections.HashPMap;
import org.pcollections.HashTreePMap;
import org.pcollections.HashTreePSet;
import org.pcollections.MapPSet;
import org.pcollections.PVector;
import org.pcollections.TreePVector;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PCollectionsUnitTest {
@Test
public void whenEmpty_thenCreateEmptyHashPMap() {
HashPMap<String, String> pmap = HashTreePMap.empty();
assertEquals(pmap.size(), 0);
}
@Test
public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() {
HashPMap<String, String> pmap1 = HashTreePMap.singleton("key1", "value1");
assertEquals(pmap1.size(), 1);
}
@Test
public void givenExistingHashMap_whenFrom_thenCreateHashPMap() {
Map<String, String> map = new HashMap<>();
map.put("mkey1", "mval1");
map.put("mkey2", "mval2");
HashPMap<String, String> pmap2 = HashTreePMap.from(map);
assertEquals(pmap2.size(), 2);
}
@Test
public void whenHashPMapMethods_thenPerformOperations() {
HashPMap<String, String> pmap = HashTreePMap.empty();
HashPMap<String, String> pmap0 = pmap.plus("key1", "value1");
Map<String, String> map = new HashMap<>();
map.put("key2", "val2");
map.put("key3", "val3");
HashPMap<String, String> pmap1 = pmap0.plusAll(map);
HashPMap<String, String> pmap2 = pmap1.minus("key1");
HashPMap<String, String> pmap3 = pmap2.minusAll(map.keySet());
assertEquals(pmap0.size(), 1);
assertEquals(pmap1.size(), 3);
assertFalse(pmap2.containsKey("key1"));
assertEquals(pmap3.size(), 0);
}
@Test
public void whenTreePVectorMethods_thenPerformOperations() {
TreePVector<String> pVector = TreePVector.empty();
TreePVector<String> pV1 = pVector.plus("e1");
TreePVector<String> pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(1, pV1.size());
assertEquals(4, pV2.size());
TreePVector<String> pV3 = pV2.minus("e1");
TreePVector<String> pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(pV3.size(), 3);
assertEquals(pV4.size(), 0);
TreePVector<String> pSub = pV2.subList(0, 2);
assertTrue(pSub.contains("e1") && pSub.contains("e2"));
PVector<String> pVW = pV2.with(0, "e10");
assertEquals(pVW.get(0), "e10");
}
@Test
public void whenMapPSetMethods_thenPerformOperations() {
MapPSet pSet = HashTreePSet.empty().plusAll(Arrays.asList("e1", "e2", "e3", "e4"));
assertEquals(pSet.size(), 4);
MapPSet pSet1 = pSet.minus("e4");
assertFalse(pSet1.contains("e4"));
}
}
@@ -0,0 +1,55 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.collectors.CollectorUtils;
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
import org.junit.Test;
import java.util.Optional;
import java.util.stream.Stream;
import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy;
import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class CollectorUtilsUnitTest {
@Test
public void givenIntegerStream_whenCollectOnMaxByProjection_shouldReturnOptionalMaxValue() {
Stream<String> integerStream = Stream.of("a", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(maxBy(String::length));
assertThat(max.get(), is("ccc"));
}
@Test
public void givenIntegerStream_whenCollectOnMinByProjection_shouldReturnOptionalMinValue() {
Stream<String> integerStream = Stream.of("abc", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(minBy(String::length));
assertThat(max.get(), is("1"));
}
@Test
public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() {
assertThat(Stream.empty().collect(CollectorUtils.unique()), equalTo(Optional.empty()));
}
@Test
public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() {
assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.unique()), equalTo(Optional.of(3)));
}
@Test
public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() {
assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.uniqueNullable()), equalTo(3));
}
@Test(expected = NonUniqueValueException.class)
public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() {
Stream.of(1, 2, 3).filter(i -> i > 1).collect(CollectorUtils.unique());
}
}
@@ -0,0 +1,180 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.selectors.Selectors;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class StreamUtilsUnitTest {
@Test
public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList());
assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz")));
}
@Test
public void givenTwoStreams_whenZip_shouldReturnZippedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList());
assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot"));
}
@Test
public void givenThreeStreams_whenZip_shouldReturnZippedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList());
assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot"));
}
@Test
// givenThreeStreams_whenMerge_shouldReturnMergedStream
public void givenThreeStreams_whenMerge_shouldReturnMergedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry");
Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC);
assertThat(merged.collect(toList()), contains(asList("A", "apple", "fritter"), asList("B", "banana", "split"), asList("C", "carrot", "cake"), asList("date", "roll"), asList("pastry")));
}
@Test
// givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream
public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() {
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy");
Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC);
assertThat(interleaved.collect(Collectors.toList()), contains("Peter", "A", "foo", "Paul", "B", "bar", "Mary", "C", "baz", "D", "xyzzy", "E"));
}
@Test
// givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10
public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
assertThat(finiteInts.collect(Collectors.toList()), hasSize(10));
}
@Test
public void givenInfiniteStream_whenTakeUntil10_shouldReturnStreamUpto10() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteInts = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
assertThat(finiteInts.collect(Collectors.toList()), hasSize(11));
}
@Test
public void givenIntegerStreamOfTen_whenSkipWhileLessThanFour_shouldReturnStreamFromFourToTen() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skipped = StreamUtils.skipWhile(ints, i -> i < 4);
List<Integer> collected = skipped.collect(Collectors.toList());
assertThat(collected, contains(4, 5, 6, 7, 8, 9, 10));
}
@Test
public void givenIntegerStreamOfTen_whenSkipUntilFour_shouldReturnStreamFromFiveToTen() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skipped = StreamUtils.skipUntil(ints, i -> i > 4);
List<Integer> collected = skipped.collect(Collectors.toList());
assertThat(collected, contains(5, 6, 7, 8, 9, 10));
}
@Test
public void givenSeedValue_withUnfold_shouldReturnStreamAccordingToGeneratorMethod() {
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
assertThat(unfolded.collect(Collectors.toList()), contains(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Test
public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList());
assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5)));
}
@Test
public void givenAStream_whenAggregate_shouldReturnAggregatedStreamOnTheBasisOfBiFunction() {
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
assertThat(aggregated.collect(toList()), contains(asList("a1"), asList("b1", "b2"), asList("c1")));
}
@Test
public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList());
assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5)));
}
@Test
// givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 3, 2).collect(toList());
assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5)));
}
@Test
public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() {
ArrayList<Integer> ints = new ArrayList<>();
ints.stream().collect(maxBy((a, b) -> a.toString().compareTo(b.toString())));
List<List<Integer>> windows = StreamUtils.windowed(ints.stream(), 2).collect(toList());
assertThat(windows, iterableWithSize(0));
}
@Test
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5)));
}
@Test
public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() {
LongStream indices = StreamUtils.indices().limit(500);
assertThat(indices.count(), equalTo(500L));
}
}
@@ -0,0 +1,50 @@
package com.baeldung.reflections;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
public class ReflectionsUnitTest {
@Test
public void givenTypeThenGetAllSubTypes() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getReflectionsSubTypes()
.isEmpty());
}
@Test
public void givenTypeAndUsingBuilderThenGetAllSubTypes() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder()
.isEmpty());
}
@Test
public void givenAnnotationThenGetAllAnnotatedMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getDateDeprecatedMethods()
.isEmpty());
}
@Test
public void givenAnnotationThenGetAllAnnotatedConstructors() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getDateDeprecatedConstructors()
.isEmpty());
}
@Test
public void givenParamTypeThenGetAllMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getMethodsWithDateParam()
.isEmpty());
}
@Test
public void givenReturnTypeThenGetAllMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getMethodsWithVoidReturn()
.isEmpty());
}
}
@@ -0,0 +1,126 @@
package com.baeldung.resilience4j;
import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.bulkhead.BulkheadRegistry;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.function.Function;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class Resilience4jUnitTest {
interface RemoteService {
int process(int i);
}
private RemoteService service;
@Before
public void setUp() {
service = mock(RemoteService.class);
}
@Test
public void whenCircuitBreakerIsUsed_thenItWorksAsExpected() {
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
// Percentage of failures to start short-circuit
.failureRateThreshold(20)
// Min number of call attempts
.ringBufferSizeInClosedState(5)
.build();
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
Function<Integer, Integer> decorated = CircuitBreaker.decorateFunction(circuitBreaker, service::process);
when(service.process(anyInt())).thenThrow(new RuntimeException());
for (int i = 0; i < 10; i++) {
try {
decorated.apply(i);
} catch (Exception ignore) {
}
}
verify(service, times(5)).process(any(Integer.class));
}
@Test
public void whenBulkheadIsUsed_thenItWorksAsExpected() throws InterruptedException {
BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build();
BulkheadRegistry registry = BulkheadRegistry.of(config);
Bulkhead bulkhead = registry.bulkhead("my");
Function<Integer, Integer> decorated = Bulkhead.decorateFunction(bulkhead, service::process);
Future<?> taskInProgress = callAndBlock(decorated);
try {
assertThat(bulkhead.isCallPermitted()).isFalse();
} finally {
taskInProgress.cancel(true);
}
}
private Future<?> callAndBlock(Function<Integer, Integer> decoratedService) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
when(service.process(anyInt())).thenAnswer(invocation -> {
latch.countDown();
Thread.currentThread().join();
return null;
});
ForkJoinTask<?> result = ForkJoinPool.commonPool().submit(() -> {
decoratedService.apply(1);
});
latch.await();
return result;
}
@Test
public void whenRetryIsUsed_thenItWorksAsExpected() {
RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
RetryRegistry registry = RetryRegistry.of(config);
Retry retry = registry.retry("my");
Function<Integer, Void> decorated = Retry.decorateFunction(retry, (Integer s) -> {
service.process(s);
return null;
});
when(service.process(anyInt())).thenThrow(new RuntimeException());
try {
decorated.apply(1);
fail("Expected an exception to be thrown if all retries failed");
} catch (Exception e) {
verify(service, times(2)).process(any(Integer.class));
}
}
@SuppressWarnings("unchecked")
@Test
public void whenTimeLimiterIsUsed_thenItWorksAsExpected() throws Exception {
long ttl = 1;
TimeLimiterConfig config = TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build();
TimeLimiter timeLimiter = TimeLimiter.of(config);
Future futureMock = mock(Future.class);
Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock);
restrictedCall.call();
verify(futureMock).get(ttl, TimeUnit.MILLISECONDS);
}
}
@@ -0,0 +1,141 @@
package com.baeldung.stm;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class AccountUnitTest {
@Test
public void givenAccount_whenDecrement_thenShouldReturnProperValue() {
// given
Account a = new Account(10);
// when
a.adjustBy(-5);
// then
assertThat(a.getBalance()).isEqualTo(5);
}
@Test(expected = IllegalArgumentException.class)
public void givenAccount_whenDecrementTooMuch_thenShouldThrow() {
// given
Account a = new Account(10);
// when
a.adjustBy(-11);
}
@Test
public void givenTwoThreads_whenBothApplyOperation_thenShouldThrow() throws InterruptedException {
// given
ExecutorService ex = Executors.newFixedThreadPool(2);
Account a = new Account(10);
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicBoolean exceptionThrown = new AtomicBoolean(false);
// when
ex.submit(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
a.adjustBy(-6);
} catch (IllegalArgumentException e) {
exceptionThrown.set(true);
}
});
ex.submit(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
a.adjustBy(-5);
} catch (IllegalArgumentException e) {
exceptionThrown.set(true);
}
});
countDownLatch.countDown();
ex.awaitTermination(1, TimeUnit.SECONDS);
ex.shutdown();
// then
assertTrue(exceptionThrown.get());
}
@Test
public void givenTwoAccounts_whenFailedWhileTransferring_thenShouldRollbackTransaction() {
// given
final Account a = new Account(10);
final Account b = new Account(10);
// when
a.transferTo(b, 5);
// then
assertThat(a.getBalance()).isEqualTo(5);
assertThat(b.getBalance()).isEqualTo(15);
// and
try {
a.transferTo(b, 20);
} catch (final IllegalArgumentException e) {
System.out.println("failed to transfer money");
}
// then
assertThat(a.getBalance()).isEqualTo(5);
assertThat(b.getBalance()).isEqualTo(15);
}
@Test
public void givenTwoThreads_whenBothTryToTransfer_thenShouldNotDeadlock() throws InterruptedException {
// given
ExecutorService ex = Executors.newFixedThreadPool(2);
final Account a = new Account(10);
final Account b = new Account(10);
CountDownLatch countDownLatch = new CountDownLatch(1);
// when
ex.submit(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
a.transferTo(b, 10);
});
ex.submit(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
b.transferTo(a, 1);
});
countDownLatch.countDown();
ex.awaitTermination(1, TimeUnit.SECONDS);
ex.shutdown();
// then
assertThat(a.getBalance()).isEqualTo(1);
assertThat(b.getBalance()).isEqualTo(19);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.stream;
import org.jooq.lambda.Seq;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertEquals;
public class JoolMergeStreamsUnitTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Stream<Integer> seq1 = Stream.of(1, 3, 5);
Stream<Integer> seq2 = Stream.of(2, 4, 6);
Stream<Integer> resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<String> seq = Stream.of("foo", "bar");
Stream<String> openingBracketSeq = Stream.of("[");
Stream<String> closingBracketSeq = Stream.of("]");
Stream<String> resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq);
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
}
}
@@ -0,0 +1,47 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class MergeStreamsUnitTest {
@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 = Stream.concat(stream1, stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_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> resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), 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 = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity());
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
}
}
@@ -0,0 +1,47 @@
package com.baeldung.stream;
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()));
}
}
@@ -0,0 +1,100 @@
package com.baeldung.streamutils;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.StreamUtils;
import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
public class CopyStreamUnitTest {
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copy(in, out);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent, outputFileContent);
}
@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copyRange(in, out, 1, 10);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}
@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(string, StandardCharsets.UTF_8, out);
assertTrue(outputFile.exists());
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
@Test
public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(byteArray, out);
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream in = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(in);
String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
}