Merge remote-tracking branch 'upstream/master'

Conflicts:
	libraries/pom.xml
This commit is contained in:
parthkaria
2017-09-27 14:42:30 +05:30
652 changed files with 21671 additions and 1550 deletions
+11 -2
View File
@@ -27,11 +27,20 @@
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
- [Introduction to Neuroph](http://www.baeldung.com/neuroph)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception)
- [Introduction to PCollections](http://www.baeldung.com/java-pcollections)
- [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly)
- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain)
- [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections)
- [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by)
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
- [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
+122 -27
View File
@@ -105,7 +105,6 @@
</executions>
</plugin>
<!-- /Neuroph -->
</plugins>
</build>
<dependencies>
@@ -136,6 +135,11 @@
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>tec.units</groupId>
<artifactId>unit-ri</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
@@ -190,7 +194,7 @@
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.0</version>
<version>0.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
@@ -295,22 +299,22 @@
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.jdo</artifactId>
<version>3.2.0-m6</version>
<version>3.2.0-m7</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>5.1.0-m1</version>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jdo</artifactId>
<version>5.1.0-m1</version>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-rdbms</artifactId>
<version>5.1.0-m1</version>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
@@ -364,7 +368,7 @@
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.1</version>
<version>2.6.3</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -483,20 +487,103 @@
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
<!-- Retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>com.darwinsys</groupId>
<artifactId>hirondelle-date4j</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>com.darwinsys</groupId>
<artifactId>hirondelle-date4j</artifactId>
<version>${hirondelle-date4j.version}</version>
</dependency>
<dependency>
<groupId>com.haulmont.yarg</groupId>
<artifactId>yarg</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>net.engio</groupId>
<artifactId>mbassador</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.jdeferred</groupId>
<artifactId>jdeferred-core</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java8</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-quickcheck</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java-core</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>${cache.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
</dependency>
<dependency>
<groupId>javax.measure</groupId>
@@ -511,17 +598,16 @@
<url>http://download.java.net/maven/2</url>
</repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>bintray-cuba-platform-main</id>
<name>bintray</name>
<url>http://dl.bintray.com/cuba-platform/main</url>
</repository>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>opengeo</id>
<name>OpenGeo Maven Repository</name>
<url>http://repo.opengeo.org</url>
<id>atlassian-public</id>
<url>https://packages.atlassian.com/maven/repository/public</url>
</repository>
</repositories>
<properties>
@@ -554,7 +640,7 @@
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version>
<jUnitParams.version>1.1.0</jUnitParams.version>
<netty.version>4.1.10.Final</netty.version>
<netty.version>4.1.15.Final</netty.version>
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<java-lsh.version>0.10</java-lsh.version>
@@ -570,5 +656,14 @@
<vavr.version>0.9.0</vavr.version>
<geotools.version>15.2</geotools.version>
<javax-measure.version>0.9.1</javax-measure.version>
<joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<retrofit.version>2.3.0</retrofit.version>
<joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<protonpack.version>1.14</protonpack.version>
<unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>
@@ -0,0 +1,43 @@
package com.baeldung.commons.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitor {
public static void main(String[] args) throws Exception {
File folder = FileUtils.getTempDirectory();
startFileMonitor(folder);
}
/**
* @param folder
* @throws Exception
*/
public static void startFileMonitor(File folder) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
// on create action
}
@Override
public void onFileDelete(File file) {
// on delete action
}
};
observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();
}
}
@@ -0,0 +1,11 @@
package com.baeldung.commons.lang3;
import org.apache.commons.lang3.concurrent.LazyInitializer;
public class SampleLazyInitializer extends LazyInitializer<SampleObject> {
@Override
protected SampleObject initialize() {
return new SampleObject();
}
}
@@ -0,0 +1,7 @@
package com.baeldung.commons.lang3;
public class SampleObject {
//Ignored
}
@@ -0,0 +1,47 @@
package com.baeldung.fj;
import fj.F;
import fj.F1Functions;
import fj.Unit;
import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
return Unit.unit();
};
}
public static void main(String[] args) {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions
.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input);
IO<String> readInput = IOFunctions.stdinReadLine();
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput,
transformInput);
IO<Unit> program = IOFunctions.bind(userInput,
nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
}
}
@@ -0,0 +1,48 @@
package com.baeldung.fj;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Show.optionShow(Show.intShow).println(result1);
Show.optionShow(Show.intShow).println(result2);
}
}
@@ -1,187 +0,0 @@
package com.baeldung.geotools;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class ShapeFile {
private static final String FILE_NAME = "shapefile.shp";
public static void main(String[] args) throws Exception {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String");
SimpleFeatureType CITY = createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
addLocations(featureBuilder, collection);
File shapeFile = getNewShapeFile();
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", shapeFile.toURI()
.toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
dataStore.createSchema(CITY);
// If you decide to use the TYPE type and create a Data Store with it,
// You will need to uncomment this line to set the Coordinate Reference System
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
}
public static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("Location", Point.class);
builder.length(15)
.add("Name", String.class);
SimpleFeatureType CITY = builder.buildFeatureType();
return CITY;
}
public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) {
Map<String, List<Double>> locations = new HashMap<>();
double lat = 13.752222;
double lng = 100.493889;
String name = "Bangkok";
addToLocationMap(name, lat, lng, locations);
lat = 53.083333;
lng = -0.15;
name = "New York";
addToLocationMap(name, lat, lng, locations);
lat = -33.925278;
lng = 18.423889;
name = "Cape Town";
addToLocationMap(name, lat, lng, locations);
lat = -33.859972;
lng = 151.211111;
name = "Sydney";
addToLocationMap(name, lat, lng, locations);
lat = 45.420833;
lng = -75.69;
name = "Ottawa";
addToLocationMap(name, lat, lng, locations);
lat = 30.07708;
lng = 31.285909;
name = "Cairo";
addToLocationMap(name, lat, lng, locations);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
for (Map.Entry<String, List<Double>> location : locations.entrySet()) {
Point point = geometryFactory.createPoint(new Coordinate(location.getValue()
.get(0),
location.getValue()
.get(1)));
featureBuilder.add(point);
featureBuilder.add(name);
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
List<Double> coordinates = new ArrayList<>();
coordinates.add(lat);
coordinates.add(lng);
locations.put(name, coordinates);
}
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
File shapeFile = chooser.getSelectedFile();
if (shapeFile.equals(filePath)) {
System.out.println("Error: cannot replace " + filePath);
System.exit(0);
}
return shapeFile;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jcache;
import java.io.Serializable;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryUpdatedListener;
public class SimpleCacheEntryListener implements CacheEntryCreatedListener<String, String>, CacheEntryUpdatedListener<String, String>, Serializable {
/**
*
*/
private static final long serialVersionUID = -712657810462878763L;
private boolean updated;
private boolean created;
public boolean getUpdated() {
return this.updated;
}
public boolean getCreated() {
return this.created;
}
public void onUpdated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
this.updated = true;
}
public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
this.created = true;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jcache;
import java.util.HashMap;
import java.util.Map;
import javax.cache.integration.CacheLoader;
import javax.cache.integration.CacheLoaderException;
public class SimpleCacheLoader implements CacheLoader<Integer, String> {
@Override
public String load(Integer key) throws CacheLoaderException {
return "fromCache" + key;
}
@Override
public Map<Integer, String> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException {
Map<Integer, String> data = new HashMap<>();
for (int key : keys) {
data.put(key, load(key));
}
return data;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jcache;
import java.io.Serializable;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
public class SimpleEntryProcessor implements EntryProcessor<String, String, String>, Serializable {
/**
*
*/
private static final long serialVersionUID = -5616476363722945132L;
public String process(MutableEntry<String, String> entry, Object... args) throws EntryProcessorException {
if (entry.exists()) {
String current = entry.getValue();
entry.setValue(current + " - modified");
return current;
}
return null;
}
}
@@ -0,0 +1,24 @@
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;
}
}
@@ -0,0 +1,35 @@
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;
}
}
@@ -0,0 +1,24 @@
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");
}
}
@@ -0,0 +1,38 @@
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");
}
}
@@ -0,0 +1,22 @@
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");
}
}
@@ -0,0 +1,24 @@
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");
}
}
@@ -0,0 +1,14 @@
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);
}
}
@@ -0,0 +1,57 @@
package com.baeldung.jira;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class JiraClient {
private static final String USERNAME = "jira.user";
private static final String PASSWORD = "secret";
private static final String JIRA_URL = "http://jira.company.com";
public static void main(String[] args) {
final Issue issue = new JiraClient().getIssue("MYKEY-1234");
System.out.println(issue.getDescription());
}
private Issue getIssue(String issueKey) {
JiraRestClient restClient = getJiraRestClient();
Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
closeRestClient(restClient);
return issue;
}
private JiraRestClient getJiraRestClient() {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI jiraServerUri = getJiraUri();
return factory
.createWithBasicHttpAuthentication(jiraServerUri, USERNAME, PASSWORD);
}
private URI getJiraUri() {
URI jiraServerUri = null;
try {
jiraServerUri = new URI(JIRA_URL);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jiraServerUri;
}
private void closeRestClient(JiraRestClient restClient) {
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.mbassador;
public class AckMessage extends Message {
}
@@ -0,0 +1,5 @@
package com.baeldung.mbassador;
public class Message {
}
@@ -0,0 +1,15 @@
package com.baeldung.mbassador;
public class RejectMessage extends Message {
int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.measurement;
import javax.measure.Quantity;
import javax.measure.quantity.Volume;
public class WaterTank {
private Quantity<Volume> capacityMeasure;
private double capacityDouble;
public void setCapacityMeasure(Quantity<Volume> capacityMeasure) {
this.capacityMeasure = capacityMeasure;
}
public void setCapacityDouble(double capacityDouble) {
this.capacityDouble = capacityDouble;
}
public Quantity<Volume> getCapacityMeasure() {
return capacityMeasure;
}
public double getCapacityDouble() {
return capacityDouble;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.protonpack;
import java.util.Optional;
import java.util.stream.Stream;
import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy;
import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy;
public class CollectorUtilsExample {
public void minMaxProjectionCollector() {
Stream<String> integerStream = Stream.of("a", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(maxBy(String::length));
Optional<String> min = integerStream.collect(minBy(String::length));
}
}
@@ -0,0 +1,107 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.selectors.Selectors;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class StreamUtilsExample {
public void createInfiniteIndex() {
LongStream indices = StreamUtils.indices();
}
public void zipAStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils
.zipWithIndex(source)
.collect(Collectors.toList());
}
public void zipAPairOfStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
.collect(Collectors.toList());
}
public void zipThreeStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
.collect(Collectors.toList());
}
public void mergeThreeStreams() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry");
Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC);
}
public void interleavingStreamsUsingRoundRobin() {
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy");
Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC);
}
public void takeWhileAndTakeUntilStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
Stream<Integer> finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
}
public void skipWhileAndSkipUntilStream() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4);
Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4);
}
public void unfoldStream() {
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
}
public void windowedStream() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2)
.collect(toList());
List<List<Integer>> windowsWithSkipIndex = StreamUtils
.windowed(integerStream, 3, 2)
.collect(toList());
List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils
.windowed(integerStream, 2, 2, true)
.collect(toList());
}
public void groupRunsStreams() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils
.groupRuns(integerStream)
.collect(toList());
}
public void aggreagateOnBiElementPredicate() {
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.basic;
import java.util.List;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubBasicApi {
/**
* List GitHub repositories of user
* @param user GitHub Account
* @return GitHub repositories
*/
@GET("users/{user}/repos")
Call<List<Repository>> listRepos(@Path("user") String user);
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
* @param repo GitHub Repository
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Call<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
}
@@ -0,0 +1,14 @@
package com.baeldung.retrofit.basic;
import java.io.IOException;
import java.util.List;
public class GitHubBasicApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
List<String> topContributors = new GitHubBasicService()
.getTopContributors(userName);
topContributors.forEach(System.out::println);
}
}
@@ -0,0 +1,60 @@
package com.baeldung.retrofit.basic;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GitHubBasicService {
private GitHubBasicApi gitHubApi;
GitHubBasicService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubBasicApi.class);
}
List<String> getTopContributors(String userName) throws IOException {
List<Repository> repos = gitHubApi
.listRepos(userName)
.execute()
.body();
repos = repos != null ? repos : Collections.emptyList();
return repos.stream()
.flatMap(repo -> getContributors(userName, repo))
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct()
.sorted()
.collect(Collectors.toList());
}
private Stream<Contributor> getContributors(String userName, Repository repo) {
List<Contributor> contributors = null;
try {
contributors = gitHubApi
.listRepoContributors(userName, repo.getName())
.execute()
.body();
} catch (IOException e) {
e.printStackTrace();
}
contributors = contributors != null ? contributors : Collections.emptyList();
return contributors.stream()
.filter(c -> c.getContributions() > 100);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.retrofit.models;
import com.google.gson.annotations.SerializedName;
public class Contributor {
@SerializedName("login")
private String name;
private Integer contributions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getContributions() {
return contributions;
}
public void setContributions(Integer contributions) {
this.contributions = contributions;
}
@Override
public String toString() {
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
}
}
@@ -0,0 +1,27 @@
package com.baeldung.retrofit.models;
public class Repository {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Repository [name=" + name + ", description=" + description + "]";
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.rx;
import java.util.List;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
public interface GitHubRxApi {
/**
* List GitHub repositories of user
* @param user GitHub Account
* @return GitHub repositories
*/
@GET("users/{user}/repos")
Observable<List<Repository>> listRepos(@Path("user") String user);
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
* @param repo GitHub Repository
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Observable<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
}
@@ -0,0 +1,12 @@
package com.baeldung.retrofit.rx;
import java.io.IOException;
public class GitHubRxApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
new GitHubRxService().getTopContributors(userName)
.subscribe(System.out::println);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.retrofit.rx;
import com.baeldung.retrofit.models.Contributor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
class GitHubRxService {
private GitHubRxApi gitHubApi;
GitHubRxService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubRxApi.class);
}
Observable<String> getTopContributors(String userName) {
return gitHubApi.listRepos(userName)
.flatMapIterable(x -> x)
.flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName()))
.flatMapIterable(x -> x)
.filter(c -> c.getContributions() > 100)
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct();
}
}
@@ -0,0 +1,58 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/";
private static Retrofit.Builder builder
= new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient
= new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging
= new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
httpClient.addInterceptor(logging);
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, final String token) {
if (token != null) {
httpClient.interceptors().clear();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}
});
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Main {
public static void main(String[] args) {
//Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
UserService service = retrofit.create(UserService.class);
//Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class);
Call<User> callSync = service.getUser("eugenp");
Call<User> callAsync = service.getUser("eugenp");
try {
Response<User> response = callSync.execute();
User user = response.body();
System.out.println(user);
} catch (IOException ex) {
}
// Execute the call asynchronously. Get a positive or negative callback.
callAsync.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
System.out.println(user);
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
System.out.println(throwable);
}
});
}
}
@@ -0,0 +1,65 @@
package com.baeldung.retrofitguide;
public class User {
private String login;
private long id;
private String url;
private String company;
private String blog;
private String email;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}
@@ -0,0 +1,17 @@
package com.baeldung.retrofitguide;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface UserService {
@GET("/users")
public Call<List<User>> getUsers(@Query("per_page") int per_page, @Query("page") int page);
@GET("/users/{username}")
public Call<User> getUser(@Path("username") String username);
}
@@ -0,0 +1,56 @@
/*
* 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());
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"main": {
"title" : "INTRODUCTION TO YARG",
"name" : "Baeldung",
"content" : "This is the content of the letter, can be anything we like."
}
}
Binary file not shown.
@@ -1,85 +1,111 @@
package com.baeldung.commons.collections4;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.CollectionBag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;
import org.junit.Assert;
import org.junit.Before;
import org.apache.commons.collections4.SortedBag;
import org.apache.commons.collections4.bag.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class BagTests {
Bag<String> baseBag;
TreeBag<String> treeBag;
@Before
public void before() {
baseBag = new HashBag<String>();
treeBag = new TreeBag<String>();
treeBag = new TreeBag<String>();
}
@Test
public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
baseBag.remove("lemon");
Assert.assertEquals(3, baseBag.size());
Assert.assertFalse(baseBag.contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertFalse(baseBag.containsAll(containList));
}
@Test
public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
CollectionBag<String> baseCollectionBag = new CollectionBag<String>(
baseBag);
baseCollectionBag.remove("lemon");
Assert.assertEquals(8, baseCollectionBag.size());
Assert.assertTrue(baseCollectionBag.contains("lemon"));
baseCollectionBag.remove("lemon",1);
Assert.assertEquals(7, baseCollectionBag.size());
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertTrue(baseBag.containsAll(containList));
}
@Test
public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() {
treeBag.add("banana", 8);
treeBag.add("apple", 2);
treeBag.add("lime");
Assert.assertEquals(11, treeBag.size());
Assert.assertEquals("apple", treeBag.first());
Assert.assertEquals("lime", treeBag.last());
treeBag.remove("apple");
Assert.assertEquals(9, treeBag.size());
Assert.assertEquals("banana", treeBag.first());
}
@Test
public void givenMultipleCopies_whenAdded_theCountIsKept() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
assertThat(bag.getCount(1), equalTo(2));
}
@Test
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
Collection<Integer> collection = new ArrayList<>();
// Collection contract defines that add() should return true
assertThat(collection.add(9), is(true));
// Even when element is already in the collection
collection.add(1);
assertThat(collection.add(1), is(true));
Bag<Integer> bag = new HashBag<>();
// Bag returns true on adding a new element
assertThat(bag.add(9), is(true));
bag.add(1);
// But breaks the contract with false when it has to increment the count
assertThat(bag.add(1), is(not(true)));
}
@Test
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
bag.add(1);
// This time the behavior is compliant to the Java Collection
assertThat(bag.add(1), is((true)));
}
@Test
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
Bag<Integer> bag = new HashBag<>();
// Adding 1 for 5 times
bag.add(1, 5);
assertThat(bag.getCount(1), equalTo(5));
}
@Test
public void givenMultipleCopies_whenRemove_allAreRemoved() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
// From 3 we delete 1, 2 remain
bag.remove(3, 1);
assertThat(bag.getCount(3), equalTo(2));
// From 2 we delete all
bag.remove(1);
assertThat(bag.getCount(1), equalTo(0));
}
@Test
public void givenTree_whenDuplicateElementsAdded_thenSort() {
TreeBag<Integer> bag = new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
@Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
SortedBag<Integer> bag = CollectionSortedBag
.collectionSortedBag(new TreeBag<>());
bag.add(1);
assertThat(bag.add(1), is((true)));
}
@Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag
.synchronizedSortedBag(new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
}
@@ -0,0 +1,151 @@
package com.baeldung.commons.io;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.PathFileComparator;
import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
public class CommonsIOUnitTest {
@Test
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData()
throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
File file = FileUtils.getFile(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File tempDir = FileUtils.getTempDirectory();
FileUtils.copyFileToDirectory(file, tempDir);
File newTempFile = FileUtils.getFile(tempDir, file.getName());
String data = FileUtils.readFileToString(newTempFile,
Charset.defaultCharset());
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void whenUsingFileNameUtils_thenshowdifferentFileOperations()
throws IOException {
String path = getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath();
String fullPath = FilenameUtils.getFullPath(path);
String extension = FilenameUtils.getExtension(path);
String baseName = FilenameUtils.getBaseName(path);
System.out.println("full path" + fullPath);
System.out.println("Extension" + extension);
System.out.println("Base name" + baseName);
}
@Test
public void whenUsingFileSystemUtils_thenDriveFreeSpace()
throws IOException {
long freeSpace = FileSystemUtils.freeSpaceKb("/");
}
@SuppressWarnings("resource")
@Test
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams()
throws IOException {
final String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
Assert.assertEquals(str, String.valueOf(outputStream1));
Assert.assertEquals(str, String.valueOf(outputStream2));
}
@Test
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt()
throws IOException {
final String testFile = "fileTest.txt";
String path = getClass().getClassLoader()
.getResource(testFile)
.getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
String[] possibleNames = { "NotThisOne", testFile };
Assert.assertEquals(testFile,
dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
}
@Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt()
throws IOException {
String path = getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
Assert.assertEquals("sample.txt",
dir.list(new AndFileFilter(
new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
new SuffixFileFilter("txt")))[0]);
}
@Test
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt()
throws IOException {
PathFileComparator pathFileComparator = new PathFileComparator(
IOCase.INSENSITIVE);
String path = FilenameUtils.getFullPath(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File dir = new File(path);
File[] files = dir.listFiles();
pathFileComparator.sort(files);
Assert.assertEquals("aaa.txt", files[0].getName());
}
@Test
public void whenSizeFileComparator_thenLargerFile()
throws IOException {
SizeFileComparator sizeFileComparator = new SizeFileComparator();
File largerFile = FileUtils.getFile(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File smallerFile = FileUtils.getFile(getClass().getClassLoader()
.getResource("sample.txt")
.getPath());
int i = sizeFileComparator.compare(largerFile, smallerFile);
Assert.assertTrue(i > 0);
}
}
@@ -1,6 +1,7 @@
package com.baeldung.commons.lang3;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
@@ -12,12 +13,14 @@ import java.beans.PropertyChangeListener;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.lang3.ArchUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.arch.Processor;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.apache.commons.lang3.event.EventUtils;
@@ -97,22 +100,37 @@ public class Lang3UtilsTest {
public void testAddEventListenerThrowsException() {
final ExceptionEventSource src = new ExceptionEventSource();
try {
EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent e) {
// Do nothing!
}
});
EventUtils.addEventListener(src, PropertyChangeListener.class, (PropertyChangeEvent e) -> {
/* Change event*/});
fail("Add method should have thrown an exception, so method should fail.");
} catch (final RuntimeException e) {
}
}
@Test
public void ConcurrentExceptionSample() throws ConcurrentException {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals("Wrong error", err, e);
}
}
public static class ExceptionEventSource {
public void addPropertyChangeListener(final PropertyChangeListener listener) {
throw new RuntimeException();
}
}
@Test
public void testLazyInitializer() throws Exception {
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
SampleObject sampleObjectOne = sampleLazyInitializer.get();
SampleObject sampleObjectTwo = sampleLazyInitializer.get();
assertEquals(sampleObjectOne, sampleObjectTwo);
}
}
@@ -0,0 +1,71 @@
package com.baeldung.date;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class DateDiffUnitTest {
@Test
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date firstDate = sdf.parse("06/24/2017");
Date secondDate = sdf.parse("06/30/2017");
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime sixMinutesBehind = now.minusMinutes(6);
Duration duration = Duration.between(now, sixMinutesBehind);
long diff = Math.abs(duration.toMinutes());
assertEquals(diff, 6);
}
@Test
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
long diff = Math.abs(period.getDays());
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJodaTime_whenDifferentiating_thenWeGetSix() {
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
long diff = Math.abs(period.getDays());
}
@Test
public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() {
hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault());
hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6);
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
assertEquals(diff, 6);
}
}
@@ -0,0 +1,79 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import fj.F;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
List<Boolean> evenListFalseResult = List.list(true, false, false, true);
assertEquals(evenList.equals(evenListTrueResult), true);
assertEquals(evenList.equals(evenListFalseResult), false);
}
@Test
public void mapList_givenIntList_returnResult() {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
List<Integer> falseResultList = List.list(15, 504, 105, 106);
assertEquals(fList.equals(resultList), true);
assertEquals(fList.equals(falseResultList), false);
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(Integers.even);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
assertEquals(isExist, true);
assertEquals(isExist2, false);
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
assertEquals(result1, Option.none());
assertEquals(result2, Option.some(102));
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
assertEquals(sum, 260);
}
}
@@ -1,27 +0,0 @@
package com.baeldung.geotools;
import static org.junit.Assert.assertNotNull;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
public class GeoToolsUnitTestTest {
@Test
public void givenFeatureType_whenAddLocations_returnFeatureCollection() {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
SimpleFeatureType CITY = ShapeFile.createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
ShapeFile.addLocations(featureBuilder, collection);
assertNotNull(collection);
}
}
@@ -0,0 +1,141 @@
package com.baeldung.java.io;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.FileSystemUtils;
public class JavaDirectoryDeleteUnitTest {
private static Path TEMP_DIRECTORY;
private static final String DIRECTORY_NAME = "toBeDeleted";
private static final List<String> ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6");
@BeforeClass
public static void initializeTempDirectory() throws IOException {
TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit");
}
@AfterClass
public static void cleanTempDirectory() throws IOException {
FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile());
}
@Before
public void setupDirectory() throws IOException {
Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME));
// Create a directory structure
Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2));
Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4));
Files.createDirectories(tempPathForEachTest.resolve("Empty"));
Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty"));
Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5));
Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3));
aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory"));
Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5));
Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2));
}
@After
public void checkAndCleanupIfRequired() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
if (Files.exists(pathToBeDeleted)) {
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
@Test
public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = deleteDirectory(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
}
@@ -0,0 +1,44 @@
package com.baeldung.jcache;
import static org.junit.Assert.assertEquals;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CacheLoaderTest {
private static final String CACHE_NAME = "SimpleCache";
private Cache<Integer, String> cache;
@Before
public void setup() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true)
.setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
this.cache = cacheManager.createCache("SimpleCache", config);
}
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test
public void whenReadingFromStorage_thenCorrect() {
for (int i = 1; i < 4; i++) {
String value = cache.get(i);
assertEquals("fromCache" + i, value);
}
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jcache;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class EntryProcessorTest {
private static final String CACHE_NAME = "MyCache";
private Cache<String, String> cache;
@Before
public void instantiateCache() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, String> config = new MutableConfiguration<>();
this.cache = cacheManager.createCache(CACHE_NAME, config);
this.cache.put("key", "value");
}
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test
public void whenModifyValue_thenCorrect() {
this.cache.invoke("key", new SimpleEntryProcessor());
assertEquals("value - modified", cache.get("key"));
}
}
@@ -0,0 +1,56 @@
package com.baeldung.jcache;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class EventListenerTest {
private static final String CACHE_NAME = "MyCache";
private Cache<String, String> cache;
private SimpleCacheEntryListener listener;
private MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
@Before
public void setup() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();
this.cache = cacheManager.createCache("MyCache", config);
this.listener = new SimpleCacheEntryListener();
}
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test
public void whenRunEvent_thenCorrect() throws InterruptedException {
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder
.factoryOf(this.listener), null, false, true);
this.cache.registerCacheEntryListener(this.listenerConfiguration);
assertEquals(false, this.listener.getCreated());
this.cache.put("key", "value");
assertEquals(true, this.listener.getCreated());
assertEquals(false, this.listener.getUpdated());
this.cache.put("key", "newValue");
assertEquals(true, this.listener.getUpdated());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.jcache;
import org.junit.Test;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class JCacheTest {
@Test
public void instantiateCache() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, String> config = new MutableConfiguration<>();
Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
cache.put("key1", "value1");
cache.put("key2", "value2");
assertEquals("value1", cache.get("key1"));
assertEquals("value2", cache.get("key2"));
cacheManager.close();
}
}
@@ -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 AppTest {
@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 MBassadorAsyncDispatchTest {
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,47 @@
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 MBassadorAsyncInvocationTest {
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 MBassadorBasicTest {
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,91 @@
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.*;
public class MBassadorConfigurationTest 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 MBassadorFilterTest {
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 MBassadorHierarchyTest {
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,86 @@
package com.baeldung.measurement;
import javax.measure.Quantity;
import javax.measure.quantity.Area;
import javax.measure.quantity.Length;
import javax.measure.quantity.Pressure;
import javax.measure.quantity.Volume;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.measurement.WaterTank;
import tec.units.ri.format.SimpleUnitFormat;
import tec.units.ri.quantity.Quantities;
import tec.units.ri.unit.MetricPrefix;
import static tec.units.ri.unit.Units.*;
public class WaterTankTests {
@Test
public void givenQuantity_whenGetUnitAndConvertValue_thenSuccess() {
WaterTank waterTank = new WaterTank();
waterTank.setCapacityMeasure(Quantities.getQuantity(9.2, LITRE));
assertEquals(LITRE, waterTank.getCapacityMeasure().getUnit());
Quantity<Volume> waterCapacity = waterTank.getCapacityMeasure();
double volumeInLitre = waterCapacity.getValue().doubleValue();
assertEquals(9.2, volumeInLitre, 0.0f);
double volumeInMilliLitre = waterCapacity.to(MetricPrefix.MILLI(LITRE)).getValue().doubleValue();
assertEquals(9200.0, volumeInMilliLitre, 0.0f);
// compilation error
// volumeInMilliLitre = waterCapacity.to(MetricPrefix.MILLI(KILOGRAM));
Unit<Length> Kilometer = MetricPrefix.KILO(METRE);
// compilation error
// Unit<Length> Centimeter = MetricPrefix.CENTI(LITRE);
}
@Test
public void givenUnit_whenAlternateUnit_ThenGetAlternateUnit() {
Unit<Pressure> PASCAL = NEWTON.divide(METRE.pow(2)).alternate("Pa").asType(Pressure.class);
assertTrue(SimpleUnitFormat.getInstance().parse("Pa").equals(PASCAL));
}
@Test
public void givenUnit_whenProduct_ThenGetProductUnit() {
Unit<Area> squareMetre = METRE.multiply(METRE).asType(Area.class);
Quantity<Length> line = Quantities.getQuantity(2, METRE);
assertEquals(line.multiply(line).getUnit(), squareMetre);
}
@Test
public void givenMeters_whenConvertToKilometer_ThenConverted() {
double distanceInMeters = 50.0;
UnitConverter metreToKilometre = METRE.getConverterTo(MetricPrefix.KILO(METRE));
double distanceInKilometers = metreToKilometre.convert(distanceInMeters);
assertEquals(0.05, distanceInKilometers, 0.00f);
}
@Test
public void givenSymbol_WhenCompareToSystemUnit_ThenSuccess() {
assertTrue(SimpleUnitFormat.getInstance().parse("kW").equals(MetricPrefix.KILO(WATT)));
assertTrue(SimpleUnitFormat.getInstance().parse("ms").equals(SECOND.divide(1000)));
}
@Test
public void givenUnits_WhenAdd_ThenSuccess() {
Quantity<Length> total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, METRE));
assertEquals(total.getValue().intValue(), 5);
// compilation error
// Quantity<Length> total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, LITRE));
Quantity<Length> totalKm = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, MetricPrefix.KILO(METRE)));
assertEquals(totalKm.getValue().intValue(), 3002);
}
}
@@ -0,0 +1,50 @@
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,66 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.collectors.CollectorUtils;
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
import org.junit.Test;
import java.util.Optional;
import java.util.stream.Stream;
import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy;
import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class CollectorUtilsTests {
@Test
public void givenIntegerStream_whenCollectOnMaxByProjection_shouldReturnOptionalMaxValue() {
Stream<String> integerStream = Stream.of("a", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(maxBy(String::length));
assertThat(max.get(), is("ccc"));
}
@Test
public void givenIntegerStream_whenCollectOnMinByProjection_shouldReturnOptionalMinValue() {
Stream<String> integerStream = Stream.of("abc", "bb", "ccc", "1");
Optional<String> max = integerStream.collect(minBy(String::length));
assertThat(max.get(), is("1"));
}
@Test
public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() {
assertThat(Stream
.empty()
.collect(CollectorUtils.unique()), equalTo(Optional.empty()));
}
@Test
public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() {
assertThat(Stream
.of(1, 2, 3)
.filter(i -> i > 2)
.collect(CollectorUtils.unique()), equalTo(Optional.of(3)));
}
@Test
public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() {
assertThat(Stream
.of(1, 2, 3)
.filter(i -> i > 2)
.collect(CollectorUtils.uniqueNullable()), equalTo(3));
}
@Test(expected = NonUniqueValueException.class)
public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() {
Stream
.of(1, 2, 3)
.filter(i -> i > 1)
.collect(CollectorUtils.unique());
}
}
@@ -0,0 +1,202 @@
package com.baeldung.protonpack;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.selectors.Selectors;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class StreamUtilsTests {
@Test
public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils
.zipWithIndex(source)
.collect(Collectors.toList());
assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz")));
}
@Test
public void givenTwoStreams_whenZip_shouldReturnZippedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
.collect(Collectors.toList());
assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot"));
}
@Test
public void givenThreeStreams_whenZip_shouldReturnZippedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
.collect(Collectors.toList());
assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot"));
}
@Test
//givenThreeStreams_whenMerge_shouldReturnMergedStream
public void givenThreeStreams_whenMerge_shouldReturnMergedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry");
Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC);
assertThat(merged.collect(toList()), contains(asList("A", "apple", "fritter"), asList("B", "banana", "split"), asList("C", "carrot", "cake"), asList("date", "roll"), asList("pastry")));
}
@Test
//givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream
public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() {
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy");
Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC);
assertThat(interleaved.collect(Collectors.toList()), contains("Peter", "A", "foo", "Paul", "B", "bar", "Mary", "C", "baz", "D", "xyzzy", "E"));
}
@Test
//givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10
public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
assertThat(finiteInts.collect(Collectors.toList()), hasSize(10));
}
@Test
public void givenInfiniteStream_whenTakeUntil10_shouldReturnStreamUpto10() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteInts = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
assertThat(finiteInts.collect(Collectors.toList()), hasSize(11));
}
@Test
public void givenIntegerStreamOfTen_whenSkipWhileLessThanFour_shouldReturnStreamFromFourToTen() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skipped = StreamUtils.skipWhile(ints, i -> i < 4);
List<Integer> collected = skipped.collect(Collectors.toList());
assertThat(collected, contains(4, 5, 6, 7, 8, 9, 10));
}
@Test
public void givenIntegerStreamOfTen_whenSkipUntilFour_shouldReturnStreamFromFiveToTen() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skipped = StreamUtils.skipUntil(ints, i -> i > 4);
List<Integer> collected = skipped.collect(Collectors.toList());
assertThat(collected, contains(5, 6, 7, 8, 9, 10));
}
@Test
public void givenSeedValue_withUnfold_shouldReturnStreamAccordingToGeneratorMethod() {
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
assertThat(unfolded.collect(Collectors.toList()), contains(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Test
public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils
.groupRuns(integerStream)
.collect(toList());
assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5)));
}
@Test
public void givenAStream_whenAggregate_shouldReturnAggregatedStreamOnTheBasisOfBiFunction() {
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
assertThat(aggregated.collect(toList()), contains(asList("a1"), asList("b1", "b2"), asList("c1")));
}
@Test
public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2)
.collect(toList());
assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5)));
}
@Test
//givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 3, 2)
.collect(toList());
assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5)));
}
@Test
public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() {
ArrayList<Integer> ints = new ArrayList<>();
ints
.stream()
.collect(maxBy((a, b) -> a
.toString()
.compareTo(b.toString())));
List<List<Integer>> windows = StreamUtils
.windowed(ints.stream(), 2)
.collect(toList());
assertThat(windows, iterableWithSize(0));
}
@Test
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2, 2, true)
.collect(toList());
assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5)));
}
@Test
public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() {
LongStream indices = StreamUtils
.indices()
.limit(500);
assertThat(indices.count(), equalTo(500));
}
}
@@ -0,0 +1,65 @@
package com.baeldung.retrofit.basic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.retrofit.basic.GitHubBasicApi;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubBasicApiLiveTest {
GitHubBasicApi gitHub;
@Before
public void init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
gitHub = retrofit.create(GitHubBasicApi.class);
}
@Test
public void whenListRepos_thenExpectReposThatContainTutorials() {
try {
List<Repository> repos = gitHub
.listRepos("eugenp")
.execute()
.body();
assertThat(repos)
.isNotEmpty()
.extracting(Repository::getName).contains("tutorials");
} catch (IOException e) {
fail("Can not communicate with GitHub API");
}
}
@Test
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
try {
List<Contributor> contributors = gitHub
.listRepoContributors("eugenp", "tutorials")
.execute()
.body();
assertThat(contributors)
.isNotEmpty()
.extracting(Contributor::getName).contains("eugenp");
} catch (IOException e) {
fail("Can not communicate with GitHub API");
}
}
}
@@ -0,0 +1,53 @@
package com.baeldung.retrofit.rx;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import com.baeldung.retrofit.rx.GitHubRxApi;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubRxApiTest {
GitHubRxApi gitHub;
@Before
public void init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
gitHub = retrofit.create(GitHubRxApi.class);
}
@Test
public void whenListRepos_thenExpectReposThatContainTutorials() {
gitHub
.listRepos("eugenp")
.subscribe( repos -> {
assertThat(repos)
.isNotEmpty()
.extracting(Repository::getName).contains("tutorials");
});
}
@Test
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
gitHub
.listRepoContributors("eugenp", "tutorials")
.subscribe(contributors -> {
assertThat(contributors)
.isNotEmpty()
.extracting(Contributor::getName).contains("eugenp");
});
}
}
+1
View File
@@ -0,0 +1 @@
Hello World from ABC.txt!!!
+1
View File
@@ -0,0 +1 @@
Hello World from aaa.txt!!!
@@ -0,0 +1 @@
Hello World from fileTest.txt!!!
+2
View File
@@ -0,0 +1,2 @@
line 1
a second line