Merge branch 'master' into master
This commit is contained in:
+4
-3
@@ -23,14 +23,15 @@
|
||||
- [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave)
|
||||
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
|
||||
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
|
||||
- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text)
|
||||
- [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 NoException](http://www.baeldung.com/no-exception)
|
||||
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+667
-530
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ import net.openhft.chronicle.ExcerptAppender;
|
||||
|
||||
public class ChronicleQueue {
|
||||
|
||||
public static void writeToQueue(
|
||||
static void writeToQueue(
|
||||
Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
|
||||
throws IOException {
|
||||
ExcerptAppender appender = chronicle.createAppender();
|
||||
|
||||
@@ -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,60 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
|
||||
public class BuilderMethods {
|
||||
|
||||
private final int intValue;
|
||||
private final String strSample;
|
||||
|
||||
public BuilderMethods(final int newId, final String newName) {
|
||||
this.intValue = newId;
|
||||
this.strSample = newName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.intValue;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.strSample;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return new HashCodeBuilder().append(this.intValue)
|
||||
.append(this.strSample)
|
||||
.toHashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof BuilderMethods == false) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
final BuilderMethods otherObject = (BuilderMethods) obj;
|
||||
|
||||
return new EqualsBuilder().append(this.intValue, otherObject.intValue)
|
||||
.append(this.strSample, otherObject.strSample)
|
||||
.isEquals();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this).append("INTVALUE", this.intValue)
|
||||
.append("STRINGVALUE", this.strSample)
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static void main(final String[] arguments) {
|
||||
final BuilderMethods simple1 = new BuilderMethods(1, "The First One");
|
||||
System.out.println(simple1.getName());
|
||||
System.out.println(simple1.hashCode());
|
||||
System.out.println(simple1.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class DistinctWithJavaFunction {
|
||||
|
||||
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
|
||||
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
|
||||
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
public class Person {
|
||||
int age;
|
||||
String name;
|
||||
String email;
|
||||
|
||||
public Person(int age, String name, String email) {
|
||||
super();
|
||||
this.age = age;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Person [age=");
|
||||
builder.append(age);
|
||||
builder.append(", name=");
|
||||
builder.append(name);
|
||||
builder.append(", email=");
|
||||
builder.append(email);
|
||||
builder.append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Person other = (Person) obj;
|
||||
if (email == null) {
|
||||
if (other.email != null)
|
||||
return false;
|
||||
} else if (!email.equals(other.email))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
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,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");
|
||||
}
|
||||
}
|
||||
+24
@@ -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,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,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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.
+7
-4
@@ -11,10 +11,13 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.awaitility.Awaitility.fieldIn;
|
||||
import static org.awaitility.Awaitility.given;
|
||||
import static org.awaitility.Awaitility.setDefaultPollDelay;
|
||||
import static org.awaitility.Awaitility.setDefaultPollInterval;
|
||||
import static org.awaitility.Awaitility.setDefaultTimeout;
|
||||
import static org.awaitility.proxy.AwaitilityClassProxy.to;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
public class AsyncServiceUnitTest {
|
||||
public class AsyncServiceLongRunningUnitTest {
|
||||
private AsyncService asyncService;
|
||||
|
||||
@Before
|
||||
@@ -41,9 +44,9 @@ public class AsyncServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() {
|
||||
Awaitility.setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
|
||||
Awaitility.setDefaultPollDelay(Duration.ZERO);
|
||||
Awaitility.setDefaultTimeout(Duration.ONE_MINUTE);
|
||||
setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
|
||||
setDefaultPollDelay(Duration.ZERO);
|
||||
setDefaultTimeout(Duration.ONE_MINUTE);
|
||||
|
||||
asyncService.initialize();
|
||||
await().until(asyncService::isInitialized);
|
||||
+1
-1
@@ -13,7 +13,7 @@ import net.openhft.chronicle.ChronicleQueueBuilder;
|
||||
import net.openhft.chronicle.ExcerptTailer;
|
||||
import net.openhft.chronicle.tools.ChronicleTools;
|
||||
|
||||
public class ChronicleQueueTest {
|
||||
public class ChronicleQueueIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
|
||||
@@ -0,0 +1,85 @@
|
||||
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.junit.Test;
|
||||
|
||||
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());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.commons.csv;
|
||||
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVPrinter;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CSVReaderWriterTest {
|
||||
|
||||
public static final Map<String, String> AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
|
||||
{
|
||||
put("Dan Simmons", "Hyperion");
|
||||
put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy");
|
||||
}
|
||||
});
|
||||
public static final String[] HEADERS = { "author", "title" };
|
||||
public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy";
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
|
||||
Reader in = new FileReader("src/test/resources/book.csv");
|
||||
Iterable<CSVRecord> records = CSVFormat.DEFAULT
|
||||
.withHeader(HEADERS)
|
||||
.withFirstRecordAsHeader()
|
||||
.parse(in);
|
||||
for (CSVRecord record : records) {
|
||||
String author = record.get("author");
|
||||
String title = record.get("title");
|
||||
assertEquals(AUTHOR_BOOK_MAP.get(author), title);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException {
|
||||
StringWriter sw = new StringWriter();
|
||||
try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) {
|
||||
AUTHOR_BOOK_MAP.forEach((author, title) -> {
|
||||
try {
|
||||
printer.printRecord(author, title);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
assertEquals(EXPECTED_FILESTREAM, sw
|
||||
.toString()
|
||||
.trim());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.beans.PropertyChangeEvent;
|
||||
import java.beans.PropertyChangeListener;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Locale;
|
||||
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.ConcurrentRuntimeException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
|
||||
import org.apache.commons.lang3.event.EventUtils;
|
||||
import org.apache.commons.lang3.reflect.FieldUtils;
|
||||
import org.apache.commons.lang3.time.FastDateFormat;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Lang3UtilsTest {
|
||||
|
||||
@Test
|
||||
public void test_to_Boolean_fromString() {
|
||||
assertFalse(BooleanUtils.toBoolean("off"));
|
||||
assertTrue(BooleanUtils.toBoolean("true"));
|
||||
assertTrue(BooleanUtils.toBoolean("tRue"));
|
||||
assertFalse(BooleanUtils.toBoolean("no"));
|
||||
assertFalse(BooleanUtils.isTrue(Boolean.FALSE));
|
||||
assertFalse(BooleanUtils.isTrue(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserHome() {
|
||||
final File dir = SystemUtils.getUserHome();
|
||||
Assert.assertNotNull(dir);
|
||||
Assert.assertTrue(dir.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetJavaHome() {
|
||||
final File dir = SystemUtils.getJavaHome();
|
||||
Assert.assertNotNull(dir);
|
||||
Assert.assertTrue(dir.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessorArchType() {
|
||||
Processor processor = ArchUtils.getProcessor("x86");
|
||||
assertTrue(processor.is32Bit());
|
||||
assertFalse(processor.is64Bit());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessorArchType64Bit() {
|
||||
Processor processor = ArchUtils.getProcessor("x86_64");
|
||||
assertFalse(processor.is32Bit());
|
||||
assertTrue(processor.is64Bit());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testConcurrentRuntimeExceptionCauseError() {
|
||||
new ConcurrentRuntimeException("An error", new Error());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstantFuture_Integer() throws Exception {
|
||||
Future<Integer> test = ConcurrentUtils.constantFuture(5);
|
||||
assertTrue(test.isDone());
|
||||
assertSame(5, test.get());
|
||||
assertFalse(test.isCancelled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFieldUtilsGetAllFields() {
|
||||
final Field[] fieldsNumber = Number.class.getDeclaredFields();
|
||||
assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_getInstance_String_Locale() {
|
||||
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.US);
|
||||
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
|
||||
|
||||
assertNotSame(format1, format3);
|
||||
}
|
||||
|
||||
@Test
|
||||
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!
|
||||
}
|
||||
});
|
||||
fail("Add method should have thrown an exception, so method should fail.");
|
||||
} catch (final RuntimeException e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static class ExceptionEventSource {
|
||||
public void addPropertyChangeListener(final PropertyChangeListener listener) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.collections.impl.block.factory.HashingStrategies;
|
||||
import org.eclipse.collections.impl.utility.ListIterate;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithEclipseCollectionsUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithJavaFunctionUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = personList.stream()
|
||||
.filter(distinctByKey(p -> p.getName()))
|
||||
.collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = personList.stream()
|
||||
.filter(distinctByKey(p -> p.getAge()))
|
||||
.collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
|
||||
List<Person> personListFiltered = personList.stream()
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 5);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import one.util.streamex.StreamEx;
|
||||
|
||||
public class DistinctWithStreamexUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = StreamEx.of(personList)
|
||||
.distinct(Person::getName)
|
||||
.toList();
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = StreamEx.of(personList)
|
||||
.distinct(Person::getAge)
|
||||
.toList();
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithVavrUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
|
||||
.distinctBy(Person::getName)
|
||||
.toJavaList();
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
|
||||
.distinctBy(Person::getAge)
|
||||
.toJavaList();
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonDataGenerator {
|
||||
|
||||
public static List<Person> getPersonListWithFakeValues() {
|
||||
// @formatter:off
|
||||
return Arrays.asList(
|
||||
new Person(20, "Jhon", "jhon@test.com"),
|
||||
new Person(20, "Jhon", "jhon1@test.com"),
|
||||
new Person(20, "Jhon", "jhon2@test.com"),
|
||||
new Person(21, "Tom", "Tom@test.com"),
|
||||
new Person(21, "Mark", "Mark@test.com"),
|
||||
new Person(20, "Julia", "jhon@test.com"));
|
||||
// @formatter:on
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ import java.util.stream.LongStream;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
|
||||
public class HLLUnitTest {
|
||||
public class HLLLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
|
||||
@@ -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,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,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 maxByWithProjectionAndDefaultComparer() {
|
||||
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 minByWithProjectionAndDefaultComparer() {
|
||||
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 returnsEmptyForEmptyStream() {
|
||||
assertThat(Stream
|
||||
.empty()
|
||||
.collect(CollectorUtils.unique()), equalTo(Optional.empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsUniqueItem() {
|
||||
assertThat(Stream
|
||||
.of(1, 2, 3)
|
||||
.filter(i -> i > 2)
|
||||
.collect(CollectorUtils.unique()), equalTo(Optional.of(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsUniqueNullableItem() {
|
||||
assertThat(Stream
|
||||
.of(1, 2, 3)
|
||||
.filter(i -> i > 2)
|
||||
.collect(CollectorUtils.uniqueNullable()), equalTo(3));
|
||||
}
|
||||
|
||||
@Test(expected = NonUniqueValueException.class)
|
||||
public void throwsExceptionIfItemIsNotUnique() {
|
||||
Stream
|
||||
.of(1, 2, 3)
|
||||
.filter(i -> i > 1)
|
||||
.collect(CollectorUtils.unique());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
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 createInfiniteIndex() {
|
||||
LongStream indices = StreamUtils
|
||||
.indices()
|
||||
.limit(500);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipAStreamWithIndex() {
|
||||
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 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());
|
||||
|
||||
assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
|
||||
assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
|
||||
assertThat(merged.collect(toList()), contains(asList("A", "apple", "fritter"), asList("B", "banana", "split"), asList("C", "carrot", "cake"), asList("date", "roll"), asList("pastry")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundRobinInterleaving() {
|
||||
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
|
||||
public void takeWhileConditionIsMet() {
|
||||
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 takeUntilConditionIsNotMet() {
|
||||
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 skipWhileConditionMet() {
|
||||
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 skipUntilConditionMet() {
|
||||
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 unfoldUntilEmptyIsReturned() {
|
||||
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 groupRunsStreamTest() {
|
||||
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 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));
|
||||
assertThat(aggregated.collect(toList()), contains(asList("a1"), asList("b1", "b2"), asList("c1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void windowingOnList() {
|
||||
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
|
||||
public void windowingOnListTwoOverlap() {
|
||||
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 windowingOnEmptyList() {
|
||||
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 windowingOnListTwoOverlapAllowLesserSize() {
|
||||
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 windowingOnListOneOverlapAllowLesserSizeMultipleLesserWindows() {
|
||||
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
List<List<Integer>> windows = StreamUtils
|
||||
.windowed(integerStream, 3, 1, true)
|
||||
.collect(toList());
|
||||
|
||||
assertThat(windows, contains(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5), asList(5)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 GitHubBasicApiTest {
|
||||
|
||||
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");
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Hello World from ABC.txt!!!
|
||||
@@ -0,0 +1 @@
|
||||
Hello World from aaa.txt!!!
|
||||
@@ -0,0 +1,3 @@
|
||||
author,title
|
||||
Dan Simmons,Hyperion
|
||||
Douglas Adams,The Hitchhiker's Guide to the Galaxy
|
||||
|
@@ -0,0 +1 @@
|
||||
Hello World from fileTest.txt!!!
|
||||
@@ -0,0 +1,2 @@
|
||||
line 1
|
||||
a second line
|
||||
Reference in New Issue
Block a user