JAVA-1470 Move 10 articles to libraries-4 module

This commit is contained in:
mikr
2020-04-26 22:34:22 +02:00
parent 6c0a91ef6e
commit da174392ed
58 changed files with 403 additions and 207 deletions
@@ -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,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,30 @@
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.Assert;
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++) {
Assert.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,138 @@
package com.baeldung.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,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,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,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,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"));
}
}