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;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user