Merge branch 'master' into master

This commit is contained in:
Amy DeGregorio 2019-01-11 11:16:57 -05:00 committed by GitHub
commit 2c80343944
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
93 changed files with 1920 additions and 286 deletions

View File

@ -14,3 +14,4 @@
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)

View File

@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -15,13 +14,7 @@ import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaInputDStream;
@ -35,7 +28,6 @@ import scala.Tuple2;
public class WordCountingApp {
@SuppressWarnings("serial")
public static void main(String[] args) throws InterruptedException {
Logger.getLogger("org")
.setLevel(Level.OFF);
@ -61,53 +53,25 @@ public class WordCountingApp {
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
JavaPairDStream<String, String> results = messages.mapToPair(new PairFunction<ConsumerRecord<String, String>, String, String>() {
@Override
public Tuple2<String, String> call(ConsumerRecord<String, String> record) {
return new Tuple2<>(record.key(), record.value());
}
});
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
JavaDStream<String> lines = results.map(new Function<Tuple2<String, String>, String>() {
@Override
public String call(Tuple2<String, String> tuple2) {
return tuple2._2();
}
});
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
@Override
public Iterator<String> call(String x) {
return Arrays.asList(x.split("\\s+"))
.iterator();
}
});
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
.iterator());
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) {
return new Tuple2<>(s, 1);
}
})
.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((i1, i2) -> i1 + i2);
wordCounts.foreachRDD(new VoidFunction<JavaPairRDD<String, Integer>>() {
@Override
public void call(JavaPairRDD<String, Integer> javaRdd) throws Exception {
wordCounts.foreachRDD(javaRdd -> {
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
for (String key : wordCountMap.keySet()) {
List<Word> words = Arrays.asList(new Word(key, wordCountMap.get(key)));
List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
JavaRDD<Word> rdd = streamingContext.sparkContext()
.parallelize(words);
.parallelize(wordList);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
}
});
streamingContext.start();

View File

@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -15,18 +14,10 @@ import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.Optional;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.Function3;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.State;
import org.apache.spark.streaming.StateSpec;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaInputDStream;
@ -43,7 +34,6 @@ public class WordCountingAppWithCheckpoint {
public static JavaSparkContext sparkContext;
@SuppressWarnings("serial")
public static void main(String[] args) throws InterruptedException {
Logger.getLogger("org")
@ -74,64 +64,31 @@ public class WordCountingAppWithCheckpoint {
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
JavaPairDStream<String, String> results = messages.mapToPair(new PairFunction<ConsumerRecord<String, String>, String, String>() {
@Override
public Tuple2<String, String> call(ConsumerRecord<String, String> record) {
return new Tuple2<>(record.key(), record.value());
}
});
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
JavaDStream<String> lines = results.map(new Function<Tuple2<String, String>, String>() {
@Override
public String call(Tuple2<String, String> tuple2) {
return tuple2._2();
}
});
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
@Override
public Iterator<String> call(String x) {
return Arrays.asList(x.split("\\s+"))
.iterator();
}
});
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
.iterator());
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) {
return new Tuple2<>(s, 1);
}
})
.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((Function2<Integer, Integer, Integer>) (i1, i2) -> i1 + i2);
Function3<String, Optional<Integer>, State<Integer>, Tuple2<String, Integer>> mappingFunc = (word, one, state) -> {
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
Tuple2<String, Integer> output = new Tuple2<>(word, sum);
state.update(sum);
return output;
};
}));
JavaPairRDD<String, Integer> initialRDD = JavaPairRDD.fromJavaRDD(sparkContext.emptyRDD());
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function(mappingFunc)
.initialState(initialRDD));
cumulativeWordCounts.foreachRDD(new VoidFunction<JavaRDD<Tuple2<String, Integer>>>() {
@Override
public void call(JavaRDD<Tuple2<String, Integer>> javaRdd) throws Exception {
cumulativeWordCounts.foreachRDD(javaRdd -> {
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
for (Tuple2<String, Integer> tuple : wordCountList) {
List<Word> words = Arrays.asList(new Word(tuple._1, tuple._2));
JavaRDD<Word> rdd = sparkContext.parallelize(words);
List<Word> wordList = Arrays.asList(new Word(tuple._1, tuple._2));
JavaRDD<Word> rdd = sparkContext.parallelize(wordList);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
}
});
streamingContext.start();

View File

@ -0,0 +1,27 @@
package com.baeldung.java.list;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("baeldung");
vector.add("Vector");
vector.add("example");
Enumeration e = vector.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
Iterator<String> iterator = vector.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

View File

@ -9,7 +9,7 @@ import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10)
public class ArrayListBenchmark {
@ -17,6 +17,7 @@ public class ArrayListBenchmark {
public static class MyState {
List<Employee> employeeList = new ArrayList<>();
Vector<Employee> employeeVector = new Vector<>();
//LinkedList<Employee> employeeList = new LinkedList<>();
long iterations = 100000;
@ -29,9 +30,11 @@ public class ArrayListBenchmark {
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
employeeVector.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeVector.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@ -46,6 +49,11 @@ public class ArrayListBenchmark {
return state.employeeList.contains(state.employee);
}
@Benchmark
public boolean testContainsVector(ArrayListBenchmark.MyState state) {
return state.employeeVector.contains(state.employee);
}
@Benchmark
public int testIndexOf(ArrayListBenchmark.MyState state) {
return state.employeeList.indexOf(state.employee);
@ -56,19 +64,24 @@ public class ArrayListBenchmark {
return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public Employee testVectorGet(ArrayListBenchmark.MyState state) {
return state.employeeVector.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(ArrayListBenchmark.MyState state) {
return state.employeeList.remove(state.employee);
}
// @Benchmark
// public void testAdd(ArrayListBenchmark.MyState state) {
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
// }
@Benchmark
public void testAdd(ArrayListBenchmark.MyState state) {
state.employeeList.add(new Employee(state.iterations + 1, "John"));
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
.include(ArrayListBenchmark.class.getSimpleName()).threads(3)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();

View File

@ -0,0 +1,48 @@
package com.baeldung.queueinterface;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.LinkedList;
public class CustomBaeldungQueue<T> extends AbstractQueue<T> {
private LinkedList<T> elements;
public CustomBaeldungQueue() {
this.elements = new LinkedList<T>();
}
@Override
public Iterator<T> iterator() {
return elements.iterator();
}
@Override
public int size() {
return elements.size();
}
@Override
public boolean offer(T t) {
if(t == null) return false;
elements.add(t);
return true;
}
@Override
public T poll() {
Iterator<T> iter = elements.iterator();
T t = iter.next();
if(t != null){
iter.remove();
return t;
}
return null;
}
@Override
public T peek() {
return elements.getFirst();
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.queueinterface;
import org.junit.Before;
import org.junit.Test;
import java.util.PriorityQueue;
import static org.junit.Assert.assertEquals;
public class PriorityQueueUnitTest {
@Test
public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() {
PriorityQueue<Integer> integerQueue = new PriorityQueue<>();
integerQueue.add(9);
integerQueue.add(2);
integerQueue.add(4);
int first = integerQueue.poll();
int second = integerQueue.poll();
int third = integerQueue.poll();
assertEquals(2, first);
assertEquals(4, second);
assertEquals(9, third);
}
@Test
public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() {
PriorityQueue<String> stringQueue = new PriorityQueue<>();
stringQueue.add("banana");
stringQueue.add("apple");
stringQueue.add("cherry");
String first = stringQueue.poll();
String second = stringQueue.poll();
String third = stringQueue.poll();
assertEquals("apple", first);
assertEquals("banana", second);
assertEquals("cherry", third);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.queueinterface;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class CustomBaeldungQueueUnitTest {
private CustomBaeldungQueue<Integer> customQueue;
@Before
public void setUp() throws Exception {
customQueue = new CustomBaeldungQueue<>();
}
@Test
public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() {
customQueue.add(7);
customQueue.add(5);
int first = customQueue.poll();
int second = customQueue.poll();
assertEquals(7, first);
assertEquals(5, second);
}
}

View File

@ -0,0 +1,86 @@
package com.baeldung.concurrent.threadsafety.application;
import com.baeldung.concurrent.threadsafety.callables.AtomicCounterCallable;
import com.baeldung.concurrent.threadsafety.mathutils.MathUtils;
import com.baeldung.concurrent.threadsafety.callables.CounterCallable;
import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable;
import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable;
import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable;
import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.AtomicCounter;
import com.baeldung.concurrent.threadsafety.services.Counter;
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
import com.baeldung.concurrent.threadsafety.services.MessageService;
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Application {
public static void main(String[] args) throws InterruptedException, ExecutionException {
new Thread(() -> {
System.out.println(MathUtils.factorial(10));
}).start();
new Thread(() -> {
System.out.println(MathUtils.factorial(5));
}).start();
ExecutorService executorService = Executors.newFixedThreadPool(10);
MessageService messageService = new MessageService("Welcome to Baeldung!");
Future<String> future1 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
Future<String> future2 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
System.out.println(future1.get());
System.out.println(future2.get());
Counter counter = new Counter();
Future<Integer> future3 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
Future<Integer> future4 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
System.out.println(future3.get());
System.out.println(future4.get());
ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter();
Future<Integer> future5 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter));
Future<Integer> future6 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter));
System.out.println(future5.get());
System.out.println(future6.get());
ReentrantLockCounter reentrantLockCounter = new ReentrantLockCounter();
Future<Integer> future7 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter));
Future<Integer> future8 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter));
System.out.println(future7.get());
System.out.println(future8.get());
ReentrantReadWriteLockCounter reentrantReadWriteLockCounter = new ReentrantReadWriteLockCounter();
Future<Integer> future9 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter));
Future<Integer> future10 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter));
System.out.println(future9.get());
System.out.println(future10.get());
AtomicCounter atomicCounter = new AtomicCounter();
Future<Integer> future11 = (Future<Integer>) executorService.submit(new AtomicCounterCallable(atomicCounter));
Future<Integer> future12 = (Future<Integer>) executorService.submit(new AtomicCounterCallable(atomicCounter));
System.out.println(future11.get());
System.out.println(future12.get());
Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());
Thread thread11 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)));
Thread thread12 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)));
thread11.start();
thread12.start();
Map<String,String> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("1", "one");
concurrentMap.put("2", "two");
concurrentMap.put("3", "three");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.AtomicCounter;
import java.util.concurrent.Callable;
public class AtomicCounterCallable implements Callable<Integer> {
private final AtomicCounter counter;
public AtomicCounterCallable(AtomicCounter counter) {
this.counter = counter;
}
@Override
public Integer call() throws Exception {
counter.incrementCounter();
return counter.getCounter();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.Counter;
import java.util.concurrent.Callable;
public class CounterCallable implements Callable<Integer> {
private final Counter counter;
public CounterCallable(Counter counter) {
this.counter = counter;
}
@Override
public Integer call() throws Exception {
counter.incrementCounter();
return counter.getCounter();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
import java.util.concurrent.Callable;
public class ExtrinsicLockCounterCallable implements Callable<Integer> {
private final ExtrinsicLockCounter counter;
public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) {
this.counter = counter;
}
@Override
public Integer call() throws Exception {
counter.incrementCounter();
return counter.getCounter();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.MessageService;
import java.util.concurrent.Callable;
public class MessageServiceCallable implements Callable<String> {
private final MessageService messageService;
public MessageServiceCallable(MessageService messageService) {
this.messageService = messageService;
}
@Override
public String call() {
return messageService.getMesssage();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
import java.util.concurrent.Callable;
public class ReentranReadWriteLockCounterCallable implements Callable<Integer> {
private final ReentrantReadWriteLockCounter counter;
public ReentranReadWriteLockCounterCallable(ReentrantReadWriteLockCounter counter) {
this.counter = counter;
}
@Override
public Integer call() throws Exception {
counter.incrementCounter();
return counter.getCounter();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.concurrent.threadsafety.callables;
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
import java.util.concurrent.Callable;
public class ReentrantLockCounterCallable implements Callable<Integer> {
private final ReentrantLockCounter counter;
public ReentrantLockCounterCallable(ReentrantLockCounter counter) {
this.counter = counter;
}
@Override
public Integer call() throws Exception {
counter.incrementCounter();
return counter.getCounter();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.concurrent.threadsafety.mathutils;
import java.math.BigInteger;
public class MathUtils {
public static BigInteger factorial(int number) {
BigInteger f = new BigInteger("1");
for (int i = 2; i <= number; i++) {
f = f.multiply(BigInteger.valueOf(i));
}
return f;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.concurrent.threadsafety.services;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private final AtomicInteger counter = new AtomicInteger();
public AtomicCounter() {}
public void incrementCounter() {
counter.incrementAndGet();
}
public synchronized int getCounter() {
return counter.get();
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.concurrent.threadsafety.services;
public class Counter {
private volatile int counter;
public Counter() {
this.counter = 0;
}
public synchronized void incrementCounter() {
counter += 1;
}
public int getCounter() {
return counter;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.services;
public class ExtrinsicLockCounter {
private int counter;
private final Object lock = new Object();
public ExtrinsicLockCounter() {
this.counter = 0;
}
public void incrementCounter() {
synchronized (lock) {
counter += 1;
}
}
public int getCounter() {
synchronized (lock) {
return counter;
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.concurrent.threadsafety.services;
public class MessageService {
private final String message;
public MessageService(String message) {
this.message = message;
}
public String getMesssage() {
return message;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.concurrent.threadsafety.services;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockCounter {
private int counter;
private final ReentrantLock reLock = new ReentrantLock(true);
public ReentrantLockCounter() {
this.counter = 0;
}
public void incrementCounter() {
reLock.lock();
try {
counter += 1;
} finally {
reLock.unlock();
}
}
public int getCounter() {
return counter;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.concurrent.threadsafety.services;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReentrantReadWriteLockCounter {
private int counter;
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
private final Lock writeLock = rwLock.writeLock();
public ReentrantReadWriteLockCounter() {
this.counter = 0;
}
public void incrementCounter() {
writeLock.lock();
try {
counter += 1;
} finally {
writeLock.unlock();
}
}
public int getCounter() {
readLock.lock();
try {
return counter;
} finally {
readLock.unlock();
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.concurrent.threadsafety.services;
public class StateHolder {
private final String state;
public StateHolder(String state) {
this.state = state;
}
public String getState() {
return state;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.CounterCallable;
import com.baeldung.concurrent.threadsafety.services.Counter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Counter counter = new Counter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExtrinsicLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ExtrinsicLockCounter counter = new ExtrinsicLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.mathutils.MathUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MathUtilsTest {
@Test
public void whenCalledFactorialMethod_thenCorrect() {
assertThat(MathUtils.factorial(2)).isEqualTo(2);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable;
import com.baeldung.concurrent.threadsafety.services.MessageService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MessageServiceTest {
@Test
public void whenCalledgetMessage_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
MessageService messageService = new MessageService("Welcome to Baeldung!");
Future<String> future1 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
Future<String> future2 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
assertThat(future1.get()).isEqualTo("Welcome to Baeldung!");
assertThat(future2.get()).isEqualTo("Welcome to Baeldung!");
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ReentrantLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantLockCounter counter = new ReentrantLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ReentrantReadWriteLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@ -0,0 +1,60 @@
package org.baeldung.java.io;
import com.google.common.io.ByteStreams;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InputStreamToByteBufferUnitTest {
@Test
public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length());
FileInputStream in = new FileInputStream(inputFile);
in.getChannel().read(bufferByte);
assertEquals(bufferByte.position(), inputFile.length());
}
@Test
public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length());
ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel();
IOUtils.readFully(readableByteChannel, bufferByte);
assertEquals(bufferByte.position(), inputFile.length());
}
@Test
public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
FileInputStream in = new FileInputStream(inputFile);
byte[] targetArray = ByteStreams.toByteArray(in);
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
bufferByte.rewind();
while (bufferByte.hasRemaining()) {
bufferByte.get();
}
assertEquals(bufferByte.position(), inputFile.length());
}
private File getFile() {
ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader();
String fileName = "frontenac-2257154_960_720.jpg";
return new File(classLoader.getResource(fileName).getFile());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

View File

@ -0,0 +1,32 @@
package com.baeldung.flightrecorder;
import java.util.ArrayList;
import java.util.List;
/**
* Simple program that illustrates how to use Java Flight Recorder.
*
* This programs creates a list, inserts objects in it until
* an OutOfMemoryError is thrown.
*
*/
public class FlightRecorder {
public static void main(String[] args) {
List<Object> items = new ArrayList<>(1);
try {
while (true) {
items.add(new Object());
}
} catch (OutOfMemoryError e) {
System.out.println(e.getMessage());
}
assert items.size() > 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}

View File

@ -0,0 +1,115 @@
package com.baeldung.ssl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EnableTLSv12 {
private final Logger logger = LoggerFactory.getLogger(EnableTLSv12.class);
public String url = "";
public Integer port = null;
public EnableTLSv12() {
}
public static void main(String[] args) throws IOException, KeyManagementException, NoSuchAlgorithmException {
EnableTLSv12 enableTLSv12 = new EnableTLSv12();
if (args.length != 2) {
System.out.println("Provide the server url and the secure port:");
System.exit(-1);
}
enableTLSv12.setHost(args);
enableTLSv12.setPort(args);
enableTLSv12.enableTLSv12UsingHttpConnection();
enableTLSv12.enableTLSv12UsingProtocol();
enableTLSv12.enableTLSv12UsingSSLContext();
enableTLSv12.enableTLSv12UsingSSLParameters();
}
private void setPort(String[] args) {
url = args[0];
}
private void setHost(String[] args) {
String portNumber = args[1];
port = Integer.parseInt(portNumber);
}
private void handleCommunication(SSLSocket socket, String usedTLSProcess) throws IOException {
logger.debug("Enabled TLS v1.2 on " + usedTLSProcess);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println("GET / HTTP/1.0");
out.println();
out.flush();
if (out.checkError()) {
logger.error("SSLSocketClient: java.io.PrintWriter error");
return;
}
String inputLine;
while ((inputLine = in.readLine()) != null)
logger.info(inputLine);
}
}
public void enableTLSv12UsingSSLParameters() throws UnknownHostException, IOException {
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url.trim(), port);
SSLParameters params = new SSLParameters();
params.setProtocols(new String[] { "TLSv1.2" });
sslSocket.setSSLParameters(params);
sslSocket.startHandshake();
handleCommunication(sslSocket, "SSLSocketFactory-SSLParameters");
}
public void enableTLSv12UsingProtocol() throws IOException {
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url, port);
sslSocket.setEnabledProtocols(new String[] { "TLSv1.2" });
sslSocket.startHandshake();
handleCommunication(sslSocket, "SSLSocketFactory-EnabledProtocols");
}
public void enableTLSv12UsingHttpConnection() throws IOException, NoSuchAlgorithmException, KeyManagementException {
URL urls = new URL("https://" + url + ":" + port);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
HttpsURLConnection connection = (HttpsURLConnection) urls.openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String input;
while ((input = br.readLine()) != null) {
logger.info(input);
}
}
logger.debug("Created TLSv1.2 connection on HttpsURLConnection");
}
public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port);
handleCommunication(socket, "SSLContext");
}
}

View File

@ -3,19 +3,16 @@ package com.baeldung.curltojava;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
public class JavaCurlExamplesUnitTest {
public class JavaCurlExamplesLiveTest {
@Test
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"";
ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" "));
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
@ -28,8 +25,8 @@ public class JavaCurlExamplesUnitTest {
@Test
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"";
ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" "));
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
@ -40,16 +37,14 @@ public class JavaCurlExamplesUnitTest {
}
@Test
public void whenRequestGet_thenReturnSuccessResponseCode() throws IOException {
String url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.connect();
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(command);
Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
// Get the POST result
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
Assert.assertTrue(null != content && !content.isEmpty());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.leapyear;
import java.time.Year;
import java.util.GregorianCalendar;
import org.junit.Assert;
import org.junit.Test;
public class LeapYearUnitTest {
//Before Java8
@Test
public void testLeapYearUsingGregorianCalendar () {
Assert.assertFalse(new GregorianCalendar().isLeapYear(2018));
}
//Java 8 and above
@Test
public void testLeapYearUsingJavaTimeYear () {
Assert.assertTrue(Year.isLeap(2012));
}
@Test
public void testBCYearUsingJavaTimeYear () {
Assert.assertTrue(Year.isLeap(-4));
}
@Test
public void testWrongLeapYearUsingJavaTimeYear () {
Assert.assertFalse(Year.isLeap(2018));
}
@Test
public void testLeapYearInDateUsingJavaTimeYear () {
LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE);
Assert.assertTrue(Year.from(date).isLeap());
}
}

View File

@ -72,17 +72,6 @@
<artifactId>injekt-core</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>uy.kohesive.kovert</groupId>
<artifactId>kovert-vertx</artifactId>
<version>[1.5.0,1.6.0)</version>
<exclusions>
<exclusion>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,34 @@
package com.baeldung.convert;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.stream.Collectors;
public class MapToString {
public static String convertWithIteration(Map<Integer, ?> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (Integer key : map.keySet()) {
mapAsString.append(key + "=" + map.get(key) + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
return mapAsString.toString();
}
public static String convertWithStream(Map<Integer, ?> map) {
String mapAsString = map.keySet().stream()
.map(key -> key + "=" + map.get(key))
.collect(Collectors.joining(", ", "{", "}"));
return mapAsString;
}
public static String convertWithGuava(Map<Integer, ?> map) {
return Joiner.on(",").withKeyValueSeparator("=").join(map);
}
public static String convertWithApache(Map map) {
return StringUtils.join(map);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.convert;
import com.google.common.base.Splitter;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class StringToMap {
public static Map<String, String> convertWithStream(String mapAsString) {
Map<String, String> map = Arrays.stream(mapAsString.split(","))
.map(entry -> entry.split("="))
.collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
return map;
}
public static Map<String, String> convertWithGuava(String mapAsString) {
return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.convert;
import org.apache.commons.collections4.MapUtils;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
public class MapToStringUnitTest {
private Map<Integer, String> wordsByKey = new HashMap<>();
@BeforeEach
public void setup() {
wordsByKey.clear();
wordsByKey.put(1, "one");
wordsByKey.put(2, "two");
wordsByKey.put(3, "three");
wordsByKey.put(4, "four");
}
@Test
public void givenMap_WhenUsingIteration_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithIteration(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}
@Test
public void givenMap_WhenUsingStream_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithStream(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}
@Test
public void givenMap_WhenUsingGuava_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithGuava(wordsByKey);
Assert.assertEquals("1=one,2=two,3=three,4=four", mapAsString);
}
@Test
public void givenMap_WhenUsingApache_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithApache(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
MapUtils.debugPrint(System.out, "Map as String", wordsByKey);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.convert;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.util.Map;
public class StringToMapUnitTest {
@Test
public void givenString_WhenUsingStream_ThenResultingStringIsCorrect() {
Map<String, String> wordsByKey = StringToMap.convertWithStream("1=one,2=two,3=three,4=four");
Assert.assertEquals(4, wordsByKey.size());
Assert.assertEquals("one", wordsByKey.get("1"));
}
@Test
void givenString_WhenUsingGuava_ThenResultingStringIsCorrect() {
Map<String, String> wordsByKey = StringToMap.convertWithGuava("1=one,2=two,3=three,4=four");
Assert.assertEquals(4, wordsByKey.size());
Assert.assertEquals("one", wordsByKey.get("1"));
}
}

View File

@ -72,16 +72,6 @@
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -0,0 +1,61 @@
package com.baeldung.string;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Pangram {
private static final int ALPHABET_COUNT = 26;
public static boolean isPangram(String str) {
if (str == null)
return false;
Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT];
Arrays.fill(alphabetMarker, false);
int alphabetIndex = 0;
String strUpper = str.toUpperCase();
for (int i = 0; i < str.length(); i++) {
if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') {
alphabetIndex = strUpper.charAt(i) - 'A';
alphabetMarker[alphabetIndex] = true;
}
}
for (boolean index : alphabetMarker) {
if (!index)
return false;
}
return true;
}
public static boolean isPangramWithStreams(String str) {
if (str == null)
return false;
// filtered character stream
String strUpper = str.toUpperCase();
Stream<Character> filteredCharStream = strUpper.chars()
.filter(item -> ((item >= 'A' && item <= 'Z')))
.mapToObj(c -> (char) c);
Map<Character, Boolean> alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1));
return (alphabetMap.size() == ALPHABET_COUNT);
}
public static boolean isPerfectPangram(String str) {
if (str == null)
return false;
// filtered character stream
String strUpper = str.toUpperCase();
Stream<Character> filteredCharStream = strUpper.chars()
.filter(item -> ((item >= 'A' && item <= 'Z')))
.mapToObj(c -> (char) c);
Map<Character, Long> alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values()
.stream()
.allMatch(item -> item == 1));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.string.tostring;
public class Customer {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.string.tostring;
import java.util.Arrays;
public class CustomerArrayToString extends Customer {
private Order[] orders;
public Order[] getOrders() {
return orders;
}
public void setOrders(Order[] orders) {
this.orders = orders;
}
@Override
public String toString() {
return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName()
+ ", getLastName()=" + getLastName() + "]";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.string.tostring;
public class CustomerComplexObjectToString extends Customer {
private Order order;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
@Override
public String toString() {
return "Customer [order=" + order + ", getFirstName()=" + getFirstName()
+ ", getLastName()=" + getLastName() + "]";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.string.tostring;
public class CustomerPrimitiveToString extends Customer {
private long balance;
public long getBalance() {
return balance;
}
public void setBalance(long balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName()
+ ", getLastName()=" + getLastName() + "]";
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.string.tostring;
import java.util.List;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class CustomerReflectionToString extends Customer{
private Integer score;
private List<String> orders;
private StringBuffer fullname;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public List<String> getOrders() {
return orders;
}
public void setOrders(List<String> orders) {
this.orders = orders;
}
public StringBuffer getFullname() {
return fullname;
}
public void setFullname(StringBuffer fullname) {
this.fullname = fullname;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.string.tostring;
import java.util.List;
public class CustomerWrapperCollectionToString extends Customer {
private Integer score;
private List<String> orders;
private StringBuffer fullname;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public List<String> getOrders() {
return orders;
}
public void setOrders(List<String> orders) {
this.orders = orders;
}
public StringBuffer getFullname() {
return fullname;
}
public void setFullname(StringBuffer fullname) {
this.fullname = fullname;
}
@Override
public String toString() {
return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname
+ ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.string.tostring;
public class Order {
private String orderId;
private String desc;
private long value;
private String status;
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]";
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.string;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PangramUnitTest {
@Test
public void givenValidString_isPangram_shouldReturnSuccess() {
String input = "Two driven jocks help fax my big quiz";
assertTrue(Pangram.isPangram(input));
assertTrue(Pangram.isPangramWithStreams(input));
}
@Test
public void givenNullString_isPangram_shouldReturnFailure() {
String input = null;
assertFalse(Pangram.isPangram(input));
assertFalse(Pangram.isPangramWithStreams(input));
assertFalse(Pangram.isPerfectPangram(input));
}
@Test
public void givenPerfectPangramString_isPerfectPangram_shouldReturnSuccess() {
String input = "abcdefghijklmNoPqrStuVwxyz";
assertTrue(Pangram.isPerfectPangram(input));
}
@Test
public void givenNonPangramString_isPangram_shouldReturnFailure() {
String input = "invalid pangram";
assertFalse(Pangram.isPangram(input));
assertFalse(Pangram.isPangramWithStreams(input));
}
@Test
public void givenPangram_isPerfectPangram_shouldReturnFailure() {
String input = "Two driven jocks help fax my big quiz";
assertFalse(Pangram.isPerfectPangram(input));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.string.tostring;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CustomerArrayToStringUnitTest {
private static final String CUSTOMER_ARRAY_TO_STRING
= "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]";
@Test
public void givenArray_whenToString_thenCustomerDetails() {
CustomerArrayToString customer = new CustomerArrayToString();
customer.setFirstName("Rajesh");
customer.setLastName("Bhojwani");
Order[] orders = new Order[1];
orders[0] = new Order();
orders[0].setOrderId("A1111");
orders[0].setDesc("Game");
orders[0].setStatus("In-Shiping");
customer.setOrders(orders);
assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString());
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.string.tostring;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CustomerComplexObjectToStringUnitTest {
private static final String CUSTOMER_COMPLEX_TO_STRING
= "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]";
@Test
public void givenComplex_whenToString_thenCustomerDetails() {
CustomerComplexObjectToString customer = new CustomerComplexObjectToString();
customer.setFirstName("Rajesh");
customer.setLastName("Bhojwani");
Order order = new Order();
order.setOrderId("A1111");
order.setDesc("Game");
order.setStatus("In-Shiping");
customer.setOrder(order);
assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.string.tostring;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CustomerPrimitiveToStringUnitTest {
private static final String CUSTOMER_PRIMITIVE_TO_STRING
= "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]";
@Test
public void givenPrimitive_whenToString_thenCustomerDetails() {
CustomerPrimitiveToString customer = new CustomerPrimitiveToString();
customer.setFirstName("Rajesh");
customer.setLastName("Bhojwani");
customer.setBalance(110);
assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString());
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.string.tostring;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class CustomerWrapperCollectionToStringUnitTest {
private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING
= "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]";
@Test
public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() {
CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString();
customer.setFirstName("Rajesh");
customer.setLastName("Bhojwani");
customer.setScore(8);
List<String> orders = new ArrayList<String>();
orders.add("Book");
orders.add("Pen");
customer.setOrders(orders);
StringBuffer fullname = new StringBuffer();
fullname.append(customer.getLastName()+", "+ customer.getFirstName());
customer.setFullname(fullname);
assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString());
}
}

View File

@ -95,6 +95,23 @@
<version>0.7.3</version>
</dependency>
<dependency>
<groupId>uy.kohesive.kovert</groupId>
<artifactId>kovert-vertx</artifactId>
<version>[1.5.0,1.6.0)</version>
<exclusions>
<exclusion>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
<version>3.3.0</version>
<type>pom</type>
</dependency>
</dependencies>
<properties>

View File

@ -1,88 +0,0 @@
##
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended
# to be used with the examples, and some settings may differ from those used in a production system, especially
# the `bootstrap.servers` and those specifying replication factors.
# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
bootstrap.servers=localhost:9092
# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs
group.id=connect-cluster
# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
# need to configure these based on the format they want their data in when loaded from or stored into Kafka
key.converter=org.apache.kafka.connect.json.JsonConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
# it to
key.converter.schemas.enable=true
value.converter.schemas.enable=true
# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted.
# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
# the topic before starting Kafka Connect if a specific topic configuration is needed.
# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
offset.storage.topic=connect-offsets
offset.storage.replication.factor=1
#offset.storage.partitions=25
# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated,
# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
# the topic before starting Kafka Connect if a specific topic configuration is needed.
# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
config.storage.topic=connect-configs
config.storage.replication.factor=1
# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted.
# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
# the topic before starting Kafka Connect if a specific topic configuration is needed.
# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
status.storage.topic=connect-status
status.storage.replication.factor=1
#status.storage.partitions=5
# Flush much faster than normal, which is useful for testing/debugging
offset.flush.interval.ms=10000
# These are provided to inform the user about the presence of the REST host and port configs
# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests.
#rest.host.name=
#rest.port=8083
# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers.
#rest.advertised.host.name=
#rest.advertised.port=
# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
# (connectors, converters, transformations). The list should consist of top level directories that include
# any combination of:
# a) directories immediately containing jars with plugins and their dependencies
# b) uber-jars with plugins and their dependencies
# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
# Examples:
# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a
# directory other than the home directory of Confluent Platform.
plugin.path=./share/java

View File

@ -1,22 +1,14 @@
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [{
"type": "home",
"number": "212 555-1234"
}, {
"type": "fax",
"number": "646 555-4567"
}
],
"gender": {
"type": "male"
"name": "mongodb-sink",
"config": {
"connector.class": "at.grahsl.kafka.connect.mongodb.MongoDbSinkConnector",
"tasks.max": 1,
"topics": "connect-custom",
"mongodb.connection.uri": "mongodb://mongo-db/test?retryWrites=true",
"mongodb.collection": "MyCollection",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": false,
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": false
}
}

View File

@ -3,9 +3,11 @@
"config": {
"connector.class": "io.confluent.connect.mqtt.MqttSourceConnector",
"tasks.max": 1,
"mqtt.server.uri": "ws://broker.hivemq.com:8000/mqtt",
"mqtt.server.uri": "tcp://mosquitto:1883",
"mqtt.topics": "baeldung",
"kafka.topic": "connect-custom",
"value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter"
"value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter",
"confluent.topic.bootstrap.servers": "kafka:9092",
"confluent.topic.replication.factor": 1
}
}

View File

@ -0,0 +1,94 @@
version: '3.3'
services:
mosquitto:
image: eclipse-mosquitto:1.5.5
hostname: mosquitto
container_name: mosquitto
expose:
- "1883"
ports:
- "1883:1883"
zookeeper:
image: zookeeper:3.4.9
restart: unless-stopped
hostname: zookeeper
container_name: zookeeper
ports:
- "2181:2181"
environment:
ZOO_MY_ID: 1
ZOO_PORT: 2181
ZOO_SERVERS: server.1=zookeeper:2888:3888
volumes:
- ./zookeeper/data:/data
- ./zookeeper/datalog:/datalog
kafka:
image: confluentinc/cp-kafka:5.1.0
hostname: kafka
container_name: kafka
ports:
- "9092:9092"
environment:
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
KAFKA_BROKER_ID: 1
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
volumes:
- ./kafka/data:/var/lib/kafka/data
depends_on:
- zookeeper
kafka-connect:
image: confluentinc/cp-kafka-connect:5.1.0
hostname: kafka-connect
container_name: kafka-connect
ports:
- "8083:8083"
environment:
CONNECT_BOOTSTRAP_SERVERS: "kafka:9092"
CONNECT_REST_ADVERTISED_HOST_NAME: connect
CONNECT_REST_PORT: 8083
CONNECT_GROUP_ID: compose-connect-group
CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs
CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets
CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status
CONNECT_KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter
CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter
CONNECT_INTERNAL_KEY_CONVERTER: "org.apache.kafka.connect.json.JsonConverter"
CONNECT_INTERNAL_VALUE_CONVERTER: "org.apache.kafka.connect.json.JsonConverter"
CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: "1"
CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: "1"
CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: "1"
CONNECT_PLUGIN_PATH: '/usr/share/java,/etc/kafka-connect/jars'
CONNECT_CONFLUENT_TOPIC_REPLICATION_FACTOR: 1
volumes:
- /tmp/custom/jars:/etc/kafka-connect/jars
depends_on:
- zookeeper
- kafka
- mosquitto
mongo-db:
image: mongo:4.0.5
hostname: mongo-db
container_name: mongo-db
expose:
- "27017"
ports:
- "27017:27017"
command: --bind_ip_all --smallfiles
volumes:
- ./mongo-db:/data
mongoclient:
image: mongoclient/mongoclient:2.2.0
container_name: mongoclient
hostname: mongoclient
depends_on:
- mongo-db
ports:
- 3000:3000
environment:
MONGO_URL: "mongodb://mongo-db:27017"
PORT: 3000
expose:
- "3000"

View File

@ -24,7 +24,7 @@
</dependencies>
<properties>
<guava.version>22.0</guava.version>
<guava.version>23.0</guava.version>
</properties>
</project>

View File

@ -1,6 +1,7 @@
package com.baeldung.dao.repositories.user;
import com.baeldung.domain.user.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -13,7 +14,7 @@ import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
public interface UserRepository extends JpaRepository<User, Integer> {
public interface UserRepository extends JpaRepository<User, Integer> , UserRepositoryCustom{
Stream<User> findAllByName(String name);

View File

@ -0,0 +1,10 @@
package com.baeldung.dao.repositories.user;
import java.util.List;
import java.util.Set;
import com.baeldung.domain.user.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
}

View File

@ -0,0 +1,43 @@
package com.baeldung.dao.repositories.user;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.baeldung.domain.user.User;
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByEmails(Set<String> emails) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> user = query.from(User.class);
Path<String> emailPath = user.get("email");
List<Predicate> predicates = new ArrayList<>();
for (String email : emails) {
predicates.add(cb.like(emailPath, email));
}
query.select(user)
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
}

View File

@ -18,7 +18,9 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
@ -274,8 +276,7 @@ public class UserRepositoryIntegrationTest {
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName
.get(0)
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@ -289,8 +290,7 @@ public class UserRepositoryIntegrationTest {
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength
.get(0)
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@ -304,8 +304,7 @@ public class UserRepositoryIntegrationTest {
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength
.get(0)
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@ -320,8 +319,7 @@ public class UserRepositoryIntegrationTest {
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage
.getContent()
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@ -337,8 +335,7 @@ public class UserRepositoryIntegrationTest {
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength
.getContent()
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@ -370,6 +367,30 @@ public class UserRepositoryIntegrationTest {
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindByEmailsWithDynamicQueryThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();

View File

@ -232,6 +232,7 @@
<version>${maven-war-plugin.version}</version>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>com.vackosar.gitflowincrementalbuilder</groupId>
@ -436,7 +437,7 @@
<module>java-collections-conversions</module>
<module>java-collections-maps</module>
<!-- <module>java-dates</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>java-ee-8-security-api</module>
<!-- <module>java-ee-8-security-api</module> --> <!-- long running -->
<module>java-lite</module>
<module>java-numbers</module>
<module>java-rmi</module>
@ -644,6 +645,7 @@
<module>spring-boot-logging-log4j2</module>
<module>spring-boot-mvc</module>
<module>spring-boot-ops</module>
<module>spring-boot-rest</module>
<module>spring-boot-property-exp</module>
<module>spring-boot-security</module>
<module>spring-boot-testing</module>
@ -1355,6 +1357,7 @@
<module>spring-boot-logging-log4j2</module>
<module>spring-boot-mvc</module>
<module>spring-boot-ops</module>
<module>spring-boot-rest</module>
<module>spring-boot-property-exp</module>
<module>spring-boot-security</module>
<module>spring-boot-vue</module>

View File

@ -57,6 +57,27 @@
</dependencies>
<profiles>
<profile>
<id>beanstalk</id>
<build>
<finalName>${project.name}-eb</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/cloud/config/*.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>openshift</id>
<properties>

View File

@ -0,0 +1,3 @@
spring.datasource.url=jdbc:mysql://${rds.hostname}:${rds.port}/${rds.db.name}
spring.datasource.username=${rds.username}
spring.datasource.password=${rds.password}

View File

@ -0,0 +1,3 @@
Module for the articles that are part of the Spring REST E-book:
1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)

43
spring-boot-rest/pom.xml Normal file
View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.web</groupId>
<artifactId>spring-boot-rest</artifactId>
<name>spring-boot-rest</name>
<description>Spring Boot Rest Module</description>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<start-class>com.baeldung.SpringBootRestApplication</start-class>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.web.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
}

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.boot.rest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringContextIntegrationTest {
@Test
public void contextLoads() {
}
}

View File

@ -33,7 +33,7 @@
</dependencies>
<properties>
<spring-kafka.version>1.1.3.RELEASE</spring-kafka.version>
<spring-kafka.version>2.2.2.RELEASE</spring-kafka.version>
<jackson.version>2.9.7</jackson.version>
</properties>

View File

@ -13,8 +13,11 @@ import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.TopicPartition;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@SpringBootApplication
public class KafkaApplication {
@ -98,7 +101,20 @@ public class KafkaApplication {
private String greetingTopicName;
public void sendMessage(String message) {
kafkaTemplate.send(topicName, message);
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topicName, message);
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata().offset() + "]");
}
@Override
public void onFailure(Throwable ex) {
System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage());
}
});
}
public void sendMessageToPartion(String message, int partition) {

View File

@ -0,0 +1,57 @@
package com.baeldung.spring.kafka;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaAdmin;
@Configuration
public class KafkaTopicConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Value(value = "${message.topic.name}")
private String topicName;
@Value(value = "${partitioned.topic.name}")
private String partionedTopicName;
@Value(value = "${filtered.topic.name}")
private String filteredTopicName;
@Value(value = "${greeting.topic.name}")
private String greetingTopicName;
@Bean
public KafkaAdmin kafkaAdmin() {
Map<String, Object> configs = new HashMap<>();
configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
return new KafkaAdmin(configs);
}
@Bean
public NewTopic topic1() {
return new NewTopic(topicName, 1, (short) 1);
}
@Bean
public NewTopic topic2() {
return new NewTopic(partionedTopicName, 6, (short) 1);
}
@Bean
public NewTopic topic3() {
return new NewTopic(filteredTopicName, 1, (short) 1);
}
@Bean
public NewTopic topic4() {
return new NewTopic(greetingTopicName, 1, (short) 1);
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.spring.kafka.KafkaApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = KafkaApplication.class)
public class SpringContextLiveTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}