Merge remote-tracking branch 'upstream/master'

This commit is contained in:
amdegregorio 2019-01-14 13:18:59 -05:00
commit 593dec6bec
184 changed files with 3431 additions and 545 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,52 +53,24 @@ 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 {
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
for (String key : wordCountMap.keySet()) {
List<Word> words = Arrays.asList(new Word(key, wordCountMap.get(key)));
JavaRDD<Word> rdd = streamingContext.sparkContext()
.parallelize(words);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
wordCounts.foreachRDD(javaRdd -> {
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
for (String key : wordCountMap.keySet()) {
List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
JavaRDD<Word> rdd = streamingContext.sparkContext()
.parallelize(wordList);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
});

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,63 +64,30 @@ 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 {
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);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
cumulativeWordCounts.foreachRDD(javaRdd -> {
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
for (Tuple2<String, Integer> tuple : wordCountList) {
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();
}
});

View File

@ -0,0 +1,42 @@
package com.baeldung.time;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Instant.class })
public class InstantUnitTest {
@Test
public void givenInstantMock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock);
mockStatic(Instant.class);
when(Instant.now()).thenReturn(instant);
Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
}
@Test
public void givenFixedClock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock);
assertThat(instant.toString()).isEqualTo(instantExpected);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.time;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
public class InstantWithJMockUnitTest {
@Test
public void givenInstantWithJMock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-21T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
new MockUp<Instant>() {
@Mock
public Instant now() {
return Instant.now(clock);
}
};
Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
}
@Test
public void givenInstantWithExpectations_whenNow_thenGetFixedInstant() {
Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC"));
Instant instantExpected = Instant.now(clock);
new Expectations(Instant.class) {
{
Instant.now();
result = instantExpected;
}
};
Instant now = Instant.now();
assertThat(now).isEqualTo(instantExpected);
}
}

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,100 @@
package com.baeldung.directories;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NewDirectoryUnitTest {
private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
@Before
public void beforeEach() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedInNewDirectory = new File(newDirectory, "nested_directory");
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
File nestedInExistingDirectory = new File(existingDirectory, "nested_directory");
nestedInNewDirectory.delete();
newDirectory.delete();
nestedInExistingDirectory.delete();
existingDirectory.mkdir();
existingNestedDirectory.mkdir();
}
@Test
public void givenUnexistingDirectory_whenMkdir_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
assertFalse(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertTrue(directoryCreated);
}
@Test
public void givenExistingDirectory_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
newDirectory.mkdir();
assertTrue(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertFalse(directoryCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdir();
assertFalse(directoriesCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingParentDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "existing_directory");
newDirectory.mkdir();
File nestedDirectory = new File(newDirectory, "nested_directory");
assertTrue(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingNestedDirectories_whenMkdirs_thenFalse() {
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
assertTrue(existingDirectory.exists());
assertTrue(existingNestedDirectory.exists());
boolean directoriesCreated = existingNestedDirectory.mkdirs();
assertFalse(directoriesCreated);
}
}

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,5 @@
package com.baeldung.keyword;
public class Circle extends Round implements Shape {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Ring extends Round {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Round {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.keyword;
public interface Shape {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Triangle implements Shape {
}

View File

@ -0,0 +1,55 @@
package com.baeldung.keyword.test;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import com.baeldung.keyword.Circle;
import com.baeldung.keyword.Ring;
import com.baeldung.keyword.Round;
import com.baeldung.keyword.Shape;
import com.baeldung.keyword.Triangle;
public class InstanceOfUnitTest {
@Test
public void giveWhenInstanceIsCorrect_thenReturnTrue() {
Ring ring = new Ring();
Assert.assertTrue("ring is instance of Round ", ring instanceof Round);
}
@Test
public void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle);
}
@Test
public void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Round", circle instanceof Round);
}
@Test
public void giveWhenTypeIsInterface_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Shape", circle instanceof Shape);
}
@Test
public void giveWhenTypeIsOfObjectType_thenReturnTrue() {
Thread thread = new Thread();
Assert.assertTrue("thread is instance of Object", thread instanceof Object);
}
@Test
public void giveWhenInstanceValueIsNull_thenReturnFalse() {
Circle circle = null;
Assert.assertFalse("circle is instance of Round", circle instanceof Round);
}
@Test
public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
// Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle);
}
}

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

@ -13,6 +13,7 @@
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-io</groupId>

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,41 @@
package com.baeldung.leapyear;
import java.time.LocalDate;
import java.time.Year;
import java.time.format.DateTimeFormatter;
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

@ -37,17 +37,17 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<!-- Ethereum -->
@ -123,12 +123,12 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
@ -212,7 +212,6 @@
<tomcat.version>8.5.4</tomcat.version>
<ethereumj-core.version>1.5.0-RELEASE</ethereumj-core.version>
<web3j.core.version>3.3.1</web3j.core.version>
<springframework.version>5.0.5.RELEASE</springframework.version>
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
<mockito.version>2.21.0</mockito.version>
<jackson-databind.version>2.9.7</jackson-databind.version>

View File

@ -0,0 +1,24 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Employee {
private final long id;
private final String name;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = Person.Builder.class)
public class Person {
private final String name;
private final Integer age;
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@JsonPOJOBuilder
static class Builder {
String name;
Integer age;
Builder withName(String name) {
this.name = name;
return this;
}
Builder withAge(Integer age) {
this.age = age;
return this;
}
Person build() {
return new Person(name, age);
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jackson.deserialization.immutable;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class ImmutableObjectDeserializationUnitTest {
@Test
public void whenPublicConstructorIsUsed_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\",\"id\":5000}";
Employee employee = new ObjectMapper().readValue(json, Employee.class);
assertEquals("Frank", employee.getName());
assertEquals(5000, employee.getId());
}
@Test
public void whenBuilderIsUsedAndFieldIsNull_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\"}";
Person person = new ObjectMapper().readValue(json, Person.class);
assertEquals("Frank", person.getName());
assertNull(person.getAge());
}
@Test
public void whenBuilderIsUsedAndAllFieldsPresent_thenObjectIsDeserialized() throws IOException {
final String json = "{\"name\":\"Frank\",\"age\":50}";
Person person = new ObjectMapper().readValue(json, Person.class);
assertEquals("Frank", person.getName());
assertEquals(50, (int) person.getAge());
}
}

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,118 @@
package com.baeldung.stream;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.StringWriter;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PeekUnitTest {
private StringWriter out;
@BeforeEach
void setup() {
out = new StringWriter();
}
@Test
void givenStringStream_whenCallingPeekOnly_thenNoElementProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append);
// then
assertThat(out.toString()).isEmpty();
}
@Test
void givenStringStream_whenCallingForEachOnly_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndNoopForEach_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.forEach(this::noop);
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndCollect_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.collect(Collectors.toList());
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndForEach_thenElementsProcessedTwice() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("AliceAliceBobBobChuckChuck");
}
@Test
void givenStringStream_whenCallingPeek_thenElementsProcessedTwice() {
// given
Stream<User> userStream = Stream.of(new User("Alice"), new User("Bob"), new User("Chuck"));
// when
userStream.peek(u -> u.setName(u.getName().toLowerCase()))
.map(User::getName)
.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("alicebobchuck");
}
private static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private void noop(String s) {
}
}

View File

@ -49,3 +49,4 @@
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Java toString() Method](https://www.baeldung.com/java-tostring)

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

@ -1,7 +1,7 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.RegExUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@ -9,7 +9,6 @@ import static org.junit.Assert.assertTrue;
public class StringReplaceAndRemoveUnitTest {
@Test
public void givenTestStrings_whenReplace_thenProcessedString() {
@ -26,7 +25,7 @@ public class StringReplaceAndRemoveUnitTest {
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
String master2 = "Welcome to Baeldung, Hello World Baeldung";
String regexTarget= "(Baeldung)$";
String regexTarget = "(Baeldung)$";
String replacement = "Java";
String processed2 = master2.replaceAll(regexTarget, replacement);
assertTrue(processed2.endsWith("Java"));
@ -45,18 +44,16 @@ public class StringReplaceAndRemoveUnitTest {
StringBuilder builder = new StringBuilder(master);
builder.delete(startIndex, stopIndex);
assertFalse(builder.toString().contains(target));
assertFalse(builder.toString()
.contains(target));
builder.replace(startIndex, stopIndex, replacement);
assertTrue(builder.toString().contains(replacement));
assertTrue(builder.toString()
.contains(replacement));
}
@Test
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
@ -74,10 +71,20 @@ public class StringReplaceAndRemoveUnitTest {
}
@Test
public void givenTestStrings_whenReplaceExactWord_thenProcessedString() {
String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!";
String regexTarget = "\\bcar\\b";
String exactWordReplaced = sentence.replaceAll(regexTarget, "truck");
assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced));
}
@Test
public void givenTestStrings_whenReplaceExactWordUsingRegExUtilsMethod_thenProcessedString() {
String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!";
String regexTarget = "\\bcar\\b";
String exactWordReplaced = RegExUtils.replaceAll(sentence, regexTarget, "truck");
assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced));
}
}

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

@ -29,11 +29,11 @@
</dependencies>
<properties>
<spring.version>5.0.6.RELEASE</spring.version>
<spring.version>5.1.2.RELEASE</spring.version>
<junit.jupiter.version>5.0.2</junit.jupiter.version>
<jackson-databind.version>2.9.6</jackson-databind.version>
<jackson.version>2.9.6</jackson.version>
<spring-security.version>5.0.6.RELEASE</spring-security.version>
<spring-security.version>5.1.2.RELEASE</spring-security.version>
</properties>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
@Entity
public class EntityWithNoId {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.hibernate.exception;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName)
throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
}
private static SessionFactory makeSessionFactory(
ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Product.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry()
throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME,
"hibernate-exception.properties"));
try (FileInputStream inputStream = new FileInputStream(
propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Product {
private int id;
private String name;
private String description;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,425 @@
package com.baeldung.hibernate.exception;
import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PropertyValueException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.query.NativeQuery;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateExceptionUnitTest {
private static final Logger logger = LoggerFactory
.getLogger(HibernateExceptionUnitTest.class);
private SessionFactory sessionFactory;
@Before
public void setUp() throws IOException {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Rule
public ExpectedException thrown = ExpectedException.none();
private Configuration getConfiguration() {
Configuration cfg = new Configuration();
cfg.setProperty(AvailableSettings.DIALECT,
"org.hibernate.dialect.H2Dialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver");
cfg.setProperty(AvailableSettings.URL,
"jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1");
cfg.setProperty(AvailableSettings.USER, "sa");
cfg.setProperty(AvailableSettings.PASS, "");
return cfg;
}
@Test
public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
thrown.expectCause(isA(MappingException.class));
thrown.expectMessage("Unknown entity: java.lang.String");
Session session = sessionFactory.openSession();
NativeQuery<String> query = session
.createNativeQuery("select name from PRODUCT", String.class);
query.getResultList();
}
@Test
@SuppressWarnings("rawtypes")
public void whenQueryExecuted_thenOK() {
Session session = sessionFactory.openSession();
NativeQuery query = session
.createNativeQuery("select name from PRODUCT");
List results = query.getResultList();
assertNotNull(results);
}
@Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
thrown.expect(AnnotationException.class);
thrown.expectMessage("No identifier specified for entity");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(EntityWithNoId.class);
cfg.buildSessionFactory();
}
@Test
public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() {
thrown.expect(SchemaManagementException.class);
thrown.expectMessage("Schema-validation: missing table");
Configuration cfg = getConfiguration();
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");
cfg.addAnnotatedClass(Product.class);
cfg.buildSessionFactory();
}
@Test
public void whenWrongDialectSpecified_thenCommandAcceptanceException() {
thrown.expect(SchemaManagementException.class);
thrown.expectCause(isA(CommandAcceptanceException.class));
thrown.expectMessage("Halting on error : Error executing DDL");
Configuration cfg = getConfiguration();
cfg.setProperty(AvailableSettings.DIALECT,
"org.hibernate.dialect.MySQLDialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");
// This does not work due to hibernate bug
// cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true");
cfg.getProperties()
.put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true);
cfg.addAnnotatedClass(Product.class);
cfg.buildSessionFactory();
}
@Test
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown
.expectMessage("SQLGrammarException: could not prepare statement");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class);
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
product.setName("Product 1");
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
closeSessionFactoryQuietly(sessionFactory);
}
}
@Test
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown
.expectMessage("SQLGrammarException: could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery(
"select * from NON_EXISTING_TABLE", Product.class);
query.getResultList();
}
@Test
public void whenDuplicateIdSaved_thenConstraintViolationException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class));
thrown.expectMessage(
"ConstraintViolationException: could not execute statement");
Session session = null;
Transaction transaction = null;
for (int i = 1; i <= 2; i++) {
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
product.setName("Product " + i);
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
}
@Test
public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() {
thrown.expect(isA(PropertyValueException.class));
thrown.expectMessage(
"not-null property references a null or transient value");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));
thrown.expectMessage(
"org.hibernate.exception.DataException: could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery(
"select * from PRODUCT where id='wrongTypeId'", Product.class);
query.getResultList();
}
@Test
public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() {
thrown.expect(isA(NonUniqueObjectException.class));
thrown.expectMessage(
"A different object with the same identifier value was already associated with the session");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(1);
product1.setName("Product 1");
session.save(product1);
Product product2 = new Product();
product2.setId(1);
product2.setName("Product 2");
session.save(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void whenDeletingADeletedObject_thenOptimisticLockException() {
thrown.expect(isA(OptimisticLockException.class));
thrown.expectMessage(
"Batch update returned unexpected row count from update");
thrown.expectCause(isA(StaleStateException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(12);
product1.setName("Product 12");
session.save(product1);
transaction.commit();
session.close();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product2 = session.get(Product.class, 12);
session.createNativeQuery("delete from Product where id=12")
.executeUpdate();
// We need to refresh to fix the error.
// session.refresh(product2);
session.delete(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class));
thrown
.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(15);
product1.setName("Product1");
session.update(product1);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
thrown.expect(isA(TransactionException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(15);
product1.setName("Product1");
session.save(product1);
transaction.setRollbackOnly();
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
private void rollbackTransactionQuietly(Transaction transaction) {
if (transaction != null && transaction.isActive()) {
try {
transaction.rollback();
} catch (Exception e) {
logger.error("Exception while rolling back transaction", e);
}
}
}
private void closeSessionQuietly(Session session) {
if (session != null) {
try {
session.close();
} catch (Exception e) {
logger.error("Exception while closing session", e);
}
}
}
private void closeSessionFactoryQuietly(SessionFactory sessionFactory) {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (Exception e) {
logger.error("Exception while closing sessionFactory", e);
}
}
}
@Test
public void givenExistingEntity_whenIdUpdated_thenHibernateException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(HibernateException.class));
thrown.expectMessage(
"identifier of an instance of com.baeldung.hibernate.exception.Product was altered");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(222);
product1.setName("Product 222");
session.save(product1);
transaction.commit();
closeSessionQuietly(session);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product2 = session.get(Product.class, 222);
product2.setId(333);
session.save(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
}

View File

@ -0,0 +1,16 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory

View File

@ -0,0 +1,25 @@
package com.baeldung.util;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Optional;
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate localDate) {
return Optional.ofNullable(localDate)
.map(Date::valueOf)
.orElse(null);
}
@Override
public LocalDate convertToEntityAttribute(Date date) {
return Optional.ofNullable(date)
.map(Date::toLocalDate)
.orElse(null);
}
}

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