Fix conflicts in librarie/pom.xml
This commit is contained in:
+2
-2
@@ -27,10 +27,10 @@
|
||||
- [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)
|
||||
|
||||
|
||||
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.
|
||||
|
||||
+62
-9
@@ -105,7 +105,6 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- /Neuroph -->
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
@@ -137,6 +136,11 @@
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tec.units</groupId>
|
||||
<artifactId>unit-ri</artifactId>
|
||||
<version>1.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons.collections.version}</version>
|
||||
@@ -190,7 +194,7 @@
|
||||
<dependency>
|
||||
<groupId>io.specto</groupId>
|
||||
<artifactId>hoverfly-java</artifactId>
|
||||
<version>0.8.0</version>
|
||||
<version>0.8.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
@@ -295,22 +299,22 @@
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>javax.jdo</artifactId>
|
||||
<version>3.2.0-m6</version>
|
||||
<version>3.2.0-m7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-core</artifactId>
|
||||
<version>5.1.0-m1</version>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-api-jdo</artifactId>
|
||||
<version>5.1.0-m1</version>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-rdbms</artifactId>
|
||||
<version>5.1.0-m1</version>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
@@ -364,7 +368,7 @@
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>2.6.1</version>
|
||||
<version>2.6.3</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -483,7 +487,7 @@
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-shapefile</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
@@ -498,6 +502,22 @@
|
||||
<artifactId>gt-swing</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
</dependency>
|
||||
<!-- Retrofit -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-gson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
@@ -514,6 +534,26 @@
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>${hirondelle-date4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.haulmont.yarg</groupId>
|
||||
<artifactId>yarg</artifactId>
|
||||
<version>2.0.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.engio</groupId>
|
||||
<artifactId>mbassador</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jdeferred</groupId>
|
||||
<artifactId>jdeferred-core</artifactId>
|
||||
<version>1.2.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
@@ -534,6 +574,14 @@
|
||||
<name>OpenGeo Maven Repository</name>
|
||||
<url>http://repo.opengeo.org</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
<id>bintray-cuba-platform-main</id>
|
||||
<name>bintray</name>
|
||||
<url>http://dl.bintray.com/cuba-platform/main</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
@@ -565,7 +613,7 @@
|
||||
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
|
||||
<serenity.plugin.version>1.4.0</serenity.plugin.version>
|
||||
<jUnitParams.version>1.1.0</jUnitParams.version>
|
||||
<netty.version>4.1.10.Final</netty.version>
|
||||
<netty.version>4.1.15.Final</netty.version>
|
||||
<commons.collections.version>4.1</commons.collections.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<java-lsh.version>0.10</java-lsh.version>
|
||||
@@ -582,5 +630,10 @@
|
||||
<geotools.version>15.2</geotools.version>
|
||||
<joda-time.version>2.9.9</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<retrofit.version>2.3.0</retrofit.version>
|
||||
<joda-time.version>2.9.9</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<protonpack.version>1.14</protonpack.version>
|
||||
<unit-ri.version>1.0.3</unit-ri.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.commons.io;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class FileMonitor {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File folder = FileUtils.getTempDirectory();
|
||||
startFileMonitor(folder);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param folder
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void startFileMonitor(File folder) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(folder);
|
||||
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
|
||||
|
||||
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
|
||||
|
||||
@Override
|
||||
public void onFileCreate(File file) {
|
||||
// on create action
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileDelete(File file) {
|
||||
// on delete action
|
||||
}
|
||||
};
|
||||
|
||||
observer.addListener(fal);
|
||||
monitor.addObserver(observer);
|
||||
monitor.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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.
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -28,17 +28,6 @@ public class DateDiffUnitTest {
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDate now = LocalDate.now();
|
||||
LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
Duration duration = Duration.between(now, sixDaysBehind);
|
||||
long diff = Math.abs(duration.toDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
@@ -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 @@
|
||||
Hello World from fileTest.txt!!!
|
||||
@@ -0,0 +1,2 @@
|
||||
line 1
|
||||
a second line
|
||||
Reference in New Issue
Block a user