Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
|
||||
+5
-4
@@ -8,26 +8,27 @@ import java.util.regex.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ScannerUnitTest {
|
||||
@Test public void scannerSkipUsingPattern() {
|
||||
@Test public void givenScannerWithPattern_thenSkipUsingPattern() {
|
||||
String str = "Java scanner skip tutorial";
|
||||
// Instantiates Scanner
|
||||
Scanner sc = new Scanner(str);
|
||||
// By using skip(Pattern) method is to skip that meets the given pattern
|
||||
sc.skip(Pattern.compile(".ava"));
|
||||
assertEquals(sc.nextLine(), " scanner skip tutorial");
|
||||
|
||||
assertEquals(" scanner skip tutorial", sc.nextLine());
|
||||
// Scanner closed
|
||||
sc.close();
|
||||
}
|
||||
|
||||
@Test public void scannerSkipUsingStringPattern() {
|
||||
@Test public void givenScannerWithString_thenSkipUsingStringPattern() {
|
||||
String str = "Java scanner skip tutorial";
|
||||
// Instantiates Scanner
|
||||
Scanner sc = new Scanner(str);
|
||||
// By using skip(String) method is to skip that meets the given
|
||||
// pattern constructed from the given String
|
||||
sc.skip("Java");
|
||||
assertEquals(sc.nextLine(), " scanner skip tutorial");
|
||||
|
||||
assertEquals(" scanner skip tutorial", sc.nextLine());
|
||||
// Scanner closed
|
||||
sc.close();
|
||||
}
|
||||
|
||||
+8
@@ -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;
|
||||
}
|
||||
}
|
||||
+10
@@ -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;
|
||||
}
|
||||
}
|
||||
+77
@@ -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 {
|
||||
}
|
||||
}
|
||||
+157
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
+22
@@ -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)];
|
||||
}
|
||||
}
|
||||
+17
@@ -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)];
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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_NAME = "file.dat";
|
||||
static String FILE_MD5_HASH = "c959feb066b37f5c4f0e0f45bbbb4f86";
|
||||
static String FILE_MD5_HASH = "753197aa27f162faa3e3c2e48ee5eb07";
|
||||
|
||||
@Test
|
||||
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 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)
|
||||
- [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)
|
||||
|
||||
@@ -4,4 +4,5 @@
|
||||
- [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)
|
||||
- [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
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [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)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey)
|
||||
|
||||
@@ -14,6 +14,11 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>${json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
@@ -148,6 +153,7 @@
|
||||
<jsoniter.version>0.9.23</jsoniter.version>
|
||||
<moshi.version>1.9.2</moshi.version>
|
||||
<fastjson.version>1.2.21</fastjson.version>
|
||||
<json.version>20211205</json.version>
|
||||
</properties>
|
||||
|
||||
</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));
|
||||
}
|
||||
}
|
||||
+37
-26
@@ -1,47 +1,58 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
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.Test;
|
||||
|
||||
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.CharArrayWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest {
|
||||
|
||||
private static Logger logger;
|
||||
private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
|
||||
private PrintStream ps = new PrintStream(consoleOutput);
|
||||
private Appender appender;
|
||||
private Logger logger;
|
||||
private final Writer writer = new CharArrayWriter();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
// Redirect console output to our stream
|
||||
System.setOut(ps);
|
||||
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
|
||||
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() {
|
||||
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() throws Exception {
|
||||
logger.debug("Debug message");
|
||||
String currentLog = consoleOutput.toString();
|
||||
assertTrue(currentLog.isEmpty());
|
||||
assertTrue(isValidJSON(currentLog));
|
||||
|
||||
writer.flush();
|
||||
assertTrue(isValidJSON(writer.toString()));
|
||||
}
|
||||
|
||||
public static boolean isValidJSON(String jsonInString) {
|
||||
try {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.readTree(jsonInString);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
@After
|
||||
public void cleanup() {
|
||||
((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender);
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>maven-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user