Merge branch 'master' into bael-16656

This commit is contained in:
Josh Cummings
2019-10-26 15:37:05 -06:00
committed by GitHub
parent db85c8f275
commit 0be2175c89
20539 changed files with 1643630 additions and 0 deletions
@@ -0,0 +1,32 @@
package com.baeldung.akka;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class FirstActor extends AbstractActor {
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
public static Props props() {
return Props.create(FirstActor.class);
}
@Override
public void preStart() {
log.info("Actor started");
}
@Override
public void postStop() {
log.info("Actor stopped");
}
// Messages will not be handled
@Override
public Receive createReceive() {
return receiveBuilder()
.build();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.akka;
import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class MyActor extends AbstractActor {
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
@Override
public void postStop() {
log.info("Stopping actor {}", this);
}
public Receive createReceive() {
return receiveBuilder()
.matchEquals("printit", p -> {
System.out.println("The address of this actor is: " + getSelf());
getSender().tell("Got Message", getSelf());
})
.build();
}
}
@@ -0,0 +1,45 @@
package com.baeldung.akka;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class PrinterActor extends AbstractActor {
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
public static Props props(String text) {
return Props.create(PrinterActor.class, text);
}
public static final class PrintFinalResult {
Integer totalNumberOfWords;
public PrintFinalResult(Integer totalNumberOfWords) {
this.totalNumberOfWords = totalNumberOfWords;
}
}
@Override
public void preStart() {
log.info("Starting PrinterActor {}", this);
}
@Override
public void postStop() {
log.info("Stopping PrinterActor {}", this);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(PrinterActor.PrintFinalResult.class,
r -> {
log.info("Received PrintFinalResult message from " + getSender());
log.info("The text has a total number of {} words", r.totalNumberOfWords);
})
.build();
}
}
@@ -0,0 +1,73 @@
package com.baeldung.akka;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static akka.pattern.PatternsCS.ask;
public class ReadingActor extends AbstractActor {
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
private String text;
public ReadingActor(String text) {
this.text = text;
}
public static Props props(String text) {
return Props.create(ReadingActor.class, text);
}
public static final class ReadLines {
}
@Override
public void preStart() {
log.info("Starting ReadingActor {}", this);
}
@Override
public void postStop() {
log.info("Stopping ReadingActor {}", this);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(ReadLines.class, r -> {
log.info("Received ReadLines message from " + getSender());
String[] lines = text.split("\n");
List<CompletableFuture> futures = new ArrayList<>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
ActorRef wordCounterActorRef = getContext().actorOf(Props.create(WordCounterActor.class), "word-counter-" + i);
CompletableFuture<Object> future =
ask(wordCounterActorRef, new WordCounterActor.CountWords(line), 1000).toCompletableFuture();
futures.add(future);
}
Integer totalNumberOfWords = futures.stream()
.map(CompletableFuture::join)
.mapToInt(n -> (Integer) n)
.sum();
ActorRef printerActorRef = getContext().actorOf(Props.create(PrinterActor.class), "Printer-Actor");
printerActorRef.forward(new PrinterActor.PrintFinalResult(totalNumberOfWords), getContext());
// printerActorRef.tell(new PrinterActor.PrintFinalResult(totalNumberOfWords), getSelf());
})
.build();
}
}
@@ -0,0 +1,55 @@
package com.baeldung.akka;
import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class WordCounterActor extends AbstractActor {
private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
public static final class CountWords {
String line;
public CountWords(String line) {
this.line = line;
}
}
@Override
public void preStart() {
log.info("Starting WordCounterActor {}", this);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(CountWords.class, r -> {
try {
log.info("Received CountWords message from " + getSender());
int numberOfWords = countWordsFromLine(r.line);
getSender().tell(numberOfWords, getSelf());
} catch (Exception ex) {
getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
throw ex;
}
})
.build();
}
private int countWordsFromLine(String line) throws Exception {
if (line == null) {
throw new IllegalArgumentException("The text to process can't be null!");
}
int numberOfWords = 0;
String[] words = line.split(" ");
for (String possibleWord : words) {
if (possibleWord.trim().length() > 0) {
numberOfWords++;
}
}
return numberOfWords;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.bytebuddy;
import net.bytebuddy.implementation.bind.annotation.BindingPriority;
public class Bar {
@BindingPriority(3)
public static String sayHelloBar() {
return "Holla in Bar!";
}
@BindingPriority(2)
public static String sayBar() {
return "bar";
}
public String bar() {
return Bar.class.getSimpleName() + " - Bar";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.bytebuddy;
public class Foo {
public String sayHelloFoo() {
return "Hello in Foo!";
}
}
@@ -0,0 +1,30 @@
package com.baeldung.caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class DataObject {
private final String data;
private static int objectCounter = 0;
private static final Logger log = LoggerFactory.getLogger(DataObject.class);
private DataObject(String data) {
this.data = data;
}
public String getData() {
return data;
}
@Override
public String toString() {
return "DataObject{" + "data='" + data + '\'' + '}';
}
public static DataObject get(String data) {
objectCounter++;
log.info("Init DataObject#{} with '{}'", objectCounter, data);
return new DataObject(data);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.cglib.mixin;
public class Class1 implements Interface1 {
@Override
public String first() {
return "first behaviour";
}
}
@@ -0,0 +1,8 @@
package com.baeldung.cglib.mixin;
public class Class2 implements Interface2 {
@Override
public String second() {
return "second behaviour";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.cglib.mixin;
public interface Interface1 {
String first();
}
@@ -0,0 +1,5 @@
package com.baeldung.cglib.mixin;
public interface Interface2 {
String second();
}
@@ -0,0 +1,4 @@
package com.baeldung.cglib.mixin;
public interface MixinInterface extends Interface1, Interface2 {
}
@@ -0,0 +1,11 @@
package com.baeldung.cglib.proxy;
public class PersonService {
public String sayHello(String name) {
return "Hello " + name;
}
public Integer lengthOfName(String name) {
return name.length();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.chronicle.queue;
import java.io.IOException;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ExcerptAppender;
public class ChronicleQueue {
static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException {
ExcerptAppender appender = chronicle.createAppender();
appender.startExcerpt();
appender.writeUTF(stringValue);
appender.writeInt(intValue);
appender.writeLong(longValue);
appender.writeDouble(doubleValue);
appender.finish();
appender.close();
}
}
@@ -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,19 @@
package com.baeldung.eclipsecollections;
import java.util.List;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
public class ConvertContainerToAnother {
@SuppressWarnings("rawtypes")
public static List convertToList() {
UnifiedSet<String> cars = new UnifiedSet<>();
cars.add("Toyota");
cars.add("Mercedes");
cars.add("Volkswagen");
return cars.toList();
}
}
@@ -0,0 +1,46 @@
package com.baeldung.eclipsecollections;
import java.util.List;
public class Student {
private String firstName;
private String lastName;
private List<String> addresses;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Student(String firstName, String lastName, List<String> addresses) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.addresses = addresses;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,43 @@
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,4 @@
package com.baeldung.flips;
public class TestFlipsBean {
}
@@ -0,0 +1,64 @@
package com.baeldung.ftp;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
class FtpClient {
private final String server;
private final int port;
private final String user;
private final String password;
private FTPClient ftp;
FtpClient(String server, int port, String user, String password) {
this.server = server;
this.port = port;
this.user = user;
this.password = password;
}
void open() throws IOException {
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftp.connect(server, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new IOException("Exception in connecting to FTP Server");
}
ftp.login(user, password);
}
void close() throws IOException {
ftp.disconnect();
}
Collection<String> listFiles(String path) throws IOException {
FTPFile[] files = ftp.listFiles(path);
return Arrays.stream(files)
.map(FTPFile::getName)
.collect(Collectors.toList());
}
void putFileToPath(File file, String path) throws IOException {
ftp.storeFile(path, new FileInputStream(file));
}
void downloadFile(String source, String destination) throws IOException {
FileOutputStream out = new FileOutputStream(destination);
ftp.retrieveFile(source, out);
out.close();
}
}
@@ -0,0 +1,183 @@
package com.baeldung.javapoet;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import javax.lang.model.element.Modifier;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
public class PersonGenerator {
private static final String FOUR_WHITESPACES = " ";
private static final String PERSON_PACKAGE_NAME = "com.baeldung.javapoet.test.person";
private File outputFile;
public PersonGenerator() {
outputFile = new File(getOutputPath().toUri());
}
public static String getPersonPackageName() {
return PERSON_PACKAGE_NAME;
}
public Path getOutputPath() {
return Paths.get(new File(".").getAbsolutePath() + "/gensrc");
}
public FieldSpec getDefaultNameField() {
return FieldSpec
.builder(String.class, "DEFAULT_NAME")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", "Alice")
.build();
}
public MethodSpec getSortByLengthMethod() {
return MethodSpec
.methodBuilder("sortByLength")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(ParameterSpec
.builder(ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class)), "strings")
.build())
.addStatement("$T.sort($N, $L)", Collections.class, "strings", getComparatorAnonymousClass())
.build();
}
public MethodSpec getPrintNameMultipleTimesMethod() {
return MethodSpec
.methodBuilder("printNameMultipleTimes")
.addModifiers(Modifier.PUBLIC)
.addCode(getPrintNameMultipleTimesLambdaImpl())
.build();
}
public CodeBlock getPrintNameMultipleTimesImpl() {
return CodeBlock
.builder()
.beginControlFlow("for (int i = $L; i < $L; i++)")
.addStatement("System.out.println(name)")
.endControlFlow()
.build();
}
public CodeBlock getPrintNameMultipleTimesLambdaImpl() {
return CodeBlock
.builder()
.addStatement("$T<$T> names = new $T<>()", List.class, String.class, ArrayList.class)
.addStatement("$T.range($L, $L).forEach(i -> names.add(name))", IntStream.class, 0, 10)
.addStatement("names.forEach(System.out::println)")
.build();
}
public TypeSpec getGenderEnum() {
return TypeSpec
.enumBuilder("Gender")
.addModifiers(Modifier.PUBLIC)
.addEnumConstant("MALE")
.addEnumConstant("FEMALE")
.addEnumConstant("UNSPECIFIED")
.build();
}
public TypeSpec getPersonInterface() {
return TypeSpec
.interfaceBuilder("Person")
.addModifiers(Modifier.PUBLIC)
.addField(getDefaultNameField())
.addMethod(MethodSpec
.methodBuilder("getName")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.returns(String.class)
.build())
.addMethod(MethodSpec
.methodBuilder("getDefaultName")
.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
.returns(String.class)
.addCode(CodeBlock
.builder()
.addStatement("return DEFAULT_NAME")
.build())
.build())
.build();
}
public TypeSpec getStudentClass() {
return TypeSpec
.classBuilder("Student")
.addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person"))
.addModifiers(Modifier.PUBLIC)
.addField(FieldSpec
.builder(String.class, "name")
.addModifiers(Modifier.PRIVATE)
.build())
.addMethod(MethodSpec
.methodBuilder("getName")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(String.class)
.addStatement("return this.name")
.build())
.addMethod(MethodSpec
.methodBuilder("setName")
.addParameter(String.class, "name")
.addModifiers(Modifier.PUBLIC)
.addStatement("this.name = name")
.build())
.addMethod(getPrintNameMultipleTimesMethod())
.addMethod(getSortByLengthMethod())
.build();
}
public TypeSpec getComparatorAnonymousClass() {
return TypeSpec
.anonymousClassBuilder("")
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
.addMethod(MethodSpec
.methodBuilder("compare")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(String.class, "a")
.addParameter(String.class, "b")
.returns(int.class)
.addStatement("return a.length() - b.length()")
.build())
.build();
}
public void generateGenderEnum() throws IOException {
writeToOutputFile(getPersonPackageName(), getGenderEnum());
}
public void generatePersonInterface() throws IOException {
writeToOutputFile(getPersonPackageName(), getPersonInterface());
}
public void generateStudentClass() throws IOException {
writeToOutputFile(getPersonPackageName(), getStudentClass());
}
private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException {
JavaFile javaFile = JavaFile
.builder(packageName, typeSpec)
.indent(FOUR_WHITESPACES)
.build();
javaFile.writeTo(outputFile);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.javasisst;
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void move(int x, int y) {
this.x = x;
this.y = y;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.javasisst;
public class ThreeDimensionalPoint {
public int x = 0;
public int y = 0;
public int z = 0;
public ThreeDimensionalPoint(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void move(int x, int y) {
this.x = x;
this.y = y;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.javers;
public class Address {
private String country;
public Address(String country) {
this.country = country;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.javers;
public class Person {
private Integer id;
private String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.javers;
import java.util.List;
public class PersonWithAddress {
private Integer id;
private String name;
private List<Address> address;
public PersonWithAddress(Integer id, String name, List<Address> address) {
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
@@ -0,0 +1,73 @@
package com.baeldung.jctools;
import org.jctools.queues.MpmcArrayQueue;
import org.jctools.queues.atomic.MpmcAtomicArrayQueue;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Control;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
@Warmup(iterations = 1)
@Measurement(iterations = 3)
@State(Scope.Group)
public class MpmcBenchmark {
public static final String PARAM_UNSAFE = "MpmcArrayQueue";
public static final String PARAM_AFU = "MpmcAtomicArrayQueue";
public static final String PARAM_JDK = "ArrayBlockingQueue";
public static final int PRODUCER_THREADS_NUMBER = 32;
public static final int CONSUMER_THREADS_NUMBER = 32;
public static final String GROUP_NAME = "MyGroup";
public static final int CAPACITY = 128;
@Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK})
public volatile String implementation;
public volatile Queue<Long> queue;
@Setup(Level.Trial)
public void setUp() {
switch (implementation) {
case PARAM_UNSAFE:
queue = new MpmcArrayQueue<>(CAPACITY);
break;
case PARAM_AFU:
queue = new MpmcAtomicArrayQueue<>(CAPACITY);
break;
case PARAM_JDK:
queue = new ArrayBlockingQueue<>(CAPACITY);
break;
default:
throw new UnsupportedOperationException("Unsupported implementation " + implementation);
}
}
@Benchmark
@Group(GROUP_NAME)
@GroupThreads(PRODUCER_THREADS_NUMBER)
public void write(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && !queue.offer(1L)) {
// Is intentionally left blank
}
}
@Benchmark
@Group(GROUP_NAME)
@GroupThreads(CONSUMER_THREADS_NUMBER)
public void read(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && queue.poll() == null) {
// Is intentionally left blank
}
}
}
@@ -0,0 +1,7 @@
## How to build and run the JMH benchmark
Execute the following from the project's root:
```bash
mvn clean install
java -jar ./target/benchmarks.jar MpmcBenchmark -si true
```
@@ -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,32 @@
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,21 @@
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,36 @@
package com.baeldung.jdeffered;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
public class ThreadSafeDemo {
public static void task() {
DeferredManager dm = new DefaultDeferredManager();
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> p1 = deferred.promise();
Promise<String, String, String> p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
synchronized (p) {
while (p.isPending()) {
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
p.waitSafely();
} catch (InterruptedException e) {
e.printStackTrace();
}
deferred.resolve("Hello Baeldung");
}
}
@@ -0,0 +1,22 @@
package com.baeldung.jdeffered.manager;
import org.jdeferred.Deferred;
import org.jdeferred.DeferredManager;
import org.jdeferred.Promise;
import org.jdeferred.impl.DefaultDeferredManager;
import org.jdeferred.impl.DeferredObject;
class DeferredManagerDemo {
public static void initiate() {
Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager();
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3).done((result) -> {
System.out.println("done");
}).fail((result) -> {
System.out.println("fail");
});
deferred.resolve("Hello Baeldung");
}
}
@@ -0,0 +1,22 @@
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,12 @@
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,12 @@
package com.baeldung.jmh;
import org.openjdk.jmh.annotations.Benchmark;
public class BenchMark {
@Benchmark
public void init() {
}
}
@@ -0,0 +1,12 @@
package com.baeldung.jmh;
import java.io.IOException;
import org.openjdk.jmh.Main;
import org.openjdk.jmh.runner.RunnerException;
public class JmhDemo {
public static void main(String[] args) throws RunnerException, IOException {
Main.main(args);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jmh.warmup;
public class MainApplication {
static {
long start = System.nanoTime();
ManualClassLoader.load();
long end = System.nanoTime();
System.out.println("Warm Up time : " + (end - start));
}
public static void main(String[] args) {
long start = System.nanoTime();
ManualClassLoader.load();
long end = System.nanoTime();
System.out.println("Total time taken : " + (end - start));
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jmh.warmup;
import com.baeldung.jmh.warmup.dummy.Dummy;
public class ManualClassLoader {
public static void load() {
for (int i = 0; i < 100000; i++) {
// load all(or most) important classes
Dummy dummy = new Dummy();
dummy.m();
}
}
}
@@ -0,0 +1,9 @@
package com.baeldung.jmh.warmup.dummy;
public class Dummy {
public void m() {
}
}
@@ -0,0 +1,122 @@
package com.baeldung.jnats;
import io.nats.client.AsyncSubscription;
import io.nats.client.Connection;
import io.nats.client.Message;
import io.nats.client.Nats;
import io.nats.client.Options;
import io.nats.client.Subscription;
import io.nats.client.SyncSubscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public final class NatsClient {
private final String serverURI;
private final Connection natsConnection;
private final Map<String, Subscription> subscriptions = new HashMap<>();
private final static Logger log = LoggerFactory.getLogger(NatsClient.class);
NatsClient() {
this.serverURI = "jnats://localhost:4222";
natsConnection = initConnection(serverURI);
}
public NatsClient(String serverURI) {
if ((serverURI != null) && (!serverURI.isEmpty())) {
this.serverURI = serverURI;
} else {
this.serverURI = "jnats://localhost:4222";
}
natsConnection = initConnection(serverURI);
}
public void closeConnection() {
// Close connection
natsConnection.close();
}
private Connection initConnection(String uri) {
try {
Options options = new Options.Builder()
.errorCb(ex -> log.error("Connection Exception: ", ex))
.disconnectedCb(event -> log.error("Channel disconnected: {}", event.getConnection()))
.reconnectedCb(event -> log.error("Reconnected to server: {}", event.getConnection()))
.build();
return Nats.connect(uri, options);
} catch (IOException ioe) {
log.error("Error connecting to NATs! ", ioe);
return null;
}
}
void publishMessage(String topic, String replyTo, String message) {
try {
natsConnection.publish(topic, replyTo, message.getBytes());
} catch (IOException ioe) {
log.error("Error publishing message: {} to {} ", message, topic, ioe);
}
}
public void subscribeAsync(String topic) {
AsyncSubscription subscription = natsConnection.subscribe(
topic, msg -> log.info("Received message on {}", msg.getSubject()));
if (subscription == null) {
log.error("Error subscribing to {}", topic);
} else {
subscriptions.put(topic, subscription);
}
}
SyncSubscription subscribeSync(String topic) {
return natsConnection.subscribe(topic);
}
public void unsubscribe(String topic) {
try {
Subscription subscription = subscriptions.get(topic);
if (subscription != null) {
subscription.unsubscribe();
} else {
log.error("{} not found. Unable to unsubscribe.", topic);
}
} catch (IOException ioe) {
log.error("Error unsubscribing from {} ", topic, ioe);
}
}
Message makeRequest(String topic, String request) {
try {
return natsConnection.request(topic, request.getBytes(), 100);
} catch (IOException | InterruptedException ioe) {
log.error("Error making request {} to {} ", topic, request, ioe);
return null;
}
}
void installReply(String topic, String reply) {
natsConnection.subscribe(topic, message -> {
try {
natsConnection.publish(message.getReplyTo(), reply.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
});
}
SyncSubscription joinQueueGroup(String topic, String queue) {
return natsConnection.subscribe(topic, queue);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.junitparams;
class SafeAdditionUtil {
int safeAdd(int a, int b) {
long result = ((long) a) + b;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) result;
}
}
@@ -0,0 +1,56 @@
package com.baeldung.kafka;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import java.util.Properties;
import java.util.stream.Stream;
import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
public class TransactionalMessageProducer {
private static final String DATA_MESSAGE_1 = "Put any space separated data here for count";
private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message";
public static void main(String[] args) {
KafkaProducer<String, String> producer = createKafkaProducer();
producer.initTransactions();
try{
producer.beginTransaction();
Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send(
new ProducerRecord<String, String>("input", null, s)));
producer.commitTransaction();
}catch (KafkaException e){
producer.abortTransaction();
}
}
private static KafkaProducer<String, String> createKafkaProducer() {
Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ENABLE_IDEMPOTENCE_CONFIG, "true");
props.put(TRANSACTIONAL_ID_CONFIG, "prod-0");
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
return new KafkaProducer(props);
}
}
@@ -0,0 +1,105 @@
package com.baeldung.kafka;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.time.Duration.ofSeconds;
import static java.util.Collections.singleton;
import static org.apache.kafka.clients.consumer.ConsumerConfig.*;
import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.*;
public class TransactionalWordCount {
private static final String CONSUMER_GROUP_ID = "my-group-id";
private static final String OUTPUT_TOPIC = "output";
private static final String INPUT_TOPIC = "input";
public static void main(String[] args) {
KafkaConsumer<String, String> consumer = createKafkaConsumer();
KafkaProducer<String, String> producer = createKafkaProducer();
producer.initTransactions();
try {
while (true) {
ConsumerRecords<String, String> records = consumer.poll(ofSeconds(60));
Map<String, Integer> wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0))
.stream()
.flatMap(record -> Stream.of(record.value().split(" ")))
.map(word -> Tuple.of(word, 1))
.collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2));
producer.beginTransaction();
wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord<String, String>(OUTPUT_TOPIC, key, value.toString())));
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> partitionedRecords = records.records(partition);
long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset();
offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1));
}
producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID);
producer.commitTransaction();
}
} catch (KafkaException e) {
producer.abortTransaction();
}
}
private static KafkaConsumer<String, String> createKafkaConsumer() {
Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID);
props.put(ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ISOLATION_LEVEL_CONFIG, "read_committed");
props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(singleton(INPUT_TOPIC));
return consumer;
}
private static KafkaProducer<String, String> createKafkaProducer() {
Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ENABLE_IDEMPOTENCE_CONFIG, "true");
props.put(TRANSACTIONAL_ID_CONFIG, "prod-1");
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
return new KafkaProducer(props);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.kafka;
public class Tuple {
private String key;
private Integer value;
private Tuple(String key, Integer value) {
this.key = key;
this.value = value;
}
public static Tuple of(String key, Integer value){
return new Tuple(key,value);
}
public String getKey() {
return key;
}
public Integer getValue() {
return value;
}
}
@@ -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,73 @@
package com.baeldung.neuroph;
import org.neuroph.core.Layer;
import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.Neuron;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.data.DataSetRow;
import org.neuroph.nnet.learning.BackPropagation;
import org.neuroph.util.ConnectionFactory;
import org.neuroph.util.NeuralNetworkType;
public class NeurophXOR {
public static NeuralNetwork assembleNeuralNetwork() {
Layer inputLayer = new Layer();
inputLayer.addNeuron(new Neuron());
inputLayer.addNeuron(new Neuron());
Layer hiddenLayerOne = new Layer();
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
Layer hiddenLayerTwo = new Layer();
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
Layer outputLayer = new Layer();
outputLayer.addNeuron(new Neuron());
NeuralNetwork ann = new NeuralNetwork();
ann.addLayer(0, inputLayer);
ann.addLayer(1, hiddenLayerOne);
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1));
ann.addLayer(2, hiddenLayerTwo);
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
ann.addLayer(3, outputLayer);
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false);
ann.setInputNeurons(inputLayer.getNeurons());
ann.setOutputNeurons(outputLayer.getNeurons());
ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON);
return ann;
}
public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
int inputSize = 2;
int outputSize = 1;
DataSet ds = new DataSet(inputSize, outputSize);
DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 });
ds.addRow(rOne);
DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 });
ds.addRow(rTwo);
DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 });
ds.addRow(rThree);
DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 });
ds.addRow(rFour);
BackPropagation backPropagation = new BackPropagation();
backPropagation.setMaxIterations(1000);
ann.learn(ds, backPropagation);
return ann;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.noexception;
import com.machinezoo.noexception.ExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomExceptionHandler extends ExceptionHandler {
private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@Override
public boolean handle(Throwable throwable) {
if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) {
return false;
} else {
logger.error("Caught Exception ", throwable);
return true;
}
}
}
@@ -0,0 +1,33 @@
package com.baeldung.pairs;
public class CustomPair {
private String key;
private String value;
public CustomPair(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Object[] getPair() {
return new Object[] { this.key, this.value};
}
}
@@ -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,93 @@
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,13 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class JobA implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is the job A");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class JobB implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is the job B");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.quartz;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String args[]) {
SchedulerFactory schedFact = new StdSchedulerFactory();
try {
Scheduler sched = schedFact.getScheduler();
JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build();
JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();
Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build();
sched.scheduleJob(job, trigger);
sched.scheduleJob(jobA, triggerA);
sched.scheduleJob(jobB, triggerB);
sched.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SimpleJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String jobSays = dataMap.getString("jobSays");
float myFloatValue = dataMap.getFloat("myFloatValue");
System.out.println("Job says: " + jobSays + ", and val is: " + myFloatValue);
}
}
@@ -0,0 +1,71 @@
package com.baeldung.reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import java.util.regex.Pattern;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.Scanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class ReflectionsApp {
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
Reflections reflections = new Reflections("org.reflections");
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
public Set<Class<?>> getJDKFunctinalInterfaces() {
Reflections reflections = new Reflections("java.util.function");
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
return typesSet;
}
public Set<Method> getDateDeprecatedMethods() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
return deprecatedMethodsSet;
}
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
return constructorsSet;
}
public Set<Method> getMethodsWithDateParam() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
return methodsSet;
}
public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
return methodsSet;
}
public Set<String> getPomXmlPaths() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
return resourcesSet;
}
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
.setScanners(new SubTypesScanner()));
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
}
@@ -0,0 +1,76 @@
package com.baeldung.rome;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RSSRomeExample {
public static void main(String[] args) throws IOException, FeedException {
SyndFeed feed = createFeed();
addEntryToFeed(feed);
publishFeed(feed);
readFeed();
}
private static SyndFeed createFeed() {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
return feed;
}
private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException {
URL feedSource = new URL("http://rssblog.whatisrss.com/feed/");
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
}
@@ -0,0 +1,49 @@
package com.baeldung.stm;
import org.multiverse.api.StmUtils;
import org.multiverse.api.callables.TxnCallable;
import org.multiverse.api.references.TxnInteger;
import org.multiverse.api.references.TxnLong;
public class Account {
private final TxnLong lastUpdate;
private final TxnInteger balance;
Account(final int balance) {
this.lastUpdate = StmUtils.newTxnLong(System.currentTimeMillis());
this.balance = StmUtils.newTxnInteger(balance);
}
Integer getBalance() {
return balance.atomicGet();
}
void adjustBy(final int amount) {
adjustBy(amount, System.currentTimeMillis());
}
private void adjustBy(final int amount, final long date) {
StmUtils.atomic(() -> {
balance.increment(amount);
lastUpdate.set(date);
if (balance.get() < 0) {
throw new IllegalArgumentException("Not enough money");
}
});
}
void transferTo(final Account other, final int amount) {
StmUtils.atomic(() -> {
final long date = System.currentTimeMillis();
adjustBy(-amount, date);
other.adjustBy(amount, date);
});
}
@Override
public String toString() {
return StmUtils.atomic((TxnCallable<String>) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
}
}
@@ -0,0 +1,5 @@
package com.baeldung.streamex;
public class Role {
}
@@ -0,0 +1,58 @@
package com.baeldung.streamex;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import one.util.streamex.DoubleStreamEx;
import one.util.streamex.EntryStream;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
public class StreamEX {
public static void main(String[] args) {
// Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
List<User> users = Arrays.asList(new User("name"), new User(), new User());
users.stream().map(User::getName).collect(Collectors.toList());
List<String> userNames = StreamEx.of(users).map(User::getName).toList();
Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
// Selecting stream elements of specific type
List usersAndRoles = Arrays.asList(new User(), new Role());
List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
System.out.println(roles);
// adding elements to Stream
List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
System.out.println(appendedUsers);
// Removing unwanted elements and using the stream as Iterable:
for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
System.out.println(line);
}
// Selecting map keys by value predicate:
Map<String, Role> nameToRole = new HashMap<>();
nameToRole.put("first", new Role());
nameToRole.put("second", null);
Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
System.out.println(nonNullRoles);
// Operating on key-value pairs:
Map<User, List<Role>> users2roles = transformMap(role2users);
Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
// Support of byte/char/short/float types:
short[] src = { 1, 2, 3 };
char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
}
public double[] getDiffBetweenPairs(double... numbers) {
return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
}
public static Map<User, List<Role>> transformMap(Map<Role, List<User>> role2users) {
Map<User, List<Role>> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
return users2roles;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.streamex;
public class User {
int id;
String name;
Role role = new Role();
public User() {
}
public User(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.streamutils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}
@@ -0,0 +1,11 @@
package com.baeldung.streamutils;
import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
public InputStream getInputStream() {
return StreamUtils.emptyInput();
}
}
@@ -0,0 +1,48 @@
/*
* 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());
}
}
+20
View File
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDPjCCAiagAwIBAgIJAPvd1gx14C3CMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
BAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREw
DwYDVQQDEwhCYWVsZHVuZzAeFw0xNzEwMTIxMDQzMTRaFw0yNzEwMTMxMDQzMTRa
MEcxCzAJBgNVBAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNh
YmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMyi5GmOeN4QaH/CP5gSOyHX8znb5TDHWV8wc+ZT7kNU8zt5tGMh
jozK6hax155/6tOsBDR0rSYBhL+Dm/+uCVS7qOlRHhf6cNGtzGF1gnNJB2WjI8oM
AYm24xpLj1WphKUwKrn3nTMPnQup5OoNAMYl99flANrRYVjjxrLQvDZDUio6Iujr
CZ2TtXGM0g/gP++28KT7g1KlUui3xtB0u33wx7UN8Fix3JmjOaPHGwxGpwP3VGSj
fs8cuhqVwRQaZpCOoHU/P8wpXKw80sSdhz+SRueMPtVYqK0CiLL5/O0h0Y3le4IV
whgg3KG1iTGOWn60UMFn1EYmQ18k5Nsma6UCAwEAAaMtMCswCQYDVR0TBAIwADAR
BglghkgBhvhCAQEEBAMCBPAwCwYDVR0PBAQDAgUgMA0GCSqGSIb3DQEBBQUAA4IB
AQC8DDBmJ3p4xytxBiE0s4p1715WT6Dm/QJHp0XC0hkSoyZKDh+XVmrzm+J3SiW1
vpswb5hLgPo040YX9jnDmgOD+TpleTuKHxZRYj92UYWmdjkWLVtFMcvOh+gxBiAP
pHIqZsqo8lfcyAuh8Jx834IXbknfCUtERDLG/rU9P/3XJhrM2GC5qPQznrW4EYhU
CGPyIJXmvATMVvXMWCtfogAL+n42vjYXQXZoAWomHhLHoNbSJUErnNdWDOh4WoJt
XJCxA6U5LSBplqb3wB2hUTqw+0admKltvmy+KA1PD7OxoGiY7V544zeGqJam1qxU
ia7y5BL6uOa/4ShSV8pcJDYz
-----END CERTIFICATE-----
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
{
"main": {
"title" : "INTRODUCTION TO YARG",
"name" : "Baeldung",
"content" : "This is the content of the letter, can be anything we like."
}
}
+19
View File
@@ -0,0 +1,19 @@
pragma solidity ^0.4.0;
contract Greeting {
address creator;
string message;
function Greeting(string _message) {
message = _message;
creator = msg.sender;
}
function greet() constant returns (string) {
return message;
}
function setGreeting(string _message) {
message = _message;
}
}
Binary file not shown.
@@ -0,0 +1,4 @@
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
datanucleus.xml.indentSize=6
datanucleus.schema.autoCreateAll=true
@@ -0,0 +1,5 @@
ColA,ColB,ColC,ColD
A,B,B,B
C,D,W,W
G,G,E,E
G,F,Q,Q
1 ColA ColB ColC ColD
2 A B B B
3 C D W W
4 G G E E
5 G F Q Q
@@ -0,0 +1,5 @@
name,age
adam,1000
martin,27
gigi,41
seraphine,30
1 name age
2 adam 1000
3 martin 27
4 gigi 41
5 seraphine 30
@@ -0,0 +1,5 @@
ColA,ColB
A,B
C,D
G,G
G,F
1 ColA ColB
2 A B
3 C D
4 G G
5 G F
Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,104 @@
package com.baeldung.akka;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.testkit.TestKit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.concurrent.duration.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static akka.pattern.PatternsCS.ask;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class AkkaActorsUnitTest {
private static ActorSystem system = null;
@BeforeClass
public static void setup() {
system = ActorSystem.create("test-system");
}
@AfterClass
public static void teardown() {
TestKit.shutdownActorSystem(system, Duration.apply(1000, TimeUnit.MILLISECONDS), true);
system = null;
}
@Test
public void givenAnActor_sendHimAMessageUsingTell() {
final TestKit probe = new TestKit(system);
ActorRef myActorRef = probe.childActorOf(Props.create(MyActor.class));
myActorRef.tell("printit", probe.testActor());
probe.expectMsg("Got Message");
}
@Test
public void givenAnActor_sendHimAMessageUsingAsk() throws ExecutionException, InterruptedException {
final TestKit probe = new TestKit(system);
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
CompletableFuture<Object> future =
ask(wordCounterActorRef, new WordCounterActor.CountWords("this is a text"), 1000).toCompletableFuture();
Integer numberOfWords = (Integer) future.get();
assertTrue("The actor should count 4 words", 4 == numberOfWords);
}
@Test
public void givenAnActor_whenTheMessageIsNull_respondWithException() {
final TestKit probe = new TestKit(system);
ActorRef wordCounterActorRef = probe.childActorOf(Props.create(WordCounterActor.class));
CompletableFuture<Object> future =
ask(wordCounterActorRef, new WordCounterActor.CountWords(null), 1000).toCompletableFuture();
try {
future.get(1000, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
assertTrue("Invalid error message", e.getMessage().contains("The text to process can't be null!"));
} catch (InterruptedException | TimeoutException e) {
fail("Actor should respond with an exception instead of timing out !");
}
}
@Test
public void givenAnAkkaSystem_countTheWordsInAText() {
ActorSystem system = ActorSystem.create("test-system");
ActorRef myActorRef = system.actorOf(Props.create(MyActor.class), "my-actor");
myActorRef.tell("printit", null);
// system.stop(myActorRef);
// myActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
// myActorRef.tell(Kill.getInstance(), ActorRef.noSender());
ActorRef readingActorRef = system.actorOf(ReadingActor.props(TEXT), "readingActor");
readingActorRef.tell(new ReadingActor.ReadLines(), ActorRef.noSender()); //ActorRef.noSender() means the sender ref is akka://test-system/deadLetters
// Future<Terminated> terminateResponse = system.terminate();
}
private static String TEXT = "Lorem Ipsum is simply dummy text\n" +
"of the printing and typesetting industry.\n" +
"Lorem Ipsum has been the industry's standard dummy text\n" +
"ever since the 1500s, when an unknown printer took a galley\n" +
"of type and scrambled it to make a type specimen book.\n" +
" It has survived not only five centuries, but also the leap\n" +
"into electronic typesetting, remaining essentially unchanged.\n" +
" It was popularised in the 1960s with the release of Letraset\n" +
" sheets containing Lorem Ipsum passages, and more recently with\n" +
" desktop publishing software like Aldus PageMaker including\n" +
"versions of Lorem Ipsum.";
}
@@ -0,0 +1,231 @@
package com.baeldung.atlassian.fugue;
import io.atlassian.fugue.*;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.function.Function;
import static org.junit.Assert.*;
import static io.atlassian.fugue.Unit.Unit;
public class FugueUnitTest {
@Test
public void whenSome_thenDefined() {
Option<String> some = Option.some("value");
assertTrue(some.isDefined());
assertEquals("value", some.get());
}
@Test
public void whenNone_thenNotDefined() {
Option<Object> none = Option.none();
assertFalse(none.isDefined());
assertEquals(1, none.getOrElse(1));
}
@Test
public void whenSomeNull_thenException() {
try {
Option.some(null);
fail("some(null) should throw");
} catch (NullPointerException e) {
//Expected
}
}
@Test
public void whenNullOption_thenSome() {
Option<String> some = Option.some("value") .map(String::toUpperCase);
assertEquals("VALUE", some.get());
some = some.map(x -> null);
assertNull(some.get());
some.forEach(Assert::assertNull);
for(Object value : some) {
assertNull(value);
}
assertEquals(1, some.toStream().count());
Option<Object> none = Option.some("value").flatMap(x -> Option.none());
assertFalse(none.isDefined());
none = Option.some("value").flatMap(Options.nullSafe(x -> null));
assertFalse(none.isDefined());
}
@Test
public void whenNone_thenEmptyOptional() {
Optional<Object> optional = Option.none().toOptional();
assertFalse(optional.isPresent());
assertTrue(Option.fromOptional(optional).isEmpty());
}
@Test
public void whenOption_thenIterable() {
Option<String> some = Option.some("value");
Iterable<String> strings = Iterables.concat(some, Arrays.asList("a", "b", "c"));
List<String> stringList = new ArrayList<>();
Iterables.addAll(stringList, strings);
assertEquals(4, stringList.size());
}
@Test
public void whenOption_thenStream() {
assertEquals(0, Option.none().toStream().count());
assertEquals(1, Option.some("value").toStream().count());
}
@Test
public void whenLift_thenPartialFunction() {
Function<Integer, Integer> f = (Integer x) -> x > 0 ? x + 1 : null;
Function<Option<Integer>, Option<Integer>> lifted = Options.lift(f);
assertEquals(2, (long) lifted.apply(Option.some(1)).get());
assertTrue(lifted.apply(Option.none()).isEmpty());
assertEquals(null, lifted.apply(Option.some(0)).get());
}
@Test
public void whenLeft_thenEither() {
Either<Integer, String> right = Either.right("value");
Either<Integer, String> left = Either.left(-1);
if(right.isLeft()) {
fail();
}
if(left.isRight()) {
fail();
}
String s = right.map(String::toUpperCase).getOrNull();
assertEquals("VALUE", s);
Either<String, String> either = right.left().map(x -> decodeSQLErrorCode(x));
assertTrue(either.isRight());
assertEquals("value", either.right().get());
either.right().forEach(x -> assertEquals("value", x));
}
private static String decodeSQLErrorCode(Integer x) {
return "error";
}
@Test
public void whenTryIsFailure_thenIsFailureReturnsTrue() {
assertTrue(Try.failure(new Exception("Fail!")).isFailure());
}
@Test
public void whenTryIsSuccess_thenIsSuccessReturnsTrue() {
assertTrue(Try.successful("OK").isSuccess());
}
@Test
public void givenFunctionReturning_whenCheckedOf_thenSuccess() {
assertTrue(Checked.of(() -> "ok").isSuccess());
}
@Test
public void givenFunctionThrowing_whenCheckedOf_thenFailure() {
assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure());
}
@Test
public void givenFunctionThrowing_whenCheckedLift_thenFailure() {
Checked.Function<String, Object, Exception> throwException = (String x) -> {
throw new Exception(x);
};
assertTrue(Checked.lift(throwException).apply("ko").isFailure());
}
@Test
public void whenRecover_thenSuccessfulTry() {
Try<Object> recover = Try.
failure(new Exception("boo!")).
recover((Exception e) -> e.getMessage() + " recovered.");
assertTrue(recover.isSuccess());
assertEquals("boo! recovered.", recover.getOrElse(() -> null));
recover = Try.
failure(new Exception("boo!")).
recoverWith((Exception e) -> Try.successful("recovered again!"));
assertTrue(recover.isSuccess());
assertEquals("recovered again!", recover.getOrElse(() -> null));
}
@Test
public void whenFailure_thenMapNotCalled() {
Try<Object> recover = Try.failure(new Exception("boo!")).map(x -> {
fail("Oh, no!");
return null;
}).recover(Function.identity());
Exception exception = (Exception) recover.toOption().get();
assertTrue(recover.isSuccess());
assertEquals("boo!", exception.getMessage());
}
@Test
public void whenException_thenTryThrows() {
Try<Object> checked = Checked.of(() -> {
throw new Exception("Aaargh!");
});
Either<Exception, Object> either = checked.toEither();
assertTrue(checked.isFailure());
assertTrue(either.isLeft());
assertEquals(42, checked.getOrElse(() -> 42));
try {
checked.getOrElse(() -> {
throw new NoSuchElementException("fail");
});
fail("Was expecting exception");
} catch (Exception e) {
assertEquals("fail", e.getMessage());
}
}
@Test
public void whenRecoverThrows_thenFailure() {
Try<Object> failure = Try.failure(new Exception("boo!")).recover(x -> {
throw new RuntimeException(x);
});
assertTrue(failure.isFailure());
}
Unit doSomething() {
System.out.println("Hello! Side effect");
return Unit();
}
@Test
public void whenPair_thenLeftAndRight() {
Pair<Integer, String> pair = Pair.pair(1, "a");
assertEquals(1, (int) pair.left());
assertEquals("a", pair.right());
}
}
@@ -0,0 +1,60 @@
package com.baeldung.bytebuddy;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ByteBuddyUnitTest {
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install();
new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
}
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
Class<?> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
Method m = type.getDeclaredMethod("custom", null);
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
assertNotNull(type.getDeclaredField("x"));
}
}
@@ -0,0 +1,144 @@
package com.baeldung.caffeine;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.junit.Test;
import com.github.benmanes.caffeine.cache.*;
public class CaffeineUnitTest {
@Test
public void givenCache_whenPopulate_thenValueStored() {
Cache<String, DataObject> cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build();
String key = "A";
DataObject dataObject = cache.getIfPresent(key);
assertNull(dataObject);
dataObject = cache.get(key, k -> DataObject.get("Data for A"));
assertNotNull(dataObject);
assertEquals("Data for A", dataObject.getData());
cache.put(key, dataObject);
dataObject = cache.getIfPresent(key);
assertNotNull(dataObject);
cache.invalidate(key);
dataObject = cache.getIfPresent(key);
assertNull(dataObject);
}
@Test
public void givenLoadingCache_whenGet_thenValuePopulated() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
String key = "A";
DataObject dataObject = cache.get(key);
assertNotNull(dataObject);
assertEquals("Data for " + key, dataObject.getData());
Map<String, DataObject> dataObjectMap = cache.getAll(Arrays.asList("A", "B", "C"));
assertEquals(3, dataObjectMap.size());
}
@Test
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k));
String key = "A";
cache.get(key).thenAccept(dataObject -> {
assertNotNull(dataObject);
assertEquals("Data for " + key, dataObject.getData());
});
cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
}
@Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
cache.cleanUp();
assertEquals(1, cache.estimatedSize());
}
@Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
cache.get("B");
assertEquals(2, cache.estimatedSize());
cache.get("C");
cache.cleanUp();
assertEquals(2, cache.estimatedSize());
}
@Test
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
@Override
public long expireAfterCreate(@Nonnull String key, @Nonnull DataObject value, long currentTime) {
return value.getData().length() * 1000;
}
@Override
public long expireAfterUpdate(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
return currentDuration;
}
@Override
public long expireAfterRead(@Nonnull String key, @Nonnull DataObject value, long currentTime, long currentDuration) {
return currentDuration;
}
}).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
}
@Test
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k));
cache.get("A");
cache.get("A");
assertEquals(1, cache.stats().hitCount());
assertEquals(1, cache.stats().missCount());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.cglib.proxy;
import net.sf.cglib.beans.BeanGenerator;
import org.junit.Test;
import java.lang.reflect.Method;
import static junit.framework.TestCase.assertEquals;
public class BeanGeneratorIntegrationTest {
@Test
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
// given
BeanGenerator beanGenerator = new BeanGenerator();
// when
beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create();
Method setter = myBean.getClass().getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib");
// then
Method getter = myBean.getClass().getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.cglib.proxy;
import com.baeldung.cglib.mixin.Class1;
import com.baeldung.cglib.mixin.Class2;
import com.baeldung.cglib.mixin.Interface1;
import com.baeldung.cglib.mixin.Interface2;
import com.baeldung.cglib.mixin.MixinInterface;
import net.sf.cglib.proxy.Mixin;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class MixinUnitTest {
@Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
// when
Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
MixinInterface mixinDelegate = (MixinInterface) mixin;
// then
assertEquals("first behaviour", mixinDelegate.first());
assertEquals("second behaviour", mixinDelegate.second());
}
}
@@ -0,0 +1,60 @@
package com.baeldung.cglib.proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ProxyIntegrationTest {
@Test
public void givenPersonService_whenSayHello_thenReturnResult() {
// given
PersonService personService = new PersonService();
// when
String res = personService.sayHello("Tom");
// then
assertEquals(res, "Hello Tom");
}
@Test
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((FixedValue) () -> "Hello Tom!");
PersonService proxy = (PersonService) enhancer.create();
// when
String res = proxy.sayHello(null);
// then
assertEquals("Hello Tom!", res);
}
@Test
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
return "Hello Tom!";
} else {
return proxy.invokeSuper(obj, args);
}
});
// when
PersonService proxy = (PersonService) enhancer.create();
// then
assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary");
assertEquals(4, lengthOfName);
}
}
@@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to cglib](http://www.baeldung.com/cglib)
@@ -0,0 +1,43 @@
package com.baeldung.chronicle.queue;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.Test;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueIntegrationTest {
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
ChronicleTools.deleteOnExit(queueDir.getPath());
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
String stringVal = "Hello World";
int intVal = 101;
long longVal = System.currentTimeMillis();
double doubleVal = 90.00192091d;
ChronicleQueue.writeToQueue(chronicle, stringVal, intVal, longVal, doubleVal);
ExcerptTailer tailer = chronicle.createTailer();
while (tailer.nextIndex()) {
assertEquals(stringVal, tailer.readUTF());
assertEquals(intVal, tailer.readInt());
assertEquals(longVal, tailer.readLong());
assertEquals((Double) doubleVal, (Double) tailer.readDouble());
}
tailer.finish();
tailer.close();
chronicle.close();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.eclipse.collections.impl.block.factory.HashingStrategies;
import org.eclipse.collections.impl.utility.ListIterate;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithEclipseCollectionsUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithJavaFunctionUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2);
}
@Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import one.util.streamex.StreamEx;
public class DistinctWithStreamexUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithVavrUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
assertTrue(personListFiltered.size() == 2);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.distinct;
import java.util.Arrays;
import java.util.List;
public class PersonDataGenerator {
public static List<Person> getPersonListWithFakeValues() {
// @formatter:off
return Arrays.asList(
new Person(20, "Jhon", "jhon@test.com"),
new Person(20, "Jhon", "jhon1@test.com"),
new Person(20, "Jhon", "jhon2@test.com"),
new Person(21, "Tom", "Tom@test.com"),
new Person(21, "Mark", "Mark@test.com"),
new Person(20, "Julia", "jhon@test.com"));
// @formatter:on
}
}
@@ -0,0 +1,123 @@
package com.baeldung.dockerapi;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.core.DockerClientBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
public class ContainerLiveTest {
private static DockerClient dockerClient;
@BeforeClass
public static void setup() {
dockerClient = DockerClientBuilder.getInstance().build();
}
@Test
public void whenListingRunningContainers_thenReturnNonEmptyList() {
// when
List<Container> containers = dockerClient.listContainersCmd().exec();
// then
assertThat(containers.size(), is(not(0)));
}
@Test
public void whenListingExitedContainers_thenReturnNonEmptyList() {
// when
List<Container> containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec();
// then
assertThat(containers.size(), is(not(0)));
}
@Test
public void whenCreatingContainer_thenMustReturnContainerId() {
// when
CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();
// then
assertThat(container.getId(), is(not(null)));
}
@Test
public void whenHavingContainer_thenRunContainer() throws InterruptedException {
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
// then
dockerClient.startContainerCmd(container.getId()).exec();
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenStopContainer() throws InterruptedException {
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
dockerClient.startContainerCmd(container.getId()).exec();
// then
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenKillContainer() throws InterruptedException {
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
dockerClient.startContainerCmd(container.getId()).exec();
Thread.sleep(3000);
dockerClient.stopContainerCmd(container.getId()).exec();
// then
dockerClient.killContainerCmd(container.getId()).exec();
}
@Test
public void whenHavingContainer_thenInspectContainer() {
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
// then
InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
assertThat(containerResponse.getId(), is(container.getId()));
}
@Test
public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
// given
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
// when
String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec();
// then
assertThat(imageId, is(not(null)));
}
}
@@ -0,0 +1,68 @@
package com.baeldung.dockerapi;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertNotNull;
public class DockerClientLiveTest {
@Test
public void whenCreatingDockerClient_thenReturnDefaultInstance() {
// when
DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
// when
DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build();
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
// when
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung")
.withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingDockerClientWithProperties_thenReturnInstance() {
// when
Properties properties = new Properties();
properties.setProperty("registry.email", "info@bealdung.com");
properties.setProperty("registry.url", "register.bealdung.io/v2/");
properties.setProperty("registry.password", "strongpassword");
properties.setProperty("registry.username", "bealdung");
properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs");
properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/");
properties.setProperty("DOCKER_TLS_VERIFY", "1");
properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
// then
assertNotNull(dockerClient);
}
}

Some files were not shown because too many files have changed in this diff Show More