[BAEL-10866] - Resolved conflicts

This commit is contained in:
amit2103 2018-12-22 18:58:28 +05:30
commit afe4a98944
239 changed files with 3435 additions and 3002 deletions

5
core-java-11/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant articles
- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)

View File

@ -0,0 +1,43 @@
package com.baeldung;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NewStringAPIUnitTest {
@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
String output = "La ".repeat(2) + "Land";
is(output).equals("La La Land");
}
@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
is("\n\t hello \u2005".strip()).equals("hello");
}
@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
is("\n\t hello \u2005".trim()).equals("hello \u2005");
}
@Test
public void whenBlankString_thenReturnTrue() {
assertTrue("\n\t\u2005 ".isBlank());
}
@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
String multilineStr = "This is\n \n a multiline\n string.";
long lineCount = multilineStr.lines()
.filter(String::isBlank)
.count();
is(lineCount).equals(3L);
}
}

View File

@ -15,7 +15,6 @@
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)

View File

@ -0,0 +1,131 @@
package com.baeldung.java8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Test;
public class Java8PredicateChainUnitTest {
private List<String> names = Arrays.asList("Adam", "Alexander", "John", "Tom");
@Test
public void whenFilterList_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
@Test
public void whenFilterListWithMultipleFilters_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.filter(name -> name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithComplexPredicate_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A") && name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesInline_thenSuccess() {
List<String> result = names.stream()
.filter(((Predicate<String>) name -> name.startsWith("A")).and(name -> name.length() < 5))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingAnd_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("A");
Predicate<String> predicate2 = str -> str.length() < 5;
List<String> result = names.stream()
.filter(predicate1.and(predicate2))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOr_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("John", "Tom"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOrAndNegate_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2.negate()))
.collect(Collectors.toList());
assertEquals(3, result.size());
assertThat(result, contains("Adam", "Alexander", "John"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> true, Predicate::and))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Alexander"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingOr_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> false, Predicate::or))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
}

View File

@ -9,7 +9,6 @@
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)

View File

@ -7,6 +7,14 @@ public class Employee implements Serializable {
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}

View File

@ -0,0 +1,90 @@
package com.baeldung.sort;
import com.baeldung.arraycopy.model.Employee;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.junit.Assert.assertArrayEquals;
public class ArraySortUnitTest {
private Employee[] employees;
private int[] numbers;
private String[] strings;
private Employee john = new Employee(6, "John");
private Employee mary = new Employee(3, "Mary");
private Employee david = new Employee(4, "David");
@Before
public void setup() {
createEmployeesArray();
createNumbersArray();
createStringArray();
}
private void createEmployeesArray() {
employees = new Employee[]{john, mary, david};
}
private void createNumbersArray() {
numbers = new int[]{-8, 7, 5, 9, 10, -2, 3};
}
private void createStringArray() {
strings = new String[]{"learning", "java", "with", "baeldung"};
}
@Test
public void givenIntArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(numbers);
assertArrayEquals(new int[]{-8, -2, 3, 5, 7, 9, 10}, numbers);
}
@Test
public void givenIntArray_whenSortingDescending_thenCorrectlySorted() {
numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
assertArrayEquals(new int[]{10, 9, 7, 5, 3, -2, -8}, numbers);
}
@Test
public void givenStringArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(strings);
assertArrayEquals(new String[]{"baeldung", "java", "learning", "with"}, strings);
}
@Test
public void givenStringArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(strings, Comparator.reverseOrder());
assertArrayEquals(new String[]{"with", "learning", "java", "baeldung"}, strings);
}
@Test
public void givenObjectArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
@Test
public void givenObjectArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed());
assertArrayEquals(new Employee[]{mary, john, david}, employees);
}
@Test
public void givenObjectArray_whenSortingMultipleAttributesAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
}

View File

@ -5,6 +5,10 @@ import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ListJUnitTest {
@ -18,4 +22,26 @@ public class ListJUnitTest {
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
}
@Test
public void whenIntersection_ShouldReturnCommonElements() throws Exception {
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Set<String> commonElements = new HashSet(Arrays.asList("red", "green"));
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, result);
Set<String> inverseResult = otherList.stream()
.distinct()
.filter(list::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, inverseResult);
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.controlstructures;
public class ConditionalBranches {
/**
* Multiple if/else/else if statements examples. Shows different syntax usage.
*/
public static void ifElseStatementsExamples() {
int count = 2; // Initial count value.
// Basic syntax. Only one statement follows. No brace usage.
if (count > 1)
System.out.println("Count is higher than 1");
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
// If/Else syntax. Two different courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
// If/Else/Else If syntax. Three or more courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
}
/**
* Ternary Operator example.
* @see ConditionalBranches#ifElseStatementsExamples()
*/
public static void ternaryExample() {
int count = 2;
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
}
/**
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
*/
public static void switchExample() {
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
case 2:
System.out.println("Count is equal to 2");
break;
default:
System.out.println("Count is either negative, or higher than 2");
break;
}
}
}

View File

@ -0,0 +1,123 @@
package com.baeldung.controlstructures;
public class Loops {
/**
* Dummy method. Only prints a generic message.
*/
private static void methodToRepeat() {
System.out.println("Dummy method.");
}
/**
* Shows how to iterate 50 times with 3 different method/control structures.
*/
public static void repetitionTo50Examples() {
for (int i = 1; i <= 50; i++) {
methodToRepeat();
}
int whileCounter = 1;
while (whileCounter <= 50) {
methodToRepeat();
whileCounter++;
}
int count = 1;
do {
methodToRepeat();
count++;
} while (count < 50);
}
/**
* Splits a sentence in words, and prints each word in a new line.
* @param sentence Sentence to print as independent words.
*/
public static void printWordByWord(String sentence) {
for (String word : sentence.split(" ")) {
System.out.println(word);
}
}
/**
* Prints text an N amount of times. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text.
*/
public static void printTextNTimes(String textToPrint, int times) {
int counter = 1;
while (true) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times.
*/
public static void printTextNTimesUpTo50(String textToPrint, int times) {
int counter = 1;
while (counter < 50) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbers(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (true) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
/**
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (amountPrinted < 100) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
}

View File

@ -1,2 +1 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -14,25 +14,20 @@
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
@ -41,9 +36,8 @@
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
@ -84,7 +78,6 @@
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)

Binary file not shown.

View File

@ -1,2 +1 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -0,0 +1,63 @@
package com.baeldung.gc;
import java.util.HashMap;
import java.util.Map;
/**
* A simple Java program to demonstrate how to enable verbose Garbage Collection (GC) logging.
* <p>
* This simple program loads 3 million {@link java.lang.String} instances into a {@link java.util.HashMap}
* object before making an explicit call to the garbage collector using <code>System.gc()</code>.
* <p>
* Finally, it removes 2 million of the {@link java.lang.String} instances from the {@link java.util.HashMap}.
* We also explicitly use <code>System.out.println</code> to make interpreting the output easier.
* <p>
* Run this program with the following arguments to see verbose GC logging in its complete form:
* <pre>
* -XX:+UseSerialGC -Xms1024m -Xmx1024m -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:/path/to/file/gc.log
* </pre>
* Where:
* <ul>
* <li><code>-XX:+UseSerialGC</code> - specify the serial garbage collector.</li>
* <li><code>-Xms1024m</code> - specify the minimal heap size.</li>
* <li><code>-Xmx1024m</code> - specify the maximal heap size.</li>
* <li><code>-verbose:gc</code> - activate the logging of garbage collection information in its simplest form.</li>
* <li><code>-XX:+PrintGCDetails</code> - activate detailed information about garbage collection.</li>
* <li><code>-XX:+PrintGCTimeStamps</code> - include a timestamp in the output reflecting the real-time passed in seconds since the JVM started.</li>
* <li><code>-XX:+PrintGCDateStamps</code> - include the absolute date and time at the start of each line.</li>
* <li><code>-Xloggc</code> - by default the GC log is written to stdout. Specify an output file via this argument.</li>
* </ul>
* <p>
* It should be noted that the first three arguments are not strictly necessary but for the purposes or the example
* help really simplify things.
*
*/
public class VerboseGarbageCollectorRunner {
private static Map<String, String> stringContainer = new HashMap<>();
public static void main(String[] args) {
System.out.println("Start of program!");
String stringWithPrefix = "stringWithPrefix";
// Load Java Heap with 3 M java.lang.String instances
for (int i = 0; i < 3000000; i++) {
String newString = stringWithPrefix + i;
stringContainer.put(newString, newString);
}
System.out.println("MAP size: " + stringContainer.size());
// Explicit GC!
System.gc();
// Remove 2 M out of 3 M
for (int i = 0; i < 2000000; i++) {
String newString = stringWithPrefix + i;
stringContainer.remove(newString);
}
System.out.println("MAP size: " + stringContainer.size());
System.out.println("End of program!");
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.nativekeyword;
public class DateTimeUtils {
public native String getSystemTime();
static {
System.loadLibrary("nativedatetimeutils");
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.nativekeyword;
import com.baeldung.nativekeyword.DateTimeUtils;
public class NativeMainApp {
public static void main(String[] args) {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
String input = dateTimeUtils.getSystemTime();
System.out.println("System time is : " + input);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.nativekeyword;
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
public class DateTimeUtilsManualTest {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DateTimeUtilsManualTest.class);
@BeforeClass
public static void setUpClass() {
System.loadLibrary("msvcr100");
System.loadLibrary("libgcc_s_sjlj-1");
System.loadLibrary("libstdc++-6");
System.loadLibrary("nativedatetimeutils");
}
@Test
public void givenNativeLibsLoaded_thenNativeMethodIsAccessible() {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
LOG.info("System time is : " + dateTimeUtils.getSystemTime());
assertNotNull(dateTimeUtils.getSystemTime());
}
}

View File

@ -34,7 +34,6 @@
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)

View File

@ -0,0 +1,23 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> myRun(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
@ExperimentalContracts
fun callsInPlace() {
val i: Int
myRun {
i = 1 // Without contract initialization is forbidden due to possible re-assignment
}
println(i) // Without contract variable might be uninitialized
}

View File

@ -0,0 +1,43 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Request(val arg: String)
class Service {
@ExperimentalContracts
fun process(request: Request?) {
validate(request)
println(request.arg)
}
}
@ExperimentalContracts
private fun validate(request: Request?) {
contract {
returns() implies (request != null)
}
if (request == null) {
throw IllegalArgumentException("Undefined request")
}
}
data class MyEvent(val message: String)
@ExperimentalContracts
fun processEvent(event: Any?) {
if (isInterested(event)) {
println(event.message) // Compiler makes smart cast here with the help of contract
}
}
@ExperimentalContracts
fun isInterested(event: Any?): Boolean {
contract {
returns(true) implies (event is MyEvent)
}
return event is MyEvent
}

View File

@ -0,0 +1,17 @@
import com.baeldung.kotlin.constant.TestKotlinConstantClass
import com.baeldung.kotlin.constant.TestKotlinConstantObject
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class ConstantUnitTest {
@Test
fun givenConstant_whenCompareWithActualValue_thenReturnTrue() {
assertEquals(10, TestKotlinConstantObject.COMPILE_TIME_CONST)
assertEquals(30, TestKotlinConstantObject.RUN_TIME_CONST)
assertEquals(20, TestKotlinConstantObject.JAVA_STATIC_FINAL_FIELD)
assertEquals(40, TestKotlinConstantClass.COMPANION_OBJECT_NUMBER)
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.kotlin.constant
class TestKotlinConstantClass {
companion object {
const val COMPANION_OBJECT_NUMBER = 40
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.kotlin.constant
object TestKotlinConstantObject {
const val COMPILE_TIME_CONST = 10
val RUN_TIME_CONST: Int
@JvmField
val JAVA_STATIC_FINAL_FIELD = 20
init {
RUN_TIME_CONST = TestKotlinConstantObject.COMPILE_TIME_CONST + 20;
}
}

View File

@ -1,4 +1,4 @@
## Relevant articles:
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
[The Trie Data Structure in Java](https://www.baeldung.com/trie-java)
[Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class BooleanExample {
public boolean value;
public String toString() {
return "{boolean: " + value + "}";
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class ByteExample {
public byte value = (byte) 1;
public String toString() {
return "{byte: " + value + "}";
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class CharExample {
public char value;
public String toString() {
return "{char: " + value + "}";
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class DoubleExample {
public double value;
public String toString() {
return "{float: " + value + "}";
}
}

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class FloatExample {
public float value;
public String toString() {
return "{float: " + value + "}";
}
}

View File

@ -0,0 +1,6 @@
package org.baeldung.gson.primitives.models;
public class InfinityValuesExample {
public float negativeInfinity;
public float positiveInfinity;
}

View File

@ -0,0 +1,9 @@
package org.baeldung.gson.primitives.models;
public class LongExample {
public long value = 1;
public String toString() {
return "{byte: " + value + "}";
}
}

View File

@ -0,0 +1,19 @@
package org.baeldung.gson.primitives.models;
public class PrimitiveBundle {
public byte byteValue;
public short shortValue;
public int intValue;
public long longValue;
public float floatValue;
public double doubleValue;
public boolean booleanValue;
public char charValue;
public String toString() {
return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", "
+ "int: " + intValue + ", " + "long: " + longValue + ", "
+ "float: " + floatValue + ", " + "double: " + doubleValue + ", "
+ "boolean: " + booleanValue + ", " + "char: " + charValue + "}";
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung.gson.primitives.models;
public class PrimitiveBundleInitialized {
// @formatter:off
public byte byteValue = (byte) 1;
public short shortValue = (short) 1;
public int intValue = 1;
public long longValue = 1L;
public float floatValue = 1.0f;
public double doubleValue = 1;
// @formatter:on
public String toString() {
return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", "
+ "int: " + intValue + ", " + "long: " + longValue + ", "
+ "float: " + floatValue + ", " + "double: " + doubleValue + "}";
}
}

View File

@ -0,0 +1,248 @@
package org.baeldung.gson.primitives;
import com.google.gson.*;
import org.baeldung.gson.primitives.models.*;
import org.junit.Test;
import java.lang.reflect.Type;
import static junit.framework.TestCase.*;
public class PrimitiveValuesUnitTest {
@Test public void whenSerializingToJSON_thenShouldCreateJSON() {
PrimitiveBundle primitiveBundle = new PrimitiveBundle();
// @formatter:off
primitiveBundle.byteValue = (byte) 0x00001111;
primitiveBundle.shortValue = (short) 3;
primitiveBundle.intValue = 3;
primitiveBundle.longValue = 3;
primitiveBundle.floatValue = 3.5f;
primitiveBundle.doubleValue = 3.5;
primitiveBundle.booleanValue = true;
primitiveBundle.charValue = 'a';
// @formatter:on
Gson gson = new Gson();
String expected = "{\"byteValue\":17,\"shortValue\":3,\"intValue\":3,"
+ "\"longValue\":3,\"floatValue\":3.5" + ",\"doubleValue\":3.5"
+ ",\"booleanValue\":true,\"charValue\":\"a\"}";
assertEquals(expected, gson.toJson(primitiveBundle));
}
@Test(expected = IllegalArgumentException.class) public void
whenSerializingInfinity_thenShouldRaiseAnException() {
InfinityValuesExample model = new InfinityValuesExample();
model.negativeInfinity = Float.NEGATIVE_INFINITY;
model.positiveInfinity = Float.POSITIVE_INFINITY;
Gson gson = new Gson();
gson.toJson(model);
}
@Test(expected = IllegalArgumentException.class) public void
whenSerializingNaN_thenShouldRaiseAnException() {
FloatExample model = new FloatExample();
model.value = Float.NaN;
Gson gson = new Gson();
gson.toJson(model);
}
@Test public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() {
String json = "{\"byteValue\": 17, \"shortValue\": 3, \"intValue\": 3, "
+ "\"longValue\": 3, \"floatValue\": 3.5" + ", \"doubleValue\": 3.5"
+ ", \"booleanValue\": true, \"charValue\": \"a\"}";
Gson gson = new Gson();
PrimitiveBundle model = gson.fromJson(json, PrimitiveBundle.class);
// @formatter:off
assertEquals(17, model.byteValue);
assertEquals(3, model.shortValue);
assertEquals(3, model.intValue);
assertEquals(3, model.longValue);
assertEquals(3.5, model.floatValue, 0.0001);
assertEquals(3.5, model.doubleValue, 0.0001);
assertTrue( model.booleanValue);
assertEquals('a', model.charValue);
// @formatter:on
}
@Test public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() {
String json = "{\"value\": 12.123425589123456}";
Gson gson = new Gson();
FloatExample model = gson.fromJson(json, FloatExample.class);
assertEquals(12.123426f, model.value, 0.000001);
}
@Test public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() {
String json = "{\"value\": 12.123425589123556}";
Gson gson = new Gson();
DoubleExample model = gson.fromJson(json, DoubleExample.class);
assertEquals(12.123425589124f, model.value, 0.000001);
}
@Test public void whenDeserializingValueThatOverflows_thenShouldOverflowSilently() {
Gson gson = new Gson();
String json = "{\"value\": \"300\"}";
ByteExample model = gson.fromJson(json, ByteExample.class);
assertEquals(44, model.value);
}
@Test public void whenDeserializingRealIntoByte_thenShouldRaiseAnException() {
Gson gson = new Gson();
String json = "{\"value\": 2.3}";
try {
gson.fromJson(json, ByteExample.class);
} catch (Exception ex) {
assertTrue(ex instanceof JsonSyntaxException);
assertTrue(ex.getCause() instanceof NumberFormatException);
return;
}
fail();
}
@Test public void whenDeserializingRealIntoLong_thenShouldRaiseAnException() {
Gson gson = new Gson();
String json = "{\"value\": 2.3}";
try {
gson.fromJson(json, LongExample.class);
} catch (Exception ex) {
assertTrue(ex instanceof JsonSyntaxException);
assertTrue(ex.getCause() instanceof NumberFormatException);
return;
}
fail();
}
@Test public void whenDeserializingRealWhoseDecimalPartIs0_thenShouldParseItCorrectly() {
Gson gson = new Gson();
String json = "{\"value\": 2.0}";
LongExample model = gson.fromJson(json, LongExample.class);
assertEquals(2, model.value);
}
@Test public void whenDeserializingUnicodeChar_thenShouldParseItCorrectly() {
Gson gson = new Gson();
String json = "{\"value\": \"\\u00AE\"}";
CharExample model = gson.fromJson(json, CharExample.class);
assertEquals('\u00AE', model.value);
}
@Test public void whenDeserializingNullValues_thenShouldIgnoreThoseFields() {
Gson gson = new Gson();
// @formatter:off
String json = "{\"byteValue\": null, \"shortValue\": null, "
+ "\"intValue\": null, " + "\"longValue\": null, \"floatValue\": null"
+ ", \"doubleValue\": null}";
// @formatter:on
PrimitiveBundleInitialized model = gson.fromJson(json,
PrimitiveBundleInitialized.class);
assertEquals(1, model.byteValue);
assertEquals(1, model.shortValue);
assertEquals(1, model.intValue);
assertEquals(1, model.longValue);
assertEquals(1, model.floatValue, 0.0001);
assertEquals(1, model.doubleValue, 0.0001);
}
@Test(expected = JsonSyntaxException.class) public void
whenDeserializingTheEmptyString_thenShouldRaiseAnException() {
Gson gson = new Gson();
// @formatter:off
String json = "{\"byteValue\": \"\", \"shortValue\": \"\", "
+ "\"intValue\": \"\", " + "\"longValue\": \"\", \"floatValue\": \"\""
+ ", \"doubleValue\": \"\"" + ", \"booleanValue\": \"\"}";
// @formatter:on
gson.fromJson(json, PrimitiveBundleInitialized.class);
}
@Test public void whenDeserializingTheEmptyStringIntoChar_thenShouldHaveTheEmtpyChar() {
Gson gson = new Gson();
// @formatter:off
String json = "{\"charValue\": \"\"}";
// @formatter:on
CharExample model = gson.fromJson(json, CharExample.class);
assertEquals(Character.MIN_VALUE, model.value);
}
@Test public void whenDeserializingValidValueAppearingInAString_thenShouldParseTheValue() {
Gson gson = new Gson();
// @formatter:off
String json = "{\"byteValue\": \"15\", \"shortValue\": \"15\", "
+ "\"intValue\": \"15\", " + "\"longValue\": \"15\", \"floatValue\": \"15.0\""
+ ", \"doubleValue\": \"15.0\"}";
// @formatter:on
PrimitiveBundleInitialized model = gson.fromJson(json,
PrimitiveBundleInitialized.class);
assertEquals(15, model.byteValue);
assertEquals(15, model.shortValue);
assertEquals(15, model.intValue);
assertEquals(15, model.longValue);
assertEquals(15, model.floatValue, 0.0001);
assertEquals(15, model.doubleValue, 0.0001);
}
@Test public void whenDeserializingABooleanFrom0Or1Integer_thenShouldRaiseAnException() {
String json = "{\"value\": 1}";
Gson gson = new Gson();
try {
gson.fromJson(json, BooleanExample.class);
} catch (Exception ex) {
assertTrue(ex instanceof JsonSyntaxException);
assertTrue(ex.getCause() instanceof IllegalStateException);
return;
}
fail();
}
@Test public void whenDeserializingWithCustomDeserializerABooleanFrom0Or1Integer_thenShouldWork() {
String json = "{\"value\": 1}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(BooleanExample.class,
new BooleanAs2ValueIntegerDeserializer());
Gson gson = builder.create();
BooleanExample model = gson.fromJson(json, BooleanExample.class);
assertTrue(model.value);
}
// @formatter:off
static class BooleanAs2ValueIntegerDeserializer implements JsonDeserializer<BooleanExample> {
@Override public BooleanExample deserialize(
JsonElement jsonElement,
Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
BooleanExample model = new BooleanExample();
int value = jsonElement.getAsJsonObject().getAsJsonPrimitive("value").getAsInt();
if (value == 0) {
model.value = false;
} else if (value == 1) {
model.value = true;
} else {
throw new JsonParseException("Unexpected value. Trying to deserialize "
+ "a boolean from an integer different than 0 and 1.");
}
return model;
}
}
// @formatter:on
}

View File

@ -17,3 +17,5 @@
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
- [Hamcrest File Matchers](https://www.baeldung.com/hamcrest-file-matchers)
- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)

View File

@ -1,3 +1,2 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)
- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers)

View File

@ -1,2 +1 @@
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)

View File

@ -2,7 +2,7 @@
## Java Strings Cookbooks and Examples
### Relevant Articles:
### Relevant Articles:
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
@ -10,7 +10,7 @@
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
@ -27,7 +27,6 @@
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
@ -43,4 +42,4 @@
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)

View File

@ -0,0 +1,21 @@
package com.baeldung.string;
public class ReplaceCharacterInString {
public String replaceCharSubstring(String str, char ch, int index) {
String myString = str.substring(0, index) + ch + str.substring(index+1);
return myString;
}
public String replaceCharStringBuilder(String str, char ch, int index) {
StringBuilder myString = new StringBuilder(str);
myString.setCharAt(index, ch);
return myString.toString();
}
public String replaceCharStringBuffer(String str, char ch, int index) {
StringBuffer myString = new StringBuffer(str);
myString.setCharAt(index, ch);
return myString.toString();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.*;
public class ReplaceCharInStringUnitTest {
private ReplaceCharacterInString characterInString = new ReplaceCharacterInString();
@Test
public void whenReplaceCharAtIndexUsingSubstring_thenSuccess(){
assertEquals("abcme",characterInString.replaceCharSubstring("abcde",'m',3));
}
@Test
public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess(){
assertEquals("abcme",characterInString.replaceCharStringBuilder("abcde",'m',3));
}
@Test
public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess(){
assertEquals("abcme",characterInString.replaceCharStringBuffer("abcde",'m',3));
}
}

View File

@ -1,12 +1,22 @@
package com.baeldung.batch.understanding;
import javax.batch.api.chunk.AbstractCheckpointAlgorithm;
import javax.batch.runtime.context.JobContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class CustomCheckPoint extends AbstractCheckpointAlgorithm {
@Inject
JobContext jobContext;
private Integer counterRead = 0;
@Override
public boolean isReadyToCheckpoint() throws Exception {
return SimpleChunkItemReader.COUNT % 5 == 0;
counterRead = (Integer)jobContext.getTransientUserData();
System.out.println("counterRead : " + counterRead);
return counterRead % 5 == 0;
}
}

View File

@ -1,20 +1,38 @@
package com.baeldung.batch.understanding;
import java.util.Properties;
import java.util.logging.Logger;
import javax.batch.api.AbstractBatchlet;
import javax.batch.api.BatchProperty;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.context.JobContext;
import javax.batch.runtime.context.StepContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class InjectSimpleBatchLet extends AbstractBatchlet {
Logger logger = Logger.getLogger(InjectSimpleBatchLet.class.getName());
@Inject
@BatchProperty(name = "name")
private String nameString;
@Inject
StepContext stepContext;
private Properties stepProperties;
@Inject
JobContext jobContext;
private Properties jobProperties;
@Override
public String process() throws Exception {
System.out.println("Value passed in = " + nameString);
logger.info("BatchProperty : " + nameString);
stepProperties = stepContext.getProperties();
jobProperties = jobContext.getProperties();
logger.info("Step property : "+ stepProperties.getProperty("stepProp1"));
logger.info("job property : "+jobProperties.getProperty("jobProp1"));
return BatchStatus.COMPLETED.toString();
}
}

View File

@ -1,20 +1,28 @@
package com.baeldung.batch.understanding;
import java.io.Serializable;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.batch.api.chunk.AbstractItemReader;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.context.JobContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class SimpleChunkItemReader extends AbstractItemReader {
private StringTokenizer tokens;
public static int COUNT = 0;
private Integer count=0;
@Inject
JobContext jobContext;
@Override
public Integer readItem() throws Exception {
if (tokens.hasMoreTokens()) {
COUNT++;
this.count++;
String tempTokenize = tokens.nextToken();
jobContext.setTransientUserData(count);
return Integer.valueOf(tempTokenize);
}
return null;
@ -24,4 +32,5 @@ public class SimpleChunkItemReader extends AbstractItemReader {
public void open(Serializable checkpoint) throws Exception {
tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ",");
}
}

View File

@ -4,17 +4,22 @@ import java.io.Serializable;
import java.util.StringTokenizer;
import javax.batch.api.chunk.AbstractItemReader;
import javax.batch.runtime.context.JobContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class SimpleChunkItemReaderError extends AbstractItemReader {
@Inject
JobContext jobContext;
private StringTokenizer tokens;
public static int COUNT = 0;
private Integer count = 0;
@Override
public Integer readItem() throws Exception {
if (tokens.hasMoreTokens()) {
COUNT++;
count++;
jobContext.setTransientUserData(count);
int token = Integer.valueOf(tokens.nextToken());
if (token == 3) {
throw new RuntimeException("Something happened");

View File

@ -1,5 +1,6 @@
package com.baeldung.batch.understanding;
import java.util.ArrayList;
import java.util.List;
import javax.batch.api.chunk.AbstractItemWriter;
@ -7,7 +8,9 @@ import javax.inject.Named;
@Named
public class SimpleChunkWriter extends AbstractItemWriter {
List<Integer> processed = new ArrayList<>();
@Override
public void writeItems(List<Object> items) throws Exception {
items.stream().map(Integer.class::cast).forEach(this.processed::add);
}
}

View File

@ -1,13 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<job id="injectSimpleBatchLet" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"
version="1.0">
<step id="firstStep" >
<batchlet ref="injectSimpleBatchLet">
<properties>
<property name="name" value="helloThere" />
</properties>
</batchlet>
</step>
<job id="injectSimpleBatchLet"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"
version="1.0">
<step id="firstStep">
<properties>
<property name="stepProp1" value="value1" />
</properties>
<batchlet ref="injectSimpleBatchLet">
<properties>
<property name="name" value="helloThere" />
</properties>
</batchlet>
</step>
</job>

View File

@ -4,7 +4,13 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"
version="1.0">
<properties>
<property name="jobProp1" value="job-value1"/>
</properties>
<step id="firstStep">
<properties>
<property name="stepProp1" value="step-value1" />
</properties>
<batchlet ref="injectSimpleBatchLet">
<properties>
<property name="name" value="#{partitionPlan['name']}" />

View File

@ -7,6 +7,7 @@ import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.Metric;
import javax.batch.runtime.StepExecution;
public class BatchTestHelper {
private static final int MAX_TRIES = 40;
@ -68,6 +69,16 @@ public class BatchTestHelper {
return jobExecution;
}
public static long getCommitCount(StepExecution stepExecution) {
Map<Metric.MetricType, Long> metricsMap = getMetricsMap(stepExecution.getMetrics());
return metricsMap.get(Metric.MetricType.COMMIT_COUNT);
}
public static long getProcessSkipCount(StepExecution stepExecution) {
Map<Metric.MetricType, Long> metricsMap = getMetricsMap(stepExecution.getMetrics());
return metricsMap.get(Metric.MetricType.PROCESS_SKIP_COUNT);
}
public static Map<Metric.MetricType, Long> getMetricsMap(Metric[] metrics) {
Map<Metric.MetricType, Long> metricsMap = new HashMap<>();
for (Metric metric : metrics) {

View File

@ -15,7 +15,7 @@ import org.junit.jupiter.api.Test;
class CustomCheckPointUnitTest {
@Test
public void givenChunk_whenCustomCheckPoint_thenCommitCount_3() throws Exception {
public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception {
JobOperator jobOperator = BatchRuntime.getJobOperator();
Long executionId = jobOperator.start("customCheckPoint", new Properties());
JobExecution jobExecution = jobOperator.getJobExecution(executionId);
@ -23,9 +23,10 @@ class CustomCheckPointUnitTest {
for (StepExecution stepExecution : jobOperator.getStepExecutions(executionId)) {
if (stepExecution.getStepName()
.equals("firstChunkStep")) {
Map<Metric.MetricType, Long> metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics());
assertEquals(3L, metricsMap.get(Metric.MetricType.COMMIT_COUNT)
.longValue());
jobOperator.getStepExecutions(executionId)
.stream()
.map(BatchTestHelper::getCommitCount)
.forEach(count -> assertEquals(3L, count.longValue()));
}
}
assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);

View File

@ -1,18 +1,11 @@
package com.baeldung.batch.understanding;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.Metric;
import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
class SimpleBatchLetUnitTest {

View File

@ -1,5 +1,6 @@
package com.baeldung.batch.understanding;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.*;
@ -23,7 +24,6 @@ class SimpleErrorChunkUnitTest {
Long executionId = jobOperator.start("simpleErrorChunk", new Properties());
JobExecution jobExecution = jobOperator.getJobExecution(executionId);
jobExecution = BatchTestHelper.keepTestFailed(jobExecution);
System.out.println(jobExecution.getBatchStatus());
assertEquals(jobExecution.getBatchStatus(), BatchStatus.FAILED);
}
@ -37,10 +37,10 @@ class SimpleErrorChunkUnitTest {
for (StepExecution stepExecution : stepExecutions) {
if (stepExecution.getStepName()
.equals("errorStep")) {
Map<MetricType, Long> metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics());
long skipCount = metricsMap.get(MetricType.PROCESS_SKIP_COUNT)
.longValue();
assertTrue("Skip count=" + skipCount, skipCount == 1l || skipCount == 2l);
jobOperator.getStepExecutions(executionId)
.stream()
.map(BatchTestHelper::getProcessSkipCount)
.forEach(skipCount -> assertEquals(1L, skipCount.longValue()));
}
}
assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.jhipster</groupId>
<artifactId>jhipster-microservice-uaa</artifactId>
<packaging>pom</packaging>
<name>JHipster Microservice with UAA</name>
<parent>
<artifactId>jhipster</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>uaa</module>
<module>gateway</module>
<module>quotes</module>
</modules>
</project>

View File

@ -18,6 +18,7 @@
<modules>
<module>jhipster-monolithic</module>
<module>jhipster-microservice</module>
<module>jhipster-uaa</module>
</modules>
</project>

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jib</artifactId>
<version>0.1-SNAPSHOT</version>
@ -42,16 +42,4 @@
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -5,7 +5,7 @@
- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection)
- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek)
- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson)
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence)
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
- [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow)
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)

View File

@ -429,13 +429,6 @@
</plugins>
</build>
<repositories>
<repository>
<id>Apache Staging</id>
<url>https://repository.apache.org/content/groups/staging</url>
</repository>
</repositories>
<properties>
<storm.version>1.2.2</storm.version>
<kryo.version>4.0.1</kryo.version>

View File

@ -9,7 +9,7 @@
<logger name="io.ebean.DDL" level="TRACE"/>
<logger name="io.ebean.SQL" level="TRACE"/>
<logger name="io.ebean.TXN" level="TRACE"/>
<root level="INFO">
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -15,100 +15,88 @@ import com.googlecode.jmapper.api.JMapperAPI;
public class JMapperIntegrationTest {
@Test
public void givenUser_whenUseAnnotation_thenConverted(){
public void givenUser_whenUseAnnotation_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){
JMapper<UserDto1, User> userMapper= new JMapper<>(UserDto1.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
@Test
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
assertTrue(result.getAge() > 0);
}
//======================= XML
@Test
public void givenUser_whenUseXml_thenConverted(){
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseXmlGlobal_thenConverted(){
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml");
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(attribute("id").value("id"))
.add(attribute("username").value("email"))
) ;
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto result = userMapper.getDestination(user);
System.out.println(result);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseApiGlobal_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
.add(global())
) ;
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi);
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
UserDto1 result = userMapper1.getDestination(user);
System.out.println(result);
@Test
public void givenUser_whenUseGlobalMapAnnotation_thenConverted() {
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
@Test
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
assertTrue(result.getAge() > 0);
}
// ======================= XML
@Test
public void givenUser_whenUseXml_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, "user_jmapper.xml");
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseXmlGlobal_thenConverted() {
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class, "user_jmapper1.xml");
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted() {
JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(attribute("id").value("id")).add(attribute("username").value("email")));
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseApiGlobal_thenConverted() {
JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(global()));
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class, jmapperApi);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper1.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
}

View File

@ -18,7 +18,6 @@
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [Introduction to Neuroph](http://www.baeldung.com/neuroph)
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception)
- [Introduction to PCollections](http://www.baeldung.com/java-pcollections)
- [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly)
- [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections)
@ -34,7 +33,6 @@
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
- [Using Pairs in Java](http://www.baeldung.com/java-pairs)
- [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Introduction To Docx4J](http://www.baeldung.com/docx4j)
- [Introduction to StreamEx](http://www.baeldung.com/streamex)
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
@ -66,6 +64,7 @@
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client)
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -130,10 +130,10 @@
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</exclusion>
<exclusion>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -577,7 +577,7 @@
<classifier>test</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.milyn</groupId>
<artifactId>milyn-smooks-all</artifactId>
@ -654,8 +654,8 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.numericalmethod</groupId>
@ -678,11 +678,6 @@
</dependencies>
<repositories>
<!-- <repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url>
</repository> -->
<repository>
<snapshots>
<enabled>false</enabled>

58
lombok-custom/pom.xml Normal file
View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lombok-custom</artifactId>
<version>0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.kohsuke.metainf-services</groupId>
<artifactId>metainf-services</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>core</artifactId>
<version>3.3.0-v_771</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>default-tools.jar</id>
<activation>
<property>
<name>java.vendor</name>
<value>Oracle Corporation</value>
</property>
</activation>
<dependencies>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${java.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,10 @@
package com.baeldung.singleton;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
public @interface Singleton {
}

View File

@ -0,0 +1,124 @@
package com.baeldung.singleton.handlers;
import com.baeldung.singleton.Singleton;
import lombok.core.AnnotationValues;
import lombok.eclipse.EclipseAnnotationHandler;
import lombok.eclipse.EclipseNode;
import lombok.eclipse.handlers.EclipseHandlerUtil;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.kohsuke.MetaInfServices;
import static lombok.eclipse.Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccFinal;
import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccPrivate;
import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccStatic;
@MetaInfServices(EclipseAnnotationHandler.class)
public class SingletonEclipseHandler extends EclipseAnnotationHandler<Singleton> {
@Override
public void handle(AnnotationValues<Singleton> annotation, Annotation ast, EclipseNode annotationNode) {
//remove annotation
EclipseHandlerUtil.unboxAndRemoveAnnotationParameter(ast, "onType", "@Singleton(onType=", annotationNode);
//add private constructor
EclipseNode singletonClass = annotationNode.up();
TypeDeclaration singletonClassType = (TypeDeclaration) singletonClass.get();
ConstructorDeclaration constructor = addConstructor(singletonClass, singletonClassType);
TypeReference singletonTypeRef = EclipseHandlerUtil.cloneSelfType(singletonClass, singletonClassType);
//add inner class
//add instance field
StringBuilder sb = new StringBuilder();
sb.append(singletonClass.getName());
sb.append("Holder");
String innerClassName = sb.toString();
TypeDeclaration innerClass = new TypeDeclaration(singletonClassType.compilationResult);
innerClass.modifiers = AccPrivate | AccStatic;
innerClass.name = innerClassName.toCharArray();
FieldDeclaration instanceVar = addInstanceVar(constructor, singletonTypeRef, innerClass);
FieldDeclaration[] declarations = new FieldDeclaration[]{instanceVar};
innerClass.fields = declarations;
EclipseHandlerUtil.injectType(singletonClass, innerClass);
addFactoryMethod(singletonClass, singletonClassType, singletonTypeRef, innerClass, instanceVar);
}
private void addFactoryMethod(EclipseNode singletonClass, TypeDeclaration astNode, TypeReference typeReference, TypeDeclaration innerClass, FieldDeclaration field) {
MethodDeclaration factoryMethod = new MethodDeclaration(astNode.compilationResult);
factoryMethod.modifiers = AccStatic | ClassFileConstants.AccPublic;
factoryMethod.returnType = typeReference;
factoryMethod.sourceStart = astNode.sourceStart;
factoryMethod.sourceEnd = astNode.sourceEnd;
factoryMethod.selector = "getInstance".toCharArray();
factoryMethod.bits = ECLIPSE_DO_NOT_TOUCH_FLAG;
long pS = factoryMethod.sourceStart;
long pE = factoryMethod.sourceEnd;
long p = (long) pS << 32 | pE;
FieldReference ref = new FieldReference(field.name, p);
ref.receiver = new SingleNameReference(innerClass.name, p);
ReturnStatement statement = new ReturnStatement(ref, astNode.sourceStart, astNode.sourceEnd);
factoryMethod.statements = new Statement[]{statement};
EclipseHandlerUtil.injectMethod(singletonClass, factoryMethod);
}
private FieldDeclaration addInstanceVar(ConstructorDeclaration constructor, TypeReference typeReference, TypeDeclaration innerClass) {
FieldDeclaration field = new FieldDeclaration();
field.modifiers = AccPrivate | AccStatic | AccFinal;
field.name = "INSTANCE".toCharArray();
field.type = typeReference;
AllocationExpression exp = new AllocationExpression();
exp.type = typeReference;
exp.binding = constructor.binding;
exp.sourceStart = innerClass.sourceStart;
exp.sourceEnd = innerClass.sourceEnd;
field.initialization = exp;
return field;
}
private ConstructorDeclaration addConstructor(EclipseNode singletonClass, TypeDeclaration astNode) {
ConstructorDeclaration constructor = new ConstructorDeclaration(astNode.compilationResult);
constructor.modifiers = AccPrivate;
constructor.selector = astNode.name;
constructor.sourceStart = astNode.sourceStart;
constructor.sourceEnd = astNode.sourceEnd;
constructor.thrownExceptions = null;
constructor.typeParameters = null;
constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = astNode.sourceStart;
constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = astNode.sourceEnd;
constructor.arguments = null;
EclipseHandlerUtil.injectMethod(singletonClass, constructor);
return constructor;
}
}

View File

@ -0,0 +1,108 @@
package com.baeldung.singleton.handlers;
import com.baeldung.singleton.Singleton;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import lombok.core.AnnotationValues;
import lombok.javac.Javac8BasedLombokOptions;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
import lombok.javac.handlers.JavacHandlerUtil;
import org.kohsuke.MetaInfServices;
import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary;
import static lombok.javac.handlers.JavacHandlerUtil.deleteImportFromCompilationUnit;
@MetaInfServices(JavacAnnotationHandler.class)
public class SingletonJavacHandler extends JavacAnnotationHandler<Singleton> {
@Override
public void handle(AnnotationValues<Singleton> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {
Context context = annotationNode.getContext();
Javac8BasedLombokOptions options = Javac8BasedLombokOptions.replaceWithDelombokOptions(context);
options.deleteLombokAnnotations();
//remove annotation
deleteAnnotationIfNeccessary(annotationNode, Singleton.class);
//remove import
deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
//private constructor
JavacNode singletonClass = annotationNode.up();
JavacTreeMaker singletonClassTreeMaker = singletonClass.getTreeMaker();
addPrivateConstructor(singletonClass, singletonClassTreeMaker);
//singleton holder
JavacNode holderInnerClass = addInnerClass(singletonClass, singletonClassTreeMaker);
//inject static field to this
addInstanceVar(singletonClass, singletonClassTreeMaker, holderInnerClass);
//add factory method
addFactoryMethod(singletonClass, singletonClassTreeMaker, holderInnerClass);
}
private void addFactoryMethod(JavacNode singletonClass, JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) {
JCTree.JCModifiers modifiers = singletonClassTreeMaker.Modifiers(Flags.PUBLIC | Flags.STATIC);
JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get();
JCTree.JCIdent singletonClassType = singletonClassTreeMaker.Ident(singletonClassDecl.name);
JCTree.JCBlock block = addReturnBlock(singletonClassTreeMaker, holderInnerClass);
JCTree.JCMethodDecl factoryMethod = singletonClassTreeMaker.MethodDef(modifiers, singletonClass.toName("getInstance"), singletonClassType, List.nil(), List.nil(), List.nil(), block, null);
JavacHandlerUtil.injectMethod(singletonClass, factoryMethod);
}
private JCTree.JCBlock addReturnBlock(JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) {
JCTree.JCClassDecl holderInnerClassDecl = (JCTree.JCClassDecl) holderInnerClass.get();
JavacTreeMaker holderInnerClassTreeMaker = holderInnerClass.getTreeMaker();
JCTree.JCIdent holderInnerClassType = holderInnerClassTreeMaker.Ident(holderInnerClassDecl.name);
JCTree.JCFieldAccess instanceVarAccess = holderInnerClassTreeMaker.Select(holderInnerClassType, holderInnerClass.toName("INSTANCE"));
JCTree.JCReturn returnValue = singletonClassTreeMaker.Return(instanceVarAccess);
ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
statements.append(returnValue);
return singletonClassTreeMaker.Block(0L, statements.toList());
}
private void addInstanceVar(JavacNode singletonClass, JavacTreeMaker singletonClassTM, JavacNode holderClass) {
JCTree.JCModifiers fieldMod = singletonClassTM.Modifiers(Flags.PRIVATE | Flags.STATIC | Flags.FINAL);
JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get();
JCTree.JCIdent singletonClassType = singletonClassTM.Ident(singletonClassDecl.name);
JCTree.JCNewClass newKeyword = singletonClassTM.NewClass(null, List.nil(), singletonClassType, List.nil(), null);
JCTree.JCVariableDecl instanceVar = singletonClassTM.VarDef(fieldMod, singletonClass.toName("INSTANCE"), singletonClassType, newKeyword);
JavacHandlerUtil.injectField(holderClass, instanceVar);
}
private JavacNode addInnerClass(JavacNode singletonClass, JavacTreeMaker singletonTM) {
JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE | Flags.STATIC);
String innerClassName = singletonClass.getName() + "Holder";
JCTree.JCClassDecl innerClassDecl = singletonTM.ClassDef(modifiers, singletonClass.toName(innerClassName), List.nil(), null, List.nil(), List.nil());
return JavacHandlerUtil.injectType(singletonClass, innerClassDecl);
}
private void addPrivateConstructor(JavacNode singletonClass, JavacTreeMaker singletonTM) {
JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE);
JCTree.JCBlock block = singletonTM.Block(0L, List.nil());
JCTree.JCMethodDecl constructor = singletonTM.MethodDef(modifiers, singletonClass.toName("<init>"), null, List.nil(), List.nil(), List.nil(), block, null);
JavacHandlerUtil.injectMethod(singletonClass, constructor);
}
}

View File

@ -3,8 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>metrics</artifactId>
<name>metrics</name>
<name>metrics</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
@ -66,7 +66,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.ver}</version>
<version>2.0.7.RELEASE</version>
</dependency>
<dependency>
@ -85,44 +85,21 @@
<artifactId>spectator-api</artifactId>
<version>${spectator-api.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<type>pom</type>
<scope>import</scope>
<version>${spring.boot.ver}</version>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<dep.ver.metrics>3.1.2</dep.ver.metrics>
<dep.ver.servlet>3.1.0</dep.ver.servlet>
<netflix.servo.ver>0.12.17</netflix.servo.ver>
<micrometer.ver>0.12.0.RELEASE</micrometer.ver>
<spring.boot.ver>2.0.0.M5</spring.boot.ver>
<fasterxml.jackson.version>2.9.1</fasterxml.jackson.version>
<spectator-api.version>0.57.1</spectator-api.version>
</properties>

View File

@ -1,10 +1,11 @@
package com.baeldung.metrics.micrometer;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import io.micrometer.core.instrument.binder.JvmThreadMetrics;
@SpringBootApplication
public class MicrometerApp {

View File

@ -1,24 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -1,22 +0,0 @@
Setting up the Maven Wrapper on an Application
==============================================
This is the code that shows the configurations of maven wrapper on a SpringBoot project.
### Requirements
- Maven
- JDK 7
### Running
To build and start the server simply type
```bash
$ ./mvn clean install
$ ./mvn spring-boot:run
```
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
Enjoy it :)

View File

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mvn-wrapper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mvn-wrapper</name>
<description>Setting up the Maven Wrapper</description>
<parent>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

2
parent-boot-1/README.md Normal file
View File

@ -0,0 +1,2 @@
This is a parent module for all projects using Spring Boot 1.

View File

@ -1 +1,2 @@
## Relevant articles:
This is a parent module for all projects using Spring Boot 2.

2
parent-kotlin/README.md Normal file
View File

@ -0,0 +1,2 @@
Parent module for Kotlin projects.

View File

@ -202,7 +202,7 @@
</build>
<properties>
<kotlin.version>1.3.0</kotlin.version>
<kotlin.version>1.3.10</kotlin.version>
<kotlinx.version>1.0.0</kotlinx.version>
<ktor.io.version>0.9.5</ktor.io.version>
<assertj.version>3.11.0</assertj.version>

View File

@ -1,11 +1,12 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>hibernate5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate5</name>
<name>hibernate5</name>
<parent>
<groupId>com.baeldung</groupId>
@ -66,6 +67,13 @@
<artifactId>byte-buddy</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
@ -79,7 +87,7 @@
</build>
<properties>
<hibernate.version>5.3.6.Final</hibernate.version>
<hibernate.version>5.3.7.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<h2database.version>1.4.196</h2database.version>

View File

@ -0,0 +1,61 @@
package com.baeldung.hibernate.criteriaquery;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
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;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Student.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
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("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.hibernate.criteriaquery;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "grad_year")
private int gradYear;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public int getGradYear() {
return gradYear;
}
public void setGradYear(int gradYear) {
this.gradYear = gradYear;
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.hibernate.criteriaquery;
import com.baeldung.hibernate.criteriaquery.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class TypeSafeCriteriaIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() throws IOException {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() {
prepareData();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
Root<Student> root = criteriaQuery.from(Student.class);
criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965));
Query<Student> query = session.createQuery(criteriaQuery);
List<Student> results = query.getResultList();
assertNotNull(results);
assertEquals(1, results.size());
Student student = results.get(0);
assertEquals("Ken", student.getFirstName());
assertEquals("Thompson", student.getLastName());
assertEquals(1965, student.getGradYear());
}
private void prepareData() {
Student student1 = new Student();
student1.setFirstName("Ken");
student1.setLastName("Thompson");
student1.setGradYear(1965);
session.save(student1);
Student student2 = new Student();
student2.setFirstName("Dennis");
student2.setLastName("Ritchie");
student2.setGradYear(1963);
session.save(student2);
session.getTransaction().commit();
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -5,7 +5,7 @@
<groupId>com.baeldung</groupId>
<artifactId>java-cockroachdb</artifactId>
<version>1.0-SNAPSHOT</version>
<name>java-cockroachdb</name>
<name>java-cockroachdb</name>
<parent>
<artifactId>parent-modules</artifactId>
@ -22,15 +22,6 @@
</dependency>
</dependencies>
<repositories>
<repository>
<id>Central</id>
<name>Central</name>
<url>http://repo1.maven.org/maven2/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<postgresql.version>42.1.4</postgresql.version>
</properties>

View File

@ -27,15 +27,6 @@
</dependency>
</dependencies>
<repositories>
<repository>
<id>Central</id>
<name>Central</name>
<url>http://repo1.maven.org/maven2/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<jdbi3-core.version>3.1.0</jdbi3-core.version>
<hsqldb.version>2.4.0</hsqldb.version>

View File

@ -0,0 +1,3 @@
# Relevant Articles
- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field)

View File

@ -1,20 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-persistence</artifactId>
<version>0.1.0</version>
<name>spring-boot-persistence</name>
<name>spring-boot-persistence</name>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -35,42 +33,30 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat-jdbc.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
<tomcat-jdbc.version>9.0.10</tomcat-jdbc.version>
<h2database.version>1.4.197</h2database.version>
<mockito.version>2.23.0</mockito.version>
</properties>
<build>
<finalName>spring-boot-persistence</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
@ -79,4 +65,14 @@
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
<tomcat-jdbc.version>9.0.10</tomcat-jdbc.version>
<h2database.version>1.4.197</h2database.version>
<mockito.version>2.23.0</mockito.version>
</properties>
</project>

View File

@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" })
@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" })
@PropertySource("classpath:persistence-generic-entity.properties")
@EnableTransactionManagement
public class H2JpaConfig {
@ -41,7 +41,7 @@ public class H2JpaConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" });
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;

View File

@ -1,4 +1,4 @@
package org.baeldung.boot.domain;
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -1,7 +1,8 @@
package org.baeldung.boot.repository;
package com.baeldung.boot.repository;
import org.baeldung.boot.domain.GenericEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.boot.domain.GenericEntity;
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
}

View File

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

View File

@ -0,0 +1,33 @@
package com.baeldung.springboothsqldb.application.controllers;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.baeldung.springboothsqldb.application.repositories.CustomerRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
private final CustomerRepository customerRepository;
@Autowired
public CustomerController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@PostMapping("/customers")
public Customer addCustomer(@RequestBody Customer customer) {
customerRepository.save(customer);
return customer;
}
@GetMapping("/customers")
public List<Customer> getCustomers() {
return (List<Customer>) customerRepository.findAll();
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.springboothsqldb.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public Customer() {}
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.springboothsqldb.application.repositories;
import com.baeldung.springboothsqldb.application.entities.Customer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {}

View File

@ -1,16 +1,5 @@
spring.datasource.tomcat.initial-size=15
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=15
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver
spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.username = sa
spring.datasource.password =
spring.jpa.hibernate.ddl-auto = create

View File

@ -40,4 +40,4 @@
</div>
</div>
</body>
</html>
</html>

View File

@ -3,8 +3,6 @@ package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -12,10 +10,13 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.boot.config.H2JpaConfig;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, H2JpaConfig.class })
public class SpringBootH2IntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@ -23,7 +24,9 @@ public class SpringBootH2IntegrationTest {
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}

View File

@ -3,14 +3,15 @@ package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {

View File

@ -3,9 +3,6 @@ package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
import org.baeldung.config.H2TestProfileJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -13,6 +10,10 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import com.baeldung.config.H2TestProfileJPAConfig;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
@ActiveProfiles("test")

View File

@ -1,4 +1,4 @@
package org.baeldung.config;
package com.baeldung.config;
import java.util.Properties;
@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository" })
@EnableJpaRepositories(basePackages = { "com.baeldung.repository", "com.baeldung.boot.repository" })
@EnableTransactionManagement
public class H2TestProfileJPAConfig {
@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain" });
em.setPackagesToScan(new String[] { "com.baeldung.domain", "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;

View File

@ -0,0 +1,61 @@
package com.baeldung.springboothsqldb.application.tests;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerUnitTest {
private static MediaType MEDIA_TYPE_JSON;
@Autowired
private MockMvc mockMvc;
@Before
public void setUpJsonMediaType() {
MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
}
@Test
public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception {
Customer customer = new Customer("John", "john@domain.com");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter();
String requestJson = objectWriter.writeValueAsString(customer);
this.mockMvc
.perform(MockMvcRequestBuilders.post("/customers")
.contentType(MEDIA_TYPE_JSON)
.content(requestJson)
)
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/customers"))
.andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}

View File

@ -0,0 +1,3 @@
#Relevant Articles
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)

View File

@ -13,10 +13,10 @@
<description>Spring Data Cassandra reactive</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<properties>
@ -57,14 +57,5 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

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