Merge branch 'eugenp:master' into master
This commit is contained in:
commit
7dcff82ac8
@ -11,3 +11,4 @@ This module contains articles about Java 11 core features
|
|||||||
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
||||||
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)
|
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)
|
||||||
- [Call Methods at Runtime Using Java Reflection](https://www.baeldung.com/java-method-reflection)
|
- [Call Methods at Runtime Using Java Reflection](https://www.baeldung.com/java-method-reflection)
|
||||||
|
- [Java HttpClient Basic Authentication](https://www.baeldung.com/java-httpclient-basic-auth)
|
||||||
|
@ -12,4 +12,6 @@ This module contains articles about the Java List collection
|
|||||||
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
|
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
|
||||||
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
|
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
|
||||||
- [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist)
|
- [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist)
|
||||||
|
- [How to Store HashMap<String, ArrayList> Inside a List](https://www.baeldung.com/java-hashmap-inside-list)
|
||||||
|
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)
|
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)
|
||||||
|
@ -8,26 +8,27 @@ import java.util.regex.*;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
public class ScannerUnitTest {
|
public class ScannerUnitTest {
|
||||||
@Test public void scannerSkipUsingPattern() {
|
@Test public void givenScannerWithPattern_thenSkipUsingPattern() {
|
||||||
String str = "Java scanner skip tutorial";
|
String str = "Java scanner skip tutorial";
|
||||||
// Instantiates Scanner
|
// Instantiates Scanner
|
||||||
Scanner sc = new Scanner(str);
|
Scanner sc = new Scanner(str);
|
||||||
// By using skip(Pattern) method is to skip that meets the given pattern
|
// By using skip(Pattern) method is to skip that meets the given pattern
|
||||||
sc.skip(Pattern.compile(".ava"));
|
sc.skip(Pattern.compile(".ava"));
|
||||||
assertEquals(sc.nextLine(), " scanner skip tutorial");
|
|
||||||
|
assertEquals(" scanner skip tutorial", sc.nextLine());
|
||||||
// Scanner closed
|
// Scanner closed
|
||||||
sc.close();
|
sc.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test public void scannerSkipUsingStringPattern() {
|
@Test public void givenScannerWithString_thenSkipUsingStringPattern() {
|
||||||
String str = "Java scanner skip tutorial";
|
String str = "Java scanner skip tutorial";
|
||||||
// Instantiates Scanner
|
// Instantiates Scanner
|
||||||
Scanner sc = new Scanner(str);
|
Scanner sc = new Scanner(str);
|
||||||
// By using skip(String) method is to skip that meets the given
|
// By using skip(String) method is to skip that meets the given
|
||||||
// pattern constructed from the given String
|
// pattern constructed from the given String
|
||||||
sc.skip("Java");
|
sc.skip("Java");
|
||||||
assertEquals(sc.nextLine(), " scanner skip tutorial");
|
|
||||||
|
|
||||||
|
assertEquals(" scanner skip tutorial", sc.nextLine());
|
||||||
// Scanner closed
|
// Scanner closed
|
||||||
sc.close();
|
sc.close();
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.java8.lambda.serialization;
|
||||||
|
|
||||||
|
public class NotSerializableLambdaExpression {
|
||||||
|
public static Object getLambdaExpressionObject() {
|
||||||
|
Runnable r = () -> System.out.println("please serialize this message");
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.java8.lambda.serialization;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class SerializableLambdaExpression {
|
||||||
|
public static Object getLambdaExpressionObject() {
|
||||||
|
Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message");
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,77 @@
|
|||||||
|
package com.baeldung.java8.lambda.serialization;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class LambdaSerializationUnitTest {
|
||||||
|
@Test(expected = NotSerializableException.class)
|
||||||
|
public void givenRunnable_whenNoCapturing_thenSerializationFailed() throws IOException, ClassNotFoundException {
|
||||||
|
Object obj = NotSerializableLambdaExpression.getLambdaExpressionObject();
|
||||||
|
writeAndReadObject(obj, Runnable.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntersectionType_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException {
|
||||||
|
Object obj = SerializableLambdaExpression.getLambdaExpressionObject();
|
||||||
|
writeAndReadObject(obj, Runnable.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSerializableRunnable_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException {
|
||||||
|
SerializableRunnable obj = () -> System.out.println("please serialize this message");
|
||||||
|
writeAndReadObject(obj, SerializableRunnable.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSerializableFunction_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException {
|
||||||
|
SerializableFunction<String, String> obj = message -> String.format("Hello %s", message);
|
||||||
|
writeAndReadObject(obj, SerializableFunction.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSerializableConsumer_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException {
|
||||||
|
SerializableConsumer<String> obj = message -> System.out.println(message);
|
||||||
|
writeAndReadObject(obj, SerializableConsumer.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NotSerializableException.class)
|
||||||
|
public void givenSerializableConsumer_whenCapturingNotSerializable_thenSerializationFailed() throws IOException, ClassNotFoundException {
|
||||||
|
SerializableConsumer<String> obj = System.out::println;
|
||||||
|
writeAndReadObject(obj, SerializableConsumer.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> void writeAndReadObject(Object obj, Class<T> clazz) throws IOException, ClassNotFoundException {
|
||||||
|
File file = Files.createTempFile("lambda", "ser").toFile();
|
||||||
|
try (
|
||||||
|
FileOutputStream fos = new FileOutputStream(file);
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(fos)
|
||||||
|
) {
|
||||||
|
oos.writeObject(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (
|
||||||
|
FileInputStream fis = new FileInputStream(file);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(fis)
|
||||||
|
) {
|
||||||
|
Object newObj = ois.readObject();
|
||||||
|
boolean isInstance = clazz.isInstance(newObj);
|
||||||
|
|
||||||
|
assertTrue(isInstance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SerializableRunnable extends Runnable, Serializable {
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SerializableFunction<T, R> extends Function<T, R>, Serializable {
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SerializableConsumer<T> extends Consumer<T>, Serializable {
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,157 @@
|
|||||||
|
package com.baeldung.math.swap;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SwappingVariablesUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoStrings_whenSwappingInMethod_thenFails() {
|
||||||
|
|
||||||
|
String a = "a";
|
||||||
|
String b = "b";
|
||||||
|
|
||||||
|
swap(a, b);
|
||||||
|
|
||||||
|
Assertions.assertFalse(a.equals("b"));
|
||||||
|
Assertions.assertFalse(b.equals("a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoWrappers_whenSwappingInMethod_thenSuccess() {
|
||||||
|
|
||||||
|
Wrapper a = new Wrapper("a");
|
||||||
|
Wrapper b = new Wrapper("b");
|
||||||
|
|
||||||
|
swap(a, b);
|
||||||
|
|
||||||
|
Assertions.assertTrue(a.string.equals("b"));
|
||||||
|
Assertions.assertTrue(b.string.equals("a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingUsingAdditionSubstraction_thenSuccess() {
|
||||||
|
|
||||||
|
int a = 5;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
a = a + b;
|
||||||
|
b = a - b;
|
||||||
|
a = a - b;
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertTrue(b == 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingUsingMultiplicationDivision_thenSuccess() {
|
||||||
|
|
||||||
|
int a = 5;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
a = a * b;
|
||||||
|
b = a / b;
|
||||||
|
a = a / b;
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertTrue(b == 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingWithOverflow_thenFails() {
|
||||||
|
|
||||||
|
int a = Integer.MAX_VALUE;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
a = a * b;
|
||||||
|
b = a / b;
|
||||||
|
a = a / b;
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertFalse(b == Integer.MAX_VALUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoChars_whenSwappingWithCast_thenSuccess() {
|
||||||
|
|
||||||
|
char a = 'a';
|
||||||
|
char b = 'b';
|
||||||
|
|
||||||
|
a = (char)(a * b);
|
||||||
|
b = (char)(a / b);
|
||||||
|
a = (char)(a / b);
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 'b');
|
||||||
|
Assertions.assertTrue(b == 'a');
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingUsingXor_thenSuccess() {
|
||||||
|
|
||||||
|
int a = 5;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
a = a ^ b;
|
||||||
|
b = a ^ b;
|
||||||
|
a = a ^ b;
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertTrue(b == 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingUsingSingleLineXor_thenSuccess() {
|
||||||
|
|
||||||
|
int a = 5;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
a = a ^ b ^ (b = a);
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertTrue(b == 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenSwappingUsingAdditionSubstractionSingleLine_thenSuccess() {
|
||||||
|
|
||||||
|
int a = 5;
|
||||||
|
int b = 10;
|
||||||
|
|
||||||
|
b = (a + b) - (a = b);
|
||||||
|
|
||||||
|
Assertions.assertTrue(a == 10);
|
||||||
|
Assertions.assertTrue(b == 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Illustrates that swapping in a method doesn't work
|
||||||
|
*/
|
||||||
|
private void swap(String a, String b) {
|
||||||
|
|
||||||
|
String temp = b;
|
||||||
|
b = a;
|
||||||
|
a = temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Illustrates swapping in a method with Wrapper class
|
||||||
|
*/
|
||||||
|
private void swap(Wrapper a, Wrapper b) {
|
||||||
|
|
||||||
|
String temp = b.string;
|
||||||
|
b.string = a.string;
|
||||||
|
a.string = temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Wrapper {
|
||||||
|
|
||||||
|
public String string;
|
||||||
|
|
||||||
|
public Wrapper(String string) {
|
||||||
|
|
||||||
|
this.string = string;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.enums.randomenum;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents directions.
|
||||||
|
*/
|
||||||
|
public enum Direction {
|
||||||
|
EAST, WEST, SOUTH, NORTH;
|
||||||
|
|
||||||
|
private static final Random PRNG = new Random();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a random direction.
|
||||||
|
*
|
||||||
|
* @return a random direction
|
||||||
|
*/
|
||||||
|
public static Direction randomDirection() {
|
||||||
|
Direction[] directions = values();
|
||||||
|
return directions[PRNG.nextInt(directions.length)];
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.enums.randomenum;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class RandomEnumGenerator<T extends Enum<T>> {
|
||||||
|
|
||||||
|
private static final Random PRNG = new Random();
|
||||||
|
private final T[] values;
|
||||||
|
|
||||||
|
public RandomEnumGenerator(Class<T> e) {
|
||||||
|
values = e.getEnumConstants();
|
||||||
|
}
|
||||||
|
|
||||||
|
public T randomEnum() {
|
||||||
|
return values[PRNG.nextInt(values.length)];
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.enums.randomenum;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class RandomEnumUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEnumType_whenUsingStaticMethod_valueIsRandomlyGenerated() {
|
||||||
|
Direction direction = Direction.randomDirection();
|
||||||
|
assertThat(direction).isNotNull();
|
||||||
|
assertThat(direction instanceof Direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEnumType_whenGeneratingRandomValue_valueIsOfClassAndNotNull() {
|
||||||
|
RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class);
|
||||||
|
Object direction = reg.randomEnum();
|
||||||
|
assertThat(direction).isNotNull();
|
||||||
|
assertThat(direction instanceof Direction);
|
||||||
|
}
|
||||||
|
}
|
@ -19,7 +19,7 @@ public class FileDownloadIntegrationTest {
|
|||||||
|
|
||||||
static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson+by+Baeldung.pdf";
|
static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson+by+Baeldung.pdf";
|
||||||
static String FILE_NAME = "file.dat";
|
static String FILE_NAME = "file.dat";
|
||||||
static String FILE_MD5_HASH = "c959feb066b37f5c4f0e0f45bbbb4f86";
|
static String FILE_MD5_HASH = "753197aa27f162faa3e3c2e48ee5eb07";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
|
||||||
|
@ -10,4 +10,5 @@ This module contains articles about networking in Java
|
|||||||
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
|
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
|
||||||
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
|
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
|
||||||
- [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket)
|
- [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket)
|
||||||
|
- [Get the IP Address of the Current Machine Using Java](https://www.baeldung.com/java-get-ip-address)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
|
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
|
||||||
|
@ -4,4 +4,5 @@
|
|||||||
- [Lookahead and Lookbehind in Java Regex](https://www.baeldung.com/java-regex-lookahead-lookbehind)
|
- [Lookahead and Lookbehind in Java Regex](https://www.baeldung.com/java-regex-lookahead-lookbehind)
|
||||||
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
|
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
|
||||||
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
|
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
|
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
## Core Java Cookbooks and Examples
|
## Core Java Cookbooks and Examples
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||||
|
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
|
||||||
|
@ -6,3 +6,4 @@ This module contains articles about GraphQL with Java
|
|||||||
|
|
||||||
- [Introduction to GraphQL](https://www.baeldung.com/graphql)
|
- [Introduction to GraphQL](https://www.baeldung.com/graphql)
|
||||||
- [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service)
|
- [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service)
|
||||||
|
- [Return Map from GraphQL](https://www.baeldung.com/java-graphql-return-map)
|
||||||
|
@ -10,3 +10,4 @@ This module contains articles about Jersey.
|
|||||||
- [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test)
|
- [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test)
|
||||||
- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters)
|
- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters)
|
||||||
- [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers)
|
- [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers)
|
||||||
|
- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey)
|
||||||
|
@ -14,6 +14,11 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.json</groupId>
|
||||||
|
<artifactId>json</artifactId>
|
||||||
|
<version>${json.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba</groupId>
|
<groupId>com.alibaba</groupId>
|
||||||
<artifactId>fastjson</artifactId>
|
<artifactId>fastjson</artifactId>
|
||||||
@ -148,6 +153,7 @@
|
|||||||
<jsoniter.version>0.9.23</jsoniter.version>
|
<jsoniter.version>0.9.23</jsoniter.version>
|
||||||
<moshi.version>1.9.2</moshi.version>
|
<moshi.version>1.9.2</moshi.version>
|
||||||
<fastjson.version>1.2.21</fastjson.version>
|
<fastjson.version>1.2.21</fastjson.version>
|
||||||
|
<json.version>20211205</json.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import com.google.gson.JsonSyntaxException;
|
||||||
|
import com.google.gson.TypeAdapter;
|
||||||
|
|
||||||
|
public class GsonValidator {
|
||||||
|
|
||||||
|
final TypeAdapter<JsonElement> strictAdapter = new Gson().getAdapter(JsonElement.class);
|
||||||
|
|
||||||
|
public boolean isValid(String json) {
|
||||||
|
try {
|
||||||
|
JsonParser.parseString(json);
|
||||||
|
} catch (JsonSyntaxException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isValidStrict(String json) {
|
||||||
|
try {
|
||||||
|
strictAdapter.fromJson(json);
|
||||||
|
} catch (JsonSyntaxException | IOException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JacksonException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
public class JacksonValidator {
|
||||||
|
|
||||||
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
public boolean isValid(String json) {
|
||||||
|
try {
|
||||||
|
mapper.readTree(json);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import org.json.JSONArray;
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
public class JsonValidator {
|
||||||
|
|
||||||
|
public boolean isValidObject(String json) {
|
||||||
|
try {
|
||||||
|
new JSONObject(json);
|
||||||
|
} catch (JSONException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isValidJson(String json) {
|
||||||
|
try {
|
||||||
|
new JSONObject(json);
|
||||||
|
} catch (JSONException e) {
|
||||||
|
try {
|
||||||
|
new JSONArray(json);
|
||||||
|
} catch (JSONException ne) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class GsonValidatorUnitTest {
|
||||||
|
|
||||||
|
private final GsonValidator validator = new GsonValidator();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidObjectJson_whenValidatingNonStrict_thenValid() {
|
||||||
|
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
|
||||||
|
assertTrue(validator.isValid(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidArrayJson_whenValidatingNonStrict_thenValid() {
|
||||||
|
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
|
||||||
|
assertTrue(validator.isValid(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidJson_whenValidatingNonStrict_thenValid() {
|
||||||
|
String json = "Invalid_Json";
|
||||||
|
assertTrue(validator.isValid(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidJson_whenValidatingStrict_thenInvalid() {
|
||||||
|
String json = "Invalid_Json";
|
||||||
|
assertFalse(validator.isValidStrict(json));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class JacksonValidatorUnitTest {
|
||||||
|
|
||||||
|
private final JacksonValidator validator = new JacksonValidator();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidObjectJson_whenValidating_thenValid() {
|
||||||
|
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
|
||||||
|
assertTrue(validator.isValid(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidArrayJson_whenValidating_thenValid() {
|
||||||
|
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
|
||||||
|
assertTrue(validator.isValid(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidJson_whenValidating_thenInvalid() {
|
||||||
|
String json = "Invalid_Json";
|
||||||
|
assertFalse(validator.isValid(json));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.jsonvalidation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class JsonValidatorUnitTest {
|
||||||
|
|
||||||
|
private final JsonValidator validator = new JsonValidator();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidObjectJson_whenValidatingObject_thenValid() {
|
||||||
|
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
|
||||||
|
assertTrue(validator.isValidObject(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidJson_whenValidating_thenInvalid() {
|
||||||
|
String json = "Invalid_Json";
|
||||||
|
assertFalse(validator.isValidObject(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidArrayJson_whenValidatingObject_thenInvalid() {
|
||||||
|
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
|
||||||
|
assertFalse(validator.isValidObject(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidJson_whenValidatingJson_thenValid() {
|
||||||
|
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
|
||||||
|
assertTrue(validator.isValidJson(json));
|
||||||
|
}
|
||||||
|
}
|
@ -1,47 +1,58 @@
|
|||||||
package com.baeldung.logging.log4j2.tests;
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import java.io.ByteArrayOutputStream;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.PrintStream;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.core.Appender;
|
||||||
|
import org.apache.logging.log4j.core.appender.WriterAppender;
|
||||||
|
import org.apache.logging.log4j.core.layout.JsonLayout;
|
||||||
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
|
import java.io.CharArrayWriter;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import java.io.Writer;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest {
|
public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest {
|
||||||
|
|
||||||
private static Logger logger;
|
private Appender appender;
|
||||||
private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
|
private Logger logger;
|
||||||
private PrintStream ps = new PrintStream(consoleOutput);
|
private final Writer writer = new CharArrayWriter();
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
// Redirect console output to our stream
|
|
||||||
System.setOut(ps);
|
|
||||||
logger = LogManager.getLogger("CONSOLE_JSON_APPENDER");
|
logger = LogManager.getLogger("CONSOLE_JSON_APPENDER");
|
||||||
|
|
||||||
|
appender = WriterAppender.newBuilder()
|
||||||
|
.setTarget(writer)
|
||||||
|
.setLayout(JsonLayout.newBuilder().build())
|
||||||
|
.setName("json_layout_for_testing")
|
||||||
|
.build();
|
||||||
|
appender.start();
|
||||||
|
|
||||||
|
((org.apache.logging.log4j.core.Logger) logger).addAppender(appender);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() {
|
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() throws Exception {
|
||||||
logger.debug("Debug message");
|
logger.debug("Debug message");
|
||||||
String currentLog = consoleOutput.toString();
|
|
||||||
assertTrue(currentLog.isEmpty());
|
writer.flush();
|
||||||
assertTrue(isValidJSON(currentLog));
|
assertTrue(isValidJSON(writer.toString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isValidJSON(String jsonInString) {
|
@After
|
||||||
try {
|
public void cleanup() {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender);
|
||||||
mapper.readTree(jsonInString);
|
|
||||||
return true;
|
|
||||||
} catch (IOException e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static boolean isValidJSON(String jsonInString) throws Exception {
|
||||||
|
JsonNode jsonNode = new ObjectMapper().readTree(jsonInString);
|
||||||
|
return jsonNode.get("message").asText().equals("Debug message");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
@ -11,8 +11,8 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>maven-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<build>
|
<build>
|
@ -0,0 +1,31 @@
|
|||||||
|
<?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.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>empty-phase</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>disable-plugin-examples</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-enforcer-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>enforce-file-exists</id>
|
||||||
|
<phase/>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,31 @@
|
|||||||
|
<?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.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>phase-none</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>disable-plugin-examples</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-enforcer-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>enforce-file-exists</id>
|
||||||
|
<phase>any-value-that-is-not-a-phase</phase>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,17 @@
|
|||||||
|
<?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.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>plugin-enabled</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>disable-plugin-examples</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1 @@
|
|||||||
|
Example source file
|
@ -0,0 +1,55 @@
|
|||||||
|
<?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.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>disable-plugin-examples</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>maven-parent-pom-resolution</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-enforcer-plugin</artifactId>
|
||||||
|
<version>3.0.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>enforce-file-exists</id>
|
||||||
|
<goals>
|
||||||
|
<goal>enforce</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<rules>
|
||||||
|
<requireFilesExist>
|
||||||
|
<files>
|
||||||
|
<file>${project.basedir}/src/file-that-must-exist.txt</file>
|
||||||
|
</files>
|
||||||
|
</requireFilesExist>
|
||||||
|
</rules>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>plugin-enabled</module>
|
||||||
|
<module>skip-parameter</module>
|
||||||
|
<module>phase-none</module>
|
||||||
|
<module>empty-phase</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,28 @@
|
|||||||
|
<?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.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>skip-parameter</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
|
||||||
|
<artifactId>disable-plugin-examples</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-enforcer-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<skip>true</skip>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1 @@
|
|||||||
|
Example source file
|
@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>aggregator</module>
|
<module>aggregator</module>
|
||||||
|
<module>disable-plugin-examples</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<!-- to detect the POM hierarchy, just type "mvn dependency:display-ancestors" -->
|
<!-- to detect the POM hierarchy, just type "mvn dependency:display-ancestors" -->
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>maven-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../..</relativePath>
|
<relativePath>../..</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
@ -10,8 +10,8 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>maven-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
@ -15,6 +15,8 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
|
<module>animal-sniffer-mvn-plugin</module>
|
||||||
|
<module>maven-archetype</module>
|
||||||
<!-- <module>compiler-plugin-java-9</module> --> <!-- We haven't upgraded to java 9. -->
|
<!-- <module>compiler-plugin-java-9</module> --> <!-- We haven't upgraded to java 9. -->
|
||||||
<module>maven-copy-files</module>
|
<module>maven-copy-files</module>
|
||||||
<module>maven-custom-plugin</module>
|
<module>maven-custom-plugin</module>
|
||||||
@ -23,6 +25,7 @@
|
|||||||
<module>maven-integration-test</module>
|
<module>maven-integration-test</module>
|
||||||
<module>maven-multi-source</module>
|
<module>maven-multi-source</module>
|
||||||
<module>maven-plugins</module>
|
<module>maven-plugins</module>
|
||||||
|
<module>maven-polyglot</module>
|
||||||
<module>maven-properties</module>
|
<module>maven-properties</module>
|
||||||
<!-- <module>maven-proxy</module> --> <!-- Not a maven project -->
|
<!-- <module>maven-proxy</module> --> <!-- Not a maven project -->
|
||||||
<module>maven-unused-dependencies</module>
|
<module>maven-unused-dependencies</module>
|
||||||
|
@ -0,0 +1,76 @@
|
|||||||
|
package com.baeldung.hibernate.criteria.model;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
|
||||||
|
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"),
|
||||||
|
@org.hibernate.annotations.NamedQuery(name = "Employee_findAllByEmployeeSalary", query = "from Employee where salary = :employeeSalary")})
|
||||||
|
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "Employee_FindByEmployeeId", query = "select * from employee emp where employeeId=:employeeId", resultClass = Employee.class)})
|
||||||
|
@Entity
|
||||||
|
public class Employee implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
private Integer id;
|
||||||
|
private String name;
|
||||||
|
private Long salary;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
public Employee() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Employee(final Integer id, final String name, final Long salary) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.salary = salary;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(final Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
final Employee other = (Employee) obj;
|
||||||
|
if (id == null) {
|
||||||
|
if (other.id != null)
|
||||||
|
return false;
|
||||||
|
} else if (!id.equals(other.id))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getSalary() {
|
||||||
|
return salary;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSalary(Long salary) {
|
||||||
|
this.salary = salary;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.hibernate.criteria.view;
|
||||||
|
|
||||||
|
import com.baeldung.hibernate.criteria.model.Employee;
|
||||||
|
import com.baeldung.hibernate.criteria.util.HibernateUtil;
|
||||||
|
import java.util.List;
|
||||||
|
import javax.persistence.criteria.CriteriaBuilder;
|
||||||
|
import javax.persistence.criteria.CriteriaQuery;
|
||||||
|
import javax.persistence.criteria.Root;
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.query.Query;
|
||||||
|
|
||||||
|
public class EmployeeCriteriaQueries {
|
||||||
|
|
||||||
|
public List<Employee> getAllEmployees() {
|
||||||
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
|
final CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||||
|
final CriteriaQuery<Employee> cr = cb.createQuery(Employee.class);
|
||||||
|
final Root<Employee> root = cr.from(Employee.class);
|
||||||
|
cr.select(root);
|
||||||
|
Query<Employee> query = session.createQuery(cr);
|
||||||
|
List<Employee> results = query.getResultList();
|
||||||
|
session.close();
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
// To get items having salary more than 50000
|
||||||
|
public String[] greaterThanCriteria() {
|
||||||
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
|
final CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||||
|
final CriteriaQuery<Employee> cr = cb.createQuery(Employee.class);
|
||||||
|
final Root<Employee> root = cr.from(Employee.class);
|
||||||
|
cr.select(root)
|
||||||
|
.where(cb.gt(root.get("salary"), 50000));
|
||||||
|
Query<Employee> query = session.createQuery(cr);
|
||||||
|
final List<Employee> greaterThanEmployeeList = query.getResultList();
|
||||||
|
final String employeeWithGreaterSalary[] = new String[greaterThanEmployeeList.size()];
|
||||||
|
for (int i = 0; i < greaterThanEmployeeList.size(); i++) {
|
||||||
|
employeeWithGreaterSalary[i] = greaterThanEmployeeList.get(i)
|
||||||
|
.getName();
|
||||||
|
}
|
||||||
|
session.close();
|
||||||
|
return employeeWithGreaterSalary;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,5 +1,6 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.test.context.ContextConfiguration;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
@ -13,6 +14,7 @@ import com.baeldung.hibernate.criteria.PersistenceConfig;
|
|||||||
public class SpringContextTest {
|
public class SpringContextTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@Ignore
|
||||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.hibernate.criteria;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import com.baeldung.hibernate.criteria.model.Employee;
|
||||||
|
import com.baeldung.hibernate.criteria.util.HibernateUtil;
|
||||||
|
import com.baeldung.hibernate.criteria.view.EmployeeCriteriaQueries;
|
||||||
|
import java.util.List;
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class EmployeeCriteriaIntegrationTest {
|
||||||
|
|
||||||
|
final private EmployeeCriteriaQueries employeeCriteriaQueries = new EmployeeCriteriaQueries();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGreaterThanCriteriaQuery() {
|
||||||
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
|
final List<Employee> expectedGreaterThanList = session.createQuery("From Employee where salary>50000").list();
|
||||||
|
final String expectedGreaterThanEmployees[] = new String[expectedGreaterThanList.size()];
|
||||||
|
for (int i = 0; i < expectedGreaterThanList.size(); i++) {
|
||||||
|
expectedGreaterThanEmployees[i] = expectedGreaterThanList.get(i).getName();
|
||||||
|
}
|
||||||
|
session.close();
|
||||||
|
assertArrayEquals(expectedGreaterThanEmployees, employeeCriteriaQueries.greaterThanCriteria());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetAllEmployeesQuery() {
|
||||||
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
|
final List<Employee> expectedSortCritEmployeeList = session.createQuery("From Employee").list();
|
||||||
|
session.close();
|
||||||
|
assertArrayEquals(expectedSortCritEmployeeList.toArray(), employeeCriteriaQueries.getAllEmployees().toArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<!DOCTYPE hibernate-mapping PUBLIC
|
||||||
|
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
|
||||||
|
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
|
||||||
|
<hibernate-mapping>
|
||||||
|
<class name="com.baeldung.hibernate.criteria.model.Employee" table="EMPLOYEE">
|
||||||
|
<id name="id" type="java.lang.Integer">
|
||||||
|
<column name="EMPLOYEE_ID" />
|
||||||
|
<generator class="identity" />
|
||||||
|
</id>
|
||||||
|
<property name="salary" type="java.lang.Long">
|
||||||
|
<column name="EMPLOYEE_SALARY" not-null="true" />
|
||||||
|
</property>
|
||||||
|
<property name="name" type="string">
|
||||||
|
<column name="EMPLOYEE_NAME" not-null="true" />
|
||||||
|
</property>
|
||||||
|
</class>
|
||||||
|
|
||||||
|
</hibernate-mapping>
|
@ -14,5 +14,6 @@
|
|||||||
<property name="hibernate.hbm2ddl.import_files">import-db.sql</property>
|
<property name="hibernate.hbm2ddl.import_files">import-db.sql</property>
|
||||||
<property name="show_sql">false</property>
|
<property name="show_sql">false</property>
|
||||||
<mapping resource="com/baeldung/hibernate/criteria/model/Item.hbm.xml" />
|
<mapping resource="com/baeldung/hibernate/criteria/model/Item.hbm.xml" />
|
||||||
|
<mapping resource="com/baeldung/hibernate/criteria/model/Employee.hbm.xml" />
|
||||||
</session-factory>
|
</session-factory>
|
||||||
</hibernate-configuration>
|
</hibernate-configuration>
|
@ -20,3 +20,10 @@ insert into item (item_id, item_name, item_desc, item_price) values(9,'Household
|
|||||||
insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98);
|
insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98);
|
||||||
|
|
||||||
insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
|
insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
|
||||||
|
|
||||||
|
insert into EMPLOYEE (id, name, salary) values(1,'Steve Jobs', 55000);
|
||||||
|
|
||||||
|
insert into EMPLOYEE (id, name, salary) values(1,'Bill Hages', 45000);
|
||||||
|
|
||||||
|
insert into EMPLOYEE (id, name, salary) values(1,'Mark clinch', 57000);
|
||||||
|
|
||||||
|
@ -11,4 +11,5 @@ This module contains articles about MongoDB in Java.
|
|||||||
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
|
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
|
||||||
- [Retrieve a Value from MongoDB by Its Key Name](https://www.baeldung.com/mongodb-get-value-by-key-name)
|
- [Retrieve a Value from MongoDB by Its Key Name](https://www.baeldung.com/mongodb-get-value-by-key-name)
|
||||||
- [Push and Set Operations in Same MongoDB Update](https://www.baeldung.com/java-mongodb-push-set)
|
- [Push and Set Operations in Same MongoDB Update](https://www.baeldung.com/java-mongodb-push-set)
|
||||||
|
- [Checking Connection to MongoDB](https://www.baeldung.com/mongodb-check-connection)
|
||||||
- More articles: [[<-- prev]](../java-mongodb)
|
- More articles: [[<-- prev]](../java-mongodb)
|
||||||
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.spring.data.jpa.entity;
|
||||||
|
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.GeneratedValue;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Employee {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private Long salary;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.spring.data.jpa.repository;
|
||||||
|
|
||||||
|
import com.baeldung.spring.data.jpa.entity.Employee;
|
||||||
|
import java.util.List;
|
||||||
|
import net.bytebuddy.TypeCache.Sort;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
|
||||||
|
|
||||||
|
@Query(value = "SELECT e FROM Employee e")
|
||||||
|
List<Employee> findAllEmployees(Sort sort);
|
||||||
|
|
||||||
|
@Query("SELECT e FROM Employee e WHERE e.salary = ?1")
|
||||||
|
Employee findAllEmployeesWithSalary(Long salary);
|
||||||
|
|
||||||
|
@Query("SELECT e FROM Employee e WHERE e.name = ?1 and e.salary = ?2")
|
||||||
|
Employee findUserByNameAndSalary(String name, Long salary);
|
||||||
|
|
||||||
|
@Query(
|
||||||
|
value = "SELECT * FROM Employee e WHERE e.salary = ?1",
|
||||||
|
nativeQuery = true)
|
||||||
|
Employee findUserBySalaryNative(Long salary);
|
||||||
|
|
||||||
|
@Query("SELECT e FROM Employee e WHERE e.name = :name and e.salary = :salary")
|
||||||
|
Employee findUserByEmployeeNameAndSalaryNamedParameters(
|
||||||
|
@Param("name") String employeeName,
|
||||||
|
@Param("salary") Long employeeSalary);
|
||||||
|
|
||||||
|
@Query(value = "SELECT * FROM Employee e WHERE e.name = :name and e.salary = :salary",
|
||||||
|
nativeQuery = true)
|
||||||
|
Employee findUserByNameAndSalaryNamedParamsNative(
|
||||||
|
@Param("name") String employeeName,
|
||||||
|
@Param("salary") Long employeeSalary);
|
||||||
|
|
||||||
|
}
|
@ -73,6 +73,12 @@
|
|||||||
<artifactId>querydsl-apt</artifactId>
|
<artifactId>querydsl-apt</artifactId>
|
||||||
<version>${querydsl.version}</version>
|
<version>${querydsl.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>de.flapdoodle.embed</groupId>
|
||||||
|
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||||
|
<version>${embed.mongo.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -103,6 +109,7 @@
|
|||||||
<mongodb-reactivestreams.version>4.1.0</mongodb-reactivestreams.version>
|
<mongodb-reactivestreams.version>4.1.0</mongodb-reactivestreams.version>
|
||||||
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
|
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
|
||||||
<mongodb-driver.version>4.0.5</mongodb-driver.version>
|
<mongodb-driver.version>4.0.5</mongodb-driver.version>
|
||||||
|
<embed.mongo.version>3.2.6</embed.mongo.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -3,13 +3,14 @@ package com.baeldung.projection.model;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
import org.springframework.data.mongodb.core.mapping.Document;
|
import org.springframework.data.mongodb.core.mapping.Document;
|
||||||
import org.springframework.data.mongodb.core.mapping.MongoId;
|
import org.springframework.data.mongodb.core.mapping.MongoId;
|
||||||
|
|
||||||
@Document(collection = "inventory")
|
@Document(collection = "inventory")
|
||||||
public class Inventory {
|
public class Inventory {
|
||||||
|
|
||||||
@MongoId
|
@Id
|
||||||
private String id;
|
private String id;
|
||||||
private String item;
|
private String item;
|
||||||
private String status;
|
private String status;
|
@ -1,54 +1,15 @@
|
|||||||
package com.baeldung.projection;
|
package com.baeldung.projection;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
|
||||||
import org.springframework.util.SocketUtils;
|
|
||||||
|
|
||||||
import com.baeldung.projection.model.InStock;
|
import com.baeldung.projection.model.InStock;
|
||||||
import com.baeldung.projection.model.Inventory;
|
import com.baeldung.projection.model.Inventory;
|
||||||
import com.baeldung.projection.model.Size;
|
import com.baeldung.projection.model.Size;
|
||||||
import com.mongodb.client.MongoClients;
|
|
||||||
|
|
||||||
import de.flapdoodle.embed.mongo.MongodExecutable;
|
|
||||||
import de.flapdoodle.embed.mongo.MongodStarter;
|
|
||||||
import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig;
|
|
||||||
import de.flapdoodle.embed.mongo.config.MongodConfig;
|
|
||||||
import de.flapdoodle.embed.mongo.config.Net;
|
|
||||||
import de.flapdoodle.embed.mongo.distribution.Version;
|
|
||||||
import de.flapdoodle.embed.process.runtime.Network;
|
|
||||||
|
|
||||||
abstract class AbstractTestProjection {
|
abstract class AbstractTestProjection {
|
||||||
|
|
||||||
private static final String CONNECTION_STRING = "mongodb://%s:%d";
|
|
||||||
|
|
||||||
protected MongodExecutable mongodExecutable;
|
|
||||||
protected MongoTemplate mongoTemplate;
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void clean() {
|
|
||||||
mongodExecutable.stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
void setUp() throws IOException {
|
|
||||||
String ip = "localhost";
|
|
||||||
int port = SocketUtils.findAvailableTcpPort();
|
|
||||||
|
|
||||||
ImmutableMongodConfig mongodbConfig = MongodConfig.builder()
|
|
||||||
.version(Version.Main.PRODUCTION)
|
|
||||||
.net(new Net(ip, port, Network.localhostIsIPv6()))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
MongodStarter starter = MongodStarter.getDefaultInstance();
|
|
||||||
mongodExecutable = starter.prepare(mongodbConfig);
|
|
||||||
mongodExecutable.start();
|
|
||||||
mongoTemplate = new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, ip, port)), "test");
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Inventory> getInventories() {
|
public List<Inventory> getInventories() {
|
||||||
Inventory journal = new Inventory();
|
Inventory journal = new Inventory();
|
||||||
journal.setItem("journal");
|
journal.setItem("journal");
|
@ -10,20 +10,27 @@ import java.util.List;
|
|||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||||
import org.springframework.data.mongodb.core.query.Query;
|
import org.springframework.data.mongodb.core.query.Query;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
import com.baeldung.projection.config.ProjectionConfig;
|
||||||
import com.baeldung.projection.model.InStock;
|
import com.baeldung.projection.model.InStock;
|
||||||
import com.baeldung.projection.model.Inventory;
|
import com.baeldung.projection.model.Inventory;
|
||||||
import com.baeldung.projection.model.Size;
|
import com.baeldung.projection.model.Size;
|
||||||
|
|
||||||
@SpringBootTest
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@ContextConfiguration(classes = ProjectionConfig.class)
|
||||||
public class MongoTemplateProjectionUnitTest extends AbstractTestProjection {
|
public class MongoTemplateProjectionUnitTest extends AbstractTestProjection {
|
||||||
|
|
||||||
@BeforeEach
|
@Autowired
|
||||||
void setup() throws Exception {
|
private MongoTemplate mongoTemplate;
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() {
|
||||||
List<Inventory> inventoryList = getInventories();
|
List<Inventory> inventoryList = getInventories();
|
||||||
|
|
||||||
mongoTemplate.insert(inventoryList, Inventory.class);
|
mongoTemplate.insert(inventoryList, Inventory.class);
|
@ -10,24 +10,26 @@ import java.util.List;
|
|||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
import com.baeldung.projection.config.ProjectionConfig;
|
||||||
import com.baeldung.projection.model.InStock;
|
import com.baeldung.projection.model.InStock;
|
||||||
import com.baeldung.projection.model.Inventory;
|
import com.baeldung.projection.model.Inventory;
|
||||||
import com.baeldung.projection.model.Size;
|
import com.baeldung.projection.model.Size;
|
||||||
import com.baeldung.projection.repository.InventoryRepository;
|
import com.baeldung.projection.repository.InventoryRepository;
|
||||||
|
|
||||||
@SpringBootTest
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@ContextConfiguration(classes = ProjectionConfig.class)
|
||||||
public class RepositoryProjectionUnitTest extends AbstractTestProjection {
|
public class RepositoryProjectionUnitTest extends AbstractTestProjection {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private InventoryRepository inventoryRepository;
|
private InventoryRepository inventoryRepository;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setup() throws Exception {
|
void setup() {
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
List<Inventory> inventoryList = getInventories();
|
List<Inventory> inventoryList = getInventories();
|
||||||
|
|
||||||
inventoryRepository.saveAll(inventoryList);
|
inventoryRepository.saveAll(inventoryList);
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.projection.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||||
|
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||||
|
import org.springframework.util.SocketUtils;
|
||||||
|
|
||||||
|
import com.mongodb.client.MongoClients;
|
||||||
|
|
||||||
|
import de.flapdoodle.embed.mongo.MongodExecutable;
|
||||||
|
import de.flapdoodle.embed.mongo.MongodStarter;
|
||||||
|
import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig;
|
||||||
|
import de.flapdoodle.embed.mongo.config.MongodConfig;
|
||||||
|
import de.flapdoodle.embed.mongo.config.Net;
|
||||||
|
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||||
|
import de.flapdoodle.embed.process.runtime.Network;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ComponentScan(basePackages = "com.baeldung.projection")
|
||||||
|
@EnableMongoRepositories(basePackages = "com.baeldung.projection.repository")
|
||||||
|
public class ProjectionConfig {
|
||||||
|
|
||||||
|
private static final String CONNECTION_STRING = "mongodb://%s:%d";
|
||||||
|
private static final String HOST = "localhost";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MongoTemplate mongoTemplate() throws Exception {
|
||||||
|
int randomPort = SocketUtils.findAvailableTcpPort();
|
||||||
|
|
||||||
|
ImmutableMongodConfig mongoDbConfig = MongodConfig.builder()
|
||||||
|
.version(Version.Main.PRODUCTION)
|
||||||
|
.net(new Net(HOST, randomPort, Network.localhostIsIPv6()))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MongodStarter starter = MongodStarter.getDefaultInstance();
|
||||||
|
MongodExecutable mongodExecutable = starter.prepare(mongoDbConfig);
|
||||||
|
mongodExecutable.start();
|
||||||
|
|
||||||
|
return new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, HOST, randomPort)), "mongo_auth");
|
||||||
|
}
|
||||||
|
}
|
6
pom.xml
6
pom.xml
@ -343,7 +343,6 @@
|
|||||||
<module>algorithms-searching</module>
|
<module>algorithms-searching</module>
|
||||||
<module>algorithms-sorting</module>
|
<module>algorithms-sorting</module>
|
||||||
<module>algorithms-sorting-2</module>
|
<module>algorithms-sorting-2</module>
|
||||||
<module>animal-sniffer-mvn-plugin</module>
|
|
||||||
<module>annotations</module>
|
<module>annotations</module>
|
||||||
<module>antlr</module>
|
<module>antlr</module>
|
||||||
|
|
||||||
@ -502,8 +501,6 @@
|
|||||||
<module>mapstruct</module>
|
<module>mapstruct</module>
|
||||||
|
|
||||||
<module>maven-modules</module>
|
<module>maven-modules</module>
|
||||||
<module>maven-archetype</module>
|
|
||||||
<module>maven-polyglot</module>
|
|
||||||
|
|
||||||
<module>mesos-marathon</module>
|
<module>mesos-marathon</module>
|
||||||
<module>metrics</module>
|
<module>metrics</module>
|
||||||
@ -820,7 +817,6 @@
|
|||||||
<module>algorithms-searching</module>
|
<module>algorithms-searching</module>
|
||||||
<module>algorithms-sorting</module>
|
<module>algorithms-sorting</module>
|
||||||
<module>algorithms-sorting-2</module>
|
<module>algorithms-sorting-2</module>
|
||||||
<module>animal-sniffer-mvn-plugin</module>
|
|
||||||
<module>annotations</module>
|
<module>annotations</module>
|
||||||
<module>antlr</module>
|
<module>antlr</module>
|
||||||
|
|
||||||
@ -981,8 +977,6 @@
|
|||||||
<module>mapstruct</module>
|
<module>mapstruct</module>
|
||||||
|
|
||||||
<module>maven-modules</module>
|
<module>maven-modules</module>
|
||||||
<module>maven-archetype</module>
|
|
||||||
<module>maven-polyglot</module>
|
|
||||||
|
|
||||||
<module>mesos-marathon</module>
|
<module>mesos-marathon</module>
|
||||||
<module>metrics</module>
|
<module>metrics</module>
|
||||||
|
@ -7,3 +7,4 @@ This module contains articles about Spring 4
|
|||||||
- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari)
|
- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari)
|
||||||
- [Spring JSON-P with Jackson](https://www.baeldung.com/spring-jackson-jsonp)
|
- [Spring JSON-P with Jackson](https://www.baeldung.com/spring-jackson-jsonp)
|
||||||
- [What’s New in Spring 4.3?](https://www.baeldung.com/whats-new-in-spring-4-3)
|
- [What’s New in Spring 4.3?](https://www.baeldung.com/whats-new-in-spring-4-3)
|
||||||
|
- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators)
|
||||||
|
@ -31,6 +31,10 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
|
@ -3,3 +3,24 @@ feature.new.foo=Y
|
|||||||
last.active.after=2018-03-14T00:00:00Z
|
last.active.after=2018-03-14T00:00:00Z
|
||||||
first.active.after=2999-03-15T00:00:00Z
|
first.active.after=2999-03-15T00:00:00Z
|
||||||
logging.level.org.flips=info
|
logging.level.org.flips=info
|
||||||
|
|
||||||
|
#actuator properties
|
||||||
|
### server port
|
||||||
|
server.port=8080
|
||||||
|
#port used to expose actuator
|
||||||
|
management.port=8081
|
||||||
|
#CIDR allowed to hit actuator
|
||||||
|
management.address=127.0.0.1
|
||||||
|
# Actuator Configuration
|
||||||
|
# customize /beans endpoint
|
||||||
|
endpoints.beans.id=springbeans
|
||||||
|
endpoints.beans.sensitive=false
|
||||||
|
endpoints.beans.enabled=true
|
||||||
|
# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access.
|
||||||
|
# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html
|
||||||
|
management.security.enabled=false
|
||||||
|
endpoints.health.sensitive=false
|
||||||
|
# customize /info endpoint
|
||||||
|
info.app.name=Spring Sample Application
|
||||||
|
info.app.description=This is my first spring boot application
|
||||||
|
info.app.version=1.0.0
|
@ -17,8 +17,6 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>spring-boot-1</module>
|
|
||||||
<module>spring-boot-2</module>
|
|
||||||
<module>spring-boot-admin</module>
|
<module>spring-boot-admin</module>
|
||||||
<module>spring-boot-angular</module>
|
<module>spring-boot-angular</module>
|
||||||
<module>spring-boot-annotations</module>
|
<module>spring-boot-annotations</module>
|
||||||
|
@ -1 +0,0 @@
|
|||||||
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
|
|
@ -1,11 +0,0 @@
|
|||||||
## Spring Boot 1.x Actuator
|
|
||||||
|
|
||||||
This module contains articles about Spring Boot Actuator in Spring Boot version 1.x.
|
|
||||||
|
|
||||||
## Relevant articles:
|
|
||||||
- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators)
|
|
||||||
- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer)
|
|
||||||
- [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks)
|
|
||||||
- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation)
|
|
||||||
|
|
||||||
|
|
234
spring-boot-modules/spring-boot-1/mvnw
vendored
234
spring-boot-modules/spring-boot-1/mvnw
vendored
@ -1,234 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# ----------------------------------------------------------------------------
|
|
||||||
# Licensed to the Apache Software Foundation (ASF) under one
|
|
||||||
# or more contributor license agreements. See the NOTICE file
|
|
||||||
# distributed with this work for additional information
|
|
||||||
# regarding copyright ownership. The ASF licenses this file
|
|
||||||
# to you under the Apache License, Version 2.0 (the
|
|
||||||
# "License"); you may not use this file except in compliance
|
|
||||||
# with the License. You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing,
|
|
||||||
# software distributed under the License is distributed on an
|
|
||||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
||||||
# KIND, either express or implied. See the License for the
|
|
||||||
# specific language governing permissions and limitations
|
|
||||||
# under the License.
|
|
||||||
# ----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
|
||||||
# Maven2 Start Up Batch script
|
|
||||||
#
|
|
||||||
# Required ENV vars:
|
|
||||||
# ------------------
|
|
||||||
# JAVA_HOME - location of a JDK home dir
|
|
||||||
#
|
|
||||||
# Optional ENV vars
|
|
||||||
# -----------------
|
|
||||||
# M2_HOME - location of maven2's installed home dir
|
|
||||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
|
||||||
# e.g. to debug Maven itself, use
|
|
||||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
|
||||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
|
||||||
# ----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
if [ -z "$MAVEN_SKIP_RC" ]; then
|
|
||||||
|
|
||||||
if [ -f /etc/mavenrc ]; then
|
|
||||||
. /etc/mavenrc
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -f "$HOME/.mavenrc" ]; then
|
|
||||||
. "$HOME/.mavenrc"
|
|
||||||
fi
|
|
||||||
|
|
||||||
fi
|
|
||||||
|
|
||||||
# OS specific support. $var _must_ be set to either true or false.
|
|
||||||
cygwin=false
|
|
||||||
darwin=false
|
|
||||||
mingw=false
|
|
||||||
case "$(uname)" in
|
|
||||||
CYGWIN*) cygwin=true ;;
|
|
||||||
MINGW*) mingw=true ;;
|
|
||||||
Darwin*)
|
|
||||||
darwin=true
|
|
||||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
|
||||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
|
||||||
if [ -x "/usr/libexec/java_home" ]; then
|
|
||||||
export JAVA_HOME="$(/usr/libexec/java_home)"
|
|
||||||
else
|
|
||||||
export JAVA_HOME="/Library/Java/Home"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
|
||||||
if [ -r /etc/gentoo-release ]; then
|
|
||||||
JAVA_HOME=$(java-config --jre-home)
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -z "$M2_HOME" ]; then
|
|
||||||
## resolve links - $0 may be a link to maven's home
|
|
||||||
PRG="$0"
|
|
||||||
|
|
||||||
# need this for relative symlinks
|
|
||||||
while [ -h "$PRG" ]; do
|
|
||||||
ls=$(ls -ld "$PRG")
|
|
||||||
link=$(expr "$ls" : '.*-> \(.*\)$')
|
|
||||||
if expr "$link" : '/.*' >/dev/null; then
|
|
||||||
PRG="$link"
|
|
||||||
else
|
|
||||||
PRG="$(dirname "$PRG")/$link"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
saveddir=$(pwd)
|
|
||||||
|
|
||||||
M2_HOME=$(dirname "$PRG")/..
|
|
||||||
|
|
||||||
# make it fully qualified
|
|
||||||
M2_HOME=$(cd "$M2_HOME" && pwd)
|
|
||||||
|
|
||||||
cd "$saveddir"
|
|
||||||
# echo Using m2 at $M2_HOME
|
|
||||||
fi
|
|
||||||
|
|
||||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
|
||||||
if $cygwin; then
|
|
||||||
[ -n "$M2_HOME" ] &&
|
|
||||||
M2_HOME=$(cygpath --unix "$M2_HOME")
|
|
||||||
[ -n "$JAVA_HOME" ] &&
|
|
||||||
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
|
|
||||||
[ -n "$CLASSPATH" ] &&
|
|
||||||
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
|
|
||||||
fi
|
|
||||||
|
|
||||||
# For Migwn, ensure paths are in UNIX format before anything is touched
|
|
||||||
if $mingw; then
|
|
||||||
[ -n "$M2_HOME" ] &&
|
|
||||||
M2_HOME="$( (
|
|
||||||
cd "$M2_HOME"
|
|
||||||
pwd
|
|
||||||
))"
|
|
||||||
[ -n "$JAVA_HOME" ] &&
|
|
||||||
JAVA_HOME="$( (
|
|
||||||
cd "$JAVA_HOME"
|
|
||||||
pwd
|
|
||||||
))"
|
|
||||||
# TODO classpath?
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
|
||||||
javaExecutable="$(which javac)"
|
|
||||||
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
|
|
||||||
# readlink(1) is not available as standard on Solaris 10.
|
|
||||||
readLink=$(which readlink)
|
|
||||||
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
|
|
||||||
if $darwin; then
|
|
||||||
javaHome="$(dirname \"$javaExecutable\")"
|
|
||||||
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
|
|
||||||
else
|
|
||||||
javaExecutable="$(readlink -f \"$javaExecutable\")"
|
|
||||||
fi
|
|
||||||
javaHome="$(dirname \"$javaExecutable\")"
|
|
||||||
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
|
|
||||||
JAVA_HOME="$javaHome"
|
|
||||||
export JAVA_HOME
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -z "$JAVACMD" ]; then
|
|
||||||
if [ -n "$JAVA_HOME" ]; then
|
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
|
||||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
|
||||||
else
|
|
||||||
JAVACMD="$JAVA_HOME/bin/java"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
JAVACMD="$(which java)"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ ! -x "$JAVACMD" ]; then
|
|
||||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
|
||||||
echo " We cannot execute $JAVACMD" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
|
||||||
echo "Warning: JAVA_HOME environment variable is not set."
|
|
||||||
fi
|
|
||||||
|
|
||||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
|
||||||
|
|
||||||
# traverses directory structure from process work directory to filesystem root
|
|
||||||
# first directory with .mvn subdirectory is considered project base directory
|
|
||||||
find_maven_basedir() {
|
|
||||||
|
|
||||||
if [ -z "$1" ]; then
|
|
||||||
echo "Path not specified to find_maven_basedir"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
basedir="$1"
|
|
||||||
wdir="$1"
|
|
||||||
while [ "$wdir" != '/' ]; do
|
|
||||||
if [ -d "$wdir"/.mvn ]; then
|
|
||||||
basedir=$wdir
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
|
||||||
if [ -d "${wdir}" ]; then
|
|
||||||
wdir=$(
|
|
||||||
cd "$wdir/.."
|
|
||||||
pwd
|
|
||||||
)
|
|
||||||
fi
|
|
||||||
# end of workaround
|
|
||||||
done
|
|
||||||
echo "${basedir}"
|
|
||||||
}
|
|
||||||
|
|
||||||
# concatenates all lines of a file
|
|
||||||
concat_lines() {
|
|
||||||
if [ -f "$1" ]; then
|
|
||||||
echo "$(tr -s '\n' ' ' <"$1")"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
BASE_DIR=$(find_maven_basedir "$(pwd)")
|
|
||||||
if [ -z "$BASE_DIR" ]; then
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
|
||||||
echo $MAVEN_PROJECTBASEDIR
|
|
||||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
|
||||||
|
|
||||||
# For Cygwin, switch paths to Windows format before running java
|
|
||||||
if $cygwin; then
|
|
||||||
[ -n "$M2_HOME" ] &&
|
|
||||||
M2_HOME=$(cygpath --path --windows "$M2_HOME")
|
|
||||||
[ -n "$JAVA_HOME" ] &&
|
|
||||||
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
|
|
||||||
[ -n "$CLASSPATH" ] &&
|
|
||||||
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
|
|
||||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
|
||||||
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
|
|
||||||
fi
|
|
||||||
|
|
||||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
|
||||||
|
|
||||||
exec "$JAVACMD" \
|
|
||||||
$MAVEN_OPTS \
|
|
||||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
|
||||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
|
||||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
|
143
spring-boot-modules/spring-boot-1/mvnw.cmd
vendored
143
spring-boot-modules/spring-boot-1/mvnw.cmd
vendored
@ -1,143 +0,0 @@
|
|||||||
@REM ----------------------------------------------------------------------------
|
|
||||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
|
||||||
@REM or more contributor license agreements. See the NOTICE file
|
|
||||||
@REM distributed with this work for additional information
|
|
||||||
@REM regarding copyright ownership. The ASF licenses this file
|
|
||||||
@REM to you under the Apache License, Version 2.0 (the
|
|
||||||
@REM "License"); you may not use this file except in compliance
|
|
||||||
@REM with the License. You may obtain a copy of the License at
|
|
||||||
@REM
|
|
||||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
@REM
|
|
||||||
@REM Unless required by applicable law or agreed to in writing,
|
|
||||||
@REM software distributed under the License is distributed on an
|
|
||||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
||||||
@REM KIND, either express or implied. See the License for the
|
|
||||||
@REM specific language governing permissions and limitations
|
|
||||||
@REM under the License.
|
|
||||||
@REM ----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
@REM ----------------------------------------------------------------------------
|
|
||||||
@REM Maven2 Start Up Batch script
|
|
||||||
@REM
|
|
||||||
@REM Required ENV vars:
|
|
||||||
@REM JAVA_HOME - location of a JDK home dir
|
|
||||||
@REM
|
|
||||||
@REM Optional ENV vars
|
|
||||||
@REM M2_HOME - location of maven2's installed home dir
|
|
||||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
|
||||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
|
||||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
|
||||||
@REM e.g. to debug Maven itself, use
|
|
||||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
|
||||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
|
||||||
@REM ----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
|
||||||
@echo off
|
|
||||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
|
||||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
|
||||||
|
|
||||||
@REM set %HOME% to equivalent of $HOME
|
|
||||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
|
||||||
|
|
||||||
@REM Execute a user defined script before this one
|
|
||||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
|
||||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
|
||||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
|
||||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
|
||||||
:skipRcPre
|
|
||||||
|
|
||||||
@setlocal
|
|
||||||
|
|
||||||
set ERROR_CODE=0
|
|
||||||
|
|
||||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
|
||||||
@setlocal
|
|
||||||
|
|
||||||
@REM ==== START VALIDATION ====
|
|
||||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo Error: JAVA_HOME not found in your environment. >&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
|
||||||
echo location of your Java installation. >&2
|
|
||||||
echo.
|
|
||||||
goto error
|
|
||||||
|
|
||||||
:OkJHome
|
|
||||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
|
||||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
|
||||||
echo location of your Java installation. >&2
|
|
||||||
echo.
|
|
||||||
goto error
|
|
||||||
|
|
||||||
@REM ==== END VALIDATION ====
|
|
||||||
|
|
||||||
:init
|
|
||||||
|
|
||||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
|
||||||
@REM Fallback to current working directory if not found.
|
|
||||||
|
|
||||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
|
||||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
|
||||||
|
|
||||||
set EXEC_DIR=%CD%
|
|
||||||
set WDIR=%EXEC_DIR%
|
|
||||||
:findBaseDir
|
|
||||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
|
||||||
cd ..
|
|
||||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
|
||||||
set WDIR=%CD%
|
|
||||||
goto findBaseDir
|
|
||||||
|
|
||||||
:baseDirFound
|
|
||||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
|
||||||
cd "%EXEC_DIR%"
|
|
||||||
goto endDetectBaseDir
|
|
||||||
|
|
||||||
:baseDirNotFound
|
|
||||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
|
||||||
cd "%EXEC_DIR%"
|
|
||||||
|
|
||||||
:endDetectBaseDir
|
|
||||||
|
|
||||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
|
||||||
|
|
||||||
@setlocal EnableExtensions EnableDelayedExpansion
|
|
||||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
|
||||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
|
||||||
|
|
||||||
:endReadAdditionalConfig
|
|
||||||
|
|
||||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
|
||||||
|
|
||||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
|
||||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
|
||||||
|
|
||||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
|
||||||
if ERRORLEVEL 1 goto error
|
|
||||||
goto end
|
|
||||||
|
|
||||||
:error
|
|
||||||
set ERROR_CODE=1
|
|
||||||
|
|
||||||
:end
|
|
||||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
|
||||||
|
|
||||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
|
||||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
|
||||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
|
||||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
|
||||||
:skipRcPost
|
|
||||||
|
|
||||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
|
||||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
|
||||||
|
|
||||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
|
||||||
|
|
||||||
exit /B %ERROR_CODE%
|
|
@ -1,74 +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>spring-boot-1</artifactId>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
<description>Module for Spring Boot version 1.x</description>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<!-- This module contains article about Spring Boot Actuator in Spring Boot version 1.x -->
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-boot-1</artifactId>
|
|
||||||
<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-thymeleaf</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-tomcat</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j2.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.h2database</groupId>
|
|
||||||
<artifactId>h2</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>${spring-boot.version}</version>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<log4j2.version>2.17.1</log4j2.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,19 +0,0 @@
|
|||||||
### server port
|
|
||||||
server.port=8080
|
|
||||||
#port used to expose actuator
|
|
||||||
management.port=8081
|
|
||||||
#CIDR allowed to hit actuator
|
|
||||||
management.address=127.0.0.1
|
|
||||||
# Actuator Configuration
|
|
||||||
# customize /beans endpoint
|
|
||||||
endpoints.beans.id=springbeans
|
|
||||||
endpoints.beans.sensitive=false
|
|
||||||
endpoints.beans.enabled=true
|
|
||||||
# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access.
|
|
||||||
# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html
|
|
||||||
management.security.enabled=false
|
|
||||||
endpoints.health.sensitive=false
|
|
||||||
# customize /info endpoint
|
|
||||||
info.app.name=Spring Sample Application
|
|
||||||
info.app.description=This is my first spring boot application
|
|
||||||
info.app.version=1.0.0
|
|
@ -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>
|
|
@ -1,12 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
@ -1,117 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2007-present the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
import java.net.*;
|
|
||||||
import java.io.*;
|
|
||||||
import java.nio.channels.*;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
public class MavenWrapperDownloader {
|
|
||||||
|
|
||||||
private static final String WRAPPER_VERSION = "0.5.6";
|
|
||||||
/**
|
|
||||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
|
||||||
*/
|
|
||||||
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
|
|
||||||
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
|
||||||
* use instead of the default one.
|
|
||||||
*/
|
|
||||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
|
||||||
".mvn/wrapper/maven-wrapper.properties";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Path where the maven-wrapper.jar will be saved to.
|
|
||||||
*/
|
|
||||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
|
||||||
".mvn/wrapper/maven-wrapper.jar";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Name of the property which should be used to override the default download url for the wrapper.
|
|
||||||
*/
|
|
||||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
|
||||||
|
|
||||||
public static void main(String args[]) {
|
|
||||||
System.out.println("- Downloader started");
|
|
||||||
File baseDirectory = new File(args[0]);
|
|
||||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
|
||||||
|
|
||||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
|
||||||
// wrapperUrl parameter.
|
|
||||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
|
||||||
String url = DEFAULT_DOWNLOAD_URL;
|
|
||||||
if(mavenWrapperPropertyFile.exists()) {
|
|
||||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
|
||||||
try {
|
|
||||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
|
||||||
Properties mavenWrapperProperties = new Properties();
|
|
||||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
|
||||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
if(mavenWrapperPropertyFileInputStream != null) {
|
|
||||||
mavenWrapperPropertyFileInputStream.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Ignore ...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
System.out.println("- Downloading from: " + url);
|
|
||||||
|
|
||||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
|
||||||
if(!outputFile.getParentFile().exists()) {
|
|
||||||
if(!outputFile.getParentFile().mkdirs()) {
|
|
||||||
System.out.println(
|
|
||||||
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
|
||||||
try {
|
|
||||||
downloadFileFromURL(url, outputFile);
|
|
||||||
System.out.println("Done");
|
|
||||||
System.exit(0);
|
|
||||||
} catch (Throwable e) {
|
|
||||||
System.out.println("- Error downloading");
|
|
||||||
e.printStackTrace();
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
|
||||||
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
|
|
||||||
String username = System.getenv("MVNW_USERNAME");
|
|
||||||
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
|
|
||||||
Authenticator.setDefault(new Authenticator() {
|
|
||||||
@Override
|
|
||||||
protected PasswordAuthentication getPasswordAuthentication() {
|
|
||||||
return new PasswordAuthentication(username, password);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
URL website = new URL(urlString);
|
|
||||||
ReadableByteChannel rbc;
|
|
||||||
rbc = Channels.newChannel(website.openStream());
|
|
||||||
FileOutputStream fos = new FileOutputStream(destination);
|
|
||||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
|
||||||
fos.close();
|
|
||||||
rbc.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user