Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu 2019-03-04 21:47:56 +02:00 committed by GitHub
commit d7f1c4a6b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
112 changed files with 1414 additions and 445 deletions

View File

@ -4,3 +4,7 @@
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy) - [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json) - [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)

View File

@ -23,6 +23,12 @@
<groupId>org.codehaus.groovy</groupId> <groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId> <artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version> <version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.codehaus.groovy</groupId> <groupId>org.codehaus.groovy</groupId>
@ -103,9 +109,12 @@
<properties> <properties>
<junit.platform.version>1.0.0</junit.platform.version> <junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.4.13</groovy.version> <!-- <groovy.version>2.4.13</groovy.version> -->
<groovy-all.version>2.4.13</groovy-all.version> <!-- <groovy-all.version>2.4.13</groovy-all.version> -->
<groovy-sql.version>2.4.13</groovy-sql.version> <!-- <groovy-sql.version>2.4.13</groovy-sql.version> -->
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version> <hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version> <spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version> <gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>

View File

@ -0,0 +1,57 @@
package com.baeldung.groovy.sql
import static org.junit.Assert.*
import java.util.Calendar.*
import java.time.LocalDate
import java.text.SimpleDateFormat
import org.junit.Test
class DateTest {
def dateStr = "2019-02-28"
def pattern = "yyyy-MM-dd"
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() {
def dateFormat = new SimpleDateFormat(pattern)
def date = dateFormat.parse(dateStr)
println(" String to Date with DateFormatter : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() {
def date = Date.parse(pattern, dateStr)
println(" String to Date with Date.parse : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() {
def date = LocalDate.parse(dateStr, pattern)
println(" String to Date with LocalDate : " + date)
assertEquals(date.getYear(),2019)
assertEquals(date.getMonth(),java.time.Month.FEBRUARY)
assertEquals(date.getDayOfMonth(),28)
}
}

View File

@ -38,3 +38,4 @@
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs) - [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) - [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
- [Method References in Java](https://www.baeldung.com/java-method-references)

View File

@ -27,3 +27,5 @@
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)

View File

@ -28,3 +28,5 @@
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)

View File

@ -32,3 +32,4 @@
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) - [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)

View File

@ -0,0 +1,39 @@
package com.baeldung.java.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsSortCompare {
public static void main(String[] args) {
sortPrimitives();
sortReferenceType();
sortCollection();
}
private static void sortReferenceType() {
Integer[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
private static void sortCollection() {
List<Integer> numbersList = new ArrayList<>();
numbersList.add(5);
numbersList.add(22);
numbersList.add(10);
numbersList.add(0);
Collections.sort(numbersList);
numbersList.forEach(System.out::print);
}
private static void sortPrimitives() {
int[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
public class ArraySortBenchmark {
@State(Scope.Thread)
public static class Initialize {
Integer[] numbers = {5, 22, 10, 0};
int[] primitives = {5, 22, 10, 0};
}
@Benchmark
public Integer[] benchmarkArraysIntegerSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.numbers);
return state.numbers;
}
@Benchmark
public int[] benchmarkArraysIntSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.primitives);
return state.primitives;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArraySortBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -22,3 +22,4 @@
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) - [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) - [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)

View File

@ -41,3 +41,4 @@
- [Java Interfaces](https://www.baeldung.com/java-interfaces) - [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)

View File

@ -14,3 +14,4 @@
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding)
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) - [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)

View File

@ -19,7 +19,6 @@
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [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) - [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)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
@ -51,3 +50,4 @@
- [Using Curl in Java](https://www.baeldung.com/java-curl) - [Using Curl in Java](https://www.baeldung.com/java-curl)
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)

View File

@ -0,0 +1,46 @@
package com.baeldung.urlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}

View File

@ -1,3 +1,4 @@
## Relevant articles: ## Relevant articles:
- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type)
- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges)

View File

@ -0,0 +1,47 @@
package stringcomparison
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class StringComparisonUnitTest {
@Test
fun `compare using equals operator`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first == second }
assertFalse { first == firstCapitalized }
}
@Test
fun `compare using referential equals operator`() {
val first = "kotlin"
val second = "kotlin"
val copyOfFirst = buildString { "kotlin" }
assertTrue { first === second }
assertFalse { first === copyOfFirst }
}
@Test
fun `compare using equals method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.equals(second) }
assertFalse { first.equals(firstCapitalized) }
assertTrue { first.equals(firstCapitalized, true) }
}
@Test
fun `compare using compare method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.compareTo(second) == 0 }
assertTrue { first.compareTo(firstCapitalized) == 32 }
assertTrue { firstCapitalized.compareTo(first) == -32 }
assertTrue { first.compareTo(firstCapitalized, true) == 0 }
}
}

View File

@ -52,3 +52,5 @@
- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes)
- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) - [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final)
- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach)
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)

View File

@ -33,24 +33,11 @@
</dependencies> </dependencies>
<repositories> <repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url>
</repository>
<repository> <repository>
<id>osgeo</id> <id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name> <name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url> <url>http://download.osgeo.org/webdav/geotools/</url>
</repository> </repository>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>opengeo</id>
<name>OpenGeo Maven Repository</name>
<url>http://repo.opengeo.org</url>
</repository>
</repositories> </repositories>
<properties> <properties>

View File

@ -10,3 +10,4 @@
- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file) - [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file)
- [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map)
- [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) - [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives)
- [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject)

View File

@ -2,3 +2,4 @@
### Relevant Articles ### Relevant Articles
- [Guide to Google Guice](http://www.baeldung.com/guice) - [Guide to Google Guice](http://www.baeldung.com/guice)
- [Guice vs Spring Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection)

View File

@ -20,3 +20,4 @@
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps)
- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) - [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion)
- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map)

View File

@ -0,0 +1,70 @@
package com.baeldung.reduce.application;
import com.baeldung.reduce.entities.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
public class Application {
public static void main(String[] args) throws Exception {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
System.out.println(result1);
int result2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(result2);
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
System.out.println(result3);
String result4 = letters.stream().reduce("", String::concat);
System.out.println(result4);
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
System.out.println(result5);
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result6);
String result7 = letters.parallelStream().reduce("", String::concat);
System.out.println(result7);
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result8);
org.openjdk.jmh.Main.main(args);
}
@Benchmark
@Fork(value = 1, warmups = 2)
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
public void executeReduceOnParallelizedStream() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
@Benchmark
@Fork(value = 1, warmups = 2)
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
public void executeReduceOnSequentialStream() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.reduce.entities;
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.reduce.utilities;
import java.util.List;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class NumberUtils {
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
public static int divideListElements(List<Integer> values, Integer divider) {
return values.stream()
.reduce(0, (a, b) -> {
try {
return a / divider + b / divider;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return 0;
});
}
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
}
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
}
private static int divide(int value, int factor) {
int result = 0;
try {
result = value / factor;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return result;
}
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
try {
return function.apply(a, b);
}
catch(Exception e) {
LOGGER.log(Level.INFO, "Exception occurred!");
}
return 0;
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.reduce.tests;
import com.baeldung.reduce.entities.User;
import com.baeldung.reduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StreamReduceUnitTest {
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, (a, b) -> a + b);
assertThat(result).isEqualTo(21);
}
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a + b);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
assertThat(result).isEqualTo("ABCDE");
}
@Test
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65);
}
@Test
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.parallelStream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
}
@Test
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
}
}

View File

@ -53,3 +53,4 @@
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) - [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) - [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)

View File

@ -3,3 +3,4 @@
- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) - [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices)
- [Intro to JHipster](http://www.baeldung.com/jhipster) - [Intro to JHipster](http://www.baeldung.com/jhipster)
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) - [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles)

View File

@ -2,9 +2,8 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" <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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.jhipster</groupId> <artifactId>jhipster-uaa</artifactId>
<artifactId>jhipster-microservice-uaa</artifactId> <name>jhipster-uaa</name>
<name>JHipster Microservice with UAA</name>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>

View File

@ -11,3 +11,5 @@
- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer) - [Overview of JSON Pointer](https://www.baeldung.com/json-pointer)
- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) - [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api)
- [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key)
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections)

View File

@ -66,6 +66,7 @@
- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client)
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
- [Intro to Derive4J](https://www.baeldung.com/derive4j) - [Intro to Derive4J](https://www.baeldung.com/derive4j)
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-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. 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

@ -5,6 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>lombok-custom</artifactId> <artifactId>lombok-custom</artifactId>
<name>lombok-custom</name>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<parent> <parent>

View File

@ -14,3 +14,4 @@
- [Apache Maven Tutorial](https://www.baeldung.com/maven) - [Apache Maven Tutorial](https://www.baeldung.com/maven)
- [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) - [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version)
- [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module)
- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin)

View File

@ -9,6 +9,7 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>custom-rule</artifactId> <artifactId>custom-rule</artifactId>
<name>custom-rule</name>
<properties> <properties>
<api.version>3.0.0-M2</api.version> <api.version>3.0.0-M2</api.version>

View File

@ -9,6 +9,7 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>maven-enforcer</artifactId> <artifactId>maven-enforcer</artifactId>
<name>maven-enforcer</name>
<build> <build>
<plugins> <plugins>

View File

@ -3,6 +3,7 @@
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> <modelVersion>4.0.0</modelVersion>
<artifactId>osgi-intro-sample-activator</artifactId> <artifactId>osgi-intro-sample-activator</artifactId>
<name>osgi-intro-sample-activator</name>
<!-- Please, note this is not the usual 'jar'. --> <!-- Please, note this is not the usual 'jar'. -->
<packaging>bundle</packaging> <packaging>bundle</packaging>

View File

@ -5,6 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<!-- mvn:com.baeldung/osgi-intro-sample-client/1.0-SNAPSHOT --> <!-- mvn:com.baeldung/osgi-intro-sample-client/1.0-SNAPSHOT -->
<artifactId>osgi-intro-sample-client</artifactId> <artifactId>osgi-intro-sample-client</artifactId>
<name>osgi-intro-sample-client</name>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<parent> <parent>

View File

@ -3,6 +3,7 @@
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> <modelVersion>4.0.0</modelVersion>
<artifactId>osgi-intro-sample-service</artifactId> <artifactId>osgi-intro-sample-service</artifactId>
<name>osgi-intro-sample-service</name>
<!-- Please, note this is not the usual 'jar'. --> <!-- Please, note this is not the usual 'jar'. -->
<packaging>bundle</packaging> <packaging>bundle</packaging>

View File

@ -55,7 +55,7 @@
<properties> <properties>
<rest-assured.version>3.1.0</rest-assured.version> <rest-assured.version>3.1.0</rest-assured.version>
<spring-boot.version>1.5.16.RELEASE</spring-boot.version> <spring-boot.version>1.5.19.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -77,9 +77,7 @@
<properties> <properties>
<rest-assured.version>3.1.0</rest-assured.version> <rest-assured.version>3.1.0</rest-assured.version>
<!-- plugins --> <!-- plugins -->
<thin.version>1.0.11.RELEASE</thin.version> <thin.version>1.0.21.RELEASE</thin.version>
<spring-boot.version>2.1.1.RELEASE</spring-boot.version> <spring-boot.version>2.1.3.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -18,3 +18,4 @@
- [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern) - [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern)
- [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) - [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern)
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
- [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern)

View File

@ -5,6 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>solid</artifactId> <artifactId>solid</artifactId>
<name>solid</name>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>

View File

@ -30,3 +30,5 @@
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)

View File

@ -20,6 +20,8 @@
- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) - [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert)
- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) - [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example)
- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test)
- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation)
### Eclipse Config ### Eclipse Config
After importing the project into Eclipse, you may see the following error: After importing the project into Eclipse, you may see the following error:

View File

@ -1,5 +1,7 @@
package com.baeldung.dao.repositories; package com.baeldung.dao.repositories;
import java.util.List;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.baeldung.domain.Item; import com.baeldung.domain.Item;
@ -12,4 +14,8 @@ public interface CustomItemRepository {
Item findItemById(Long id); Item findItemById(Long id);
void findThenDelete(Long id); void findThenDelete(Long id);
List<Item> findItemsByColorAndGrade();
List<Item> findItemByColorOrGrade();
} }

View File

@ -1,12 +1,18 @@
package com.baeldung.dao.repositories.impl; package com.baeldung.dao.repositories.impl;
import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.baeldung.domain.Item;
import com.baeldung.dao.repositories.CustomItemRepository; import com.baeldung.dao.repositories.CustomItemRepository;
import com.baeldung.domain.Item;
@Repository @Repository
public class CustomItemRepositoryImpl implements CustomItemRepository { public class CustomItemRepositoryImpl implements CustomItemRepository {
@ -29,4 +35,54 @@ public class CustomItemRepositoryImpl implements CustomItemRepository {
final Item item = entityManager.find(Item.class, id); final Item item = entityManager.find(Item.class, id);
entityManager.remove(item); entityManager.remove(item);
} }
@Override
public List<Item> findItemsByColorAndGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor);
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
@Override
public List<Item> findItemByColorOrGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D");
Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA);
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
} }

View File

@ -0,0 +1,94 @@
package com.baeldung.dao.repositories.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.List;
import javax.persistence.EntityManager;
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.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;
import com.baeldung.config.PersistenceConfiguration;
import com.baeldung.config.PersistenceProductConfiguration;
import com.baeldung.config.PersistenceUserConfiguration;
import com.baeldung.dao.repositories.CustomItemRepository;
import com.baeldung.domain.Item;
@RunWith(SpringRunner.class)
@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class })
public class CustomItemRepositoryIntegrationTest {
@Autowired
CustomItemRepository customItemRepositoryImpl;
@Autowired
EntityManager entityManager;
@Before
public void setUp() {
Item firstItem = new Item();
firstItem.setColor("blue");
firstItem.setGrade("C");
firstItem.setId(10l);
entityManager.persist(firstItem);
Item secondItem = new Item();
secondItem.setColor("red");
secondItem.setGrade("C");
secondItem.setId(11l);
entityManager.persist(secondItem);
Item thirdItem = new Item();
thirdItem.setColor("blue");
thirdItem.setGrade("A");
thirdItem.setId(12l);
entityManager.persist(thirdItem);
Item fourthItem = new Item();
fourthItem.setColor("red");
fourthItem.setGrade("D");
fourthItem.setId(13l);
entityManager.persist(fourthItem);
}
@Test
public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() {
List<Item> items = customItemRepositoryImpl.findItemsByColorAndGrade();
assertFalse("No items found", CollectionUtils.isEmpty(items));
assertEquals("There should be only one item", 1, items.size());
Item item = items.get(0);
assertEquals("this item do not have blue color", "blue", item.getColor());
assertEquals("this item does not belong to A grade", "A", item.getGrade());
}
@Test
public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() {
List<Item> items = customItemRepositoryImpl.findItemByColorOrGrade();
assertFalse("No items found", CollectionUtils.isEmpty(items));
assertEquals("There should be only one item", 1, items.size());
Item item = items.get(0);
assertEquals("this item do not have red color", "red", item.getColor());
assertEquals("this item does not belong to D grade", "D", item.getGrade());
}
}

View File

@ -15,7 +15,6 @@
- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database)
- [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source)
- [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)
- [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)

View File

@ -412,7 +412,7 @@
<module>feign</module> <module>feign</module>
<module>flyway-cdi-extension</module> <module>flyway-cdi-extension</module>
<!-- <module>geotools</module> --> <!-- Hangs the build. Fixing in BAEL-10943 --> <module>geotools</module>
<module>google-cloud</module> <module>google-cloud</module>
<module>google-web-toolkit</module> <module>google-web-toolkit</module>
<!-- <module>gradle</module> --> <!-- Not a maven project --> <!-- <module>gradle</module> --> <!-- Not a maven project -->
@ -542,7 +542,7 @@
<module>persistence-modules/spring-data-couchbase-2</module> <module>persistence-modules/spring-data-couchbase-2</module>
<module>persistence-modules/spring-data-dynamodb</module> <module>persistence-modules/spring-data-dynamodb</module>
<module>persistence-modules/spring-data-eclipselink</module> <module>persistence-modules/spring-data-eclipselink</module>
<!-- <module>persistence-modules/spring-data-elasticsearch</module> --> <!-- Fixing in BAEL-10995 --> <module>persistence-modules/spring-data-elasticsearch</module>
<module>persistence-modules/spring-data-gemfire</module> <module>persistence-modules/spring-data-gemfire</module>
<module>persistence-modules/spring-data-jpa</module> <module>persistence-modules/spring-data-jpa</module>
<module>persistence-modules/spring-data-keyvalue</module> <module>persistence-modules/spring-data-keyvalue</module>
@ -1130,7 +1130,7 @@
<module>feign</module> <module>feign</module>
<module>flyway-cdi-extension</module> <module>flyway-cdi-extension</module>
<!-- <module>geotools</module> --> <!-- Hangs the build. Fixing in BAEL-10943 --> <module>geotools</module>
<module>google-cloud</module> <module>google-cloud</module>
<module>google-web-toolkit</module> <module>google-web-toolkit</module>
<!-- <module>gradle</module> --> <!-- Not a maven project --> <!-- <module>gradle</module> --> <!-- Not a maven project -->
@ -1260,7 +1260,7 @@
<module>persistence-modules/spring-data-couchbase-2</module> <module>persistence-modules/spring-data-couchbase-2</module>
<module>persistence-modules/spring-data-dynamodb</module> <module>persistence-modules/spring-data-dynamodb</module>
<module>persistence-modules/spring-data-eclipselink</module> <module>persistence-modules/spring-data-eclipselink</module>
<!-- <module>persistence-modules/spring-data-elasticsearch</module> --> <!-- Fixing in BAEL-10995 --> <module>persistence-modules/spring-data-elasticsearch</module>
<module>persistence-modules/spring-data-gemfire</module> <module>persistence-modules/spring-data-gemfire</module>
<module>persistence-modules/spring-data-jpa</module> <module>persistence-modules/spring-data-jpa</module>
<module>persistence-modules/spring-data-keyvalue</module> <module>persistence-modules/spring-data-keyvalue</module>

View File

@ -5,3 +5,4 @@
- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot)
- [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix)
- [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client)
- [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava)

View File

@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>restx</artifactId> <artifactId>restx</artifactId>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<name>restx-demo</name> <name>restx</name>
<packaging>war</packaging> <packaging>war</packaging>
<parent> <parent>

View File

@ -4,6 +4,7 @@
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> <modelVersion>4.0.0</modelVersion>
<artifactId>rxjava-2</artifactId> <artifactId>rxjava-2</artifactId>
<name>rxjava-2</name>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [SQL Injection and How to Prevent It?](https://www.baeldung.com/sql-injection)

View File

@ -2,7 +2,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"> <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.springbootangular</groupId> <groupId>com.baeldung.springbootangular</groupId>
<artifactId>springbootangular</artifactId> <artifactId>spring-boot-angular</artifactId>
<name>spring-boot-angular</name>
<version>1.0</version> <version>1.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>

View File

@ -84,7 +84,7 @@
<id>openshift</id> <id>openshift</id>
<properties> <properties>
<spring-cloud-k8s.version>0.3.0.RELEASE</spring-cloud-k8s.version> <spring-cloud-k8s.version>0.3.0.RELEASE</spring-cloud-k8s.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<fabric8.maven.plugin.version>3.5.37</fabric8.maven.plugin.version> <fabric8.maven.plugin.version>3.5.37</fabric8.maven.plugin.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
@ -166,7 +166,7 @@
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version> <version>Greenwich.RELEASE</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
@ -214,7 +214,7 @@
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version> <version>Greenwich.RELEASE</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>

View File

@ -4,12 +4,10 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ServletComponentScan @ServletComponentScan
@SpringBootApplication @SpringBootApplication(scanBasePackages = "com.baeldung")
@ComponentScan("com.baeldung")
@EnableJpaRepositories("com.baeldung.persistence.repo") @EnableJpaRepositories("com.baeldung.persistence.repo")
@EntityScan("com.baeldung.persistence.model") @EntityScan("com.baeldung.persistence.model")
public class Application { public class Application {

View File

@ -1,19 +1,19 @@
<html lang="en"> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head> <head>
<title>Error Occurred</title> <title>Error Occurred</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head> </head>
<body> <body>
<div class="container"> <div class="container">
<h1>Error Occurred!</h1> <h1>Error Occurred!</h1>
<div class="alert alert-danger" role="alert"> <div class="alert alert-danger" role="alert">
<b> <b>
[<span th:text="${status}">status</span>] [<span th:text="${status}">status</span>]
<span th:text="${error}">error</span> <span th:text="${error}">error</span>
</b> </b>
<p th:text="${message}">message</p> <p th:text="${message}">message</p>
</div> </div>
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,7 +1,7 @@
<html> <html xmlns:th="http://www.w3.org/1999/xhtml" lang="en">
<head><title>Home Page</title></head> <head><title>Home Page</title></head>
<body> <body>
<h1>Hello !</h1> <h1>Hello !</h1>
<p>Welcome to <span th:text="${appName}">Our App</span></p> <p>Welcome to <span th:text="${appName}">Our App</span></p>
</body> </body>
</html> </html>

View File

@ -4,3 +4,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles: ### Relevant Articles:
- [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) - [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring)
- [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web)

View File

@ -11,3 +11,4 @@
- [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) - [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache)
- [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api)
- [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally)
- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js)

View File

@ -9,3 +9,4 @@ Module for the articles that are part of the Spring REST E-book:
7. [Versioning a REST API](http://www.baeldung.com/rest-versioning) 7. [Versioning a REST API](http://www.baeldung.com/rest-versioning)
8. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) 8. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest)
9. [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) 9. [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring)
10. [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)

View File

@ -27,8 +27,7 @@ public class TestMarshallerFactory implements FactoryBean<IMarshaller> {
case "json": case "json":
return new JacksonMarshaller(); return new JacksonMarshaller();
case "xml": case "xml":
// If we need to implement xml marshaller we can include spring-rest-full XStreamMarshaller return new XStreamMarshaller();
throw new IllegalStateException();
default: default:
throw new IllegalStateException(); throw new IllegalStateException();
} }

View File

@ -1,8 +1,8 @@
package org.baeldung.test; package com.baeldung.test;
import java.util.List; import java.util.List;
import org.baeldung.persistence.model.Foo; import com.baeldung.persistence.model.Foo;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;

View File

@ -60,22 +60,11 @@
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.M3</spring-cloud.version> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
</project> </project>

View File

@ -52,22 +52,11 @@
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.M3</spring-cloud.version> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
</project> </project>

View File

@ -4,6 +4,7 @@
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> <modelVersion>4.0.0</modelVersion>
<artifactId>liveness-example</artifactId> <artifactId>liveness-example</artifactId>
<name>liveness-example</name>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>

View File

@ -4,6 +4,7 @@
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> <modelVersion>4.0.0</modelVersion>
<artifactId>readiness-example</artifactId> <artifactId>readiness-example</artifactId>
<name>readiness-example</name>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.cloud</groupId>
<artifactId>openfeign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>openfeign</name>
<description>OpenFeign project for Spring Boot</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<properties>
<spring-boot.version>2.0.1.RELEASE</spring-boot.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

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

View File

@ -0,0 +1,25 @@
package com.baeldung.cloud.openfeign.client;
import com.baeldung.cloud.openfeign.config.ClientConfiguration;
import com.baeldung.cloud.openfeign.hystrix.JSONPlaceHolderFallback;
import com.baeldung.cloud.openfeign.model.Post;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@FeignClient(value = "jplaceholder",
url = "https://jsonplaceholder.typicode.com/",
configuration = ClientConfiguration.class,
fallback = JSONPlaceHolderFallback.class)
public interface JSONPlaceHolderClient {
@RequestMapping(method = RequestMethod.GET, value = "/posts")
List<Post> getPosts();
@RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json")
Post getPostById(@PathVariable("postId") Long postId);
}

View File

@ -0,0 +1,37 @@
package com.baeldung.cloud.openfeign.config;
import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import feign.okhttp.OkHttpClient;
import org.apache.http.entity.ContentType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClientConfiguration {
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean
public ErrorDecoder errorDecoder() {
return new ErrorDecoder.Default();
}
@Bean
public OkHttpClient client() {
return new OkHttpClient();
}
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
requestTemplate.header("user", "ajeje");
requestTemplate.header("password", "brazof");
requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType());
};
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.cloud.openfeign.config;
import com.baeldung.cloud.openfeign.exception.BadRequestException;
import com.baeldung.cloud.openfeign.exception.NotFoundException;
import feign.Response;
import feign.codec.ErrorDecoder;
public class CustomErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
switch (response.status()){
case 400:
return new BadRequestException();
case 404:
return new NotFoundException();
default:
return new Exception("Generic error");
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.cloud.openfeign.exception;
public class BadRequestException extends Exception {
public BadRequestException() {
}
public BadRequestException(String message) {
super(message);
}
public BadRequestException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return "BadRequestException: "+getMessage();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.cloud.openfeign.exception;
public class NotFoundException extends Exception {
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return "NotFoundException: "+getMessage();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.cloud.openfeign.hystrix;
import com.baeldung.cloud.openfeign.client.JSONPlaceHolderClient;
import com.baeldung.cloud.openfeign.model.Post;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
@Component
public class JSONPlaceHolderFallback implements JSONPlaceHolderClient {
@Override
public List<Post> getPosts() {
return Collections.emptyList();
}
@Override
public Post getPostById(Long postId) {
return null;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.cloud.openfeign.model;
public class Post {
private String userId;
private Long id;
private String title;
private String body;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.cloud.openfeign.service;
import com.baeldung.cloud.openfeign.model.Post;
import java.util.List;
public interface JSONPlaceHolderService {
List<Post> getPosts();
Post getPostById(Long id);
}

View File

@ -0,0 +1,26 @@
package com.baeldung.cloud.openfeign.service.impl;
import com.baeldung.cloud.openfeign.client.JSONPlaceHolderClient;
import com.baeldung.cloud.openfeign.model.Post;
import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class JSONPlaceHolderServiceImpl implements JSONPlaceHolderService {
@Autowired
private JSONPlaceHolderClient jsonPlaceHolderClient;
@Override
public List<Post> getPosts() {
return jsonPlaceHolderClient.getPosts();
}
@Override
public Post getPostById(Long id) {
return jsonPlaceHolderClient.getPostById(id);
}
}

View File

@ -0,0 +1,3 @@
spring.application.name= openfeign
logging.level.com.baeldung.cloud.openfeign.client: DEBUG
feign.hystrix.enabled=true

View File

@ -0,0 +1,43 @@
package com.baeldung.cloud.openfeign;
import com.baeldung.cloud.openfeign.model.Post;
import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService;
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 java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OpenfeignUnitTest {
@Autowired
private JSONPlaceHolderService jsonPlaceHolderService;
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
@Test
public void whenGetPosts_thenListPostSizeGreaterThanZero() {
List<Post> posts = jsonPlaceHolderService.getPosts();
assertFalse(posts.isEmpty());
}
@Test
public void whenGetPostWithId_thenPostExist() {
Post post = jsonPlaceHolderService.getPostById(1L);
assertNotNull(post);
}
}

View File

@ -65,22 +65,11 @@
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.M3</spring-cloud.version> <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,17 @@
package com.baeldung.spring.jms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ErrorHandler;
public class SampleJmsErrorHandler implements ErrorHandler {
private static final Logger LOG = LoggerFactory.getLogger(SampleJmsErrorHandler.class);
@Override
public void handleError(Throwable t) {
LOG.warn("In default jms error handler...");
LOG.error("Error Message : {}", t.getMessage());
}
}

View File

@ -26,4 +26,8 @@ public class SampleJmsMessageSender {
public void sendMessage(final Employee employee) { public void sendMessage(final Employee employee) {
this.jmsTemplate.convertAndSend(employee); this.jmsTemplate.convertAndSend(employee);
} }
public void sendTextMessage(String msg) {
this.jmsTemplate.send(queue, s -> s.createTextMessage(msg));
}
} }

View File

@ -27,6 +27,9 @@ public class SampleListener implements MessageListener {
try { try {
String msg = ((TextMessage) message).getText(); String msg = ((TextMessage) message).getText();
System.out.println("Received message: " + msg); System.out.println("Received message: " + msg);
if (msg == null) {
throw new IllegalArgumentException("Null value received...");
}
} catch (JMSException ex) { } catch (JMSException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
@ -37,4 +40,5 @@ public class SampleListener implements MessageListener {
Map map = (Map) this.jmsTemplate.receiveAndConvert(); Map map = (Map) this.jmsTemplate.receiveAndConvert();
return new Employee((String) map.get("name"), (Integer) map.get("age")); return new Employee((String) map.get("name"), (Integer) map.get("age"));
} }
} }

View File

@ -1,51 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd"> http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
<!-- JmsTemplate Definition --> <!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" /> <property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="destinationQueue" /> <property name="defaultDestination" ref="destinationQueue" />
<property name="messageConverter" ref="myMessageConverter" /> <property name="messageConverter" ref="myMessageConverter" />
</bean> </bean>
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg index="0" value="tcp://localhost:61616" />
</bean>
<!-- ConnectionFactory Definition --> <bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<bean id="connectionFactory" <constructor-arg index="0" value="tcp://localhost:61616" />
class="org.springframework.jms.connection.SingleConnectionFactory"> </bean>
<constructor-arg ref="amqConnectionFactory" />
</bean> <!-- ConnectionFactory Definition -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="IN_QUEUE" />
</bean>
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue"> <bean id="SampleJmsMessageSender" class="com.baeldung.spring.jms.SampleJmsMessageSender">
<constructor-arg index="0" value="IN_QUEUE" /> <property name="queue" ref="destinationQueue" />
</bean> <property name="jmsTemplate" ref="jmsTemplate" />
</bean>
<bean id="myMessageConverter" class="com.baeldung.spring.jms.SampleMessageConverter" />
<bean id="SampleJmsMessageSender" class="com.baeldung.spring.jms.SampleJmsMessageSender"> <!-- this is the Message-Driven POJO (MDP) -->
<property name="queue" ref="destinationQueue" /> <bean id="messageListener" class="com.baeldung.spring.jms.SampleListener">
<property name="jmsTemplate" ref="jmsTemplate" /> <property name="jmsTemplate" ref="jmsTemplate" />
</bean> <property name="queue" ref="destinationQueue" />
</bean>
<bean id="myMessageConverter" class="com.baeldung.spring.jms.SampleMessageConverter" /> <bean id="errorHandler" class="com.baeldung.spring.jms.SampleJmsErrorHandler" />
<!-- this is the Message-Driven POJO (MDP) --> <!-- and this is the message listener container -->
<bean id="messageListener" class="com.baeldung.spring.jms.SampleListener"> <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="jmsTemplate" ref="jmsTemplate" /> <property name="connectionFactory" ref="connectionFactory" />
<property name="queue" ref="destinationQueue" /> <property name="destinationName" value="IN_QUEUE" />
</bean> <property name="messageListener" ref="messageListener" />
<property name="errorHandler" ref="errorHandler" />
</bean>
<!-- and this is the message listener container -->
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destinationName" value="IN_QUEUE" />
<property name="messageListener" ref="messageListener" />
</bean>
</beans> </beans>

View File

@ -8,12 +8,14 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DefaultTextMessageSenderIntegrationTest { public class DefaultTextMessageSenderIntegrationTest {
private static SampleJmsMessageSender messageProducer; private static SampleJmsMessageSender messageProducer;
private static SampleListener messageListener;
@SuppressWarnings("resource") @SuppressWarnings("resource")
@BeforeClass @BeforeClass
public static void setUp() { public static void setUp() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
messageListener = (SampleListener) applicationContext.getBean("messageListener");
} }
@Test @Test
@ -21,4 +23,9 @@ public class DefaultTextMessageSenderIntegrationTest {
messageProducer.simpleSend(); messageProducer.simpleSend();
} }
@Test
public void testSendTextMessage() {
messageProducer.sendTextMessage(null);
}
} }

View File

@ -8,3 +8,4 @@
- [Guide to Spring Email](http://www.baeldung.com/spring-email) - [Guide to Spring Email](http://www.baeldung.com/spring-email)
- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405)
- [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param)
- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable)

View File

@ -0,0 +1,21 @@
package com.baeldung.spring.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.ConstraintViolationException;
@ControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}

View File

@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-remoting-hessian-burlap-client</artifactId> <artifactId>remoting-hessian-burlap-client</artifactId>
<name>spring-remoting-hessian-burlap-client</name> <name>remoting-hessian-burlap-client</name>
<parent> <parent>
<artifactId>remoting-hessian-burlap</artifactId> <artifactId>remoting-hessian-burlap</artifactId>

View File

@ -158,11 +158,6 @@
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<!-- util --> <!-- util -->

View File

@ -1,25 +0,0 @@
package org.baeldung.web.error;
import org.baeldung.web.exception.MyResourceNotFoundException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public RestResponseEntityExceptionHandler() {
super();
}
@ExceptionHandler(value = { MyResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}

View File

@ -1,36 +0,0 @@
package org.baeldung.web.util;
import javax.servlet.http.HttpServletResponse;
/**
* Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object
*/
public final class LinkUtil {
public static final String REL_COLLECTION = "collection";
public static final String REL_NEXT = "next";
public static final String REL_PREV = "prev";
public static final String REL_FIRST = "first";
public static final String REL_LAST = "last";
private LinkUtil() {
throw new AssertionError();
}
//
/**
* Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user
*
* @param uri
* the base uri
* @param rel
* the relative path
*
* @return the complete url
*/
public static String createLinkHeader(final String uri, final String rel) {
return "<" + uri + ">; rel=\"" + rel + "\"";
}
}

View File

@ -1,64 +0,0 @@
package org.baeldung.common.web;
import static org.baeldung.Consts.APPLICATION_PORT;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.Serializable;
import org.baeldung.test.IMarshaller;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
public abstract class AbstractLiveTest<T extends Serializable> {
protected final Class<T> clazz;
@Autowired
protected IMarshaller marshaller;
public AbstractLiveTest(final Class<T> clazzToSet) {
super();
Preconditions.checkNotNull(clazzToSet);
clazz = clazzToSet;
}
// template method
public abstract void create();
public abstract String createAsUri();
protected final void create(final T resource) {
createAsUri(resource);
}
protected final String createAsUri(final T resource) {
final Response response = createAsResponse(resource);
Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode());
final String locationOfCreatedResource = response.getHeader(HttpHeaders.LOCATION);
Preconditions.checkNotNull(locationOfCreatedResource);
return locationOfCreatedResource;
}
final Response createAsResponse(final T resource) {
Preconditions.checkNotNull(resource);
final String resourceAsString = marshaller.encode(resource);
return RestAssured.given()
.contentType(marshaller.getMime())
.body(resourceAsString)
.post(getURL());
}
//
protected String getURL() {
return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos";
}
}

View File

@ -1,17 +0,0 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ComponentScan("org.baeldung.test")
public class ConfigIntegrationTest extends WebMvcConfigurerAdapter {
public ConfigIntegrationTest() {
super();
}
// API
}

View File

@ -1,15 +0,0 @@
package org.baeldung.test;
import java.util.List;
public interface IMarshaller {
<T> String encode(final T entity);
<T> T decode(final String entityAsString, final Class<T> clazz);
<T> List<T> decodeList(final String entitiesAsString, final Class<T> clazz);
String getMime();
}

View File

@ -1,81 +0,0 @@
package org.baeldung.test;
import java.io.IOException;
import java.util.List;
import org.baeldung.persistence.model.Foo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
public final class JacksonMarshaller implements IMarshaller {
private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class);
private final ObjectMapper objectMapper;
public JacksonMarshaller() {
super();
objectMapper = new ObjectMapper();
}
// API
@Override
public final <T> String encode(final T resource) {
Preconditions.checkNotNull(resource);
String entityAsJSON = null;
try {
entityAsJSON = objectMapper.writeValueAsString(resource);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entityAsJSON;
}
@Override
public final <T> T decode(final String resourceAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourceAsString);
T entity = null;
try {
entity = objectMapper.readValue(resourceAsString, clazz);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entity;
}
@SuppressWarnings("unchecked")
@Override
public final <T> List<T> decodeList(final String resourcesAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourcesAsString);
List<T> entities = null;
try {
if (clazz.equals(Foo.class)) {
entities = objectMapper.readValue(resourcesAsString, new TypeReference<List<Foo>>() {
// ...
});
} else {
entities = objectMapper.readValue(resourcesAsString, List.class);
}
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entities;
}
@Override
public final String getMime() {
return MediaType.APPLICATION_JSON.toString();
}
}

View File

@ -1,48 +0,0 @@
package org.baeldung.test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Profile("test")
public class TestMarshallerFactory implements FactoryBean<IMarshaller> {
@Autowired
private Environment env;
public TestMarshallerFactory() {
super();
}
// API
@Override
public IMarshaller getObject() {
final String testMime = env.getProperty("test.mime");
if (testMime != null) {
switch (testMime) {
case "json":
return new JacksonMarshaller();
case "xml":
return new XStreamMarshaller();
default:
throw new IllegalStateException();
}
}
return new JacksonMarshaller();
}
@Override
public Class<IMarshaller> getObjectType() {
return IMarshaller.class;
}
@Override
public boolean isSingleton() {
return true;
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Filtering Jackson JSON Output Based on Spring Security Role](https://www.baeldung.com/spring-security-role-filter-json)

View File

@ -28,7 +28,7 @@ public class SleuthService {
public void doSomeWorkNewSpan() throws InterruptedException { public void doSomeWorkNewSpan() throws InterruptedException {
logger.info("I'm in the original span"); logger.info("I'm in the original span");
Span newSpan = tracer.newTrace().name("newSpan").start(); Span newSpan = tracer.nextSpan().name("newSpan").start();
try (SpanInScope ws = tracer.withSpanInScope(newSpan.start())) { try (SpanInScope ws = tracer.withSpanInScope(newSpan.start())) {
Thread.sleep(1000L); Thread.sleep(1000L);
logger.info("I'm in the new span doing some cool work that needs its own span"); logger.info("I'm in the new span doing some cool work that needs its own span");

View File

@ -1,13 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <!-- this is the configuration needed for the Sleuth examples;
<appender-ref ref="STDOUT" /> don't override this with the standard logback config
</root> -->
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="feign" level="DEBUG"/>
<logger name="org.springframework.cloud.sleuth" level="TRACE"/>
<logger name="org.springframework.boot.autoconfigure.logging" level="INFO"/>
<logger name="org.springframework.cloud.sleuth.log" level="DEBUG"/>
<logger name="org.springframework.cloud.sleuth.trace" level="DEBUG"/>
<logger name="org.springframework.cloud.sleuth.instrument.rxjava" level="DEBUG"/>
<logger name="org.springframework.cloud.sleuth.instrument.reactor" level="TRACE"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration> </configuration>

3
spring-soap/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Creating a SOAP Web Service with Spring](https://www.baeldung.com/spring-boot-soap-web-service)

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