Java-1470 Split libraries module
This commit is contained in:
@@ -1,32 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.bytebuddy;
|
||||
|
||||
public class Foo {
|
||||
|
||||
public String sayHelloFoo() {
|
||||
return "Hello in Foo!";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.fj;
|
||||
|
||||
import fj.F;
|
||||
import fj.Show;
|
||||
import fj.data.Array;
|
||||
import fj.data.List;
|
||||
import fj.data.Option;
|
||||
import fj.function.Characters;
|
||||
import fj.function.Integers;
|
||||
|
||||
public class FunctionalJavaMain {
|
||||
|
||||
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
List<Boolean> evenList = fList.map(isEven);
|
||||
Show.listShow(Show.booleanShow).println(evenList);
|
||||
|
||||
fList = fList.map(i -> i + 1);
|
||||
Show.listShow(Show.intShow).println(fList);
|
||||
|
||||
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
Array<Integer> b = a.filter(Integers.even);
|
||||
Show.arrayShow(Show.intShow).println(b);
|
||||
|
||||
Array<String> array = Array.array("Welcome", "To", "baeldung");
|
||||
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
|
||||
System.out.println(isExist);
|
||||
|
||||
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
int sum = intArray.foldLeft(Integers.add, 0);
|
||||
System.out.println(sum);
|
||||
|
||||
Option<Integer> n1 = Option.some(1);
|
||||
Option<Integer> n2 = Option.some(2);
|
||||
|
||||
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
|
||||
|
||||
Option<Integer> result1 = n1.bind(f1);
|
||||
Option<Integer> result2 = n2.bind(f1);
|
||||
|
||||
Show.optionShow(Show.intShow).println(result1);
|
||||
Show.optionShow(Show.intShow).println(result2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
## 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
|
||||
```
|
||||
@@ -1,122 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
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);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
public class Role {
|
||||
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
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.";
|
||||
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
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"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
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)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectImageResponse;
|
||||
import com.github.dockerjava.api.model.Image;
|
||||
import com.github.dockerjava.api.model.SearchItem;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import com.github.dockerjava.core.command.BuildImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PullImageResultCallback;
|
||||
import com.github.dockerjava.core.command.PushImageResultCallback;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class ImageLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImages_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
|
||||
|
||||
// then
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingDanglingImages_thenReturnNonNullList() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().withDanglingFilter(true).exec();
|
||||
|
||||
// then
|
||||
assertThat(images, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuildingImage_thenMustReturnImageId() {
|
||||
|
||||
// when
|
||||
String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId();
|
||||
|
||||
// then
|
||||
assertThat(imageId, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
|
||||
|
||||
// given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
// when
|
||||
InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
|
||||
|
||||
// then
|
||||
assertThat(imageResponse.getId(), is(image.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfImages_whenTagImage_thenListMustIncrement() {
|
||||
|
||||
// given
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
|
||||
// when
|
||||
dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();
|
||||
|
||||
// then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(greaterThan(images.size())));
|
||||
}
|
||||
|
||||
public void pushingAnImage() throws InterruptedException {
|
||||
|
||||
dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
|
||||
|
||||
// when
|
||||
dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);
|
||||
|
||||
// then
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
assertThat(images.size(), is(not(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingImage_thenImageListDecrease() {
|
||||
|
||||
// when
|
||||
List<Image> images = dockerClient.listImagesCmd().exec();
|
||||
Image image = images.get(0);
|
||||
dockerClient.removeImageCmd(image.getId()).exec();
|
||||
|
||||
// then
|
||||
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
|
||||
assertThat(imagesNow.size(), is(lessThan(images.size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSearchingImage_thenMustReturn25Items() {
|
||||
|
||||
// when
|
||||
List<SearchItem> items = dockerClient.searchImagesCmd("Java").exec();
|
||||
|
||||
// then
|
||||
assertThat(items.size(), is(25));
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateNetworkResponse;
|
||||
import com.github.dockerjava.api.model.Network;
|
||||
import com.github.dockerjava.api.model.Network.Ipam;
|
||||
import com.github.dockerjava.core.DockerClientBuilder;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class NetworkLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("temporarily")
|
||||
public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
List<Network> networks = dockerClient.listNetworksCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(networks.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRetrieveResponse() {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
assertThat(networkResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
String networkName = "bridge";
|
||||
Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
|
||||
|
||||
// then
|
||||
assertThat(network.getName(), is(networkName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNetwork_thenRemove() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
|
||||
|
||||
// then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeNetworkCmd(networkResponse.getId()).exec();
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package com.baeldung.dockerapi;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateVolumeResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesResponse;
|
||||
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.greaterThan;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
|
||||
public class VolumeLiveTest {
|
||||
|
||||
private static DockerClient dockerClient;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
dockerClient = DockerClientBuilder.getInstance().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListingVolumes_thenSizeMustBeGreaterThanZero() {
|
||||
|
||||
// when
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
|
||||
// then
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
assertThat(volumes.size(), is(greaterThan(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() {
|
||||
|
||||
// given
|
||||
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
|
||||
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
|
||||
InspectVolumeResponse volume = volumes.get(0);
|
||||
|
||||
// when
|
||||
InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec();
|
||||
|
||||
// then
|
||||
assertThat(volumeResponse, is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingUnnamedVolume_thenGetVolumeId() {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
|
||||
|
||||
// then
|
||||
assertThat(unnamedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingNamedVolume_thenGetVolumeId() {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
|
||||
|
||||
// then
|
||||
assertThat(namedVolume.getName(), is(not(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
|
||||
|
||||
// when
|
||||
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
|
||||
|
||||
// then
|
||||
Thread.sleep(4000);
|
||||
dockerClient.removeVolumeCmd(namedVolume.getName()).exec();
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.baeldung.fj;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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 FunctionalJavaUnitTest {
|
||||
|
||||
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
|
||||
|
||||
public static final Integer timesTwoRegular(Integer i) {
|
||||
return i * 2;
|
||||
}
|
||||
|
||||
public static final F<Integer, Integer> timesTwo = i -> i * 2;
|
||||
|
||||
public static final F<Integer, Integer> plusOne = i -> i + 1;
|
||||
|
||||
@Test
|
||||
public void multiplyNumbers_givenIntList_returnTrue() {
|
||||
List<Integer> fList = List.list(1, 2, 3, 4);
|
||||
List<Integer> fList1 = fList.map(timesTwo);
|
||||
List<Integer> fList2 = fList.map(i -> i * 2);
|
||||
|
||||
assertTrue(fList1.equals(fList2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyMultipleFunctions_givenIntList_returnFalse() {
|
||||
List<Integer> fList = List.list(1, 2, 3, 4);
|
||||
List<Integer> fList1 = fList.map(timesTwo).map(plusOne);
|
||||
Show.listShow(Show.intShow).println(fList1);
|
||||
List<Integer> fList2 = fList.map(plusOne).map(timesTwo);
|
||||
Show.listShow(Show.intShow).println(fList2);
|
||||
|
||||
assertFalse(fList1.equals(fList2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void calculateEvenNumbers_givenIntList_returnTrue() {
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
List<Boolean> evenList = fList.map(isEven);
|
||||
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
|
||||
|
||||
assertTrue(evenList.equals(evenListTrueResult));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapList_givenIntList_returnResult() {
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
fList = fList.map(i -> i + 100);
|
||||
List<Integer> resultList = List.list(103, 104, 105, 106);
|
||||
|
||||
assertTrue(fList.equals(resultList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterList_givenIntList_returnResult() {
|
||||
Array<Integer> array = Array.array(3, 4, 5, 6);
|
||||
Array<Integer> filteredArray = array.filter(isEven);
|
||||
Array<Integer> result = Array.array(4, 6);
|
||||
|
||||
assertTrue(filteredArray.equals(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkForLowerCase_givenStringArray_returnResult() {
|
||||
Array<String> array = Array.array("Welcome", "To", "baeldung");
|
||||
assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
|
||||
|
||||
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
|
||||
assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
|
||||
|
||||
assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptions_givenOptions_returnResult() {
|
||||
Option<Integer> n1 = Option.some(1);
|
||||
Option<Integer> n2 = Option.some(2);
|
||||
Option<Integer> n3 = Option.none();
|
||||
|
||||
F<Integer, Option<Integer>> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
|
||||
|
||||
Option<Integer> result1 = n1.bind(function);
|
||||
Option<Integer> result2 = n2.bind(function);
|
||||
Option<Integer> result3 = n3.bind(function);
|
||||
|
||||
assertEquals(Option.none(), result1);
|
||||
assertEquals(Option.some(102), result2);
|
||||
assertEquals(Option.none(), result3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void foldLeft_givenArray_returnResult() {
|
||||
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
int sumAll = intArray.foldLeft(Integers.add, 0);
|
||||
|
||||
assertEquals(260, sumAll);
|
||||
|
||||
int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
|
||||
|
||||
assertEquals(148, sumEven);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.baeldung.ftp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockftpserver.fake.FakeFtpServer;
|
||||
import org.mockftpserver.fake.UserAccount;
|
||||
import org.mockftpserver.fake.filesystem.DirectoryEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileSystem;
|
||||
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class FtpClientIntegrationTest {
|
||||
|
||||
private FakeFtpServer fakeFtpServer;
|
||||
|
||||
private FtpClient ftpClient;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
fakeFtpServer = new FakeFtpServer();
|
||||
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
|
||||
|
||||
FileSystem fileSystem = new UnixFakeFileSystem();
|
||||
fileSystem.add(new DirectoryEntry("/data"));
|
||||
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
|
||||
fakeFtpServer.setFileSystem(fileSystem);
|
||||
fakeFtpServer.setServerControlPort(0);
|
||||
|
||||
fakeFtpServer.start();
|
||||
|
||||
ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password");
|
||||
ftpClient.open();
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
ftpClient.close();
|
||||
fakeFtpServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException {
|
||||
Collection<String> files = ftpClient.listFiles("");
|
||||
|
||||
assertThat(files).contains("foobar.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
|
||||
ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt");
|
||||
|
||||
assertThat(new File("downloaded_buz.txt")).exists();
|
||||
new File("downloaded_buz.txt").delete(); // cleanup
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException {
|
||||
File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI());
|
||||
|
||||
ftpClient.putFileToPath(file, "/buz.txt");
|
||||
|
||||
assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.ftp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockftpserver.fake.FakeFtpServer;
|
||||
import org.mockftpserver.fake.UserAccount;
|
||||
import org.mockftpserver.fake.filesystem.DirectoryEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileSystem;
|
||||
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JdkFtpClientIntegrationTest {
|
||||
|
||||
private FakeFtpServer fakeFtpServer;
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
fakeFtpServer = new FakeFtpServer();
|
||||
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
|
||||
|
||||
FileSystem fileSystem = new UnixFakeFileSystem();
|
||||
fileSystem.add(new DirectoryEntry("/data"));
|
||||
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
|
||||
fakeFtpServer.setFileSystem(fileSystem);
|
||||
fakeFtpServer.setServerControlPort(0);
|
||||
|
||||
fakeFtpServer.start();
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
fakeFtpServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
|
||||
String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort());
|
||||
|
||||
URLConnection urlConnection = new URL(ftpUrl).openConnection();
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
Files.copy(inputStream, new File("downloaded_buz.txt").toPath());
|
||||
inputStream.close();
|
||||
|
||||
assertThat(new File("downloaded_buz.txt")).exists();
|
||||
|
||||
new File("downloaded_buz.txt").delete(); // cleanup
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.baeldung.javapoet.test;
|
||||
|
||||
import com.baeldung.javapoet.PersonGenerator;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class PersonGeneratorUnitTest {
|
||||
|
||||
private PersonGenerator generator;
|
||||
private Path generatedFolderPath;
|
||||
private Path expectedFolderPath;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
String packagePath = this
|
||||
.getClass()
|
||||
.getPackage()
|
||||
.getName()
|
||||
.replace(".", "/") + "/person";
|
||||
generator = new PersonGenerator();
|
||||
generatedFolderPath = generator
|
||||
.getOutputPath()
|
||||
.resolve(packagePath);
|
||||
expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
FileUtils.deleteDirectory(new File(generator
|
||||
.getOutputPath()
|
||||
.toUri()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException {
|
||||
generator.generateGenderEnum();
|
||||
String fileName = "Gender.java";
|
||||
assertThatFileIsGeneratedAsExpected(fileName);
|
||||
deleteGeneratedFile(fileName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException {
|
||||
generator.generatePersonInterface();
|
||||
String fileName = "Person.java";
|
||||
assertThatFileIsGeneratedAsExpected(fileName);
|
||||
deleteGeneratedFile(fileName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException {
|
||||
generator.generateStudentClass();
|
||||
String fileName = "Student.java";
|
||||
assertThatFileIsGeneratedAsExpected(fileName);
|
||||
deleteGeneratedFile(fileName);
|
||||
}
|
||||
|
||||
private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException {
|
||||
String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName));
|
||||
String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName));
|
||||
|
||||
assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent)));
|
||||
|
||||
}
|
||||
|
||||
private void deleteGeneratedFile(String fileName) throws IOException {
|
||||
Path generatedFilePath = generatedFolderPath.resolve(fileName);
|
||||
Files.delete(generatedFilePath);
|
||||
}
|
||||
|
||||
private String extractFileContent(Path filePath) throws IOException {
|
||||
byte[] fileContentAsBytes = Files.readAllBytes(filePath);
|
||||
String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8);
|
||||
|
||||
if (!fileContentAsString.contains("\r\n")) {
|
||||
// file is not in DOS format
|
||||
// convert it first, so that the content comparison will be relevant
|
||||
return fileContentAsString.replaceAll("\n", "\r\n");
|
||||
}
|
||||
return fileContentAsString;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.javapoet.test.person;
|
||||
|
||||
public enum Gender {
|
||||
MALE,
|
||||
|
||||
FEMALE,
|
||||
|
||||
UNSPECIFIED
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.javapoet.test.person;
|
||||
|
||||
import java.lang.String;
|
||||
|
||||
public interface Person {
|
||||
String DEFAULT_NAME = "Alice";
|
||||
|
||||
String getName();
|
||||
|
||||
default String getDefaultName() {
|
||||
return DEFAULT_NAME;
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.baeldung.javapoet.test.person;
|
||||
|
||||
import java.lang.Override;
|
||||
import java.lang.String;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class Student implements Person {
|
||||
private String name;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void printNameMultipleTimes() {
|
||||
List<String> names = new ArrayList<>();
|
||||
IntStream.range(0, 10).forEach(i -> names.add(name));
|
||||
names.forEach(System.out::println);
|
||||
}
|
||||
|
||||
public static void sortByLength(List<String> strings) {
|
||||
Collections.sort(strings, new Comparator<String>() {
|
||||
@Override
|
||||
public int compare(String a, String b) {
|
||||
return a.length() - b.length();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package com.baeldung.jctools;
|
||||
|
||||
import org.jctools.queues.SpscArrayQueue;
|
||||
import org.jctools.queues.SpscChunkedArrayQueue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
public class JCToolsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleProducers_whenSpscQueueUsed_thenNoWarningOccurs() throws InterruptedException {
|
||||
SpscArrayQueue<Integer> queue = new SpscArrayQueue<Integer>(2);
|
||||
|
||||
Thread producer1 = new Thread(() -> {
|
||||
queue.offer(1);
|
||||
});
|
||||
producer1.start();
|
||||
producer1.join();
|
||||
|
||||
Thread producer2 = new Thread(() -> {
|
||||
queue.offer(2);
|
||||
});
|
||||
producer2.start();
|
||||
producer2.join();
|
||||
|
||||
Set<Integer> fromQueue = new HashSet<>();
|
||||
Thread consumer = new Thread(() -> queue.drain(fromQueue::add));
|
||||
consumer.start();
|
||||
consumer.join();
|
||||
|
||||
assertThat(fromQueue).containsOnly(1, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException {
|
||||
SpscChunkedArrayQueue<Integer> queue = new SpscChunkedArrayQueue<>(8, 16);
|
||||
assertThat(queue.capacity()).isEqualTo(16);
|
||||
|
||||
CountDownLatch startConsuming = new CountDownLatch(1);
|
||||
CountDownLatch awakeProducer = new CountDownLatch(1);
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
Thread producer = new Thread(() -> {
|
||||
IntStream.range(0, queue.capacity()).forEach(i -> {
|
||||
assertThat(queue.offer(i)).isTrue();
|
||||
});
|
||||
assertThat(queue.offer(queue.capacity())).isFalse();
|
||||
startConsuming.countDown();
|
||||
try {
|
||||
awakeProducer.await();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
assertThat(queue.offer(queue.capacity())).isTrue();
|
||||
});
|
||||
producer.setUncaughtExceptionHandler((t, e) -> {
|
||||
error.set(e);
|
||||
startConsuming.countDown();
|
||||
});
|
||||
producer.start();
|
||||
|
||||
startConsuming.await();
|
||||
|
||||
if (error.get() != null) {
|
||||
fail("Producer's assertion failed", error.get());
|
||||
}
|
||||
|
||||
Set<Integer> fromQueue = new HashSet<>();
|
||||
queue.drain(fromQueue::add);
|
||||
awakeProducer.countDown();
|
||||
producer.join();
|
||||
queue.drain(fromQueue::add);
|
||||
|
||||
assertThat(fromQueue).containsAll(IntStream.range(0, 17).boxed().collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package com.baeldung.jnats;
|
||||
|
||||
import io.nats.client.Message;
|
||||
import io.nats.client.SyncSubscription;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class NatsClientLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenMessageExchange_MessagesReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.bar");
|
||||
SyncSubscription barSubscription = client.subscribeSync("bar.foo");
|
||||
client.publishMessage("foo.bar", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
|
||||
client.publishMessage(message.getReplyTo(), message.getSubject(), "hello back");
|
||||
|
||||
message = barSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello back", new String(message.getData()));
|
||||
}
|
||||
|
||||
|
||||
private NatsClient connectClient() {
|
||||
return new NatsClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWildCardSubscription_andMatchTopic_MessageReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
|
||||
|
||||
client.publishMessage("foo.bar", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWildCardSubscription_andNotMatchTopic_NoMessageReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
|
||||
|
||||
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
|
||||
|
||||
Message message = fooSubscription.nextMessage(200);
|
||||
assertNull("Got message!", message);
|
||||
|
||||
|
||||
SyncSubscription barSubscription = client.subscribeSync("foo.>");
|
||||
|
||||
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
|
||||
|
||||
message = barSubscription.nextMessage(200);
|
||||
assertNotNull("No message!", message);
|
||||
assertEquals("hello there", new String(message.getData()));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRequest_ReplyReceived() {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
client.installReply("salary.requests", "denied!");
|
||||
|
||||
Message reply = client.makeRequest("salary.requests", "I need a raise.");
|
||||
assertNotNull("No message!", reply);
|
||||
assertEquals("denied!", new String(reply.getData()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueueMessage_OnlyOneReceived() throws Exception {
|
||||
|
||||
NatsClient client = connectClient();
|
||||
|
||||
SyncSubscription queue1 = client.joinQueueGroup("foo.bar.requests", "queue1");
|
||||
SyncSubscription queue2 = client.joinQueueGroup("foo.bar.requests", "queue1");
|
||||
|
||||
client.publishMessage("foo.bar.requests", "queuerequestor", "foobar");
|
||||
|
||||
List<Message> messages = new ArrayList<>();
|
||||
|
||||
Message message = queue1.nextMessage(200);
|
||||
|
||||
if (message != null) messages.add(message);
|
||||
message = queue2.nextMessage(200);
|
||||
|
||||
if (message != null) messages.add(message);
|
||||
assertEquals(1, messages.size());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package com.baeldung.jool;
|
||||
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.jooq.lambda.Unchecked;
|
||||
import org.jooq.lambda.function.Function1;
|
||||
import org.jooq.lambda.function.Function2;
|
||||
import org.jooq.lambda.tuple.Tuple2;
|
||||
import org.jooq.lambda.tuple.Tuple3;
|
||||
import org.jooq.lambda.tuple.Tuple4;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.jooq.lambda.tuple.Tuple.tuple;
|
||||
|
||||
public class JOOLUnitTest {
|
||||
@Test
|
||||
public void givenSeq_whenCheckContains_shouldReturnTrue() {
|
||||
List<Integer> concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList();
|
||||
|
||||
assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).contains(2));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3));
|
||||
|
||||
assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() {
|
||||
// given
|
||||
Stream<Integer> left = Stream.of(1, 2, 4);
|
||||
Stream<Integer> right = Stream.of(1, 2, 3);
|
||||
|
||||
// when
|
||||
List<Integer> rightCollected = right.collect(Collectors.toList());
|
||||
List<Integer> collect = left.filter(rightCollected::contains).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() {
|
||||
assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)));
|
||||
|
||||
assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() {
|
||||
assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5);
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2))
|
||||
|
||||
);
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() {
|
||||
|
||||
Map<Integer, List<Integer>> expectedAfterGroupBy = new HashMap<>();
|
||||
expectedAfterGroupBy.put(1, Arrays.asList(1, 3));
|
||||
expectedAfterGroupBy.put(0, Arrays.asList(2, 4));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy);
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc");
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() {
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeq_whenZip_shouldHaveZippedSeq() {
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")));
|
||||
|
||||
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c"));
|
||||
|
||||
assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)));
|
||||
}
|
||||
|
||||
public Integer methodThatThrowsChecked(String arg) throws Exception {
|
||||
return arg.length();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() {
|
||||
// when
|
||||
List<Integer> collect = Stream.of("a", "b", "c").map(elem -> {
|
||||
try {
|
||||
return methodThatThrowsChecked(elem);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 1, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
|
||||
// when
|
||||
List<Integer> collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertEquals(collect, Arrays.asList(1, 1, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() {
|
||||
// given
|
||||
Function2<Integer, Integer, Integer> addTwoNumbers = (v1, v2) -> v1 + v2;
|
||||
addTwoNumbers.toBiFunction();
|
||||
Function1<Integer, Integer> addToTwo = addTwoNumbers.applyPartially(2);
|
||||
|
||||
// when
|
||||
Integer result = addToTwo.apply(5);
|
||||
|
||||
// then
|
||||
assertEquals(result, (Integer) 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() {
|
||||
// given
|
||||
Seq<Tuple3<String, String, Integer>> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43));
|
||||
Tuple2<String, String> tuple = tuple("winter", "summer");
|
||||
|
||||
// when
|
||||
List<Tuple4<String, String, String, String>> result = personDetails.map(t -> t.limit2().concat(tuple)).toList();
|
||||
|
||||
// then
|
||||
assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")));
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.kafkastreams;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.common.serialization.Serde;
|
||||
import org.apache.kafka.common.serialization.Serdes;
|
||||
import org.apache.kafka.streams.KafkaStreams;
|
||||
import org.apache.kafka.streams.StreamsBuilder;
|
||||
import org.apache.kafka.streams.StreamsConfig;
|
||||
import org.apache.kafka.streams.Topology;
|
||||
import org.apache.kafka.streams.kstream.KStream;
|
||||
import org.apache.kafka.streams.kstream.KTable;
|
||||
import org.apache.kafka.streams.kstream.Produced;
|
||||
import org.apache.kafka.test.TestUtils;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class KafkaStreamsLiveTest {
|
||||
private String bootstrapServers = "localhost:9092";
|
||||
|
||||
@Test
|
||||
@Ignore("it needs to have kafka broker running on local")
|
||||
public void shouldTestKafkaStreams() throws InterruptedException {
|
||||
// given
|
||||
String inputTopic = "inputTopic";
|
||||
|
||||
Properties streamsConfiguration = new Properties();
|
||||
streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-live-test");
|
||||
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
|
||||
streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
|
||||
streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
|
||||
streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000);
|
||||
streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
||||
// Use a temporary directory for storing state, which will be automatically removed after the test.
|
||||
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());
|
||||
|
||||
// when
|
||||
StreamsBuilder builder = new StreamsBuilder();
|
||||
KStream<String, String> textLines = builder.stream(inputTopic);
|
||||
Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS);
|
||||
|
||||
KTable<String, Long> wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count();
|
||||
|
||||
textLines.foreach((word, count) -> System.out.println("word: " + word + " -> " + count));
|
||||
|
||||
String outputTopic = "outputTopic";
|
||||
final Serde<String> stringSerde = Serdes.String();
|
||||
final Serde<String> longSerde = Serdes.String();
|
||||
textLines.to(outputTopic, Produced.with(stringSerde,longSerde));
|
||||
|
||||
KafkaStreams streams = new KafkaStreams(new Topology(), streamsConfiguration);
|
||||
streams.start();
|
||||
|
||||
// then
|
||||
Thread.sleep(30000);
|
||||
streams.close();
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.baeldung.pact;
|
||||
|
||||
import au.com.dius.pact.consumer.Pact;
|
||||
import au.com.dius.pact.consumer.PactProviderRuleMk2;
|
||||
import au.com.dius.pact.consumer.PactVerification;
|
||||
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||
import au.com.dius.pact.model.RequestResponsePact;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
@Rule
|
||||
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
||||
|
||||
@Pact(consumer = "test_consumer")
|
||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||
Map<String, String> headers = new HashMap<String, String>();
|
||||
headers.put("Content-Type", "application/json");
|
||||
|
||||
return builder.given("test GET").uponReceiving("GET REQUEST").path("/pact").method("GET").willRespondWith().status(200).headers(headers).body("{\"condition\": true, \"name\": \"tom\"}").given("test POST").uponReceiving("POST REQUEST").method("POST")
|
||||
.headers(headers).body("{\"name\": \"Michael\"}").path("/pact").willRespondWith().status(201).toPact();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
@PactVerification()
|
||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||
// when
|
||||
ResponseEntity<String> response = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class);
|
||||
|
||||
// then
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
|
||||
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
|
||||
|
||||
// and
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
String jsonBody = "{\"name\": \"Michael\"}";
|
||||
|
||||
// when
|
||||
ResponseEntity<String> postResponse = new RestTemplate().exchange(mockProvider.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class);
|
||||
|
||||
// then
|
||||
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.reflections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ReflectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTypeThenGetAllSubTypes() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getReflectionsSubTypes()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTypeAndUsingBuilderThenGetAllSubTypes() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnnotationThenGetAllAnnotatedMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getDateDeprecatedMethods()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnnotationThenGetAllAnnotatedConstructors() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getDateDeprecatedConstructors()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParamTypeThenGetAllMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getMethodsWithDateParam()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReturnTypeThenGetAllMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getMethodsWithVoidReturn()
|
||||
.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package com.baeldung.resilience4j;
|
||||
|
||||
import io.github.resilience4j.bulkhead.Bulkhead;
|
||||
import io.github.resilience4j.bulkhead.BulkheadConfig;
|
||||
import io.github.resilience4j.bulkhead.BulkheadRegistry;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.github.resilience4j.retry.RetryRegistry;
|
||||
import io.github.resilience4j.timelimiter.TimeLimiter;
|
||||
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class Resilience4jUnitTest {
|
||||
|
||||
interface RemoteService {
|
||||
|
||||
int process(int i);
|
||||
}
|
||||
|
||||
private RemoteService service;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
service = mock(RemoteService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCircuitBreakerIsUsed_thenItWorksAsExpected() {
|
||||
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
|
||||
// Percentage of failures to start short-circuit
|
||||
.failureRateThreshold(20)
|
||||
// Min number of call attempts
|
||||
.ringBufferSizeInClosedState(5)
|
||||
.build();
|
||||
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
|
||||
CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
|
||||
Function<Integer, Integer> decorated = CircuitBreaker.decorateFunction(circuitBreaker, service::process);
|
||||
|
||||
when(service.process(anyInt())).thenThrow(new RuntimeException());
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
decorated.apply(i);
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
}
|
||||
|
||||
verify(service, times(5)).process(any(Integer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBulkheadIsUsed_thenItWorksAsExpected() throws InterruptedException {
|
||||
BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build();
|
||||
BulkheadRegistry registry = BulkheadRegistry.of(config);
|
||||
Bulkhead bulkhead = registry.bulkhead("my");
|
||||
Function<Integer, Integer> decorated = Bulkhead.decorateFunction(bulkhead, service::process);
|
||||
|
||||
Future<?> taskInProgress = callAndBlock(decorated);
|
||||
try {
|
||||
assertThat(bulkhead.isCallPermitted()).isFalse();
|
||||
} finally {
|
||||
taskInProgress.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
private Future<?> callAndBlock(Function<Integer, Integer> decoratedService) throws InterruptedException {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
when(service.process(anyInt())).thenAnswer(invocation -> {
|
||||
latch.countDown();
|
||||
Thread.currentThread().join();
|
||||
return null;
|
||||
});
|
||||
|
||||
ForkJoinTask<?> result = ForkJoinPool.commonPool().submit(() -> {
|
||||
decoratedService.apply(1);
|
||||
});
|
||||
latch.await();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetryIsUsed_thenItWorksAsExpected() {
|
||||
RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
|
||||
RetryRegistry registry = RetryRegistry.of(config);
|
||||
Retry retry = registry.retry("my");
|
||||
Function<Integer, Void> decorated = Retry.decorateFunction(retry, (Integer s) -> {
|
||||
service.process(s);
|
||||
return null;
|
||||
});
|
||||
|
||||
when(service.process(anyInt())).thenThrow(new RuntimeException());
|
||||
try {
|
||||
decorated.apply(1);
|
||||
fail("Expected an exception to be thrown if all retries failed");
|
||||
} catch (Exception e) {
|
||||
verify(service, times(2)).process(any(Integer.class));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void whenTimeLimiterIsUsed_thenItWorksAsExpected() throws Exception {
|
||||
long ttl = 1;
|
||||
TimeLimiterConfig config = TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build();
|
||||
TimeLimiter timeLimiter = TimeLimiter.of(config);
|
||||
|
||||
Future futureMock = mock(Future.class);
|
||||
Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock);
|
||||
restrictedCall.call();
|
||||
|
||||
verify(futureMock).get(ttl, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import one.util.streamex.StreamEx;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamExMergeStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
Stream<Integer> stream3 = Stream.of(18, 15, 36);
|
||||
Stream<Integer> stream4 = Stream.of(99);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<String> stream1 = Stream.of("foo", "bar");
|
||||
Stream<String> openingBracketStream = Stream.of("[");
|
||||
Stream<String> closingBracketStream = Stream.of("]");
|
||||
|
||||
Stream<String> resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream);
|
||||
|
||||
assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
FROM alpine:3.6
|
||||
|
||||
RUN apk --update add git openssh && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
rm /var/cache/apk/*
|
||||
|
||||
ENTRYPOINT ["git"]
|
||||
CMD ["--help"]
|
||||
Reference in New Issue
Block a user