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
+8 -1
View File
@@ -19,6 +19,8 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Software Transactional Memory in Java Using Multiverse](https://www.baeldung.com/java-multiverse-stm)
- [Locality-Sensitive Hashing in Java Using Java-LSH](https://www.baeldung.com/locality-sensitive-hashing)
- [Introduction to Neuroph](https://www.baeldung.com/neuroph)
#4
- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss)
- [Introduction to PCollections](https://www.baeldung.com/java-pcollections)
- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections)
@@ -29,6 +31,8 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Guide to JDeferred](https://www.baeldung.com/jdeferred)
- [Introduction to MBassador](https://www.baeldung.com/mbassador)
- [Using Pairs in Java](https://www.baeldung.com/java-pairs)
#5
- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine)
- [Introduction to StreamEx](https://www.baeldung.com/streamex)
- [A Docker Guide for Java](https://www.baeldung.com/docker-java-api)
@@ -39,10 +43,13 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue)
- [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client)
- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools)
#6
- [Introduction to JavaPoet](https://www.baeldung.com/java-poet)
- [Guide to Resilience4j](https://www.baeldung.com/resilience4j)
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client)
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library)
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
- More articles [[next -->]](/libraries-2)
+67 -67
View File
@@ -70,11 +70,11 @@
<version>${jnats.version}</version>
</dependency>
<dependency>
<groupId>rome</groupId>
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>rome</groupId>-->
<!-- <artifactId>rome</artifactId>-->
<!-- <version>${rome.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
@@ -218,11 +218,11 @@
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>one.util</groupId>-->
<!-- <artifactId>streamex</artifactId>-->
<!-- <version>${streamex.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
@@ -256,18 +256,18 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility-proxy</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.awaitility</groupId>-->
<!-- <artifactId>awaitility</artifactId>-->
<!-- <version>${awaitility.version}</version>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.awaitility</groupId>-->
<!-- <artifactId>awaitility-proxy</artifactId>-->
<!-- <version>${awaitility.version}</version>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
@@ -284,42 +284,42 @@
<artifactId>byte-buddy-agent</artifactId>
<version>${bytebuddy.version}</version>
</dependency>
<dependency>
<groupId>org.pcollections</groupId>
<artifactId>pcollections</artifactId>
<version>${pcollections.version}</version>
</dependency>
<dependency>
<groupId>com.machinezoo.noexception</groupId>
<artifactId>noexception</artifactId>
<version>${noexception.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.pcollections</groupId>-->
<!-- <artifactId>pcollections</artifactId>-->
<!-- <version>${pcollections.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.machinezoo.noexception</groupId>-->
<!-- <artifactId>noexception</artifactId>-->
<!-- <version>${noexception.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.eclipse.collections</groupId>-->
<!-- <artifactId>eclipse-collections</artifactId>-->
<!-- <version>${eclipse-collections.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.vavr</groupId>-->
<!-- <artifactId>vavr</artifactId>-->
<!-- <version>${vavr.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.haulmont.yarg</groupId>
<artifactId>yarg</artifactId>
<version>${yarg.version}</version>
</dependency>
<dependency>
<groupId>net.engio</groupId>
<artifactId>mbassador</artifactId>
<version>${mbassador.version}</version>
</dependency>
<dependency>
<groupId>org.jdeferred</groupId>
<artifactId>jdeferred-core</artifactId>
<version>${jdeferred.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.haulmont.yarg</groupId>-->
<!-- <artifactId>yarg</artifactId>-->
<!-- <version>${yarg.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>net.engio</groupId>-->
<!-- <artifactId>mbassador</artifactId>-->
<!-- <version>${mbassador.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.jdeferred</groupId>-->
<!-- <artifactId>jdeferred-core</artifactId>-->
<!-- <version>${jdeferred.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
@@ -572,14 +572,14 @@
<jUnitParams.version>1.1.0</jUnitParams.version>
<java-lsh.version>0.10</java-lsh.version>
<pact.version>3.5.0</pact.version>
<awaitility.version>3.0.0</awaitility.version>
<!-- <awaitility.version>3.0.0</awaitility.version>-->
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
<bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version>
<rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- <pcollections.version>2.1.2</pcollections.version>-->
<!-- <rome.version>1.0</rome.version>-->
<!-- <eclipse-collections.version>8.2.0</eclipse-collections.version>-->
<!-- <streamex.version>0.6.5</streamex.version>-->
<!-- <vavr.version>0.9.0</vavr.version>-->
<protonpack.version>1.15</protonpack.version>
<caffeine.version>2.5.5</caffeine.version>
@@ -604,10 +604,10 @@
<quartz.version>2.3.0</quartz.version>
<jool.version>0.9.12</jool.version>
<jmh.version>1.19</jmh.version>
<noexception.version>1.1.0</noexception.version>
<yarg.version>2.0.4</yarg.version>
<mbassador.version>1.3.1</mbassador.version>
<jdeferred.version>1.2.6</jdeferred.version>
<!-- <noexception.version>1.1.0</noexception.version>-->
<!-- <yarg.version>2.0.4</yarg.version>-->
<!-- <mbassador.version>1.3.1</mbassador.version>-->
<!-- <jdeferred.version>1.2.6</jdeferred.version>-->
<functionaljava.version>4.8.1</functionaljava.version>
<fugue.version>4.5.1</fugue.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
@@ -1,15 +0,0 @@
package com.baeldung.distinct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctWithJavaFunction {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
@@ -1,65 +0,0 @@
package com.baeldung.distinct;
public class Person {
int age;
String name;
String email;
public Person(int age, String name, String email) {
super();
this.age = age;
this.name = name;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [age=");
builder.append(age);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}
@@ -1,19 +0,0 @@
package com.baeldung.eclipsecollections;
import java.util.List;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
public class ConvertContainerToAnother {
@SuppressWarnings("rawtypes")
public static List convertToList() {
UnifiedSet<String> cars = new UnifiedSet<>();
cars.add("Toyota");
cars.add("Mercedes");
cars.add("Volkswagen");
return cars.toList();
}
}
@@ -1,46 +0,0 @@
package com.baeldung.eclipsecollections;
import java.util.List;
public class Student {
private String firstName;
private String lastName;
private List<String> addresses;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Student(String firstName, String lastName, List<String> addresses) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.addresses = addresses;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -1,24 +0,0 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class FilterDemo {
private static String modifiedMsg;
static String filter(String msg) {
Deferred<String, ?, ?> d = new DeferredObject<>();
Promise<String, ?, ?> p = d.promise();
Promise<String, ?, ?> filtered = p.then((result) -> {
modifiedMsg = "Hello " + result;
});
filtered.done(r -> System.out.println("filtering done"));
d.resolve(msg);
return modifiedMsg;
}
}
@@ -1,32 +0,0 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.DonePipe;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class PipeDemo {
public enum Result {
SUCCESS, FAILURE
};
private static Result status;
static Result validate(int num) {
Deferred<Integer, ?, ?> d = new DeferredObject<>();
Promise<Integer, ?, ?> p = d.promise();
p.then((DonePipe<Integer, Integer, Exception, Void>) result -> {
if (result < 90) {
return new DeferredObject<Integer, Exception, Void>().resolve(result);
} else {
return new DeferredObject<Integer, Exception, Void>().reject(new Exception("Unacceptable value"));
}
}).done(r -> status = Result.SUCCESS).fail(r -> status = Result.FAILURE);
d.resolve(num);
return status;
}
}
@@ -1,21 +0,0 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.Promise;
import org.jdeferred.impl.DeferredObject;
class PromiseDemo {
static void startJob(String jobName) {
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> promise = deferred.promise();
promise.done(result -> System.out.println("Job done")).fail(rejection -> System.out.println("Job fail")).progress(progress -> System.out.println("Job is in progress")).always((state, result, rejection) -> System.out.println("Job execution started"));
deferred.resolve(jobName);
// deferred.notify("");
// deferred.reject("oops");
}
}
@@ -1,36 +0,0 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
public class ThreadSafeDemo {
public static void task() {
DeferredManager dm = new DefaultDeferredManager();
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> p1 = deferred.promise();
Promise<String, String, String> p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
synchronized (p) {
while (p.isPending()) {
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
p.waitSafely();
} catch (InterruptedException e) {
e.printStackTrace();
}
deferred.resolve("Hello Baeldung");
}
}
@@ -1,22 +0,0 @@
package com.baeldung.jdeffered.manager;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
class DeferredManagerDemo {
public static void initiate() {
Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager();
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3).done((result) -> {
System.out.println("done");
}).fail((result) -> {
System.out.println("fail");
});
deferred.resolve("Hello Baeldung");
}
}
@@ -1,22 +0,0 @@
package com.baeldung.jdeffered.manager;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
class DeferredManagerWithExecutorDemo {
public static void initiate() {
ExecutorService executor = Executors.newFixedThreadPool(10);
Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager(executor);
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
deferred.resolve("done");
}
}
@@ -1,12 +0,0 @@
package com.baeldung.jdeffered.manager;
import org.jdeferred.DeferredManager;
import org.jdeferred.impl.DefaultDeferredManager;
class SimpleDeferredManagerDemo {
public static void initiate() {
DeferredManager dm = new DefaultDeferredManager();
dm.when(() -> 1).done(r -> System.out.println("done")).fail(Throwable::printStackTrace);
}
}
@@ -1,5 +0,0 @@
package com.baeldung.mbassador;
public class AckMessage extends Message {
}
@@ -1,5 +0,0 @@
package com.baeldung.mbassador;
public class Message {
}
@@ -1,15 +0,0 @@
package com.baeldung.mbassador;
public class RejectMessage extends Message {
int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
@@ -1,21 +0,0 @@
package com.baeldung.noexception;
import com.machinezoo.noexception.ExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomExceptionHandler extends ExceptionHandler {
private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@Override
public boolean handle(Throwable throwable) {
if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) {
return false;
} else {
logger.error("Caught Exception ", throwable);
return true;
}
}
}
@@ -1,33 +0,0 @@
package com.baeldung.pairs;
public class CustomPair {
private String key;
private String value;
public CustomPair(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Object[] getPair() {
return new Object[] { this.key, this.value};
}
}
@@ -1,76 +0,0 @@
package com.baeldung.rome;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RSSRomeExample {
public static void main(String[] args) throws IOException, FeedException {
SyndFeed feed = createFeed();
addEntryToFeed(feed);
publishFeed(feed);
readFeed();
}
private static SyndFeed createFeed() {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
return feed;
}
private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException {
URL feedSource = new URL("http://rssblog.whatisrss.com/feed/");
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
}
@@ -1,48 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.yarg;
import com.haulmont.yarg.formatters.factory.DefaultFormatterFactory;
import com.haulmont.yarg.loaders.factory.DefaultLoaderFactory;
import com.haulmont.yarg.loaders.impl.JsonDataLoader;
import com.haulmont.yarg.reporting.Reporting;
import com.haulmont.yarg.reporting.RunParams;
import com.haulmont.yarg.structure.Report;
import com.haulmont.yarg.structure.ReportBand;
import com.haulmont.yarg.structure.ReportOutputType;
import com.haulmont.yarg.structure.impl.BandBuilder;
import com.haulmont.yarg.structure.impl.ReportBuilder;
import com.haulmont.yarg.structure.impl.ReportTemplateBuilder;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DocumentController {
@RequestMapping(path = "/generate/doc", method = RequestMethod.GET)
public void generateDocument(HttpServletResponse response) throws IOException {
ReportBuilder reportBuilder = new ReportBuilder();
ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder().documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx").outputType(ReportOutputType.docx).readFileFromPath();
reportBuilder.template(reportTemplateBuilder.build());
BandBuilder bandBuilder = new BandBuilder();
String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json"));
ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build();
reportBuilder.band(main);
Report report = reportBuilder.build();
Reporting reporting = new Reporting();
reporting.setFormatterFactory(new DefaultFormatterFactory());
reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader()));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream());
}
}
@@ -1,32 +0,0 @@
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);
}
}
@@ -1,38 +0,0 @@
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);
}
}
@@ -1,32 +0,0 @@
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);
}
}
@@ -1,30 +0,0 @@
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);
}
}
@@ -1,19 +0,0 @@
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
}
}
@@ -1,26 +0,0 @@
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);
}
}
@@ -1,26 +0,0 @@
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);
}
}
@@ -1,22 +0,0 @@
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");
}
}
@@ -1,17 +0,0 @@
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"));
}
}
@@ -1,25 +0,0 @@
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);
}
}
@@ -1,49 +0,0 @@
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);
}
}
@@ -1,29 +0,0 @@
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));
}
}
}
@@ -1,23 +0,0 @@
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);
}
}
@@ -1,23 +0,0 @@
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"));
}
}
@@ -1,40 +0,0 @@
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);
}
}
@@ -1,27 +0,0 @@
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);
}
}
@@ -1,38 +0,0 @@
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);
}
}
@@ -1,33 +0,0 @@
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);
}
}
@@ -1,32 +0,0 @@
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);
}
}
@@ -1,138 +0,0 @@
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));
}
}
@@ -1,26 +0,0 @@
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);
}
}
@@ -1,37 +0,0 @@
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);
}
}
@@ -1,45 +0,0 @@
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);
}
}
@@ -1,69 +0,0 @@
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();
}
}
@@ -1,89 +0,0 @@
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);
}
}
@@ -1,103 +0,0 @@
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;
}
}
@@ -1,61 +0,0 @@
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;
}
}
@@ -1,62 +0,0 @@
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);
}
}
@@ -1,49 +0,0 @@
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");
}
}
@@ -1,17 +0,0 @@
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());
}
}
@@ -1,39 +0,0 @@
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");
}
}
@@ -1,29 +0,0 @@
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());
}
}
@@ -1,96 +0,0 @@
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"));
}
}