From 4a348df28ac3116b6ae662097494c39e3e5375ca Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Thu, 30 Sep 2021 23:19:04 +0800 Subject: [PATCH 01/40] Convert Byte Array to its Numeric Representation --- .../core-java-arrays-convert/pom.xml | 5 + .../ByteArrayToNumericRepresentation.java | 281 +++++++++++++ ...eArrayToNumericRepresentationUnitTest.java | 391 ++++++++++++++++++ 3 files changed, 677 insertions(+) create mode 100644 core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentation.java create mode 100644 core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java diff --git a/core-java-modules/core-java-arrays-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml index 4cb2946ac9..6e001e12b0 100644 --- a/core-java-modules/core-java-arrays-convert/pom.xml +++ b/core-java-modules/core-java-arrays-convert/pom.xml @@ -19,6 +19,11 @@ guava ${guava.version} + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + diff --git a/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentation.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentation.java new file mode 100644 index 0000000000..82d60e1666 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentation.java @@ -0,0 +1,281 @@ +package com.baeldung.array.conversions; + +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.Conversion; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.Arrays; + +class ByteArrayToNumericRepresentation { + + static int convertByteArrayToIntUsingShiftOperator(byte[] bytes) { + int value = 0; + for (byte b : bytes) { + value = (value << 8) + (b & 0xFF); + } + return value; + } + + static byte[] convertIntToByteArrayUsingShiftOperator(int value) { + byte[] bytes = new byte[Integer.BYTES]; + int length = bytes.length; + for (int i = 0; i < length; i++) { + bytes[length - i - 1] = (byte) (value & 0xFF); + value >>= 8; + } + return bytes; + } + + static long convertByteArrayToLongUsingShiftOperator(byte[] bytes) { + long value = 0; + for (byte b : bytes) { + value <<= 8; + value |= (b & 0xFF); + } + return value; + } + + static byte[] convertLongToByteArrayUsingShiftOperator(long value) { + byte[] bytes = new byte[Long.BYTES]; + int length = bytes.length; + for (int i = 0; i < length; i++) { + bytes[length - i - 1] = (byte) (value & 0xFF); + value >>= 8; + } + return bytes; + } + + static float convertByteArrayToFloatUsingShiftOperator(byte[] bytes) { + // convert bytes to int + int intValue = 0; + for (byte b : bytes) { + intValue = (intValue << 8) + (b & 0xFF); + } + + // convert int to float + return Float.intBitsToFloat(intValue); + } + + static byte[] convertFloatToByteArrayUsingShiftOperator(float value) { + // convert float to int + int intValue = Float.floatToIntBits(value); + + // convert int to bytes + byte[] bytes = new byte[Float.BYTES]; + int length = bytes.length; + for (int i = 0; i < length; i++) { + bytes[length - i - 1] = (byte) (intValue & 0xFF); + intValue >>= 8; + } + return bytes; + } + + static double convertingByteArrayToDoubleUsingShiftOperator(byte[] bytes) { + long longValue = 0; + for (byte b : bytes) { + longValue = (longValue << 8) + (b & 0xFF); + } + + return Double.longBitsToDouble(longValue); + } + + static byte[] convertDoubleToByteArrayUsingShiftOperator(double value) { + long longValue = Double.doubleToLongBits(value); + + byte[] bytes = new byte[Double.BYTES]; + int length = bytes.length; + for (int i = 0; i < length; i++) { + bytes[length - i - 1] = (byte) (longValue & 0xFF); + longValue >>= 8; + } + return bytes; + } + + static int convertByteArrayToIntUsingByteBuffer(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES); + buffer.put(bytes); + buffer.rewind(); + return buffer.getInt(); + } + + static byte[] convertIntToByteArrayUsingByteBuffer(int value) { + ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES); + buffer.putInt(value); + buffer.rewind(); + return buffer.array(); + } + + static long convertByteArrayToLongUsingByteBuffer(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); + buffer.put(bytes); + buffer.rewind(); + return buffer.getLong(); + } + + static byte[] convertLongToByteArrayUsingByteBuffer(long value) { + ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); + buffer.putLong(value); + buffer.rewind(); + return buffer.array(); + } + + static float convertByteArrayToFloatUsingByteBuffer(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES); + buffer.put(bytes); + buffer.rewind(); + return buffer.getFloat(); + } + + static byte[] convertFloatToByteArrayUsingByteBuffer(float value) { + ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES); + buffer.putFloat(value); + buffer.rewind(); + return buffer.array(); + } + + static double convertByteArrayToDoubleUsingByteBuffer(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES); + buffer.put(bytes); + buffer.rewind(); + return buffer.getDouble(); + } + + static byte[] convertDoubleToByteArrayUsingByteBuffer(double value) { + ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES); + buffer.putDouble(value); + buffer.rewind(); + return buffer.array(); + } + + static int convertByteArrayToIntUsingBigInteger(byte[] bytes) { + return new BigInteger(bytes).intValue(); + } + + static byte[] convertIntToByteArrayUsingBigInteger(int value) { + return BigInteger.valueOf(value).toByteArray(); + } + + static long convertByteArrayToLongUsingBigInteger(byte[] bytes) { + return new BigInteger(bytes).longValue(); + } + + static byte[] convertLongToByteArrayUsingBigInteger(long value) { + return BigInteger.valueOf(value).toByteArray(); + } + + static float convertByteArrayToFloatUsingBigInteger(byte[] bytes) { + int intValue = new BigInteger(bytes).intValue(); + return Float.intBitsToFloat(intValue); + } + + static byte[] convertFloatToByteArrayUsingBigInteger(float value) { + int intValue = Float.floatToIntBits(value); + return BigInteger.valueOf(intValue).toByteArray(); + } + + static double convertByteArrayToDoubleUsingBigInteger(byte[] bytes) { + long longValue = new BigInteger(bytes).longValue(); + return Double.longBitsToDouble(longValue); + } + + static byte[] convertDoubleToByteArrayUsingBigInteger(double value) { + long longValue = Double.doubleToLongBits(value); + return BigInteger.valueOf(longValue).toByteArray(); + } + + static int convertingByteArrayToIntUsingGuava(byte[] bytes) { + return Ints.fromByteArray(bytes); + } + + static byte[] convertIntToByteArrayUsingGuava(int value) { + return Ints.toByteArray(value); + } + + static long convertByteArrayToLongUsingGuava(byte[] bytes) { + return Longs.fromByteArray(bytes); + } + + static byte[] convertLongToByteArrayUsingGuava(long value) { + return Longs.toByteArray(value); + } + + static float convertByteArrayToFloatUsingGuava(byte[] bytes) { + int intValue = Ints.fromByteArray(bytes); + return Float.intBitsToFloat(intValue); + } + + static byte[] convertFloatToByteArrayUsingGuava(float value) { + int intValue = Float.floatToIntBits(value); + return Ints.toByteArray(intValue); + } + + static double convertByteArrayToDoubleUsingGuava(byte[] bytes) { + long longValue = Longs.fromByteArray(bytes); + return Double.longBitsToDouble(longValue); + } + + static byte[] convertDoubleToByteArrayUsingGuava(double value) { + long longValue = Double.doubleToLongBits(value); + return Longs.toByteArray(longValue); + } + + static int convertByteArrayToIntUsingCommonsLang(byte[] bytes) { + byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); + ArrayUtils.reverse(copyBytes); + return Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length); + } + + static byte[] convertIntToByteArrayUsingCommonsLang(int value) { + byte[] bytes = new byte[Integer.BYTES]; + Conversion.intToByteArray(value, 0, bytes, 0, bytes.length); + ArrayUtils.reverse(bytes); + return bytes; + } + + static long convertByteArrayToLongUsingCommonsLang(byte[] bytes) { + byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); + ArrayUtils.reverse(copyBytes); + return Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length); + } + + static byte[] convertLongToByteArrayUsingCommonsLang(long value) { + byte[] bytes = new byte[Long.BYTES]; + Conversion.longToByteArray(value, 0, bytes, 0, bytes.length); + ArrayUtils.reverse(bytes); + return bytes; + } + + static float convertByteArrayToFloatUsingCommonsLang(byte[] bytes) { + byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); + ArrayUtils.reverse(copyBytes); + int intValue = Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length); + return Float.intBitsToFloat(intValue); + } + + static byte[] convertFloatToByteArrayUsingCommonsLang(float value) { + int intValue = Float.floatToIntBits(value); + byte[] bytes = new byte[Float.BYTES]; + Conversion.intToByteArray(intValue, 0, bytes, 0, bytes.length); + ArrayUtils.reverse(bytes); + return bytes; + } + + static double convertByteArrayToDoubleUsingCommonsLang(byte[] bytes) { + byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); + ArrayUtils.reverse(copyBytes); + long longValue = Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length); + return Double.longBitsToDouble(longValue); + } + + static byte[] convertDoubleToByteArrayUsingCommonsLang(double value) { + long longValue = Double.doubleToLongBits(value); + byte[] bytes = new byte[Long.BYTES]; + Conversion.longToByteArray(longValue, 0, bytes, 0, bytes.length); + ArrayUtils.reverse(bytes); + return bytes; + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java new file mode 100644 index 0000000000..666b5a6be8 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java @@ -0,0 +1,391 @@ +package com.baeldung.array.conversions; + +import org.junit.Test; + +import java.util.Arrays; + +import static com.baeldung.array.conversions.ByteArrayToNumericRepresentation.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class ByteArrayToNumericRepresentationUnitTest { + private static final byte[] INT_BYTE_ARRAY = new byte[]{ + (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE + }; + private static final int INT_VALUE = 0xCAFEBABE; + + + private static final byte[] FLOAT_BYTE_ARRAY = new byte[]{ + (byte) 0x40, (byte) 0x48, (byte) 0xF5, (byte) 0xC3 + }; + private static final float FLOAT_VALUE = 3.14F; + + + private static final byte[] LONG_BYTE_ARRAY = new byte[]{ + (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, + (byte) 0x89, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF + }; + private static final long LONG_VALUE = 0x0123456789ABCDEFL; + + + private static final byte[] DOUBLE_BYTE_ARRAY = new byte[]{ + (byte) 0x3F, (byte) 0xE3, (byte) 0xC6, (byte) 0xA7, + (byte) 0xEF, (byte) 0x9D, (byte) 0xB2, (byte) 0x2D + }; + private static final double DOUBLE_VALUE = 0.618D; + + + private int getIntValue() { + return INT_VALUE; + } + + private byte[] getIntByteArray() { + return Arrays.copyOf(INT_BYTE_ARRAY, INT_BYTE_ARRAY.length); + } + + private long getLongValue() { + return LONG_VALUE; + } + + private byte[] getLongByteArray() { + return Arrays.copyOf(LONG_BYTE_ARRAY, LONG_BYTE_ARRAY.length); + } + + private float getFloatValue() { + return FLOAT_VALUE; + } + + private byte[] getFloatByteArray() { + return Arrays.copyOf(FLOAT_BYTE_ARRAY, FLOAT_BYTE_ARRAY.length); + } + + private double getDoubleValue() { + return DOUBLE_VALUE; + } + + private byte[] getDoubleByteArray() { + return Arrays.copyOf(DOUBLE_BYTE_ARRAY, DOUBLE_BYTE_ARRAY.length); + } + + + @Test + public void givenShiftOperator_whenConvertingByteArrayToInt_thenSuccess() { + byte[] bytes = getIntByteArray(); + int value = convertByteArrayToIntUsingShiftOperator(bytes); + + assertEquals(INT_VALUE, value); + } + + @Test + public void givenShiftOperator_whenConvertingIntToByteArray_thenSuccess() { + int value = getIntValue(); + byte[] bytes = convertIntToByteArrayUsingShiftOperator(value); + + assertArrayEquals(INT_BYTE_ARRAY, bytes); + } + + @Test + public void givenShiftOperator_whenConvertingByteArrayToLong_thenSuccess() { + byte[] bytes = getLongByteArray(); + long value = convertByteArrayToLongUsingShiftOperator(bytes); + + assertEquals(LONG_VALUE, value); + } + + @Test + public void givenShiftOperator_whenConvertingLongToByteArray_thenSuccess() { + long value = getLongValue(); + byte[] bytes = convertLongToByteArrayUsingShiftOperator(value); + + assertArrayEquals(LONG_BYTE_ARRAY, bytes); + } + + @Test + public void givenShiftOperator_whenConvertingByteArrayToFloat_thenSuccess() { + byte[] bytes = getFloatByteArray(); + float value = convertByteArrayToFloatUsingShiftOperator(bytes); + + assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); + } + + @Test + public void givenShiftOperator_whenConvertingFloatToByteArray_thenSuccess() { + float value = getFloatValue(); + byte[] bytes = convertFloatToByteArrayUsingShiftOperator(value); + + assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); + } + + @Test + public void givenShiftOperator_whenConvertingByteArrayToDouble_thenSuccess() { + byte[] bytes = getDoubleByteArray(); + double value = convertingByteArrayToDoubleUsingShiftOperator(bytes); + + assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); + } + + @Test + public void givenShiftOperator_whenConvertingDoubleToByteArray_thenSuccess() { + double value = getDoubleValue(); + byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(value); + + assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); + } + + @Test + public void givenByteBuffer_whenConvertingByteArrayToInt_thenSuccess() { + byte[] bytes = getIntByteArray(); + int value = convertByteArrayToIntUsingByteBuffer(bytes); + + assertEquals(INT_VALUE, value); + } + + @Test + public void givenByteBuffer_whenConvertingIntToByteArray_thenSuccess() { + int value = getIntValue(); + byte[] bytes = convertIntToByteArrayUsingByteBuffer(value); + + assertArrayEquals(INT_BYTE_ARRAY, bytes); + } + + @Test + public void givenByteBuffer_whenConvertingByteArrayToLong_thenSuccess() { + byte[] bytes = getLongByteArray(); + long value = convertByteArrayToLongUsingByteBuffer(bytes); + + assertEquals(LONG_VALUE, value); + } + + @Test + public void givenByteBuffer_whenConvertingLongToByteArray_thenSuccess() { + long value = getLongValue(); + byte[] bytes = convertLongToByteArrayUsingByteBuffer(value); + + assertArrayEquals(LONG_BYTE_ARRAY, bytes); + } + + @Test + public void givenByteBuffer_whenConvertingByteArrayToFloat_thenSuccess() { + byte[] bytes = getFloatByteArray(); + float value = convertByteArrayToFloatUsingByteBuffer(bytes); + + assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); + } + + @Test + public void givenByteBuffer_whenConvertingFloatToByteArray_thenSuccess() { + float value = getFloatValue(); + byte[] bytes = convertFloatToByteArrayUsingByteBuffer(value); + + assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); + } + + @Test + public void givenByteBuffer_whenConvertingByteArrayToDouble_thenSuccess() { + byte[] bytes = getDoubleByteArray(); + double value = convertByteArrayToDoubleUsingByteBuffer(bytes); + + assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); + } + + @Test + public void givenByteBuffer_whenConvertingDoubleToByteArray_thenSuccess() { + double value = getDoubleValue(); + byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(value); + + assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); + } + + @Test + public void givenBigInteger_whenConvertingByteArrayToInt_thenSuccess() { + byte[] bytes = getIntByteArray(); + int value = convertByteArrayToIntUsingBigInteger(bytes); + + assertEquals(INT_VALUE, value); + } + + @Test + public void givenBigInteger_whenConvertingIntToByteArray_thenSuccess() { + int value = getIntValue(); + byte[] bytes = convertIntToByteArrayUsingBigInteger(value); + + assertArrayEquals(INT_BYTE_ARRAY, bytes); + } + + @Test + public void givenBigInteger_whenConvertingByteArrayToLong_thenSuccess() { + byte[] bytes = getLongByteArray(); + long value = convertByteArrayToLongUsingBigInteger(bytes); + + assertEquals(LONG_VALUE, value); + } + + @Test + public void givenBigInteger_whenConvertingLongToByteArray_thenSuccess() { + long value = getLongValue(); + byte[] bytes = convertLongToByteArrayUsingBigInteger(value); + + assertArrayEquals(LONG_BYTE_ARRAY, bytes); + } + + @Test + public void givenBigInteger_whenConvertingByteArrayToFloat_thenSuccess() { + byte[] bytes = getFloatByteArray(); + float value = convertByteArrayToFloatUsingBigInteger(bytes); + + assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); + } + + @Test + public void givenBigInteger_whenConvertingFloatToByteArray_thenSuccess() { + float value = getFloatValue(); + byte[] bytes = convertFloatToByteArrayUsingBigInteger(value); + + assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); + } + + @Test + public void givenBigInteger_whenConvertingByteArrayToDouble_thenSuccess() { + byte[] bytes = getDoubleByteArray(); + double value = convertByteArrayToDoubleUsingBigInteger(bytes); + + assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); + } + + @Test + public void givenBigInteger_whenConvertingDoubleToByteArray_thenSuccess() { + double value = getDoubleValue(); + byte[] bytes = convertDoubleToByteArrayUsingBigInteger(value); + + assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); + } + + @Test + public void givenGuava_whenConvertingByteArrayToInt_thenSuccess() { + byte[] bytes = getIntByteArray(); + int value = convertingByteArrayToIntUsingGuava(bytes); + + assertEquals(INT_VALUE, value); + } + + @Test + public void givenGuava_whenConvertingIntToByteArray_thenSuccess() { + int value = getIntValue(); + byte[] bytes = convertIntToByteArrayUsingGuava(value); + + assertArrayEquals(INT_BYTE_ARRAY, bytes); + } + + @Test + public void givenGuava_whenConvertingByteArrayToLong_thenSuccess() { + byte[] bytes = getLongByteArray(); + long value = convertByteArrayToLongUsingGuava(bytes); + + assertEquals(LONG_VALUE, value); + } + + @Test + public void givenGuava_whenConvertingLongToByteArray_thenSuccess() { + long value = getLongValue(); + byte[] bytes = convertLongToByteArrayUsingGuava(value); + + assertArrayEquals(LONG_BYTE_ARRAY, bytes); + } + + @Test + public void givenGuava_whenConvertingByteArrayToFloat_thenSuccess() { + byte[] bytes = getFloatByteArray(); + float value = convertByteArrayToFloatUsingGuava(bytes); + + assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); + } + + @Test + public void givenGuava_whenConvertingFloatToByteArray_thenSuccess() { + float value = getFloatValue(); + byte[] bytes = convertFloatToByteArrayUsingGuava(value); + + assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); + } + + @Test + public void givenGuava_whenConvertingByteArrayToDouble_thenSuccess() { + byte[] bytes = getDoubleByteArray(); + double value = convertByteArrayToDoubleUsingGuava(bytes); + + assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); + } + + @Test + public void givenGuava_whenConvertingDoubleToByteArray_thenSuccess() { + double value = getDoubleValue(); + byte[] bytes = convertDoubleToByteArrayUsingGuava(value); + + assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); + } + + @Test + public void givenCommonsLang_whenConvertingByteArrayToInt_thenSuccess() { + byte[] bytes = getIntByteArray(); + int value = convertByteArrayToIntUsingCommonsLang(bytes); + + assertEquals(INT_VALUE, value); + } + + @Test + public void givenCommonsLang_whenConvertingIntToByteArray_thenSuccess() { + int value = getIntValue(); + byte[] bytes = convertIntToByteArrayUsingCommonsLang(value); + + assertArrayEquals(INT_BYTE_ARRAY, bytes); + } + + @Test + public void givenCommonsLang_whenConvertingByteArrayToLong_thenSuccess() { + byte[] bytes = getLongByteArray(); + long value = convertByteArrayToLongUsingCommonsLang(bytes); + + assertEquals(LONG_VALUE, value); + } + + @Test + public void givenCommonsLang_whenConvertingLongToByteArray_thenSuccess() { + long value = getLongValue(); + byte[] bytes = convertLongToByteArrayUsingCommonsLang(value); + + assertArrayEquals(LONG_BYTE_ARRAY, bytes); + } + + @Test + public void givenCommonsLang_whenConvertingByteArrayToFloat_thenSuccess() { + byte[] bytes = getFloatByteArray(); + float value = convertByteArrayToFloatUsingCommonsLang(bytes); + + assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); + } + + @Test + public void givenCommonsLang_whenConvertingFloatToByteArray_thenSuccess() { + float value = getFloatValue(); + byte[] bytes = convertFloatToByteArrayUsingCommonsLang(value); + + assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); + } + + @Test + public void givenCommonsLang_whenConvertingByteArrayToDouble_thenSuccess() { + byte[] bytes = getDoubleByteArray(); + double value = convertByteArrayToDoubleUsingCommonsLang(bytes); + + assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); + } + + @Test + public void givenCommonsLang_whenConvertingDoubleToByteArray_thenSuccess() { + double value = getDoubleValue(); + byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(value); + + assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); + } + +} \ No newline at end of file From b7ea6ec38893bdeb4fa505616b71083a7900fddb Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Thu, 7 Oct 2021 14:43:13 +0800 Subject: [PATCH 02/40] Remove Redundant Getter Method --- ...eArrayToNumericRepresentationUnitTest.java | 155 +++++------------- 1 file changed, 40 insertions(+), 115 deletions(-) diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java index 666b5a6be8..0fae765d9c 100644 --- a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteArrayToNumericRepresentationUnitTest.java @@ -2,8 +2,6 @@ package com.baeldung.array.conversions; import org.junit.Test; -import java.util.Arrays; - import static com.baeldung.array.conversions.ByteArrayToNumericRepresentation.*; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -35,355 +33,282 @@ public class ByteArrayToNumericRepresentationUnitTest { private static final double DOUBLE_VALUE = 0.618D; - private int getIntValue() { - return INT_VALUE; - } - - private byte[] getIntByteArray() { - return Arrays.copyOf(INT_BYTE_ARRAY, INT_BYTE_ARRAY.length); - } - - private long getLongValue() { - return LONG_VALUE; - } - - private byte[] getLongByteArray() { - return Arrays.copyOf(LONG_BYTE_ARRAY, LONG_BYTE_ARRAY.length); - } - - private float getFloatValue() { - return FLOAT_VALUE; - } - - private byte[] getFloatByteArray() { - return Arrays.copyOf(FLOAT_BYTE_ARRAY, FLOAT_BYTE_ARRAY.length); - } - - private double getDoubleValue() { - return DOUBLE_VALUE; - } - - private byte[] getDoubleByteArray() { - return Arrays.copyOf(DOUBLE_BYTE_ARRAY, DOUBLE_BYTE_ARRAY.length); - } - - @Test public void givenShiftOperator_whenConvertingByteArrayToInt_thenSuccess() { - byte[] bytes = getIntByteArray(); - int value = convertByteArrayToIntUsingShiftOperator(bytes); + int value = convertByteArrayToIntUsingShiftOperator(INT_BYTE_ARRAY); assertEquals(INT_VALUE, value); } @Test public void givenShiftOperator_whenConvertingIntToByteArray_thenSuccess() { - int value = getIntValue(); - byte[] bytes = convertIntToByteArrayUsingShiftOperator(value); + byte[] bytes = convertIntToByteArrayUsingShiftOperator(INT_VALUE); assertArrayEquals(INT_BYTE_ARRAY, bytes); } @Test public void givenShiftOperator_whenConvertingByteArrayToLong_thenSuccess() { - byte[] bytes = getLongByteArray(); - long value = convertByteArrayToLongUsingShiftOperator(bytes); + long value = convertByteArrayToLongUsingShiftOperator(LONG_BYTE_ARRAY); assertEquals(LONG_VALUE, value); } @Test public void givenShiftOperator_whenConvertingLongToByteArray_thenSuccess() { - long value = getLongValue(); - byte[] bytes = convertLongToByteArrayUsingShiftOperator(value); + byte[] bytes = convertLongToByteArrayUsingShiftOperator(LONG_VALUE); assertArrayEquals(LONG_BYTE_ARRAY, bytes); } @Test public void givenShiftOperator_whenConvertingByteArrayToFloat_thenSuccess() { - byte[] bytes = getFloatByteArray(); - float value = convertByteArrayToFloatUsingShiftOperator(bytes); + float value = convertByteArrayToFloatUsingShiftOperator(FLOAT_BYTE_ARRAY); assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); } @Test public void givenShiftOperator_whenConvertingFloatToByteArray_thenSuccess() { - float value = getFloatValue(); - byte[] bytes = convertFloatToByteArrayUsingShiftOperator(value); + byte[] bytes = convertFloatToByteArrayUsingShiftOperator(FLOAT_VALUE); assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); } @Test public void givenShiftOperator_whenConvertingByteArrayToDouble_thenSuccess() { - byte[] bytes = getDoubleByteArray(); - double value = convertingByteArrayToDoubleUsingShiftOperator(bytes); + double value = convertingByteArrayToDoubleUsingShiftOperator(DOUBLE_BYTE_ARRAY); assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); } @Test public void givenShiftOperator_whenConvertingDoubleToByteArray_thenSuccess() { - double value = getDoubleValue(); - byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(value); + byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(DOUBLE_VALUE); assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); } @Test public void givenByteBuffer_whenConvertingByteArrayToInt_thenSuccess() { - byte[] bytes = getIntByteArray(); - int value = convertByteArrayToIntUsingByteBuffer(bytes); + int value = convertByteArrayToIntUsingByteBuffer(INT_BYTE_ARRAY); assertEquals(INT_VALUE, value); } @Test public void givenByteBuffer_whenConvertingIntToByteArray_thenSuccess() { - int value = getIntValue(); - byte[] bytes = convertIntToByteArrayUsingByteBuffer(value); + byte[] bytes = convertIntToByteArrayUsingByteBuffer(INT_VALUE); assertArrayEquals(INT_BYTE_ARRAY, bytes); } @Test public void givenByteBuffer_whenConvertingByteArrayToLong_thenSuccess() { - byte[] bytes = getLongByteArray(); - long value = convertByteArrayToLongUsingByteBuffer(bytes); + long value = convertByteArrayToLongUsingByteBuffer(LONG_BYTE_ARRAY); assertEquals(LONG_VALUE, value); } @Test public void givenByteBuffer_whenConvertingLongToByteArray_thenSuccess() { - long value = getLongValue(); - byte[] bytes = convertLongToByteArrayUsingByteBuffer(value); + byte[] bytes = convertLongToByteArrayUsingByteBuffer(LONG_VALUE); assertArrayEquals(LONG_BYTE_ARRAY, bytes); } @Test public void givenByteBuffer_whenConvertingByteArrayToFloat_thenSuccess() { - byte[] bytes = getFloatByteArray(); - float value = convertByteArrayToFloatUsingByteBuffer(bytes); + float value = convertByteArrayToFloatUsingByteBuffer(FLOAT_BYTE_ARRAY); assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); } @Test public void givenByteBuffer_whenConvertingFloatToByteArray_thenSuccess() { - float value = getFloatValue(); - byte[] bytes = convertFloatToByteArrayUsingByteBuffer(value); + byte[] bytes = convertFloatToByteArrayUsingByteBuffer(FLOAT_VALUE); assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); } @Test public void givenByteBuffer_whenConvertingByteArrayToDouble_thenSuccess() { - byte[] bytes = getDoubleByteArray(); - double value = convertByteArrayToDoubleUsingByteBuffer(bytes); + double value = convertByteArrayToDoubleUsingByteBuffer(DOUBLE_BYTE_ARRAY); assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); } @Test public void givenByteBuffer_whenConvertingDoubleToByteArray_thenSuccess() { - double value = getDoubleValue(); - byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(value); + byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(DOUBLE_VALUE); assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); } @Test public void givenBigInteger_whenConvertingByteArrayToInt_thenSuccess() { - byte[] bytes = getIntByteArray(); - int value = convertByteArrayToIntUsingBigInteger(bytes); + int value = convertByteArrayToIntUsingBigInteger(INT_BYTE_ARRAY); assertEquals(INT_VALUE, value); } @Test public void givenBigInteger_whenConvertingIntToByteArray_thenSuccess() { - int value = getIntValue(); - byte[] bytes = convertIntToByteArrayUsingBigInteger(value); + byte[] bytes = convertIntToByteArrayUsingBigInteger(INT_VALUE); assertArrayEquals(INT_BYTE_ARRAY, bytes); } @Test public void givenBigInteger_whenConvertingByteArrayToLong_thenSuccess() { - byte[] bytes = getLongByteArray(); - long value = convertByteArrayToLongUsingBigInteger(bytes); + long value = convertByteArrayToLongUsingBigInteger(LONG_BYTE_ARRAY); assertEquals(LONG_VALUE, value); } @Test public void givenBigInteger_whenConvertingLongToByteArray_thenSuccess() { - long value = getLongValue(); - byte[] bytes = convertLongToByteArrayUsingBigInteger(value); + byte[] bytes = convertLongToByteArrayUsingBigInteger(LONG_VALUE); assertArrayEquals(LONG_BYTE_ARRAY, bytes); } @Test public void givenBigInteger_whenConvertingByteArrayToFloat_thenSuccess() { - byte[] bytes = getFloatByteArray(); - float value = convertByteArrayToFloatUsingBigInteger(bytes); + float value = convertByteArrayToFloatUsingBigInteger(FLOAT_BYTE_ARRAY); assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); } @Test public void givenBigInteger_whenConvertingFloatToByteArray_thenSuccess() { - float value = getFloatValue(); - byte[] bytes = convertFloatToByteArrayUsingBigInteger(value); + byte[] bytes = convertFloatToByteArrayUsingBigInteger(FLOAT_VALUE); assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); } @Test public void givenBigInteger_whenConvertingByteArrayToDouble_thenSuccess() { - byte[] bytes = getDoubleByteArray(); - double value = convertByteArrayToDoubleUsingBigInteger(bytes); + double value = convertByteArrayToDoubleUsingBigInteger(DOUBLE_BYTE_ARRAY); assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); } @Test public void givenBigInteger_whenConvertingDoubleToByteArray_thenSuccess() { - double value = getDoubleValue(); - byte[] bytes = convertDoubleToByteArrayUsingBigInteger(value); + byte[] bytes = convertDoubleToByteArrayUsingBigInteger(DOUBLE_VALUE); assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); } @Test public void givenGuava_whenConvertingByteArrayToInt_thenSuccess() { - byte[] bytes = getIntByteArray(); - int value = convertingByteArrayToIntUsingGuava(bytes); + int value = convertingByteArrayToIntUsingGuava(INT_BYTE_ARRAY); assertEquals(INT_VALUE, value); } @Test public void givenGuava_whenConvertingIntToByteArray_thenSuccess() { - int value = getIntValue(); - byte[] bytes = convertIntToByteArrayUsingGuava(value); + byte[] bytes = convertIntToByteArrayUsingGuava(INT_VALUE); assertArrayEquals(INT_BYTE_ARRAY, bytes); } @Test public void givenGuava_whenConvertingByteArrayToLong_thenSuccess() { - byte[] bytes = getLongByteArray(); - long value = convertByteArrayToLongUsingGuava(bytes); + long value = convertByteArrayToLongUsingGuava(LONG_BYTE_ARRAY); assertEquals(LONG_VALUE, value); } @Test public void givenGuava_whenConvertingLongToByteArray_thenSuccess() { - long value = getLongValue(); - byte[] bytes = convertLongToByteArrayUsingGuava(value); + byte[] bytes = convertLongToByteArrayUsingGuava(LONG_VALUE); assertArrayEquals(LONG_BYTE_ARRAY, bytes); } @Test public void givenGuava_whenConvertingByteArrayToFloat_thenSuccess() { - byte[] bytes = getFloatByteArray(); - float value = convertByteArrayToFloatUsingGuava(bytes); + float value = convertByteArrayToFloatUsingGuava(FLOAT_BYTE_ARRAY); assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); } @Test public void givenGuava_whenConvertingFloatToByteArray_thenSuccess() { - float value = getFloatValue(); - byte[] bytes = convertFloatToByteArrayUsingGuava(value); + byte[] bytes = convertFloatToByteArrayUsingGuava(FLOAT_VALUE); assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); } @Test public void givenGuava_whenConvertingByteArrayToDouble_thenSuccess() { - byte[] bytes = getDoubleByteArray(); - double value = convertByteArrayToDoubleUsingGuava(bytes); + double value = convertByteArrayToDoubleUsingGuava(DOUBLE_BYTE_ARRAY); assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); } @Test public void givenGuava_whenConvertingDoubleToByteArray_thenSuccess() { - double value = getDoubleValue(); - byte[] bytes = convertDoubleToByteArrayUsingGuava(value); + byte[] bytes = convertDoubleToByteArrayUsingGuava(DOUBLE_VALUE); assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); } @Test public void givenCommonsLang_whenConvertingByteArrayToInt_thenSuccess() { - byte[] bytes = getIntByteArray(); - int value = convertByteArrayToIntUsingCommonsLang(bytes); + int value = convertByteArrayToIntUsingCommonsLang(INT_BYTE_ARRAY); assertEquals(INT_VALUE, value); } @Test public void givenCommonsLang_whenConvertingIntToByteArray_thenSuccess() { - int value = getIntValue(); - byte[] bytes = convertIntToByteArrayUsingCommonsLang(value); + byte[] bytes = convertIntToByteArrayUsingCommonsLang(INT_VALUE); assertArrayEquals(INT_BYTE_ARRAY, bytes); } @Test public void givenCommonsLang_whenConvertingByteArrayToLong_thenSuccess() { - byte[] bytes = getLongByteArray(); - long value = convertByteArrayToLongUsingCommonsLang(bytes); + long value = convertByteArrayToLongUsingCommonsLang(LONG_BYTE_ARRAY); assertEquals(LONG_VALUE, value); } @Test public void givenCommonsLang_whenConvertingLongToByteArray_thenSuccess() { - long value = getLongValue(); - byte[] bytes = convertLongToByteArrayUsingCommonsLang(value); + byte[] bytes = convertLongToByteArrayUsingCommonsLang(LONG_VALUE); assertArrayEquals(LONG_BYTE_ARRAY, bytes); } @Test public void givenCommonsLang_whenConvertingByteArrayToFloat_thenSuccess() { - byte[] bytes = getFloatByteArray(); - float value = convertByteArrayToFloatUsingCommonsLang(bytes); + float value = convertByteArrayToFloatUsingCommonsLang(FLOAT_BYTE_ARRAY); assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value)); } @Test public void givenCommonsLang_whenConvertingFloatToByteArray_thenSuccess() { - float value = getFloatValue(); - byte[] bytes = convertFloatToByteArrayUsingCommonsLang(value); + byte[] bytes = convertFloatToByteArrayUsingCommonsLang(FLOAT_VALUE); assertArrayEquals(FLOAT_BYTE_ARRAY, bytes); } @Test public void givenCommonsLang_whenConvertingByteArrayToDouble_thenSuccess() { - byte[] bytes = getDoubleByteArray(); - double value = convertByteArrayToDoubleUsingCommonsLang(bytes); + double value = convertByteArrayToDoubleUsingCommonsLang(DOUBLE_BYTE_ARRAY); assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value)); } @Test public void givenCommonsLang_whenConvertingDoubleToByteArray_thenSuccess() { - double value = getDoubleValue(); - byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(value); + byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(DOUBLE_VALUE); assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes); } From ba638cb58aa213d3a69b5d47daf6acc648401413 Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Tue, 2 Nov 2021 16:09:03 +0800 Subject: [PATCH 03/40] BAEL-4286 How to get the value of a bit at a certain position from a byte --- .../core-java-lang-operators-2/pom.xml | 5 + .../GetABitFromIntegralValueUnitTest.java | 119 ++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml index 1779b7384c..2b81a797e0 100644 --- a/core-java-modules/core-java-lang-operators-2/pom.xml +++ b/core-java-modules/core-java-lang-operators-2/pom.xml @@ -15,6 +15,11 @@ + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + org.projectlombok lombok diff --git a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java new file mode 100644 index 0000000000..d39e3b3c47 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java @@ -0,0 +1,119 @@ +package com.baeldung.oroperators; + +import org.apache.commons.lang3.BitField; +import org.junit.Test; + +import java.math.BigInteger; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class GetABitFromIntegralValueUnitTest { + @Test + public void givenAByte_whenUsingAHardCodedMask_thenGetBitValue() { + byte val1 = 0b0110_0100; + byte val2 = 0b0110_0010; + byte mask = 0b0000_0100; + boolean isSet1 = (val1 & mask) > 0; + boolean isSet2 = (val2 & mask) > 0; + + assertTrue(isSet1); + assertFalse(isSet2); + } + + @Test + public void givenAnIntValue_whenUsingACalculatedMask_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + int mask = 1 << pos; + boolean isSet = (val & mask) > 0; + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingMultiPos_thenGetSameResult() { + int val = 0b0110_0100; + for (int i = 6; i < Integer.SIZE; i++) { + int pos = 1 << i | 2; + int mask = 1 << pos; + boolean isSet = (val & mask) > 0; + + assertTrue(isSet); + } + } + + @Test + public void givenALongValue_whenUsingACalculatedMask_thenGetBitValue() { + long val = 0b0110_0100; + int pos = 2; + long mask = 1L << pos; + boolean isSet = (val & mask) > 0; + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingALeftShiftedValue_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val << ~pos) < 0); + + assertTrue(isSet); + } + + @Test + public void givenALongValue_whenUsingALeftShiftedValue_thenGetBitValue() { + long val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val << ~pos) < 0); + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingARightShiftedValue_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val >> pos) & 1) == 1; + + assertTrue(isSet); + } + + @Test + public void givenALongValue_whenUsingARightShiftedValue_thenGetBitValue() { + long val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val >> pos) & 1) == 1; + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingBigInteger_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = BigInteger.valueOf(val).testBit(pos); + + assertTrue(isSet); + } + + @Test + public void givenALongValue_whenUsingBigInteger_thenGetBitValue() { + long val = 0b0110_0100; + int pos = 2; + boolean isSet = BigInteger.valueOf(val).testBit(pos); + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingCommonsLang_thenGetBitValue() { + int val = 0b0110_0100; + int mask = 0b0000_1100; + BitField bitField = new BitField(mask); + boolean isSet = bitField.isSet(val); + + assertTrue(isSet); + } +} From 197d10e9f1dd7bf1f87a0a5b213f1e581251feae Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Wed, 17 Nov 2021 19:18:53 +0800 Subject: [PATCH 04/40] BAEL-4286(update): remove redundant test methods --- .../GetABitFromIntegralValueUnitTest.java | 55 +++---------------- 1 file changed, 7 insertions(+), 48 deletions(-) rename core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/{oroperators => getbit}/GetABitFromIntegralValueUnitTest.java (51%) diff --git a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java similarity index 51% rename from core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java rename to core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java index d39e3b3c47..61f9885a91 100644 --- a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/oroperators/GetABitFromIntegralValueUnitTest.java +++ b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.oroperators; +package com.baeldung.getbit; -import org.apache.commons.lang3.BitField; import org.junit.Test; import java.math.BigInteger; @@ -32,39 +31,26 @@ public class GetABitFromIntegralValueUnitTest { } @Test - public void givenAnIntValue_whenUsingMultiPos_thenGetSameResult() { + public void givenAnIntValue_whenUsingALeftShiftedValue1_thenGetBitValue() { int val = 0b0110_0100; - for (int i = 6; i < Integer.SIZE; i++) { - int pos = 1 << i | 2; - int mask = 1 << pos; - boolean isSet = (val & mask) > 0; - - assertTrue(isSet); - } - } - - @Test - public void givenALongValue_whenUsingACalculatedMask_thenGetBitValue() { - long val = 0b0110_0100; int pos = 2; - long mask = 1L << pos; - boolean isSet = (val & mask) > 0; + boolean isSet = ((val << (31 - pos)) < 0); assertTrue(isSet); } @Test - public void givenAnIntValue_whenUsingALeftShiftedValue_thenGetBitValue() { + public void givenAnIntValue_whenUsingALeftShiftedValue2_thenGetBitValue() { int val = 0b0110_0100; int pos = 2; - boolean isSet = ((val << ~pos) < 0); + boolean isSet = ((val << (~pos & 31)) < 0); assertTrue(isSet); } @Test - public void givenALongValue_whenUsingALeftShiftedValue_thenGetBitValue() { - long val = 0b0110_0100; + public void givenAnIntValue_whenUsingALeftShiftedValue3_thenGetBitValue() { + int val = 0b0110_0100; int pos = 2; boolean isSet = ((val << ~pos) < 0); @@ -80,15 +66,6 @@ public class GetABitFromIntegralValueUnitTest { assertTrue(isSet); } - @Test - public void givenALongValue_whenUsingARightShiftedValue_thenGetBitValue() { - long val = 0b0110_0100; - int pos = 2; - boolean isSet = ((val >> pos) & 1) == 1; - - assertTrue(isSet); - } - @Test public void givenAnIntValue_whenUsingBigInteger_thenGetBitValue() { int val = 0b0110_0100; @@ -98,22 +75,4 @@ public class GetABitFromIntegralValueUnitTest { assertTrue(isSet); } - @Test - public void givenALongValue_whenUsingBigInteger_thenGetBitValue() { - long val = 0b0110_0100; - int pos = 2; - boolean isSet = BigInteger.valueOf(val).testBit(pos); - - assertTrue(isSet); - } - - @Test - public void givenAnIntValue_whenUsingCommonsLang_thenGetBitValue() { - int val = 0b0110_0100; - int mask = 0b0000_1100; - BitField bitField = new BitField(mask); - boolean isSet = bitField.isSet(val); - - assertTrue(isSet); - } } From 0d683d5ce4f9f787d9987ee1e1f04ed74428085e Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Thu, 24 Feb 2022 11:45:01 +0800 Subject: [PATCH 05/40] BAEL-4151: Guide to ByteBuffer --- .../bytebuffer/ByteBufferUnitTest.java | 339 ++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java diff --git a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java new file mode 100644 index 0000000000..5d108ba14a --- /dev/null +++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java @@ -0,0 +1,339 @@ +package com.baeldung.bytebuffer; + +import org.junit.Test; + +import java.lang.reflect.Field; +import java.nio.*; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.*; + +public class ByteBufferUnitTest { + @Test + public void givenBufferCreation_whenUsingAllocate_thenSuccess() { + ByteBuffer buffer = ByteBuffer.allocate(10); + assertNotNull(buffer); + } + + @Test + public void givenBufferCreation_whenUsingAllocateDirect_thenSuccess() { + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + assertNotNull(buffer); + } + + @Test + public void givenBufferCreation_whenUsingWrap_thenSuccess() { + byte[] bytes = new byte[10]; + ByteBuffer buffer = ByteBuffer.wrap(bytes); + assertNotNull(buffer); + } + + @Test + public void givenBufferIndex_whenUsingAllocate_thenInitialIndices() { + // create instance using allocate + ByteBuffer buffer = ByteBuffer.allocate(10); + + // get index + int position = buffer.position(); + int limit = buffer.limit(); + int capacity = buffer.capacity(); + + // assert + assertEquals(0, position); + assertEquals(10, limit); + assertEquals(10, capacity); + } + + @Test + public void givenBufferIndex_whenChangingPositionAndLimit_thenSuccess() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + + // change index + buffer.position(2); + buffer.limit(5); + + // assert + assertIndex(buffer, -1, 2, 5, 10); + } + + @Test + public void givenBufferIndex_whenUsingWrap_thenInitialIndices() { + // create instance + byte[] bytes = new byte[10]; + ByteBuffer buffer = ByteBuffer.wrap(bytes); + + // assert + assertIndex(buffer, -1, 0, 10, 10); + } + + @Test + public void givenBufferIndex_whenUsingWrapWithOffsetAndLength_thenInitialIndices() { + // create instance + byte[] bytes = new byte[10]; + ByteBuffer buffer = ByteBuffer.wrap(bytes, 2, 6); + + // assert + assertIndex(buffer, -1, 2, 8, 10); + } + + @Test + public void givenBufferIndex_whenUsingMarkAndReset_thenOK() { + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + buffer.position(2); + assertIndex(buffer, -1, 2, 10, 10); + + buffer.mark(); + assertIndex(buffer, 2, 2, 10, 10); + + buffer.position(5); + assertIndex(buffer, 2, 5, 10, 10); + + buffer.reset(); + assertIndex(buffer, 2, 2, 10, 10); + } + + @Test + public void givenBufferIndex_whenUsingClear_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // clear + buffer.clear(); + assertIndex(buffer, -1, 0, 10, 10); + } + + @Test + public void givenBufferIndex_whenUsingFlip_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // flip + buffer.flip(); + assertIndex(buffer, -1, 0, 5, 10); + } + + @Test + public void givenBufferIndex_whenUsingRewind_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // rewind + buffer.rewind(); + assertIndex(buffer, -1, 0, 8, 10); + } + + @Test + public void givenBufferIndex_whenUsingCompact_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // compact + buffer.compact(); + assertIndex(buffer, -1, 3, 10, 10); + } + + @Test + public void givenBufferIndex_whenUsingRemain_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + + // change index + buffer.position(2); + buffer.limit(8); + + // remain + boolean flag = buffer.hasRemaining(); + int remaining = buffer.remaining(); + + // assert + assertTrue(flag); + assertEquals(6, remaining); + } + + @Test(expected = BufferUnderflowException.class) + public void givenNotEnoughRemaining_WhenCallingGetInt_thenBufferUnderflowException() { + ByteBuffer buffer = ByteBuffer.allocate(2); + buffer.getInt(); + } + + @Test(expected = BufferOverflowException.class) + public void givenNotEnoughRemaining_WhenCallingPutInt_thenBufferOverflowException() { + ByteBuffer buffer = ByteBuffer.allocate(2); + buffer.putInt(10); + } + + @Test + public void givenBufferView_whenUsingDuplicate_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // view + ByteBuffer view = buffer.duplicate(); + assertIndex(view, 2, 5, 8, 10); + } + + @Test + public void givenBufferView_whenUsingSlice_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // view + ByteBuffer view = buffer.slice(); + assertIndex(view, -1, 0, 3, 3); + } + + @Test + public void givenBufferView_whenUsingAsReaOnlyBuffer_thenOK() { + // create instance + ByteBuffer buffer = ByteBuffer.allocate(10); + assertIndex(buffer, -1, 0, 10, 10); + + // change index + buffer.position(2); + buffer.mark(); + buffer.position(5); + buffer.limit(8); + assertIndex(buffer, 2, 5, 8, 10); + + // view + ByteBuffer view = buffer.asReadOnlyBuffer(); + assertIndex(view, 2, 5, 8, 10); + } + + @Test + public void givenBufferView_whenUsingAsIntBuffer_thenOK() { + // create instance + byte[] bytes = new byte[]{ + (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, // CAFEBABE ---> cafebabe + (byte) 0xF0, (byte) 0x07, (byte) 0xBA, (byte) 0x11, // F007BA11 ---> football + (byte) 0x0F, (byte) 0xF1, (byte) 0xCE // 0FF1CE ---> office + }; + ByteBuffer buffer = ByteBuffer.wrap(bytes); + assertIndex(buffer, -1, 0, 11, 11); + + // view + IntBuffer intBuffer = buffer.asIntBuffer(); + int capacity = intBuffer.capacity(); + assertEquals(2, capacity); + assertIndex(intBuffer, -1, 0, 2, 2); + } + + @Test + public void givenByteOrder_whenUsingBigEndian_thenOK() { + // create instance + byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; + ByteBuffer buffer = ByteBuffer.wrap(bytes); + + // change byte order + buffer.order(ByteOrder.BIG_ENDIAN); + int val = buffer.getInt(); + + // assert + assertEquals(0xCAFEBABE, val); + } + + @Test + public void givenByteOrder_whenUsingLittleEndian_thenOK() { + // create instance + byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; + ByteBuffer buffer = ByteBuffer.wrap(bytes); + + // change byte order + buffer.order(ByteOrder.LITTLE_ENDIAN); + int val = buffer.getInt(); + + // assert + assertEquals(0xBEBAFECA, val); + } + + @Test + public void givenComparing_whenUsingEqualsAndCompareTo_thenOK() { + // create instance + byte[] bytes1 = "World".getBytes(StandardCharsets.UTF_8); + byte[] bytes2 = "HelloWorld".getBytes(StandardCharsets.UTF_8); + ByteBuffer buffer1 = ByteBuffer.wrap(bytes1); + ByteBuffer buffer2 = ByteBuffer.wrap(bytes2); + + // change index + buffer2.position(5); + + // equals and compareTo + boolean equal = buffer1.equals(buffer2); + int result = buffer1.compareTo(buffer2); + + // assert + assertTrue(equal); + assertEquals(0, result); + } + + private void assertIndex(Buffer buffer, int mark, int position, int limit, int capacity) { + assertEquals(mark, getMark(buffer)); + assertEquals(position, buffer.position()); + assertEquals(limit, buffer.limit()); + assertEquals(capacity, buffer.capacity()); + } + + private int getMark(Buffer buffer) { + try { + Class clazz = Buffer.class; + Field f = clazz.getDeclaredField("mark"); + f.setAccessible(true); + Object result = f.get(buffer); + return (int) result; + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + return -1; + } +} From 4b11cc78b0a1d4f0560eda887bc71d72be1a4ca6 Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Thu, 7 Apr 2022 22:06:01 +0800 Subject: [PATCH 06/40] BAEL-1699 - Java 9 illegal reflective access warning --- .../A01-compile-and-package-baeldung-agent.sh | 11 +++ ...-compile-and-package-baeldung-reflected.sh | 11 +++ ...ompile-and-package-baeldung-intermedium.sh | 11 +++ ...e-and-package-baeldung-reflecting-named.sh | 11 +++ ...and-package-baeldung-reflecting-unnamed.sh | 11 +++ ...eldung-reflecting-named-using-add-opens.sh | 4 ++ ...ng-reflecting-named-using-forward-opens.sh | 4 ++ ...ldung-reflecting-named-using-java-agent.sh | 4 ++ ...aeldung-reflecting-unnamed-with-warning.sh | 2 + ...dung-reflecting-unnamed-using-add-opens.sh | 2 + ...ung-reflecting-unnamed-using-java-agent.sh | 2 + .../C01-clean.sh | 4 ++ .../com/baeldung/agent/LoadTimeAgent.java | 69 +++++++++++++++++++ .../baeldung-agent/manifest.txt | 3 + .../baeldung-agent/module-info.java | 3 + .../com/baeldung/intermedium/ForwardOpen.java | 15 ++++ .../baeldung-intermedium/module-info.java | 3 + .../exported/ExportedNonPublicClass.java | 11 +++ .../exported/ExportedPublicClass.java | 11 +++ .../internal/InternalNonPublicClass.java | 11 +++ .../internal/InternalPublicClass.java | 11 +++ .../opened/OpenedNonPublicClass.java | 11 +++ .../reflected/opened/OpenedPublicClass.java | 11 +++ .../baeldung-reflected/module-info.java | 4 ++ .../com/baeldung/reflecting/named/Main.java | 12 ++++ .../reflecting/named/MainWithForwardOpen.java | 18 +++++ .../module-info.java | 4 ++ .../com/baeldung/reflecting/unnamed/Main.java | 13 ++++ 28 files changed, 287 insertions(+) create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java create mode 100644 core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh new file mode 100644 index 0000000000..959fa66ec4 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A01-compile-and-package-baeldung-agent.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-agent + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar --manifest=${DIR}/manifest.txt -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh new file mode 100644 index 0000000000..fa922c54df --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A02-compile-and-package-baeldung-reflected.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflected + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh new file mode 100644 index 0000000000..af76ff5a2e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A03-compile-and-package-baeldung-intermedium.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-intermedium + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh new file mode 100644 index 0000000000..f3f91c9f04 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A04-compile-and-package-baeldung-reflecting-named.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflecting-named + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} --module-path mods $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh new file mode 100644 index 0000000000..deb0a8aaea --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/A05-compile-and-package-baeldung-reflecting-unnamed.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR=baeldung-reflecting-unnamed + +# compile +mkdir -p out/${DIR} +javac -d out/${DIR} $(find ${DIR} -type f -name "*.java") + +# package +mkdir -p mods +jar --create --file=mods/${DIR}.jar -C out/${DIR} . diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh new file mode 100644 index 0000000000..720ad69003 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B01-runtime-baeldung-reflecting-named-using-add-opens.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + --add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.reflecting.named \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh new file mode 100644 index 0000000000..9b5f9cb094 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B02-runtime-baeldung-reflecting-named-using-forward-opens.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + --add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.intermedium \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.MainWithForwardOpen diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh new file mode 100644 index 0000000000..cf66dd778f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B03-runtime-baeldung-reflecting-named-using-java-agent.sh @@ -0,0 +1,4 @@ +#!/bin/bash +java --module-path mods \ + -javaagent:mods/baeldung-agent.jar=com.baeldung.reflected.internal.InternalNonPublicClass,com.baeldung.reflecting.named.Main \ + --module baeldung.reflecting.named/com.baeldung.reflecting.named.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh new file mode 100644 index 0000000000..525b8dc58c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B04-runtime-baeldung-reflecting-unnamed-with-warning.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" com.baeldung.reflecting.unnamed.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh new file mode 100644 index 0000000000..f7f5f16237 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B05-runtime-baeldung-reflecting-unnamed-using-add-opens.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" --add-opens java.base/java.lang=ALL-UNNAMED com.baeldung.reflecting.unnamed.Main \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh new file mode 100644 index 0000000000..4b30ae1a5c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/B06-runtime-baeldung-reflecting-unnamed-using-java-agent.sh @@ -0,0 +1,2 @@ +#!/bin/bash +java -cp "mods/*" -javaagent:mods/baeldung-agent.jar com.baeldung.reflecting.unnamed.Main diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh new file mode 100644 index 0000000000..98707f810f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/C01-clean.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +rm -rf out +rm -rf mods diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java new file mode 100644 index 0000000000..a2ec9c3d4a --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java @@ -0,0 +1,69 @@ +package com.baeldung.agent; + +import java.lang.instrument.Instrumentation; +import java.util.*; + +public class LoadTimeAgent { + public static void premain(String agentArgs, Instrumentation inst) { + System.out.println("agentArgs: " + agentArgs); + + if (agentArgs != null) { + addExportsAndOpensByClassName(inst, agentArgs); + } + else { + addExportsAndOpensToUnnamedModule(inst); + } + } + + private static void addExportsAndOpensByClassName(Instrumentation inst, String agentArgs) { + String[] array = agentArgs.split(","); + try { + String className1 = array[0]; + String className2 = array[1]; + Class clazz1 = Class.forName(className1); + Class clazz2 = Class.forName(className2); + + Module srcModule = clazz1.getModule(); + Module targetModule = clazz2.getModule(); + redefineModule(inst, srcModule, targetModule); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + private static void addExportsAndOpensToUnnamedModule(Instrumentation inst) { + Module unnamedModule = ClassLoader.getSystemClassLoader().getUnnamedModule(); + Set modules = ModuleLayer.boot().modules(); + + for (Module m : modules) { + redefineModule(inst, m, unnamedModule); + } + } + + private static void redefineModule(Instrumentation inst, Module src, Module target) { + // prepare extra reads + Set extraReads = Collections.singleton(target); + + // prepare extra exports + Set packages = src.getPackages(); + Map> extraExports = new HashMap<>(); + for (String pkg : packages) { + extraExports.put(pkg, extraReads); + } + + // prepare extra opens + Map> extraOpens = new HashMap<>(); + for (String pkg : packages) { + extraOpens.put(pkg, extraReads); + } + + // prepare extra uses + Set> extraUses = Collections.emptySet(); + + // prepare extra uses + Map, List>> extraProvides = Collections.emptyMap(); + + // redefine module + inst.redefineModule(src, extraReads, extraExports, extraOpens, extraUses, extraProvides); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt new file mode 100644 index 0000000000..3dc9de7ba5 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/manifest.txt @@ -0,0 +1,3 @@ +Premain-Class: com.baeldung.agent.LoadTimeAgent +Can-Redefine-Classes: true +Can-Retransform-Classes: true diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java new file mode 100644 index 0000000000..c976de2881 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/module-info.java @@ -0,0 +1,3 @@ +module baeldung.agent { + requires java.instrument; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java new file mode 100644 index 0000000000..db031e2cfc --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/com/baeldung/intermedium/ForwardOpen.java @@ -0,0 +1,15 @@ +package com.baeldung.intermedium; + +public class ForwardOpen { + public static void addOpens(Class clazz1, Class clazz2) { + Module currentModule = ForwardOpen.class.getModule(); + Module srcModule = clazz1.getModule(); + Module targetModule = clazz2.getModule(); + + System.out.println("current module: " + currentModule.getName()); + System.out.println("source module: " + srcModule.getName()); + System.out.println("target module: " + targetModule.getName()); + + srcModule.addOpens(clazz1.getPackageName(), targetModule); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java new file mode 100644 index 0000000000..9ca6cbce43 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-intermedium/module-info.java @@ -0,0 +1,3 @@ +module baeldung.intermedium { + exports com.baeldung.intermedium; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java new file mode 100644 index 0000000000..c95e17ec1f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.exported; + +class ExportedNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("ExportedNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("ExportedNonPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java new file mode 100644 index 0000000000..3bbfca209c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/exported/ExportedPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.exported; + +public class ExportedPublicClass { + public static void testPublicStaticMethod() { + System.out.println("ExportedPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("ExportedPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java new file mode 100644 index 0000000000..052ecbea9e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.internal; + +class InternalNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("InternalNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("InternalNonPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java new file mode 100644 index 0000000000..8f7a20698f --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/internal/InternalPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.internal; + +public class InternalPublicClass { + public static void testPublicStaticMethod() { + System.out.println("InternalPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("InternalPublicClass.testPrivateStaticMethod()"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java new file mode 100644 index 0000000000..99f9850cc1 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedNonPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.opened; + +class OpenedNonPublicClass { + public static void testPublicStaticMethod() { + System.out.println("OpenedNonPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("OpenedNonPublicClass.testPrivateStaticMethod()"); + } +} diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java new file mode 100644 index 0000000000..f9a56ca26b --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/com/baeldung/reflected/opened/OpenedPublicClass.java @@ -0,0 +1,11 @@ +package com.baeldung.reflected.opened; + +public class OpenedPublicClass { + public static void testPublicStaticMethod() { + System.out.println("OpenedPublicClass.testPublicStaticMethod()"); + } + + private static void testPrivateStaticMethod() { + System.out.println("OpenedPublicClass.testPrivateStaticMethod()"); + } +} diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java new file mode 100644 index 0000000000..e2164415cf --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflected/module-info.java @@ -0,0 +1,4 @@ +module baeldung.reflected { + exports com.baeldung.reflected.exported; + opens com.baeldung.reflected.opened; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java new file mode 100644 index 0000000000..c0fa4010ab --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/Main.java @@ -0,0 +1,12 @@ +package com.baeldung.reflecting.named; + +import java.lang.reflect.Method; + +public class Main { + public static void main(String[] args) throws Exception { + Class clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass"); + Method method = clazz.getDeclaredMethod("testPrivateStaticMethod"); + method.setAccessible(true); + method.invoke(null); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java new file mode 100644 index 0000000000..fad8a9ddce --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/com/baeldung/reflecting/named/MainWithForwardOpen.java @@ -0,0 +1,18 @@ +package com.baeldung.reflecting.named; + +import com.baeldung.intermedium.ForwardOpen; + +import java.lang.reflect.Method; + +public class MainWithForwardOpen { + public static void main(String[] args) throws Exception { + Class currentClass = Main.class; + Class clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass"); + + ForwardOpen.addOpens(clazz, currentClass); + + Method method = clazz.getDeclaredMethod("testPrivateStaticMethod"); + method.setAccessible(true); + method.invoke(null); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java new file mode 100644 index 0000000000..936f53cd6e --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-named/module-info.java @@ -0,0 +1,4 @@ +module baeldung.reflecting.named { + requires baeldung.intermedium; + requires baeldung.reflected; +} \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java new file mode 100644 index 0000000000..37bdc57eaf --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-reflecting-unnamed/com/baeldung/reflecting/unnamed/Main.java @@ -0,0 +1,13 @@ +package com.baeldung.reflecting.unnamed; + +import java.lang.reflect.Field; + +public class Main { + public static void main(String[] args) throws Exception { + Class clazz = StringBuilder.class; + Field f = clazz.getDeclaredField("serialVersionUID"); + f.setAccessible(true); + Object value = f.get(null); + System.out.println(value); + } +} \ No newline at end of file From 15323bddf0477d539b1b9458410b94b22aed11de Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Tue, 5 Apr 2022 22:02:54 +0100 Subject: [PATCH 07/40] [JAVA-10446] Convert Feign-OAuth2 unit test to manual test --- spring-cloud/pom.xml | 2 +- ...nualTest.java => OpenFeignManualTest.java} | 2 +- .../openfeign/OpenFeignOAuth2ManualTest.java | 44 +++++++++++++++++++ .../openfeign/PaymentClientUnitTest.java | 30 ------------- 4 files changed, 46 insertions(+), 32 deletions(-) rename spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/{OpenfeignManualTest.java => OpenFeignManualTest.java} (96%) create mode 100644 spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java delete mode 100644 spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index a2c4b3509f..9205416cd5 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -45,7 +45,7 @@ spring-cloud-ribbon-retry spring-cloud-circuit-breaker spring-cloud-eureka-self-preservation - + spring-cloud-openfeign spring-cloud-netflix-feign spring-cloud-sentinel spring-cloud-dapr diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java similarity index 96% rename from spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java rename to spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java index 8ae6883519..4eb014de96 100644 --- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignManualTest.java +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignManualTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest -public class OpenfeignManualTest { +public class OpenFeignManualTest { @Autowired private JSONPlaceHolderService jsonPlaceHolderService; diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java new file mode 100644 index 0000000000..8084fd23cd --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignOAuth2ManualTest.java @@ -0,0 +1,44 @@ +package com.baeldung.cloud.openfeign; + +import com.baeldung.cloud.openfeign.client.PaymentClient; +import com.baeldung.cloud.openfeign.model.Payment; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.junit.Assert.assertFalse; + +/** + * This test can be used to verify OAuth2 Token functionality with Feign client + * (https://www.baeldung.com/spring-cloud-feign-oauth-token). + * + * The following components should be setup and running, as described in the article, prior to running this test. + * + * Authorization Server - embedded Keycloak server with the correct client and client-secret defined in the master realm. + * This will issue the auth tokens used by Feign client. + * Further details are available at: https://www.baeldung.com/keycloak-embedded-in-spring-boot-app + * + * Resource Server - OAuth resource server requiring valid JWT token (issued by the Authorization Server). + * Further details are available at: https://www.baeldung.com/spring-security-oauth-resource-server + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest +public class OpenFeignOAuth2ManualTest { + + @Autowired + private PaymentClient paymentClient; + + @Test + public void whenGetPayment_thenListPayments() { + + List payments = paymentClient.getPayments(); + + assertFalse(payments.isEmpty()); + } + +} diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java deleted file mode 100644 index 0372728515..0000000000 --- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.cloud.openfeign; - -import com.baeldung.cloud.openfeign.client.PaymentClient; -import com.baeldung.cloud.openfeign.model.Payment; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.junit.Assert.assertFalse; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class PaymentClientUnitTest { - - @Autowired - private PaymentClient paymentClient; - - @Test - public void whenGetPayment_thenListPayments() { - - List payments = paymentClient.getPayments(); - - assertFalse(payments.isEmpty()); - } - -} From dfad1122a467c132a4779b12eecbb2da0dffb708 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 8 Apr 2022 21:06:02 +0530 Subject: [PATCH 08/40] JAVA-8372 Split or move spring-boot-data module --- .../spring-boot-data-2/README.md | 1 + .../spring-boot-data-2/pom.xml | 9 ++++++++ .../javers/SpringBootJaVersApplication.java | 0 .../javers/config/JaversConfiguration.java | 0 .../com/baeldung/javers/domain/Address.java | 0 .../com/baeldung/javers/domain/Product.java | 0 .../com/baeldung/javers/domain/Store.java | 0 .../javers/repo/ProductRepository.java | 0 .../baeldung/javers/repo/StoreRepository.java | 0 .../baeldung/javers/service/StoreService.java | 0 .../baeldung/javers/web/RebrandStoreDto.java | 0 .../baeldung/javers/web/StoreController.java | 0 .../baeldung/javers/web/UpdatePriceDto.java | 0 .../src/main/resources/application.properties | 22 +++++++++++++++++++ .../spring-boot-data/README.md | 2 +- spring-boot-modules/spring-boot-data/pom.xml | 6 ----- .../disableautoconfig/SpringDataJPA.java | 5 ++--- .../src/main/resources/application.properties | 16 +------------- 18 files changed, 36 insertions(+), 25 deletions(-) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/config/JaversConfiguration.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/domain/Address.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/domain/Product.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/domain/Store.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/repo/ProductRepository.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/repo/StoreRepository.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/service/StoreService.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/web/StoreController.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java (100%) create mode 100644 spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index b99356492b..c01c54e29e 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -4,3 +4,4 @@ - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) +- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) diff --git a/spring-boot-modules/spring-boot-data-2/pom.xml b/spring-boot-modules/spring-boot-data-2/pom.xml index a3c2430497..ea5de6d4b5 100644 --- a/spring-boot-modules/spring-boot-data-2/pom.xml +++ b/spring-boot-modules/spring-boot-data-2/pom.xml @@ -20,11 +20,20 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.javers + javers-spring-boot-starter-sql + ${javers.version} + com.h2database h2 runtime + + + 6.5.3 + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/SpringBootJaVersApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/config/JaversConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/config/JaversConfiguration.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/config/JaversConfiguration.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Address.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Address.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Address.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Product.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Product.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Product.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Store.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/domain/Store.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/domain/Store.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/ProductRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/ProductRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/ProductRepository.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/StoreRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/repo/StoreRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/repo/StoreRepository.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/service/StoreService.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/service/StoreService.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/service/StoreService.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/RebrandStoreDto.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/StoreController.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/StoreController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/StoreController.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/javers/web/UpdatePriceDto.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties new file mode 100644 index 0000000000..60a6e0fed5 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/application.properties @@ -0,0 +1,22 @@ +spring.h2.console.path=/h2 +spring.h2.console.enabled=true +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +javers.mappingStyle=FIELD +javers.algorithm=SIMPLE +javers.commitIdGenerator=synchronized_sequence +javers.prettyPrint=true +javers.typeSafeValues=false +javers.newObjectSnapshot=true +javers.packagesToScan= +javers.auditableAspectEnabled=true +javers.springDataAuditableRepositoryAspectEnabled=true +javers.sqlSchema= +javers.sqlSchemaManagementEnabled=true +javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss +javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ +javers.prettyPrintDateFormats.localDate=dd MMM yyyy +javers.prettyPrintDateFormats.localTime=HH:mm:ss + diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index f72864e6d9..c56c87014d 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring Boot with Spring Data - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) -- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) + diff --git a/spring-boot-modules/spring-boot-data/pom.xml b/spring-boot-modules/spring-boot-data/pom.xml index 18360bbd8b..b69d0e093a 100644 --- a/spring-boot-modules/spring-boot-data/pom.xml +++ b/spring-boot-modules/spring-boot-data/pom.xml @@ -19,11 +19,6 @@ org.springframework.boot spring-boot-starter-data-redis - - org.javers - javers-spring-boot-starter-sql - ${javers.version} - org.springframework.boot spring-boot-starter-data-mongodb @@ -164,7 +159,6 @@ - 5.14.0 2.2.4 1.8 1.8 diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java index 87656f66a6..8554076612 100644 --- a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -1,6 +1,5 @@ package com.baeldung.disableautoconfig; -import org.javers.spring.boot.sql.JaversSqlAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; @@ -9,8 +8,8 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, - JaversSqlAutoConfiguration.class, SpringDataWebAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) + SpringDataWebAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, + HibernateJpaAutoConfiguration.class}) public class SpringDataJPA { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot-data/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data/src/main/resources/application.properties index 969464a41c..cee5701cb5 100644 --- a/spring-boot-modules/spring-boot-data/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-data/src/main/resources/application.properties @@ -6,19 +6,5 @@ spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= -javers.mappingStyle=FIELD -javers.algorithm=SIMPLE -javers.commitIdGenerator=synchronized_sequence -javers.prettyPrint=true -javers.typeSafeValues=false -javers.newObjectSnapshot=true -javers.packagesToScan= -javers.auditableAspectEnabled=true -javers.springDataAuditableRepositoryAspectEnabled=true -javers.sqlSchema= -javers.sqlSchemaManagementEnabled=true -javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss -javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ -javers.prettyPrintDateFormats.localDate=dd MMM yyyy -javers.prettyPrintDateFormats.localTime=HH:mm:ss + From 2712a77d08e9b444471d8beafda7e1a7e664ffc0 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Sat, 9 Apr 2022 12:01:45 +0100 Subject: [PATCH 09/40] [JAVA-11283] Fix and cleanup live test for HttpClient URL expansion --- httpclient-2/README.md | 2 +- .../HttpClientExpandUrlLiveTest.java} | 16 +++++----------- 2 files changed, 6 insertions(+), 12 deletions(-) rename httpclient-2/src/test/java/com/baeldung/httpclient/{rare/HttpClientUnshortenLiveTest.java => expandurl/HttpClientExpandUrlLiveTest.java} (91%) diff --git a/httpclient-2/README.md b/httpclient-2/README.md index 49adf470e9..695a92ce00 100644 --- a/httpclient-2/README.md +++ b/httpclient-2/README.md @@ -12,5 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string) - [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies) - [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging) -- [Unshorten URLs with HttpClient](https://www.baeldung.com/unshorten-url-httpclient) +- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/unshorten-url-httpclient) - More articles: [[<-- prev]](../httpclient) diff --git a/httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java similarity index 91% rename from httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java rename to httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java index efa7953ba8..fb3d730ec4 100644 --- a/httpclient-2/src/test/java/com/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java +++ b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.rare; +package com.baeldung.httpclient.expandurl; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; @@ -22,35 +22,29 @@ import java.util.List; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; -public class HttpClientUnshortenLiveTest { +public class HttpClientExpandUrlLiveTest { private CloseableHttpClient client; - // fixtures - @Before public final void before() { client = HttpClientBuilder.create().disableRedirectHandling().build(); } - // tests - @Test - public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException { + public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException { final String expectedResult = "http://www.baeldung.com/rest-versioning"; final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1"); assertThat(actualResult, equalTo(expectedResult)); } @Test - public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException { - final String expectedResult = "http://www.baeldung.com/rest-versioning"; + public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException { + final String expectedResult = "https://www.baeldung.com/rest-versioning"; final String actualResult = expand("http://t.co/e4rDDbnzmk"); assertThat(actualResult, equalTo(expectedResult)); } - // API - private String expand(final String urlArg) throws IOException { String originalUrl = urlArg; String newUrl = expandSingleLevel(originalUrl); From de994fdabd2f18051219f13d797583f51a2a38eb Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sat, 9 Apr 2022 14:36:40 +0300 Subject: [PATCH 10/40] BAEL-4942: added tests for hibernate nullability check --- .../persistentobject/HibernateUtil.java | 47 ++++++++++++++ .../persistentobject/entity/Article.java | 29 +++++++++ .../persistentobject/entity/Author.java | 48 ++++++++++++++ .../persistentobject/entity/Book.java | 34 ++++++++++ .../HibernatePersistentObjectUnitTest.java | 65 +++++++++++++++++++ 5 files changed, 223 insertions(+) create mode 100644 persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java create mode 100644 persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java create mode 100644 persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java create mode 100644 persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java create mode 100644 persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java new file mode 100644 index 0000000000..641b80b412 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.exception.persistentobject; + +import java.util.Properties; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.exception.persistentobject.entity.Article; +import com.baeldung.hibernate.exception.persistentobject.entity.Author; +import com.baeldung.hibernate.exception.persistentobject.entity.Book; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + try { + Configuration configuration = new Configuration(); + Properties settings = new Properties(); + + settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver"); + settings.put(Environment.URL, "jdbc:hsqldb:mem:userrole"); + settings.put(Environment.USER, "sa"); + settings.put(Environment.PASS, ""); + settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect"); + settings.put(Environment.SHOW_SQL, "true"); + settings.put(Environment.HBM2DDL_AUTO, "update"); + settings.put(Environment.CHECK_NULLABILITY, "true"); + + configuration.setProperties(settings); + configuration.addAnnotatedClass(Book.class); + configuration.addAnnotatedClass(Author.class); + configuration.addAnnotatedClass(Article.class); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } catch (Exception e) { + e.printStackTrace(); + } + } + return sessionFactory; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java new file mode 100644 index 0000000000..3c9c7c5b31 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Article { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String title; + + @ManyToOne(optional = false) + private Author author; + + public Article(String title) { + this.title = title; + } + + public void setAuthor(Author author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java new file mode 100644 index 0000000000..fa6aaa9abe --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; + +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; + +@Entity +public class Author { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + @OneToMany + @Cascade(CascadeType.ALL) + private List
articles; + + public Author(String name) { + this.name = name; + } + + public Author() { + } + + public List
getArticles() { + return articles; + } + + public void setArticles(List
articles) { + this.articles = articles; + } + + public void addArticles(List
articles) { + this.articles = articles; + articles.forEach(article -> article.setAuthor(this)); + } + +} diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java new file mode 100644 index 0000000000..342da27c77 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.exception.persistentobject.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false) + private String title; + + public Book(String title) { + this.title = title; + } + + public Book() { + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java new file mode 100644 index 0000000000..09f11b07a2 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/persistentobject/HibernatePersistentObjectUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.hibernate.exception.persistentobject; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.hibernate.PropertyValueException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.exception.persistentobject.entity.Article; +import com.baeldung.hibernate.exception.persistentobject.entity.Author; +import com.baeldung.hibernate.exception.persistentobject.entity.Book; + +public class HibernatePersistentObjectUnitTest { + + private static Session session; + + @Before + public void beforeAll() { + session = HibernateUtil.getSessionFactory() + .openSession(); + session.beginTransaction(); + } + + @After + public void afterAll() { + session.close(); + } + + @Test + public void whenSavingEntityWithNullMandatoryField_thenThrowPropertyValueException() { + Book book = new Book(); + + assertThatThrownBy(() -> session.save(book)).isInstanceOf(PropertyValueException.class) + .hasMessageContaining("not-null property references a null or transient value"); + } + + @Test + public void whenSavingEntityWithAllMandatoryField_thenDoNotThrowException() { + Book book = new Book(); + book.setTitle("Clean Code"); + + session.save(book); + } + + @Test + public void whenSavingBidirectionalEntitiesWithoutSettingParent_thenThrowPropertyValueException() { + Author author = new Author("John Doe"); + author.setArticles(asList(new Article("Java Tutorial"), new Article("What's New in JUnit5"))); + + assertThatThrownBy(() -> session.save(author)).isInstanceOf(PropertyValueException.class) + .hasMessageContaining("not-null property references a null or transient value"); + } + + @Test + public void whenSavingBidirectionalEntitiesWithCorrectParent_thenDoNotThrowException() { + Author author = new Author("John Doe"); + author.addArticles(asList(new Article("Java tutorial"), new Article("What's new in JUnit5"))); + + session.save(author); + } + +} \ No newline at end of file From 4ad546c702c789e2f8976e3c75ace975b6e191be Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Mon, 11 Apr 2022 15:55:30 +0100 Subject: [PATCH 11/40] [JAVA-11226] Fix and update Hibernate OneToMany code (#12031) --- .../hibernate-annotations/pom.xml | 2 +- .../config/HibernateAnnotationUtil.java | 43 +++++++---- .../main/HibernateManyIsOwningSide.java | 71 ++++++++++++++++++ .../main/HibernateManyisOwningSide.java | 71 ------------------ ...ide.java => HibernateOneIsOwningSide.java} | 44 +++++------ .../HibernateOneToManyAnnotationMain.java | 41 +++++----- .../hibernate/oneToMany/model/Cart.java | 8 +- .../hibernate/oneToMany/model/CartOIO.java | 8 +- .../oneToMany/model/{Items.java => Item.java} | 7 +- .../model/{ItemsOIO.java => ItemOIO.java} | 6 +- .../resources/hibernate-annotation.cfg.xml | 18 +++++ .../src/main/resources/log4j.xml | 31 ++++++++ ...neToManyAnnotationMainIntegrationTest.java | 62 +++++++-------- .../src/test/resources/log4j.xml | 13 +++- .../src/test/resources/profile.png | Bin 1117 -> 0 bytes 15 files changed, 243 insertions(+), 182 deletions(-) create mode 100644 persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java delete mode 100644 persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/{HibernateOneisOwningSide.java => HibernateOneIsOwningSide.java} (50%) rename persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/{Items.java => Item.java} (92%) rename persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/{ItemsOIO.java => ItemOIO.java} (91%) create mode 100644 persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml create mode 100644 persistence-modules/hibernate-annotations/src/main/resources/log4j.xml delete mode 100644 persistence-modules/hibernate-annotations/src/test/resources/profile.png diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index ed158216fb..023e5aa30f 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -82,7 +82,7 @@ 5.0.2.RELEASE 1.10.6.RELEASE - 5.4.7.Final + 5.6.7.Final true 2.1.7.RELEASE 1.4.200 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index 46e6824f42..6c94d34339 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -1,34 +1,51 @@ package com.baeldung.hibernate.oneToMany.config; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.CartOIO; +import com.baeldung.hibernate.oneToMany.model.Item; +import com.baeldung.hibernate.oneToMany.model.ItemOIO; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateAnnotationUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class); + private static SessionFactory sessionFactory; + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + private static SessionFactory buildSessionFactory() { try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); - Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); - SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .configure("hibernate-annotation.cfg.xml") + .build(); - return sessionFactory; + Metadata metadata = new MetadataSources(serviceRegistry) + .addAnnotatedClass(Cart.class) + .addAnnotatedClass(CartOIO.class) + .addAnnotatedClass(Item.class) + .addAnnotatedClass(ItemOIO.class) + .getMetadataBuilder() + .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder().build(); } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); + LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } - - public static SessionFactory getSessionFactory() { - if (sessionFactory == null) - sessionFactory = buildSessionFactory(); - return sessionFactory; - } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java new file mode 100644 index 0000000000..f74aecbb92 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyIsOwningSide.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Item; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateManyIsOwningSide { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateManyIsOwningSide.class); + + public static void main(String[] args) { + + Cart cart = new Cart(); + Cart cart2 = new Cart(); + + Item item1 = new Item(cart); + Item item2 = new Item(cart2); + + Set itemsSet = new HashSet<>(); + itemsSet.add(item1); + itemsSet.add(item2); + cart.setItems(itemsSet); + + // Get Session + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + + try { + LOGGER.info("Session created"); + + // start transaction + Transaction tx = session.beginTransaction(); + + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + + // Commit transaction + tx.commit(); + + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + + item1 = session.get(Item.class, 1L); + item2 = session.get(Item.class, 2L); + tx.commit(); + + LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCart().getId()); + LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCart().getId()); + + } catch (Exception e) { + LOGGER.error("Exception occurred", e); + } finally { + if (!sessionFactory.isClosed()) { + LOGGER.info("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java deleted file mode 100644 index 372fb2fc07..0000000000 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.hibernate.oneToMany.main; - -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; - -public class HibernateManyisOwningSide { - public static void main(String[] args) { - - Cart cart = new Cart(); - Cart cart2 = new Cart(); - - Items item1 = new Items(cart); - Items item2 = new Items(cart2); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - itemsSet.add(item2); - - cart.setItems(itemsSet); - - - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - // start transaction - tx = session.beginTransaction(); - // Save the Model object - session.save(cart); - session.save(cart2); - session.save(item1); - session.save(item2); - // Commit transaction - tx.commit(); - session = sessionFactory.getCurrentSession(); - tx = session.beginTransaction(); - - item1 = (Items) session.get(Items.class, new Long(1)); - item2 = (Items) session.get(Items.class, new Long(2)); - tx.commit(); - - - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() - .getId()); - - } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); - } finally { - if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } -} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java similarity index 50% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java index 0777664dd0..086e015ad1 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneIsOwningSide.java @@ -9,57 +9,59 @@ import org.hibernate.Transaction; import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; import com.baeldung.hibernate.oneToMany.model.CartOIO; -import com.baeldung.hibernate.oneToMany.model.ItemsOIO; +import com.baeldung.hibernate.oneToMany.model.ItemOIO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HibernateOneIsOwningSide { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneIsOwningSide.class); -public class HibernateOneisOwningSide { public static void main(String[] args) { CartOIO cart = new CartOIO(); CartOIO cart2 = new CartOIO(); - ItemsOIO item1 = new ItemsOIO(cart); - ItemsOIO item2 = new ItemsOIO(cart2); - Set itemsSet = new HashSet(); + ItemOIO item1 = new ItemOIO(cart); + ItemOIO item2 = new ItemOIO(cart2); + Set itemsSet = new HashSet<>(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + LOGGER.info("Session created"); + + Transaction tx; try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); // start transaction tx = session.beginTransaction(); + // Save the Model object session.save(cart); session.save(cart2); session.save(item1); session.save(item2); + // Commit transaction tx.commit(); session = sessionFactory.getCurrentSession(); tx = session.beginTransaction(); - item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); - item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); + item1 = session.get(ItemOIO.class, 1L); + item2 = session.get(ItemOIO.class, 2L); tx.commit(); - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() - .getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() - .getId()); + LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCartOIO().getId()); + LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCartOIO().getId()); } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); + LOGGER.error("Exception occurred", e); } finally { if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); + LOGGER.info("Closing SessionFactory"); sessionFactory.close(); } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java index 2bc5e514f7..99df67b4a8 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -9,52 +9,53 @@ import org.hibernate.Transaction; import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; +import com.baeldung.hibernate.oneToMany.model.Item; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateOneToManyAnnotationMain { + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneToManyAnnotationMain.class); + public static void main(String[] args) { Cart cart = new Cart(); - Items item1 = new Items(cart); - Items item2 = new Items(cart); - Set itemsSet = new HashSet(); + Item item1 = new Item(cart); + Item item2 = new Item(cart); + Set itemsSet = new HashSet<>(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; + SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + Session session = sessionFactory.getCurrentSession(); + LOGGER.info("Session created"); + try { - // Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); // start transaction - tx = session.beginTransaction(); + Transaction tx = session.beginTransaction(); + // Save the Model object session.save(cart); session.save(item1); session.save(item2); + // Commit transaction tx.commit(); - System.out.println("Cart ID=" + cart.getId()); - System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); - System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + LOGGER.info("Cart ID={}", cart.getId()); + LOGGER.info("item1 ID={}, Foreign Key Cart ID={}", item1.getId(), item1.getCart().getId()); + LOGGER.info("item2 ID={}, Foreign Key Cart ID={}", item2.getId(), item2.getCart().getId()); } catch (Exception e) { - System.out.println("Exception occured. " + e.getMessage()); - e.printStackTrace(); + LOGGER.error("Exception occurred", e); } finally { if (!sessionFactory.isClosed()) { - System.out.println("Closing SessionFactory"); + LOGGER.info("Closing SessionFactory"); sessionFactory.close(); } } } - } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index b8b991831e..53878af445 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -19,9 +19,8 @@ public class Cart { @Column(name = "cart_id") private long id; - @OneToMany(mappedBy = "cart") - private Set items; + private Set items; public long getId() { return id; @@ -31,12 +30,11 @@ public class Cart { this.id = id; } - - public Set getItems() { + public Set getItems() { return items; } - public void setItems(Set items) { + public void setItems(Set items) { this.items = items; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java index 8a5ed5e7a4..27b28a6753 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -9,8 +9,6 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; - - @Entity @Table(name = "CARTOIO") public class CartOIO { @@ -21,7 +19,7 @@ public class CartOIO { @OneToMany @JoinColumn(name = "cart_id") // we need to duplicate the physical information - private Set items; + private Set items; public long getId() { return id; @@ -31,11 +29,11 @@ public class CartOIO { this.id = id; } - public Set getItems() { + public Set getItems() { return items; } - public void setItems(Set items) { + public void setItems(Set items) { this.items = items; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java similarity index 92% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java index f63a4855b5..a055682d0d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java @@ -11,23 +11,22 @@ import javax.persistence.Table; @Entity @Table(name = "ITEMS") -public class Items { +public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; - @ManyToOne @JoinColumn(name = "cart_id", nullable = false) private Cart cart; // Hibernate requires no-args constructor - public Items() { + public Item() { } - public Items(Cart c) { + public Item(Cart c) { this.cart = c; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java similarity index 91% rename from persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java index a3d6a796c5..baaf57b106 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java @@ -10,7 +10,7 @@ import javax.persistence.Table; @Entity @Table(name = "ITEMSOIO") -public class ItemsOIO { +public class ItemOIO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -21,10 +21,10 @@ public class ItemsOIO { private CartOIO cart; // Hibernate requires no-args constructor - public ItemsOIO() { + public ItemOIO() { } - public ItemsOIO(CartOIO c) { + public ItemOIO(CartOIO c) { this.cart = c; } diff --git a/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml new file mode 100644 index 0000000000..6e845b3781 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/hibernate-annotation.cfg.xml @@ -0,0 +1,18 @@ + + + + + + org.h2.Driver + sa + + jdbc:h2:mem:spring_hibernate_one_to_many + + org.hibernate.dialect.H2Dialect + thread + true + create + + diff --git a/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml new file mode 100644 index 0000000000..bc2c24ea93 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/log4j.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java index 3bc5a6e12a..cb11df4212 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -1,26 +1,21 @@ package com.baeldung.hibernate.oneToMany.main; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.HashSet; -import java.util.Set; - +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Item; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; public class HibernateOneToManyAnnotationMainIntegrationTest { @@ -28,20 +23,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { private Session session; - public HibernateOneToManyAnnotationMainIntegrationTest() { - } - @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) - .setProperty("hibernate.dialect", H2Dialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") - .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() - .applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); } @Before @@ -52,32 +36,38 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { @Test public void givenSession_checkIfDatabaseIsEmpty() { - Cart cart = (Cart) session.get(Cart.class, new Long(1)); + Cart cart = session.get(Cart.class, 1L); assertNull(cart); - } @Test public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items(); + Set cartItems = cart.getItems(); + + assertNull(cartItems); + + Item item1 = new Item(); item1.setCart(cart); + assertNotNull(item1); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - assertNotNull(itemsSet); - cart.setItems(itemsSet); + + Set itemSet = new HashSet<>(); + itemSet.add(item1); + + assertNotNull(itemSet); + cart.setItems(itemSet); + assertNotNull(cart); + session.persist(cart); session.getTransaction().commit(); session.close(); session = sessionFactory.openSession(); session.beginTransaction(); - cart = (Cart) session.get(Cart.class, new Long(1)); + cart = session.get(Cart.class, 1L); + assertNotNull(cart); } diff --git a/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml index 7e2895f1e0..bc2c24ea93 100644 --- a/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml +++ b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml @@ -1,24 +1,31 @@ - + + + + + - + + + - \ No newline at end of file + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png deleted file mode 100644 index 1cd4e978b96d0f59a6e48692fcb68d1c6c565a20..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= From 0ad2fa54126ff49a0608ede30622ae42b185fa59 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 11 Apr 2022 21:53:04 +0530 Subject: [PATCH 12/40] JAVA-8859 --- .../reactor/core/CombiningPublishersIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java index e6108759e1..4f37718814 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java @@ -18,8 +18,8 @@ public class CombiningPublishersIntegrationTest { @Test public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { Flux fluxOfIntegers = Flux.mergeDelayError(1, - evenNumbers.delayElements(Duration.ofMillis(2000L)), - oddNumbers.delayElements(Duration.ofMillis(1000L))); + evenNumbers.delayElements(Duration.ofMillis(500L)), + oddNumbers.delayElements(Duration.ofMillis(300L))); StepVerifier.create(fluxOfIntegers) .expectNext(1) From 620653f6a6eed8ce5515db9a8b0e7ee9682aa419 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Mon, 11 Apr 2022 13:43:37 -0300 Subject: [PATCH 13/40] BAEL-5157 - Exception Handling with Jersey (#12045) First draft: https://drafts.baeldung.com/wp-admin/post.php?post=131880&action=edit --- .../ExceptionHandlingConfig.java | 19 ++++ .../jersey/exceptionhandling/data/Stock.java | 33 +++++++ .../jersey/exceptionhandling/data/Wallet.java | 51 ++++++++++ .../jersey/exceptionhandling/repo/Db.java | 32 ++++++ .../exceptionhandling/repo/Identifiable.java | 17 ++++ .../rest/StocksResource.java | 42 ++++++++ .../rest/WalletsResource.java | 98 ++++++++++++++++++ .../IllegalArgumentExceptionMapper.java | 23 +++++ .../exceptions/InvalidTradeException.java | 17 ++++ .../rest/exceptions/RestErrorResponse.java | 34 +++++++ .../exceptions/ServerExceptionMapper.java | 35 +++++++ .../exceptionhandling/service/Repository.java | 10 ++ .../rest/StocksResourceIntegrationTest.java | 99 +++++++++++++++++++ 13 files changed, 510 insertions(+) create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java create mode 100644 jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java new file mode 100644 index 0000000000..d4cc1a81a1 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.jersey.exceptionhandling; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.server.ResourceConfig; + +import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; + +@ApplicationPath("/exception-handling/*") +public class ExceptionHandlingConfig extends ResourceConfig { + + public ExceptionHandlingConfig() { + packages("com.baeldung.jersey.exceptionhandling.rest"); + register(IllegalArgumentExceptionMapper.class); + register(ServerExceptionMapper.class); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java new file mode 100644 index 0000000000..9a3f321651 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java @@ -0,0 +1,33 @@ +package com.baeldung.jersey.exceptionhandling.data; + +import com.baeldung.jersey.exceptionhandling.repo.Identifiable; + +public class Stock implements Identifiable { + private static final long serialVersionUID = 1L; + private String id; + private Double price; + + public Stock() { + } + + public Stock(String id, Double price) { + this.id = id; + this.price = price; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java new file mode 100644 index 0000000000..8ef47b4c99 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java @@ -0,0 +1,51 @@ +package com.baeldung.jersey.exceptionhandling.data; + +import com.baeldung.jersey.exceptionhandling.repo.Identifiable; + +public class Wallet implements Identifiable { + private static final long serialVersionUID = 1L; + + public static final Double MIN_CHARGE = 50.0; + public static final String MIN_CHARGE_MSG = "minimum charge is: " + MIN_CHARGE; + + private String id; + private Double balance = 0.0; + + public Wallet() { + } + + public Wallet(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Double getBalance() { + return balance; + } + + public void setBalance(Double balance) { + this.balance = balance; + } + + public Double addBalance(Double amount) { + if (balance == null) + balance = 0.0; + + return balance += amount; + } + + public boolean hasFunds(Double amount) { + if (balance == null || amount == null) { + return false; + } + + return (balance - amount) >= 0; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java new file mode 100644 index 0000000000..c91085f25b --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java @@ -0,0 +1,32 @@ +package com.baeldung.jersey.exceptionhandling.repo; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +public class Db { + private Map db = new HashMap<>(); + + public Optional findById(String id) { + return Optional.ofNullable(db.get(id)); + } + + public String save(T t) { + String id = t.getId(); + if (id == null) { + id = UUID.randomUUID() + .toString(); + t.setId(id); + } + db.put(id, t); + return id; + } + + public void remove(T t) { + db.entrySet() + .removeIf(entry -> entry.getValue() + .getId() + .equals(t.getId())); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java new file mode 100644 index 0000000000..11af44bcc5 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java @@ -0,0 +1,17 @@ +package com.baeldung.jersey.exceptionhandling.repo; + +import java.io.Serializable; + +public interface Identifiable extends Serializable { + void setId(String id); + + String getId(); + + public static void assertValid(Identifiable i) { + if (i == null) + throw new IllegalArgumentException("object cannot be null"); + + if (i.getId() == null) + throw new IllegalArgumentException("object id cannot be null"); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java new file mode 100644 index 0000000000..94ce329ad0 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java @@ -0,0 +1,42 @@ +package com.baeldung.jersey.exceptionhandling.rest; + +import java.util.Optional; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import com.baeldung.jersey.exceptionhandling.data.Stock; +import com.baeldung.jersey.exceptionhandling.repo.Db; +import com.baeldung.jersey.exceptionhandling.service.Repository; + +@Path("/stocks") +public class StocksResource { + private static final Db stocks = Repository.STOCKS_DB; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response post(Stock stock) { + stocks.save(stock); + + return Response.ok(stock) + .build(); + } + + @GET + @Path("/{ticker}") + @Produces(MediaType.APPLICATION_JSON) + public Response get(@PathParam("ticker") String id) { + Optional stock = stocks.findById(id); + stock.orElseThrow(IllegalArgumentException::new); + + return Response.ok(stock.get()) + .build(); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java new file mode 100644 index 0000000000..e5f8ddec06 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java @@ -0,0 +1,98 @@ +package com.baeldung.jersey.exceptionhandling.rest; + +import java.util.Optional; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import com.baeldung.jersey.exceptionhandling.data.Stock; +import com.baeldung.jersey.exceptionhandling.data.Wallet; +import com.baeldung.jersey.exceptionhandling.repo.Db; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.InvalidTradeException; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; +import com.baeldung.jersey.exceptionhandling.service.Repository; + +@Path("/wallets") +public class WalletsResource { + private static final Db stocks = Repository.STOCKS_DB; + private static final Db wallets = Repository.WALLETS_DB; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response post(Wallet wallet) { + wallets.save(wallet); + + return Response.ok(wallet) + .build(); + } + + @GET + @Path("/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response get(@PathParam("id") String id) { + Optional wallet = wallets.findById(id); + wallet.orElseThrow(IllegalArgumentException::new); + + return Response.ok(wallet.get()) + .build(); + } + + @PUT + @Path("/{id}/{amount}") + @Produces(MediaType.APPLICATION_JSON) + public Response putAmount(@PathParam("id") String id, @PathParam("amount") Double amount) { + Optional wallet = wallets.findById(id); + wallet.orElseThrow(IllegalArgumentException::new); + + if (amount < Wallet.MIN_CHARGE) { + throw new InvalidTradeException(Wallet.MIN_CHARGE_MSG); + } + + wallet.get() + .addBalance(amount); + wallets.save(wallet.get()); + + return Response.ok(wallet) + .build(); + } + + @POST + @Path("/{wallet}/buy/{ticker}") + @Produces(MediaType.APPLICATION_JSON) + public Response postBuyStock(@PathParam("wallet") String walletId, @PathParam("ticker") String id) { + Optional stock = stocks.findById(id); + stock.orElseThrow(InvalidTradeException::new); + + Optional w = wallets.findById(walletId); + w.orElseThrow(InvalidTradeException::new); + + Wallet wallet = w.get(); + Double price = stock.get() + .getPrice(); + + if (!wallet.hasFunds(price)) { + RestErrorResponse response = new RestErrorResponse(); + response.setSubject(wallet); + response.setMessage("insufficient balance"); + throw new WebApplicationException(Response.status(Status.NOT_ACCEPTABLE) + .entity(response) + .build()); + } + + wallet.addBalance(-price); + wallets.save(wallet); + + return Response.ok(wallet) + .build(); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java new file mode 100644 index 0000000000..b577121027 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java @@ -0,0 +1,23 @@ +package com.baeldung.jersey.exceptionhandling.rest.exceptions; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +public class IllegalArgumentExceptionMapper implements ExceptionMapper { + public static final String DEFAULT_MESSAGE = "an illegal argument was provided"; + + @Override + public Response toResponse(final IllegalArgumentException exception) { + return Response.status(Response.Status.EXPECTATION_FAILED) + .entity(build(exception.getMessage())) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + private RestErrorResponse build(String message) { + RestErrorResponse response = new RestErrorResponse(); + response.setMessage(DEFAULT_MESSAGE + ": " + message); + return response; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java new file mode 100644 index 0000000000..11277c048a --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java @@ -0,0 +1,17 @@ +package com.baeldung.jersey.exceptionhandling.rest.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class InvalidTradeException extends WebApplicationException { + private static final long serialVersionUID = 1L; + private static final String MESSAGE = "invalid trade operation"; + + public InvalidTradeException() { + super(MESSAGE, Response.Status.NOT_ACCEPTABLE); + } + + public InvalidTradeException(String detail) { + super(MESSAGE + ": " + detail, Response.Status.NOT_ACCEPTABLE); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java new file mode 100644 index 0000000000..dd193ab059 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java @@ -0,0 +1,34 @@ +package com.baeldung.jersey.exceptionhandling.rest.exceptions; + +public class RestErrorResponse { + private Object subject; + private String message; + + public RestErrorResponse() { + } + + public RestErrorResponse(String message) { + this.message = message; + } + + public RestErrorResponse(Object subject, String message) { + this.subject = subject; + this.message = message; + } + + public Object getSubject() { + return subject; + } + + public void setSubject(Object subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java new file mode 100644 index 0000000000..a6e9cc7f39 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java @@ -0,0 +1,35 @@ +package com.baeldung.jersey.exceptionhandling.rest.exceptions; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; + +public class ServerExceptionMapper implements ExceptionMapper { + public static final String HTTP_405_MESSAGE = "METHOD_NOT_ALLOWED"; + + @Override + public Response toResponse(final WebApplicationException exception) { + String message = exception.getMessage(); + Response response = exception.getResponse(); + Status status = response.getStatusInfo() + .toEnum(); + + switch (status) { + case METHOD_NOT_ALLOWED: + message = HTTP_405_MESSAGE; + break; + case INTERNAL_SERVER_ERROR: + message = "internal validation - " + exception; + break; + default: + message = "[unhandled response code] " + exception; + } + + return Response.status(status) + .entity(status + ": " + message) + .type(MediaType.TEXT_PLAIN) + .build(); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java new file mode 100644 index 0000000000..459b062068 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java @@ -0,0 +1,10 @@ +package com.baeldung.jersey.exceptionhandling.service; + +import com.baeldung.jersey.exceptionhandling.data.Stock; +import com.baeldung.jersey.exceptionhandling.data.Wallet; +import com.baeldung.jersey.exceptionhandling.repo.Db; + +public class Repository { + public static Db STOCKS_DB = new Db<>(); + public static Db WALLETS_DB = new Db<>(); +} diff --git a/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java new file mode 100644 index 0000000000..1648116918 --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java @@ -0,0 +1,99 @@ +package com.baeldung.jersey.exceptionhandling.rest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; + +import com.baeldung.jersey.exceptionhandling.ExceptionHandlingConfig; +import com.baeldung.jersey.exceptionhandling.data.Stock; +import com.baeldung.jersey.exceptionhandling.data.Wallet; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; + +public class StocksResourceIntegrationTest extends JerseyTest { + private static final Entity EMPTY_BODY = Entity.json(""); + private static final Stock STOCK = new Stock("BAEL", 51.57); + private static final String MY_WALLET = "MY-WALLET"; + private static final Wallet WALLET = new Wallet(MY_WALLET); + private static final int INSUFFICIENT_AMOUNT = (int) (Wallet.MIN_CHARGE - 1); + + @Override + protected Application configure() { + return new ExceptionHandlingConfig(); + } + + private Invocation.Builder stocks(String path) { + return target("/stocks" + path).request(); + } + + private Invocation.Builder wallets(String path, Object... args) { + return target("/wallets" + String.format(path, args)).request(); + } + + private Entity entity(Object object) { + return Entity.entity(object, MediaType.APPLICATION_JSON_TYPE); + } + + @Test + public void whenMethodNotAllowed_thenCustomMessage() { + Response response = stocks("").get(); + + assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus()); + + String content = response.readEntity(String.class); + assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE)); + } + + @Test + public void whenTickerNotExists_thenRestErrorResponse() { + Response response = stocks("/UNDEFINED").get(); + + assertEquals(Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus()); + + RestErrorResponse content = response.readEntity(RestErrorResponse.class); + assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE)); + } + + @Test + public void givenAmountLessThanMinimum_whenAddingToWallet_thenInvalidTradeException() { + wallets("").post(entity(WALLET)); + Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY); + + assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); + + String content = response.readEntity(String.class); + assertThat(content, containsString(Wallet.MIN_CHARGE_MSG)); + } + + @Test + public void givenInsifficientFunds_whenBuyingStock_thenWebApplicationException() { + stocks("").post(entity(STOCK)); + wallets("").post(entity(WALLET)); + + Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY); + assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); + + RestErrorResponse content = response.readEntity(RestErrorResponse.class); + assertNotNull(content.getSubject()); + + HashMap subject = (HashMap) content.getSubject(); + assertEquals(subject.get("id"), WALLET.getId()); + assertTrue(WALLET.getBalance() < Wallet.MIN_CHARGE); + } +} From 55deea7849ea93a724c8941f235d30a425eefcdc Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Mon, 11 Apr 2022 19:16:04 +0100 Subject: [PATCH 14/40] [JAVA-11283] Use https link for short url --- httpclient-2/README.md | 2 +- .../httpclient/expandurl/HttpClientExpandUrlLiveTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/httpclient-2/README.md b/httpclient-2/README.md index 695a92ce00..571a45f207 100644 --- a/httpclient-2/README.md +++ b/httpclient-2/README.md @@ -12,5 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string) - [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies) - [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging) -- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/unshorten-url-httpclient) +- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url) - More articles: [[<-- prev]](../httpclient) diff --git a/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java index fb3d730ec4..5a8c87f4aa 100644 --- a/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java +++ b/httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java @@ -33,8 +33,8 @@ public class HttpClientExpandUrlLiveTest { @Test public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException { - final String expectedResult = "http://www.baeldung.com/rest-versioning"; - final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1"); + final String expectedResult = "https://www.baeldung.com/rest-versioning"; + final String actualResult = expandSingleLevel("http://bit.ly/3LScTri"); assertThat(actualResult, equalTo(expectedResult)); } From add090f2e1a4ccb73e9a434d985432cb94b30a9c Mon Sep 17 00:00:00 2001 From: sanitaso <98709855+sanitaso@users.noreply.github.com> Date: Tue, 12 Apr 2022 05:15:51 +0200 Subject: [PATCH 15/40] BAEL-5416 How to Store HashMap Inside a List (#12047) * add unit test * fix the error * correcting the name of the test * trigger build process --- .../ListOfHashMapsUnitTest.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java new file mode 100644 index 0000000000..39110aedd3 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listOfHashMaps/ListOfHashMapsUnitTest.java @@ -0,0 +1,36 @@ +package test.java.com.baeldung.list.listOfHashMaps; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +public class ListOfHashMapsUnitTest { + List>> booksAuthorsMapsList = new ArrayList<>(); + + @Test + public void givenMaps_whenAddToList_thenListContainsMaps() { + HashMap> javaBooksAuthorsMap = new HashMap<>(); + HashMap> phpBooksAuthorsMap = new HashMap<>(); + javaBooksAuthorsMap.put("Head First Java", Arrays.asList("Kathy Sierra", "Bert Bates")); + javaBooksAuthorsMap.put("Effective Java", Arrays.asList("Joshua Bloch")); + javaBooksAuthorsMap.put("OCA Java SE 8", + Arrays.asList("Kathy Sierra", "Bert Bates", "Elisabeth Robson")); + phpBooksAuthorsMap.put("The Joy of PHP", Arrays.asList("Alan Forbes")); + phpBooksAuthorsMap.put("Head First PHP & MySQL", + Arrays.asList("Lynn Beighley", "Michael Morrison")); + + booksAuthorsMapsList.add(javaBooksAuthorsMap); + booksAuthorsMapsList.add(phpBooksAuthorsMap); + + assertTrue(booksAuthorsMapsList.get(0).keySet().containsAll + (javaBooksAuthorsMap.keySet().stream().collect(Collectors.toList()))); + assertTrue(booksAuthorsMapsList.get(1).keySet().containsAll + (phpBooksAuthorsMap.keySet().stream().collect(Collectors.toList()))); + } +} From f16bd2b949882a63acf4607ace610054b6e6dcc5 Mon Sep 17 00:00:00 2001 From: opokharel <66694687+opokharel@users.noreply.github.com> Date: Mon, 11 Apr 2022 21:17:54 -0600 Subject: [PATCH 16/40] [BAEL-5518] Create Array of Regex Matches (#12052) * opokharel's code for "A quick and practical example of Hexagonal Architecture in Java" * opokharel - added unit Tests * [BAEL-5518] by @opokharel * updated Files * updated formatting * whitespaceFix * [BAEL-5518] Create Array of Regex Matches * reCreatingPR --- .../src/regex/array/RegexMatches.java | 24 ++++++++++++++ .../regex/array/RegexMatchesUnitTest.java | 33 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 regexMatchesToArray/src/regex/array/RegexMatches.java create mode 100644 regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java diff --git a/regexMatchesToArray/src/regex/array/RegexMatches.java b/regexMatchesToArray/src/regex/array/RegexMatches.java new file mode 100644 index 0000000000..d7b50d95ca --- /dev/null +++ b/regexMatchesToArray/src/regex/array/RegexMatches.java @@ -0,0 +1,24 @@ +package regex.array; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.*; + +class RegexMatches { + + String[] regexMatch(String strSearch) + { + List matchesList = new ArrayList(); + String stringToSearch = strSearch; + Pattern p1 = Pattern.compile("780{1}\\d{7}"); + Matcher m1 = p1.matcher(stringToSearch); + while (m1.find()) + { + matchesList.add(m1.group()); + } + int sizeOfNewArray = matchesList.size(); + String newArrayOfMatches[] = new String[sizeOfNewArray]; + matchesList.toArray(newArrayOfMatches); + return newArrayOfMatches; + } +} diff --git a/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java b/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java new file mode 100644 index 0000000000..3e8f23c4bb --- /dev/null +++ b/regexMatchesToArray/test/regex/array/RegexMatchesUnitTest.java @@ -0,0 +1,33 @@ +package regex.array; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import regex.array.RegexMatches; + +class RegexMatchesUnitTest { + + @Test + void whenFourNums_thenFourMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 7802222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7802222222", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenThreeNums_thenThreeMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 780222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenZeroNums_thenZeroMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("78011111fsdafasdfa 780222222 sadfsadfsda78033333 sadfdasfasd 7804444"); + + assertArrayEquals(new String[] {}, actual, "success"); + } +} From 3c2b8bb1f13acdc56e605b8e099677b965e0a2c4 Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Tue, 12 Apr 2022 16:39:47 +0800 Subject: [PATCH 17/40] BAEL-1699 - modify code comment typo --- .../baeldung-agent/com/baeldung/agent/LoadTimeAgent.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java index a2ec9c3d4a..33d9a231ea 100644 --- a/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java +++ b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.reflective.access/baeldung-agent/com/baeldung/agent/LoadTimeAgent.java @@ -60,7 +60,7 @@ public class LoadTimeAgent { // prepare extra uses Set> extraUses = Collections.emptySet(); - // prepare extra uses + // prepare extra provides Map, List>> extraProvides = Collections.emptyMap(); // redefine module From 35fd43e5778330c0d148606065bf28f91c75a880 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 12 Apr 2022 20:43:57 +0530 Subject: [PATCH 18/40] JAVA-10625: Remove module immutables --- immutables/README.md | 6 ---- immutables/pom.xml | 34 ------------------- immutables/src/main/resources/logback.xml | 13 ------- libraries-3/README.md | 1 + libraries-3/pom.xml | 13 +++++++ .../java/com/baeldung/immutable/Address.java | 0 .../java/com/baeldung/immutable/Person.java | 0 .../baeldung/immutable/auxiliary/Person.java | 0 .../baeldung/immutable/default_/Person.java | 0 .../baeldung/immutable/parameter/Person.java | 0 .../baeldung/immutable/prehash/Person.java | 0 .../immutable/ImmutablePersonUnitTest.java | 0 .../ImmutablePersonAuxiliaryUnitTest.java | 0 .../ImmutablePersonDefaultUnitTest.java | 0 14 files changed, 14 insertions(+), 53 deletions(-) delete mode 100644 immutables/README.md delete mode 100644 immutables/pom.xml delete mode 100644 immutables/src/main/resources/logback.xml rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/Address.java (100%) rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/Person.java (100%) rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/auxiliary/Person.java (100%) rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/default_/Person.java (100%) rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/parameter/Person.java (100%) rename {immutables => libraries-3}/src/main/java/com/baeldung/immutable/prehash/Person.java (100%) rename {immutables => libraries-3}/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java (100%) rename {immutables => libraries-3}/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java (100%) rename {immutables => libraries-3}/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java (100%) diff --git a/immutables/README.md b/immutables/README.md deleted file mode 100644 index a93a342f9c..0000000000 --- a/immutables/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Immutables - -This module contains articles about the Immutables library. - -### Relevant Articles: -- [Introduction to Immutables](https://www.baeldung.com/immutables) diff --git a/immutables/pom.xml b/immutables/pom.xml deleted file mode 100644 index 7704cddbb6..0000000000 --- a/immutables/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - immutables - immutables - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.immutables - value - ${immutables.version} - - - org.mutabilitydetector - MutabilityDetector - ${mutabilitydetector.version} - test - - - - - 2.5.6 - 0.9.6 - - - \ No newline at end of file diff --git a/immutables/src/main/resources/logback.xml b/immutables/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/immutables/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/libraries-3/README.md b/libraries-3/README.md index 047d6738a1..b267e82ed9 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -17,4 +17,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) - [Introduction to Structurizr](https://www.baeldung.com/structurizr) +- [Introduction to Immutables](https://www.baeldung.com/immutables) - More articles [[<-- prev]](../libraries-2) [[next -->]](../libraries-4) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index e38aecd879..c51b264e83 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -112,6 +112,17 @@ structurizr-plantuml ${structurizr.version} + + org.immutables + value + ${immutables.version} + + + org.mutabilitydetector + MutabilityDetector + ${mutabilitydetector.version} + test + @@ -256,6 +267,8 @@ 2.8 2.1.3 1.0.0 + 2.5.6 + 0.9.6 \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/Address.java b/libraries-3/src/main/java/com/baeldung/immutable/Address.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/Address.java rename to libraries-3/src/main/java/com/baeldung/immutable/Address.java diff --git a/immutables/src/main/java/com/baeldung/immutable/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/auxiliary/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/auxiliary/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/default_/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/default_/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/default_/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/default_/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/parameter/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/parameter/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/parameter/Person.java diff --git a/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java b/libraries-3/src/main/java/com/baeldung/immutable/prehash/Person.java similarity index 100% rename from immutables/src/main/java/com/baeldung/immutable/prehash/Person.java rename to libraries-3/src/main/java/com/baeldung/immutable/prehash/Person.java diff --git a/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java diff --git a/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryUnitTest.java diff --git a/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java similarity index 100% rename from immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java rename to libraries-3/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultUnitTest.java From 230992c2a0788f8366769d854cb8cbf5dd1ab1cc Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 12 Apr 2022 20:44:42 +0530 Subject: [PATCH 19/40] remove immutables from main pom --- pom.xml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 441cf0e580..21589f5525 100644 --- a/pom.xml +++ b/pom.xml @@ -432,8 +432,6 @@ httpclient-simple hystrix - immutables - jackson-modules jackson-simple java-blockchain @@ -916,9 +914,7 @@ helidon httpclient httpclient-simple - hystrix - - immutables + hystrix jackson-modules jackson-simple From 266c908abf3a22a2d987b15dfe9820216b94f88b Mon Sep 17 00:00:00 2001 From: opokharel <66694687+opokharel@users.noreply.github.com> Date: Tue, 12 Apr 2022 18:25:50 -0600 Subject: [PATCH 20/40] new PR to replace PR# 12052 by @opokharel (#12054) * opokharel's code for "A quick and practical example of Hexagonal Architecture in Java" * opokharel - added unit Tests * [BAEL-5518] by @opokharel * updated Files * updated formatting * whitespaceFix * [BAEL-5518] Create Array of Regex Matches * reCreatingPR * new PR to replace PR# 12052 * moving to new locn --- .../src/regex/array/RegexMatches.java | 24 ++++++++++++++ .../regex/array/RegexMatchesUnitTest.java | 33 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java create mode 100644 core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java diff --git a/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java b/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java new file mode 100644 index 0000000000..d7b50d95ca --- /dev/null +++ b/core-java-modules/core-java-regex-2/regexMatchToArray/src/regex/array/RegexMatches.java @@ -0,0 +1,24 @@ +package regex.array; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.*; + +class RegexMatches { + + String[] regexMatch(String strSearch) + { + List matchesList = new ArrayList(); + String stringToSearch = strSearch; + Pattern p1 = Pattern.compile("780{1}\\d{7}"); + Matcher m1 = p1.matcher(stringToSearch); + while (m1.find()) + { + matchesList.add(m1.group()); + } + int sizeOfNewArray = matchesList.size(); + String newArrayOfMatches[] = new String[sizeOfNewArray]; + matchesList.toArray(newArrayOfMatches); + return newArrayOfMatches; + } +} diff --git a/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java b/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java new file mode 100644 index 0000000000..3e8f23c4bb --- /dev/null +++ b/core-java-modules/core-java-regex-2/regexMatchToArray/test/regex/array/RegexMatchesUnitTest.java @@ -0,0 +1,33 @@ +package regex.array; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +import regex.array.RegexMatches; + +class RegexMatchesUnitTest { + + @Test + void whenFourNums_thenFourMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 7802222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7802222222", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenThreeNums_thenThreeMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("7801111211fsdafasdfa 780222222 sadfsadfsda7803333333 sadfdasfasd 7804444444"); + + assertArrayEquals(new String[] {"7801111211", "7803333333", "7804444444"}, actual, "success"); + } + + @Test + void whenZeroNums_thenZeroMatches() { + RegexMatches rm = new RegexMatches(); + String actual[] = rm.regexMatch("78011111fsdafasdfa 780222222 sadfsadfsda78033333 sadfdasfasd 7804444"); + + assertArrayEquals(new String[] {}, actual, "success"); + } +} From 2c72a1e42cd4a2947a5cde2433bf2e2ce01c334b Mon Sep 17 00:00:00 2001 From: Kapil Khandelwal Date: Wed, 13 Apr 2022 05:56:26 +0530 Subject: [PATCH 21/40] BAEL-5369: Checking Connection to MongoDB (#12057) --- .../com/baeldung/mongo/ConnectionCheck.java | 46 ++++++++++++++++++ .../mongo/ConnectionCheckLiveTest.java | 47 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java create mode 100644 persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java diff --git a/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java new file mode 100644 index 0000000000..240e54ab99 --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/ConnectionCheck.java @@ -0,0 +1,46 @@ +package com.baeldung; + +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.ServerAddress; + +public class ConnectionCheck { + + public static void checkingConnection() { + + MongoClientOptions.Builder builder = MongoClientOptions.builder(); + + builder.connectionsPerHost(100); + builder.maxWaitTime(60000); + builder.connectTimeout(1500); + builder.socketTimeout(60000); + builder.socketKeepAlive(true); + + ServerAddress ServerAddress = new ServerAddress("localhost", 27017); + MongoClient mongoClient = new MongoClient(ServerAddress, builder.build()); + + try { + System.out.println("MongoDB Server is Up:- " + mongoClient.getAddress()); + DB db = mongoClient.getDB("baeldung"); + System.out.println(mongoClient.getConnectPoint()); + System.out.println(db.getStats()); + } catch (Exception e) { + System.out.println("MongoDB Server is Down"); + mongoClient.close(); + } + + } + + public static void main(String[] args) { + + // + // Connection check + // + + checkingConnection(); + + } + +} + diff --git a/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java new file mode 100644 index 0000000000..69f356997c --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/ConnectionCheckLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.mongo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.ServerAddress; + +public class ConnectionCheckLiveTest { + + private static MongoClient mongoClient; + private static MongoClientOptions.Builder builder; + private static ServerAddress ServerAddress; + + @BeforeClass + public static void setup() throws IOException { + if (mongoClient == null) { + + builder = MongoClientOptions.builder(); + builder.connectionsPerHost(100); + builder.maxWaitTime(60000); + builder.connectTimeout(1500); + builder.socketTimeout(60000); + builder.socketKeepAlive(true); + + ServerAddress = new ServerAddress("localhost", 27017); + mongoClient = new MongoClient(ServerAddress, builder.build()); + + } + } + + @Test + public void givenMongoClient_whenConnectionCheck_thenCheckingForConnectionPoint() { + + String connectionPoint = mongoClient.getConnectPoint(); + assertNotNull(connectionPoint); + assertFalse(connectionPoint.isEmpty()); + + } +} + From 1a5990f62da892c57d6f0df84a54926588b5c016 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 05:43:12 +0500 Subject: [PATCH 22/40] Updated README.md added link back o the article: https://www.baeldung.com/jmeter-basic-auth --- jmeter/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter/README.md b/jmeter/README.md index 6fdc79a2ce..23614307bd 100644 --- a/jmeter/README.md +++ b/jmeter/README.md @@ -53,3 +53,4 @@ Enjoy it :) - [Intro to Performance Testing using JMeter](https://www.baeldung.com/jmeter) - [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter) - [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file) +- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth) From 396db57d4e9e11e76f70211158c211200453d24d Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 05:49:40 +0500 Subject: [PATCH 23/40] Updated README.md added link back to the article: https://www.baeldung.com/spring-singleton-concurrent-requests --- spring-core-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-5/README.md b/spring-core-5/README.md index b6c9ba606a..ebf62ac24f 100644 --- a/spring-core-5/README.md +++ b/spring-core-5/README.md @@ -10,4 +10,5 @@ This module contains articles about core Spring functionality. - [AliasFor Annotation in Spring](https://www.baeldung.com/spring-aliasfor-annotation) - [A Quick Guide to the Spring @Lazy Annotation](https://www.baeldung.com/spring-lazy-annotation) - [Finding the Spring Version](https://www.baeldung.com/spring-find-version) +- [How Does the Spring Singleton Bean Serve Concurrent Requests?](https://www.baeldung.com/spring-singleton-concurrent-requests) - More articles: [[<-- prev]](../spring-core-4) From a8fca31d661a326aacd93562357eaabffd661a33 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 05:54:09 +0500 Subject: [PATCH 24/40] Updated README.md added link back to the article: https://www.baeldung.com/jpa-bootstrap-mode --- spring-boot-modules/spring-boot-data-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index c01c54e29e..fd9d034f8a 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -5,3 +5,4 @@ - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) +- [BootstrapMode for JPA Repositories](https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-data-2) From 789dc0d8fcac942763c0bd86a56de1782d23cbdb Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 05:57:21 +0500 Subject: [PATCH 25/40] Updated README.md added link back to the article: https://www.baeldung.com/java-human-readable-byte-size --- java-numbers-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-numbers-4/README.md b/java-numbers-4/README.md index a6d866218c..95d46203ab 100644 --- a/java-numbers-4/README.md +++ b/java-numbers-4/README.md @@ -5,3 +5,4 @@ - [Determine if an Integer’s Square Root Is an Integer in Java](https://www.baeldung.com/java-find-if-square-root-is-integer) - [Guide to Java BigInteger](https://www.baeldung.com/java-biginteger) - [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers) +- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size) From d7fdaaf92fcabb6f6ed2b84a4ca8c20369c85c93 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 09:47:32 +0500 Subject: [PATCH 26/40] Updated README.md added link back to the article: https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient --- httpclient-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/httpclient-2/README.md b/httpclient-2/README.md index 571a45f207..2e101a0609 100644 --- a/httpclient-2/README.md +++ b/httpclient-2/README.md @@ -13,4 +13,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies) - [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging) - [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url) +- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient) - More articles: [[<-- prev]](../httpclient) From 9f8d01175b9e54321f4d3079829ecf21fadf37a3 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 09:50:50 +0500 Subject: [PATCH 27/40] Updated README.md added link back to the article: https://www.baeldung.com/mongodb-return-specific-fields --- persistence-modules/spring-boot-persistence-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 91dd8718e1..6659e82677 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -8,3 +8,4 @@ - [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) - [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb) - [Logging MongoDB Queries with Spring Boot](https://www.baeldung.com/spring-boot-mongodb-logging) +- [Return Only Specific Fields for a Query in Spring Data MongoDB](https://www.baeldung.com/mongodb-return-specific-fields) From 1e519eb47efeb6f011f900b91920b71457b59225 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 09:53:15 +0500 Subject: [PATCH 28/40] Updated README.md added link back to the article: https://www.baeldung.com/java-hql-distinct --- persistence-modules/hibernate-queries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md index f1bc1cba0f..ac52e73abf 100644 --- a/persistence-modules/hibernate-queries/README.md +++ b/persistence-modules/hibernate-queries/README.md @@ -10,3 +10,4 @@ This module contains articles about use of Queries in Hibernate. - [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) - [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar) +- [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct) From 96a62ee2de9c945cef2473e6cfd8cb6fc7afe592 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 09:56:02 +0500 Subject: [PATCH 29/40] Updated README.md added link back to the article: https://www.baeldung.com/java-illegal-reflective-access --- core-java-modules/core-java-9-jigsaw/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md index b1a401d48c..cfffb86588 100644 --- a/core-java-modules/core-java-9-jigsaw/README.md +++ b/core-java-modules/core-java-9-jigsaw/README.md @@ -7,5 +7,6 @@ This module contains articles about Project Jigsaw and the Java Platform Module - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) - [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) +- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access) From 598d0e41ab9cd6842f2f9b23ecb69ab01a630ddd Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Wed, 13 Apr 2022 16:22:00 +0500 Subject: [PATCH 30/40] Updated README.md added link back to the article: https://www.baeldung.com/spring-swagger-hide-field --- spring-boot-modules/spring-boot-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 5e9ecded10..cdb2bd0fce 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -11,4 +11,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) +- [Hide a Request Field in Swagger API](https://www.baeldung.com/spring-swagger-hide-field) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) From 2b68a32cb7552dafa0184f33c451abfddd067307 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 14 Apr 2022 10:31:13 +0100 Subject: [PATCH 31/40] [JAVA-11197] Fix graphql-java Application class --- graphql/graphql-java/pom.xml | 105 +++++++++--------- .../baeldung/graphql/handler/UserHandler.java | 19 ++-- 2 files changed, 66 insertions(+), 58 deletions(-) diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index f2733bf671..5808dd17fb 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../../ + ../../pom.xml @@ -36,51 +36,15 @@ graphql-java-annotations ${graphql-java-annotations.version} - - io.ratpack - ratpack-core - ${ratpack-core.version} - - - com.github.americanexpress.nodes - nodes - 0.5.0 - - - com.graphql-java - graphql-java - 9.2 - com.graphql-java graphql-java-tools - 5.2.4 + ${graphql-java-tools.version} com.graphql-java graphql-java-servlet - 6.1.3 - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - org.apache.commons - commons-lang3 - 3.12.0 - - - org.mock-server - mockserver-netty - 5.11.2 - - - org.mock-server - mockserver-client-java - 5.11.2 + ${graphql-java-servlet.version} com.graphql-java-generator @@ -88,15 +52,47 @@ ${graphql.java.generator.version} - org.junit.jupiter - junit-jupiter-engine - 5.8.2 + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + io.ratpack + ratpack-core + ${ratpack-core.version} + + + com.github.americanexpress.nodes + nodes + ${nodes.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + org.mock-server + mockserver-netty + ${mockserver-netty.version} test - org.assertj - assertj-core - 3.22.0 + org.mock-server + mockserver-client-java + ${mockserver-client-java.version} test @@ -115,11 +111,11 @@ org.eclipse.jetty jetty-maven-plugin - 10.0.7 + ${jetty-maven-plugin.version} maven-war-plugin - 3.1.0 + ${maven-war-plugin.version} com.graphql-java-generator @@ -143,12 +139,21 @@ + 5.2.4 + 6.1.3 3.0.3 - 1.4.6 - 3.1 + 1.18 + 1.9.0 + 0.5.0 + 4.5.13 + + 5.13.2 + 5.13.2 + + 10.0.7 + 1.8 1.8 - 1.18 \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java index a6d474a70d..eb7cf021c6 100644 --- a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java @@ -19,24 +19,27 @@ import com.baeldung.graphql.utils.SchemaUtils; import static ratpack.jackson.Jackson.json; public class UserHandler implements Handler { + private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); - private GraphQL graphql; - private static List users = new ArrayList<>(); + + private static final List USERS = new ArrayList<>(); + + private final GraphQL graphql; public UserHandler() throws Exception { - graphql = new GraphQL(new UserSchema().getSchema()); + graphql = GraphQL.newGraphQL(new UserSchema().getSchema()).build(); } @Override - public void handle(Context context) throws Exception { + public void handle(Context context) { context.parse(Map.class) .then(payload -> { Map parameters = (Map) payload.get("parameters"); ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) .toString(), null, this, parameters); + Map result = new LinkedHashMap<>(); - if (executionResult.getErrors() - .isEmpty()) { + if (executionResult.getErrors().isEmpty()) { result.put(SchemaUtils.DATA, executionResult.getData()); } else { result.put(SchemaUtils.ERRORS, executionResult.getErrors()); @@ -46,8 +49,8 @@ public class UserHandler implements Handler { }); } - public static List getUsers() { - return users; + public List getUsers() { + return USERS; } public static List getUsers(DataFetchingEnvironment env) { From 0c480dbeedaf1f43660165fde4c517858b022ca5 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 14 Apr 2022 21:10:20 +0100 Subject: [PATCH 32/40] [JAVA-11252] Fix Mongodb live test --- .../bsontojson/BsonToJsonLiveTest.java | 70 +++++++++---------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java index 12053523f8..0548119d7a 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -21,7 +21,7 @@ import dev.morphia.Datastore; import dev.morphia.Morphia; public class BsonToJsonLiveTest { - + private static final String DB_NAME = "library"; private static Datastore datastore; @@ -31,17 +31,17 @@ public class BsonToJsonLiveTest { morphia.mapPackage("com.baeldung.bsontojson"); datastore = morphia.createDatastore(new MongoClient(), DB_NAME); datastore.ensureIndexes(); - + datastore.save(new Book() .setIsbn("isbn") .setTitle("title") .setAuthor("author") .setCost(3.95) .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) - .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .setPublishDate(LocalDateTime.parse("2020-01-01T17:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) .addCompanionBooks(new Book().setIsbn("isbn2"))); } - + @AfterClass public static void tearDown() { datastore.delete(datastore.createQuery(Book.class)); @@ -50,32 +50,32 @@ public class BsonToJsonLiveTest { @Test public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { - String json = null; + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); json = bson.toJson(); } - - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": 1577898812000}}"; assertNotNull(json); - + assertEquals(expectedJson, json); } - + @Test public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { - - String json = null; + + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); @@ -84,25 +84,25 @@ public class BsonToJsonLiveTest { .outputMode(JsonMode.RELAXED) .build()); } - - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; assertNotNull(json); - + assertEquals(expectedJson, json); } - + @Test public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { - String json = null; + String json; try (MongoClient mongoClient = new MongoClient()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); @@ -112,13 +112,13 @@ public class BsonToJsonLiveTest { .build()); } - String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + - "\"title\": \"title\", " + - "\"author\": \"author\", " + - "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + - "\"price\": 3.95, " + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; assertEquals(expectedJson, json); From 3045fea67032979d3da1a7ce868d2dddad898417 Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Fri, 15 Apr 2022 02:11:00 +0530 Subject: [PATCH 33/40] BAEL-5419: List vs ArrayList in Java + tests (#11936) * BAEL-5419: List vs ArrayList in Java + tests * BAEL-5419: Updated code +tests as per review comments * BAEL-5419: Fixed failing tests * BAEL-5419: Fixed JUnit test as per review comments --- .../list/listvsarraylist/ArrayListDemo.java | 51 ++++++++++ .../list/listvsarraylist/ListDemo.java | 53 +++++++++++ .../list/listvsarraylist/Passenger.java | 49 ++++++++++ .../ArrayListDemoUnitTest.java | 91 ++++++++++++++++++ .../listvsarraylist/ListDemoUnitTest.java | 92 +++++++++++++++++++ 5 files changed, 336 insertions(+) create mode 100644 core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java create mode 100644 core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java create mode 100644 core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java create mode 100644 core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java create mode 100644 core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java new file mode 100644 index 0000000000..f425f19189 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ArrayListDemo.java @@ -0,0 +1,51 @@ +package com.baeldung.list.listvsarraylist; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ArrayListDemo { + + private ArrayList passengers = new ArrayList<>(20); +// private LinkedList passengers = new LinkedList<>(); // compile time error + + public ArrayList addPassenger(Passenger passenger) { + passengers.add(passenger); + return passengers; + } + + public ArrayList removePassenger(Passenger passenger) { + passengers.remove(passenger); + return passengers; + } + + public ArrayList getPassengersBySource(String source) { + return new ArrayList(passengers.stream() + .filter(it -> it.getSource().equals(source)) + .collect(Collectors.toList())); + } + + public ArrayList getPassengersByDestination(String destination) { + return new ArrayList (passengers.stream() + .filter(it -> it.getDestination().equals(destination)) + .collect(Collectors.toList())); + } + + public long getKidsCount(ArrayList passengerList) { + return passengerList.stream() + .filter(it -> (it.getAge() <= 10)) + .count(); + } + + public ArrayList getFinalPassengersList() { + return new ArrayList (Collections.unmodifiableList(passengers)); + } + + public ArrayList getServicedCountries() { + return new ArrayList (Stream.of(Locale.getISOCountries()) + .collect(Collectors.toList())); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java new file mode 100644 index 0000000000..a9a182d21e --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/ListDemo.java @@ -0,0 +1,53 @@ +package com.baeldung.list.listvsarraylist; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ListDemo { + + private List passengers = new ArrayList<>(20); +// private List passengers = new LinkedList<>(); // No compile time error + + public List addPassenger(Passenger passenger) { + passengers.add(passenger); + return passengers; + } + + public List removePassenger(Passenger passenger) { + passengers.remove(passenger); + return passengers; + } + + public List getPassengersBySource(String source) { + return passengers.stream() + .filter(it -> it.getSource().equals(source)) + .collect(Collectors.toList()); + } + + public List getPassengersByDestination(String destination) { + return passengers.stream() + .filter(it -> it.getDestination().equals(destination)) + .collect(Collectors.toList()); + } + + public long getKidsCount(List passengerList) { + return passengerList.stream() + .filter(it -> (it.getAge() <= 10)) + .count(); + } + + public List getFinalPassengersList() { + return Collections.unmodifiableList(passengers); + } + + public List getServicedCountries() { + return Stream.of(Locale.getISOCountries()) + .collect(Collectors.toList()); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java new file mode 100644 index 0000000000..9c61b70aa6 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/listvsarraylist/Passenger.java @@ -0,0 +1,49 @@ +package com.baeldung.list.listvsarraylist; + +public class Passenger { + + private String name; + private int age; + private String source; + private String destination; + + public Passenger(String name, int age, String source, String destination) { + this.name = name; + this.age = age; + this.source = source; + this.destination = destination; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getDestination() { + return destination; + } + + public void setDestination(String destination) { + this.destination = destination; + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java new file mode 100644 index 0000000000..59094ab562 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ArrayListDemoUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.list.listvsarraylist; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Locale; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ArrayListDemoUnitTest { + + ArrayListDemo application = new ArrayListDemo(); + + Passenger passenger1; + Passenger passenger2; + Passenger passenger3; + + @BeforeEach + protected void setUp() { + passenger1 = new Passenger("Anna", 25, "London", "New York"); + passenger2 = new Passenger("Binny", 35, "New York", "London"); + passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi"); + application.addPassenger(passenger1); + application.addPassenger(passenger2); + application.addPassenger(passenger3); + } + + @Test + public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() { + ArrayList list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris")); + + assertNotNull(list); + assertThat(list).hasSize(4); + } + + @Test + public void givenPassengerList_whenRemovedPassenger_thenReturnCurrentPassengerList() { + ArrayList list = application.removePassenger(passenger3); + + assertNotNull(list); + assertThat(list).hasSize(2); + } + + @Test + public void givenPassengerList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() { + ArrayList list = application.getPassengersBySource("Singapore"); + ArrayList list2 = application.getPassengersBySource("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger1); + } + + @Test + public void givenPassengerList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() { + ArrayList list = application.getPassengersByDestination("Singapore"); + ArrayList list2 = application.getPassengersByDestination("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger2); + } + + @Test + public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() { + ArrayList list = new ArrayList<>(); + list.add(passenger1); + list.add(passenger2); + list.add(passenger3); + long count = application.getKidsCount(list); + + assertThat(count).isEqualTo(1); + } + + @Test + public void givenPassengerList_whenCalledWithCollectionsFunction_thenReturnsListType() { + ArrayList list = application.getFinalPassengersList(); + + assertNotNull(list); + assertThat(list).hasSize(3); + } + + @Test + public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() { + ArrayList servicedCountries = application.getServicedCountries(); + + assertNotNull(servicedCountries); + assertThat(servicedCountries).hasSize(Locale.getISOCountries().length); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java new file mode 100644 index 0000000000..cf239a79ce --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/listvsarraylist/ListDemoUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.list.listvsarraylist; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ListDemoUnitTest { + + ListDemo application = new ListDemo(); + + Passenger passenger1; + Passenger passenger2; + Passenger passenger3; + + @BeforeEach + protected void setUp() { + passenger1 = new Passenger("Anna", 25, "London", "New York"); + passenger2 = new Passenger("Binny", 35, "New York", "London"); + passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi"); + application.addPassenger(passenger1); + application.addPassenger(passenger2); + application.addPassenger(passenger3); + } + + @Test + public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() { + List list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris")); + + assertNotNull(list); + assertThat(list).hasSize(4); + } + + @Test + public void givenPresentList_whenRemovedPassenger_thenReturnCurrentPassengerList() { + List list = application.removePassenger(passenger3); + + assertNotNull(list); + assertThat(list).hasSize(2); + } + + @Test + public void givenPresentList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() { + List list = application.getPassengersBySource("Singapore"); + List list2 = application.getPassengersBySource("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger1); + } + + @Test + public void givenPresentList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() { + List list = application.getPassengersByDestination("Singapore"); + List list2 = application.getPassengersByDestination("London"); + + assertThat(list).isEmpty(); + assertThat(list2.get(0)).isEqualTo(passenger2); + } + + @Test + public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() { + List list = new ArrayList<>(); + list.add(passenger1); + list.add(passenger2); + list.add(passenger3); + long count = application.getKidsCount(list); + + assertThat(count).isEqualTo(1); + } + + @Test + public void givenPresentList_whenCalledWithCollectionsFunction_thenReturnsListType() { + List list = application.getFinalPassengersList(); + + assertNotNull(list); + assertThat(list).hasSize(3); + } + + @Test + public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() { + List servicedCountries = application.getServicedCountries(); + + assertNotNull(servicedCountries); + assertThat(servicedCountries).hasSize(Locale.getISOCountries().length); + } + +} From 9f584fd32f397a6820d11333ecfbabab868494e2 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Fri, 15 Apr 2022 02:30:00 +0530 Subject: [PATCH 34/40] BAEL-5268 - Using Profiles with Discovery Clients (#11913) * BAEL-5268 - Using Profiles with Discovery Clients * BAEL-5268 - Adding separate property file for dev environment Co-authored-by: Abhinav Pandey --- .../pom.xml | 48 +++++++++++++++++++ .../client/EurekaClientApplication.java | 13 +++++ .../controller/HelloWorldController.java | 13 +++++ .../main/resources/application-dev.properties | 2 + .../src/main/resources/application.properties | 9 ++++ .../eureka/client/SpringContextTest.java | 16 +++++++ 6 files changed, 101 insertions(+) create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml new file mode 100644 index 0000000000..23e06a55f9 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + spring-cloud-eureka-client-profiles + 1.0.0-SNAPSHOT + spring-cloud-eureka-client-profiles + jar + Spring Cloud Eureka Sample Client + + + com.baeldung.spring.cloud + spring-cloud-eureka + 1.0.0-SNAPSHOT + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java new file mode 100644 index 0000000000..854bab97e7 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EurekaClientApplication { + + public static void main(String[] args) { + SpringApplication.run(EurekaClientApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java new file mode 100644 index 0000000000..d0d0a6ec9f --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/java/com/baeldung/spring/cloud/eureka/client/controller/HelloWorldController.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.eureka.client.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloWorldController { + + @RequestMapping("/hello") + public String hello() { + return "Hello World!"; + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties new file mode 100644 index 0000000000..c565e42678 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application-dev.properties @@ -0,0 +1,2 @@ +server.port=8080 +spring.cloud.discovery.enabled=false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties new file mode 100644 index 0000000000..3cfecbbf08 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8080 + +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka} +eureka.instance.preferIpAddress=false + +spring.application.name=spring-cloud-eureka-client +#--- +spring.config.activate.on-profile=dev +spring.cloud.discovery.enabled=false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..a3ed012abb --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client-profiles/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} From f12099f7dd1f27f65f39a1788f49975fdc5f795e Mon Sep 17 00:00:00 2001 From: nrsureshdeveloper <86210937+nrsureshdeveloper@users.noreply.github.com> Date: Fri, 15 Apr 2022 01:49:56 -0500 Subject: [PATCH 35/40] Bael-5306: graphql error handling (#12041) * Example implementation of Hexagonal Architecture pattern * BAEL-5306 - spring boot/graphql error handling example * removed the ddd hexagonal arch module Co-authored-by: Suresh Raghavan --- graphql/graphql-error-handling/pom.xml | 97 +++++++++++++++++++ .../GraphQLErrorHandlerApplication.java | 46 +++++++++ .../error/handling/domain/Location.java | 29 ++++++ .../error/handling/domain/Vehicle.java | 26 +++++ .../exception/AbstractGraphQLException.java | 44 +++++++++ .../exception/GraphQLErrorAdapter.java | 48 +++++++++ .../exception/InvalidInputException.java | 7 ++ .../VehicleAlreadyPresentException.java | 14 +++ .../exception/VehicleNotFoundException.java | 14 +++ .../repository/InventoryRepository.java | 9 ++ .../repository/LocationRepository.java | 9 ++ .../error/handling/resolver/Mutation.java | 20 ++++ .../error/handling/resolver/Query.java | 29 ++++++ .../handling/service/InventoryService.java | 67 +++++++++++++ .../src/main/resources/application.yml | 23 +++++ .../main/resources/graphql/inventory.graphqls | 23 +++++ .../src/main/resources/import.sql | 7 ++ ...rrorHandlerApplicationIntegrationTest.java | 55 +++++++++++ .../graphql/error/handling/TestUtils.java | 15 +++ ...t_non_null_fields_partial_response.graphql | 10 ++ ...quest_error_invalid_request_syntax.graphql | 9 ++ .../request_error_unknown_operation.graphql | 9 ++ ...uest_non_null_fields_partial_response.json | 34 +++++++ .../request_error_invalid_request_syntax.json | 18 ++++ .../request_error_unknown_operation.json | 18 ++++ .../src/test/resources/init_script.sql | 0 26 files changed, 680 insertions(+) create mode 100644 graphql/graphql-error-handling/pom.xml create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java create mode 100644 graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java create mode 100644 graphql/graphql-error-handling/src/main/resources/application.yml create mode 100644 graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls create mode 100644 graphql/graphql-error-handling/src/main/resources/import.sql create mode 100644 graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java create mode 100644 graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json create mode 100644 graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json create mode 100644 graphql/graphql-error-handling/src/test/resources/init_script.sql diff --git a/graphql/graphql-error-handling/pom.xml b/graphql/graphql-error-handling/pom.xml new file mode 100644 index 0000000000..0cd00df3b9 --- /dev/null +++ b/graphql/graphql-error-handling/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + com.baeldung.graphql + graphql-error-handling + 1.0 + jar + graphql-error-handling + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + 1.8 + 1.18.18 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.graphql-java + graphql-spring-boot-starter + 5.0.2 + + + + com.graphql-java + graphql-java-tools + 5.2.4 + + + + org.projectlombok + lombok + ${lombok.version} + + + + com.h2database + h2 + ${h2.version} + + + + org.springframework.boot + spring-boot-test + test + 2.6.4 + + + + com.graphql-java + graphql-spring-boot-starter-test + test + 5.0.2 + + + + org.assertj + assertj-core + 3.22.0 + test + + + + org.skyscreamer + jsonassert + 1.5.0 + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java new file mode 100644 index 0000000000..565c9e0a15 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplication.java @@ -0,0 +1,46 @@ +package com.baeldung.graphql.error.handling; + +import com.baeldung.graphql.error.handling.exception.GraphQLErrorAdapter; +import graphql.ExceptionWhileDataFetching; +import graphql.GraphQLError; +import graphql.servlet.GraphQLErrorHandler; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@SpringBootApplication +public class GraphQLErrorHandlerApplication { + public static void main(String[] args) { + SpringApplication.run(GraphQLErrorHandlerApplication.class, args); + } + + @Bean + public GraphQLErrorHandler errorHandler() { + return new GraphQLErrorHandler() { + @Override + public List processErrors(List errors) { + List clientErrors = errors.stream() + .filter(this::isClientError) + .collect(Collectors.toList()); + + List serverErrors = errors.stream() + .filter(e -> !isClientError(e)) + .map(GraphQLErrorAdapter::new) + .collect(Collectors.toList()); + + List e = new ArrayList<>(); + e.addAll(clientErrors); + e.addAll(serverErrors); + return e; + } + + private boolean isClientError(GraphQLError error) { + return !(error instanceof ExceptionWhileDataFetching || error instanceof Throwable); + } + }; + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java new file mode 100644 index 0000000000..815bf3a26a --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Location.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql.error.handling.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +@Data +@Entity +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Location { + @Id + private String zipcode; + + private String city; + private String state; + + @OneToMany(mappedBy = "location", fetch = FetchType.EAGER) + private List vehicles = new ArrayList<>(); +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java new file mode 100644 index 0000000000..e206bdb009 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/domain/Vehicle.java @@ -0,0 +1,26 @@ +package com.baeldung.graphql.error.handling.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@Entity +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Vehicle { + @Id + private String vin; + private Integer year; + private String make; + private String model; + private String trim; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "fk_location") + private Location location; +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java new file mode 100644 index 0000000000..4e7be50ae4 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/AbstractGraphQLException.java @@ -0,0 +1,44 @@ +package com.baeldung.graphql.error.handling.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbstractGraphQLException extends RuntimeException implements GraphQLError { + private Map parameters = new HashMap(); + + public AbstractGraphQLException(String message) { + super(message); + } + + public AbstractGraphQLException(String message, Map additionParams) { + this(message); + if (additionParams != null) { + parameters = additionParams; + } + } + + @Override + public String getMessage() { + return super.getMessage(); + } + + @Override + public List getLocations() { + return null; + } + + @Override + public ErrorType getErrorType() { + return null; + } + + @Override + public Map getExtensions() { + return this.parameters; + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java new file mode 100644 index 0000000000..d982f98db3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/GraphQLErrorAdapter.java @@ -0,0 +1,48 @@ +package com.baeldung.graphql.error.handling.exception; + +import graphql.ErrorType; +import graphql.ExceptionWhileDataFetching; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.List; +import java.util.Map; + +public class GraphQLErrorAdapter implements GraphQLError { + + private GraphQLError error; + + public GraphQLErrorAdapter(GraphQLError error) { + this.error = error; + } + + @Override + public Map getExtensions() { + return error.getExtensions(); + } + + @Override + public List getLocations() { + return error.getLocations(); + } + + @Override + public ErrorType getErrorType() { + return error.getErrorType(); + } + + @Override + public List getPath() { + return error.getPath(); + } + + @Override + public Map toSpecification() { + return error.toSpecification(); + } + + @Override + public String getMessage() { + return (error instanceof ExceptionWhileDataFetching) ? ((ExceptionWhileDataFetching) error).getException().getMessage() : error.getMessage(); + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java new file mode 100644 index 0000000000..78c8e83e27 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/InvalidInputException.java @@ -0,0 +1,7 @@ +package com.baeldung.graphql.error.handling.exception; + +public class InvalidInputException extends RuntimeException { + public InvalidInputException(String message) { + super(message); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java new file mode 100644 index 0000000000..8f6f0ce615 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleAlreadyPresentException.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.error.handling.exception; + +import java.util.Map; + +public class VehicleAlreadyPresentException extends AbstractGraphQLException { + + public VehicleAlreadyPresentException(String message) { + super(message); + } + + public VehicleAlreadyPresentException(String message, Map additionParams) { + super(message, additionParams); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java new file mode 100644 index 0000000000..0d2ad8c597 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/exception/VehicleNotFoundException.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.error.handling.exception; + +import java.util.Map; + +public class VehicleNotFoundException extends AbstractGraphQLException { + + public VehicleNotFoundException(String message) { + super(message); + } + + public VehicleNotFoundException(String message, Map params) { + super(message, params); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java new file mode 100644 index 0000000000..f4a0043408 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.graphql.error.handling.repository; + +import com.baeldung.graphql.error.handling.domain.Vehicle; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java new file mode 100644 index 0000000000..716b8d3ef3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/repository/LocationRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.graphql.error.handling.repository; + +import com.baeldung.graphql.error.handling.domain.Location; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface LocationRepository extends JpaRepository { +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java new file mode 100644 index 0000000000..8463ebf8eb --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Mutation.java @@ -0,0 +1,20 @@ +package com.baeldung.graphql.error.handling.resolver; + +import com.baeldung.graphql.error.handling.domain.Location; +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.service.InventoryService; +import com.coxautodev.graphql.tools.GraphQLMutationResolver; +import org.springframework.stereotype.Component; + +@Component +public class Mutation implements GraphQLMutationResolver { + private InventoryService inventoryService; + + public Mutation(InventoryService inventoryService) { + this.inventoryService = inventoryService; + } + + public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) { + return this.inventoryService.addVehicle(vin, year, make, model, trim, location); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java new file mode 100644 index 0000000000..ece018464a --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/resolver/Query.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql.error.handling.resolver; + +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.service.InventoryService; +import com.coxautodev.graphql.tools.GraphQLQueryResolver; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class Query implements GraphQLQueryResolver { + private final InventoryService inventoryService; + + public Query(InventoryService inventoryService) { + this.inventoryService = inventoryService; + } + + public List searchAll() { + return this.inventoryService.searchAll(); + } + + public List searchByLocation(String zipcode) { + return this.inventoryService.searchByLocation(zipcode); + } + + public Vehicle searchByVin(String vin) { + return this.inventoryService.searchByVin(vin); + } +} diff --git a/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java new file mode 100644 index 0000000000..7064b08760 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/java/com/baeldung/graphql/error/handling/service/InventoryService.java @@ -0,0 +1,67 @@ +package com.baeldung.graphql.error.handling.service; + +import com.baeldung.graphql.error.handling.domain.Location; +import com.baeldung.graphql.error.handling.domain.Vehicle; +import com.baeldung.graphql.error.handling.exception.InvalidInputException; +import com.baeldung.graphql.error.handling.exception.VehicleAlreadyPresentException; +import com.baeldung.graphql.error.handling.exception.VehicleNotFoundException; +import com.baeldung.graphql.error.handling.repository.InventoryRepository; +import com.baeldung.graphql.error.handling.repository.LocationRepository; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.*; + +@Service +public class InventoryService { + private InventoryRepository inventoryRepository; + private LocationRepository locationRepository; + + public InventoryService(InventoryRepository inventoryRepository, LocationRepository locationRepository) { + this.inventoryRepository = inventoryRepository; + this.locationRepository = locationRepository; + } + + @Transactional + public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) { + Optional existingVehicle = this.inventoryRepository.findById(vin); + if (existingVehicle.isPresent()) { + Map params = new HashMap<>(); + params.put("vin", vin); + throw new VehicleAlreadyPresentException("Failed to add vehicle. Vehicle with vin " + vin + " already present.", params); + } + Vehicle vehicle = Vehicle.builder() + .vin(vin) + .year(year) + .make(make) + .model(model) + .location(location) + .trim(trim) + .build(); + + this.locationRepository.save(location); + return this.inventoryRepository.save(vehicle); + } + + public List searchAll() { + return this.inventoryRepository.findAll(); + } + + public List searchByLocation(String zipcode) { + if (StringUtils.isEmpty(zipcode) || zipcode.length() != 5) { + throw new InvalidInputException("Invalid zipcode " + zipcode + " provided."); + } + return this.locationRepository.findById(zipcode) + .map(Location::getVehicles) + .orElse(new ArrayList<>()); + } + + public Vehicle searchByVin(String vin) { + return this.inventoryRepository.findById(vin).orElseThrow(() -> { + Map params = new HashMap<>(); + params.put("vin", vin); + return new VehicleNotFoundException("Vehicle with vin " + vin + " not found.", params); + }); + } +} diff --git a/graphql/graphql-error-handling/src/main/resources/application.yml b/graphql/graphql-error-handling/src/main/resources/application.yml new file mode 100644 index 0000000000..155e133a62 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/application.yml @@ -0,0 +1,23 @@ +graphql: + servlet: + mapping: /graphql + +spring: + datasource: + url: "jdbc:h2:mem:graphqldb" + driverClassName: "org.h2.Driver" + username: sa + password: + + initialization-mode: always + platform: h2 + + jpa: + show-sql: true + properties: + hibernate: + dialect: org.hibernate.dialect.H2Dialect + ddl-auto: none + + h2: + console.enabled: true \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls b/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls new file mode 100644 index 0000000000..7dcb5403c1 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/graphql/inventory.graphqls @@ -0,0 +1,23 @@ +type Vehicle { + vin: ID! + year: Int! + make: String! + model: String! + trim: String! +} + +input Location { + city: String + state: String + zipcode: String! +} + +type Query { + searchAll: [Vehicle]! + searchByLocation(zipcode: String!): [Vehicle]! + searchByVin(vin: String!): Vehicle +} + +type Mutation { + addVehicle(vin: ID!, year: Int!, make: String!, model: String!, trim: String, location: Location): Vehicle! +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/main/resources/import.sql b/graphql/graphql-error-handling/src/main/resources/import.sql new file mode 100644 index 0000000000..62907a86c3 --- /dev/null +++ b/graphql/graphql-error-handling/src/main/resources/import.sql @@ -0,0 +1,7 @@ +insert into LOCATION values('07092', 'Mountainside', 'NJ'); +insert into LOCATION values ('94118', 'San Francisco', 'CA'); +insert into LOCATION values ('10002', 'New York', 'NY'); + +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('KM8JN72DX7U587496', 2007, 'Hyundai', 'Tucson', null, '07092'); +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('JTKKU4B41C1023346', 2012, 'Toyota', 'Scion', 'Xd', '94118'); +insert into VEHICLE (vin, year, make, model, trim, fk_location) values('1G1JC1444PZ215071', 2000, 'Chevrolet', 'CAVALIER VL', 'RS', '07092'); \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java new file mode 100644 index 0000000000..069a08ce02 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/GraphQLErrorHandlerApplicationIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.graphql.error.handling; + +import com.graphql.spring.boot.test.GraphQLResponse; +import com.graphql.spring.boot.test.GraphQLTestTemplate; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; + +import static com.baeldung.graphql.error.handling.TestUtils.readFile; +import static java.lang.String.format; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = GraphQLErrorHandlerApplication.class) +public class GraphQLErrorHandlerApplicationIntegrationTest { + + @Autowired + private GraphQLTestTemplate graphQLTestTemplate; + + private static final String GRAPHQL_TEST_REQUEST_PATH = "graphql/request/%s.graphql"; + private static final String GRAPHQL_TEST_RESPONSE_PATH = "graphql/response/%s.json"; + + @Test + public void whenUnknownOperation_thenRespondWithRequestError() throws IOException, JSONException { + String graphqlName = "request_error_unknown_operation"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } + + @Test + public void whenInvalidSyntaxRequest_thenRespondWithRequestError() throws IOException, JSONException { + String graphqlName = "request_error_invalid_request_syntax"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } + + @Test + public void whenRequestAllNonNullField_thenRespondPartialDataWithFieldError() throws IOException, JSONException { + String graphqlName = "field_error_request_non_null_fields_partial_response"; + GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName)); + String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName)); + + JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true); + } +} diff --git a/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java new file mode 100644 index 0000000000..557f1d9c91 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/java/com/baeldung/graphql/error/handling/TestUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.graphql.error.handling; + +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class TestUtils { + public static String readFile(String path) throws IOException { + return IOUtils.toString( + new ClassPathResource(path).getInputStream(), Charset.defaultCharset() + ); + } +} diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql new file mode 100644 index 0000000000..17affc50cb --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/field_error_request_non_null_fields_partial_response.graphql @@ -0,0 +1,10 @@ +# trim is non null but one of the record has null value for trim +query { + searchAll { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql new file mode 100644 index 0000000000..98920eb17a --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_invalid_request_syntax.graphql @@ -0,0 +1,9 @@ +query { + searchByVin(vin: "error) { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql new file mode 100644 index 0000000000..fb6c3d1039 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/request/request_error_unknown_operation.graphql @@ -0,0 +1,9 @@ +subscription { + searchByVin(vin: "75024") { + vin + year + make + model + trim + } +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json new file mode 100644 index 0000000000..760190128e --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/field_error_request_non_null_fields_partial_response.json @@ -0,0 +1,34 @@ +{ + "data": { + "searchAll": [ + null, + { + "vin": "JTKKU4B41C1023346", + "year": 2012, + "make": "Toyota", + "model": "Scion", + "trim": "Xd" + }, + { + "vin": "1G1JC1444PZ215071", + "year": 2000, + "make": "Chevrolet", + "model": "CAVALIER VL", + "trim": "RS" + } + ] + }, + "errors": [ + { + "message": "Cannot return null for non-nullable type: 'String' within parent 'Vehicle' (/searchAll[0]/trim)", + "path": [ + "searchAll", + 0, + "trim" + ], + "errorType": "DataFetchingException", + "locations": null, + "extensions": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json new file mode 100644 index 0000000000..2835b42133 --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_invalid_request_syntax.json @@ -0,0 +1,18 @@ +{ + "data": null, + "errors": [ + { + "message": "Invalid Syntax", + "locations": [ + { + "line": 5, + "column": 8, + "sourceName": null + } + ], + "errorType": "InvalidSyntax", + "path": null, + "extensions": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json new file mode 100644 index 0000000000..b5872fc80f --- /dev/null +++ b/graphql/graphql-error-handling/src/test/resources/graphql/response/request_error_unknown_operation.json @@ -0,0 +1,18 @@ +{ + "data": null, + "errors": [ + { + "errorType": "OperationNotSupported", + "locations": [ + { + "line": 1, + "column": 1, + "sourceName": null + } + ], + "extensions": null, + "message": "Schema is not configured for subscriptions.", + "path": null + } + ] +} \ No newline at end of file diff --git a/graphql/graphql-error-handling/src/test/resources/init_script.sql b/graphql/graphql-error-handling/src/test/resources/init_script.sql new file mode 100644 index 0000000000..e69de29bb2 From 45b2266b6acfe7ccc01ef3c278e00392ea20be12 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 15 Apr 2022 13:13:13 +0530 Subject: [PATCH 36/40] JAVA-10606: Resolve errors from module rule-engines/jess --- rule-engines/jess/pom.xml | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/rule-engines/jess/pom.xml b/rule-engines/jess/pom.xml index f5db0374ef..be26d54a1e 100644 --- a/rule-engines/jess/pom.xml +++ b/rule-engines/jess/pom.xml @@ -7,18 +7,28 @@ jess 1.0-SNAPSHOT - jsr94 jsr94 1.1 + + + + + wso2 + Numerical Method's Maven Repository + http://dist.wso2.org/maven2/ + + + \ No newline at end of file From 20762cfeb9dddc21dac53258be2836c10b323367 Mon Sep 17 00:00:00 2001 From: freelansam <79205526+freelansam@users.noreply.github.com> Date: Fri, 15 Apr 2022 14:57:20 +0530 Subject: [PATCH 37/40] JAVA-10516: Revisit spring-boot module inside spring-boot-modules folder (#12038) --- spring-boot-modules/pom.xml | 4 +- .../main/resources/templates/customer.html | 0 .../README.md | 2 + .../spring-boot-basic-customization-2/pom.xml | 13 + .../baeldung/container}/CustomContainer.java | 2 +- .../baeldung/typeconversion}/Application.java | 2 +- .../typeconversion}/config/WebConfig.java | 9 +- .../converter/GenericBigDecimalConverter.java | 2 +- .../converter/StringToEmployeeConverter.java | 4 +- .../StringToEnumConverterFactory.java | 2 +- .../StringToEmployeeConverterController.java | 4 +- .../baeldung/typeconversion/domain/Modes.java | 6 + .../typeconversion/entity}/Employee.java | 2 +- .../CustomConverterIntegrationTest.java | 8 +- ...yeeConverterControllerIntegrationTest.java | 6 +- .../spring-boot-crud/README.md | 1 + .../com/baeldung/demo/DemoApplication.java | 0 .../baeldung/demo/components/FooService.java | 0 .../demo/exceptions/CommonException.java | 0 .../demo/exceptions/FooNotFoundException.java | 0 .../java/com/baeldung/demo/model/Foo.java | 0 .../demo/repository/FooRepository.java | 0 .../baeldung/demo/service/FooController.java | 0 .../session/exception/Application.java | 0 .../exception/repository/FooRepository.java | 0 .../repository/FooRepositoryImpl.java | 0 .../boot/ApplicationIntegrationTest.java | 3 +- .../FooRepositoryIntegrationTest.java | 2 +- .../HibernateSessionIntegrationTest.java | 2 +- .../NoHibernateSessionIntegrationTest.java | 1 + .../demo}/DemoApplicationIntegrationTest.java | 2 +- .../resources/exception-hibernate.properties | 0 .../src/test/resources/exception.properties | 0 .../resources/templates/displayallbeans.html | 0 .../spring-boot-mvc-3/README.md | 2 +- .../spring-boot-mvc-4/README.md | 10 + spring-boot-modules/spring-boot-mvc-4/pom.xml | 45 ++++ .../controller/servlet/HelloWorldServlet.java | 0 .../servlet/SpringHelloWorldServlet.java | 0 .../common/error/MyCustomErrorController.java | 0 .../SpringHelloServletRegistrationBean.java | 0 .../error/controller/ErrorController.java | 0 .../MyServletContainerCustomizationBean.java | 0 .../ExecutorServiceExitCodeGenerator.java | 0 .../baeldung/main/SpringBootApplication.java | 0 .../baeldung/servlets/ApplicationMain.java | 0 .../configuration/WebAppInitializer.java | 0 .../configuration/WebMvcConfigure.java | 0 .../baeldung/servlets/props/Constants.java | 0 .../servlets/props/PropertyLoader.java | 0 .../servlets/props/PropertySourcesLoader.java | 0 .../servlets/GenericCustomServlet.java | 0 .../servlets/javaee/AnnotationServlet.java | 0 .../servlets/javaee/EEWebXmlServlet.java | 0 .../SpringRegistrationBeanServlet.java | 0 .../embedded/EmbeddedTomcatExample.java | 0 .../com/baeldung/utils/UtilsApplication.java | 0 .../utils/controller/UtilsController.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/custom.properties | 0 .../src/main/resources/logback.xml | 6 - .../src/main/resources/shutdown/shutdown.bat | 0 .../src/main/resources/templates/other.html | 0 .../src/main/resources/templates/utils.html | 0 .../src/main/webapp/WEB-INF/context.xml | 0 .../src/main/webapp/WEB-INF/dispatcher.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../src/main/webapp/annotationservlet.jsp | 0 .../src/main/webapp/index.jsp | 0 .../utils/UtilsControllerIntegrationTest.java | 0 .../spring-boot-validation/README.md | 1 + .../spring-boot-validation/pom.xml | 8 + .../application/Application.java | 0 .../controllers/UserController.java | 0 .../application/entities/User.java | 0 .../repositories/UserRepository.java | 0 .../UserControllerIntegrationTest.java | 0 spring-boot-modules/spring-boot/.gitignore | 5 - .../.mvn/wrapper/maven-wrapper.properties | 1 - spring-boot-modules/spring-boot/README.md | 16 -- spring-boot-modules/spring-boot/mvnw | 227 ------------------ spring-boot-modules/spring-boot/mvnw.cmd | 145 ----------- spring-boot-modules/spring-boot/pom.xml | 166 ------------- .../com/baeldung/boot/config/H2JpaConfig.java | 67 ------ .../java/com/baeldung/boot/domain/Modes.java | 6 - .../baeldung/buildproperties/Application.java | 18 -- .../buildproperties/BuildInfoService.java | 21 -- .../src/main/java/com/baeldung/intro/App.java | 11 - .../intro/controller/HomeController.java | 18 -- .../com/baeldung/jsondateformat/Contact.java | 70 ------ .../baeldung/jsondateformat/ContactApp.java | 13 - .../jsondateformat/ContactAppConfig.java | 33 --- .../jsondateformat/ContactController.java | 77 ------ .../ContactWithJavaUtilDate.java | 69 ------ .../baeldung/jsondateformat/PlainContact.java | 66 ----- .../PlainContactWithJavaUtilDate.java | 69 ------ .../main/java/com/baeldung/model/User.java | 49 ---- .../baeldung/repository/UserRepository.java | 79 ------ .../com/baeldung/rss/ArticleFeedView.java | 54 ----- .../baeldung/rss/ArticleRssController.java | 16 -- .../main/java/com/baeldung/rss/RssApp.java | 18 -- .../application-errorhandling.properties | 4 - .../src/main/resources/build.properties | 2 - .../spring-boot/src/main/resources/build.yml | 2 - .../src/main/resources/data-expressions.sql | 3 - .../spring-boot/src/main/resources/data.sql | 5 - .../src/main/resources/demo.properties | 2 - .../persistence-generic-entity.properties | 8 - .../src/main/resources/public/error/404.html | 8 - .../src/main/resources/schema-expressions.sql | 5 - .../spring-boot/src/main/resources/schema.sql | 8 - .../main/resources/templates/customers.html | 33 --- .../src/main/resources/templates/error.html | 16 -- .../main/resources/templates/error/404.html | 8 - .../main/resources/templates/external.html | 31 --- .../src/main/resources/templates/index.html | 19 -- .../src/main/resources/templates/layout.html | 18 -- .../BuildInfoServiceIntegrationTest.java | 24 -- .../java/com/baeldung/intro/AppLiveTest.java | 35 --- .../jsondateformat/ContactAppUnitTest.java | 109 --------- ...AppWithObjectMapperCustomizerUnitTest.java | 76 ------ .../UserRepositoryIntegrationTest.java | 73 ------ .../spring-boot/src/test/resources/README.md | 3 - .../src/test/resources/application.properties | 19 -- .../src/test/resources/conversion.properties | 11 - .../spring-boot/src/test/resources/import.sql | 1 - .../resources/org/baeldung/boot/expected.json | 4 - 127 files changed, 116 insertions(+), 1874 deletions(-) rename spring-boot-modules/{spring-boot => spring-boot-1}/src/main/resources/templates/customer.html (100%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/rss => spring-boot-basic-customization-2/src/main/java/com/baeldung/container}/CustomContainer.java (93%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/Application.java (91%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/config/WebConfig.java (67%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/converter/GenericBigDecimalConverter.java (96%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/converter/StringToEmployeeConverter.java (76%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/converter/StringToEnumConverterFactory.java (94%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/boot => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion}/converter/controller/StringToEmployeeConverterController.java (81%) create mode 100644 spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/toggle => spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity}/Employee.java (92%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung => spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion}/converter/CustomConverterIntegrationTest.java (90%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung => spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion}/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java (92%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/DemoApplication.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/components/FooService.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/exceptions/CommonException.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/model/Foo.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/repository/FooRepository.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/demo/service/FooController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/session/exception/Application.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/session/exception/repository/FooRepository.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/boot => spring-boot-crud/src/test/java/com/baeldung/demo}/DemoApplicationIntegrationTest.java (95%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/resources/exception-hibernate.properties (100%) rename spring-boot-modules/{spring-boot => spring-boot-crud}/src/test/resources/exception.properties (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/resources/templates/displayallbeans.html (100%) create mode 100644 spring-boot-modules/spring-boot-mvc-4/README.md create mode 100644 spring-boot-modules/spring-boot-mvc-4/pom.xml rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/common/error/MyCustomErrorController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/common/error/controller/ErrorController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/main/SpringBootApplication.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/ApplicationMain.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/props/Constants.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/props/PropertyLoader.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/utils/UtilsApplication.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/java/com/baeldung/utils/controller/UtilsController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/application.properties (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/custom.properties (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/logback.xml (55%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/shutdown/shutdown.bat (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/templates/other.html (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/resources/templates/utils.html (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/webapp/WEB-INF/context.xml (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/webapp/WEB-INF/dispatcher.xml (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/webapp/WEB-INF/web.xml (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/webapp/annotationservlet.jsp (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/main/webapp/index.jsp (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc-4}/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-validation}/src/main/java/com/baeldung/beanvalidation/application/Application.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-validation}/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-validation}/src/main/java/com/baeldung/beanvalidation/application/entities/User.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-validation}/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-validation}/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java (100%) delete mode 100644 spring-boot-modules/spring-boot/.gitignore delete mode 100755 spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties delete mode 100644 spring-boot-modules/spring-boot/README.md delete mode 100755 spring-boot-modules/spring-boot/mvnw delete mode 100755 spring-boot-modules/spring-boot/mvnw.cmd delete mode 100644 spring-boot-modules/spring-boot/pom.xml delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java delete mode 100644 spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/build.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/build.yml delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/data.sql delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/demo.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/public/error/404.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/schema.sql delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/customers.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/error.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/external.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/index.html delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/templates/layout.html delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/resources/README.md delete mode 100644 spring-boot-modules/spring-boot/src/test/resources/application.properties delete mode 100644 spring-boot-modules/spring-boot/src/test/resources/conversion.properties delete mode 100644 spring-boot-modules/spring-boot/src/test/resources/import.sql delete mode 100644 spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index fabd54aa92..a12ee55018 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -16,8 +16,7 @@ ../parent-boot-2 - - spring-boot + spring-boot-1 spring-boot-2 spring-boot-admin @@ -56,6 +55,7 @@ spring-boot-mvc spring-boot-mvc-2 spring-boot-mvc-3 + spring-boot-mvc-4 spring-boot-mvc-birt spring-boot-mvc-jersey spring-boot-nashorn diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/customer.html b/spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/customer.html rename to spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index 9488618ca5..bfd24a0475 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -8,3 +8,5 @@ This module contains articles about Spring Boot customization 2 - [XML Defined Beans in Spring Boot](https://www.baeldung.com/spring-boot-xml-beans) - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) + - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) + - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml index b615947de7..b537f43c23 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml @@ -19,10 +19,23 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test + + com.google.guava + guava + ${guava.version} + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java index aaa3188010..6ebd4d5c62 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/container/CustomContainer.java @@ -1,4 +1,4 @@ -package com.baeldung.rss; +package com.baeldung.container; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java index cb0d0c1532..1313032bbe 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.boot; +package com.baeldung.typeconversion; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java similarity index 67% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java index b23c910a04..bad84edf88 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/config/WebConfig.java @@ -1,12 +1,13 @@ -package com.baeldung.boot.config; +package com.baeldung.typeconversion.config; -import com.baeldung.boot.converter.StringToEmployeeConverter; -import com.baeldung.boot.converter.StringToEnumConverterFactory; -import com.baeldung.boot.converter.GenericBigDecimalConverter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.typeconversion.converter.GenericBigDecimalConverter; +import com.baeldung.typeconversion.converter.StringToEmployeeConverter; +import com.baeldung.typeconversion.converter.StringToEnumConverterFactory; + @Configuration public class WebConfig implements WebMvcConfigurer { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java index fc73cfee5f..440ffba5ee 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/GenericBigDecimalConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import com.google.common.collect.ImmutableSet; import org.springframework.core.convert.TypeDescriptor; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java similarity index 76% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java index ac635532ea..9703ed2514 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEmployeeConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import org.springframework.core.convert.converter.Converter; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.entity.Employee; public class StringToEmployeeConverter implements Converter { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java index a2dce11a6a..dc15f83d6d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.converter; +package com.baeldung.typeconversion.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java similarity index 81% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java index 260b1c734b..5c3f93f346 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterController.java @@ -1,11 +1,11 @@ -package com.baeldung.boot.converter.controller; +package com.baeldung.typeconversion.converter.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.entity.Employee; @RestController public class StringToEmployeeConverterController { diff --git a/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java new file mode 100644 index 0000000000..d905faacac --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/domain/Modes.java @@ -0,0 +1,6 @@ +package com.baeldung.typeconversion.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java similarity index 92% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java index 64a8b3ce5b..e1897de877 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/Employee.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/typeconversion/entity/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.toggle; +package com.baeldung.typeconversion.entity; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java similarity index 90% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java index 4619964783..3e12e3c58d 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/CustomConverterIntegrationTest.java @@ -1,9 +1,9 @@ -package com.baeldung.converter; +package com.baeldung.typeconversion.converter; -import com.baeldung.toggle.Employee; +import com.baeldung.typeconversion.Application; +import com.baeldung.typeconversion.domain.Modes; +import com.baeldung.typeconversion.entity.Employee; -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Modes; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 92% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 52dc542ebf..8632eebda3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/test/java/com/baeldung/typeconversion/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.converter.controller; +package com.baeldung.typeconversion.converter.controller; import org.junit.Test; import org.junit.runner.RunWith; @@ -8,14 +8,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.typeconversion.Application; + import static org.hamcrest.CoreMatchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.boot.Application; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) @AutoConfigureMockMvc diff --git a/spring-boot-modules/spring-boot-crud/README.md b/spring-boot-modules/spring-boot-crud/README.md index 6b0032deb3..3d3d8f42d7 100644 --- a/spring-boot-modules/spring-boot-crud/README.md +++ b/spring-boot-modules/spring-boot-crud/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring Boot CRUD Operations ### Relevant Articles: - [Spring Boot CRUD Application with Thymeleaf](https://www.baeldung.com/spring-boot-crud-thymeleaf) - [Using a Spring Boot Application as a Dependency](https://www.baeldung.com/spring-boot-dependency) +- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/DemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/DemoApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/components/FooService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/components/FooService.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/CommonException.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/CommonException.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/model/Foo.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/model/Foo.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/repository/FooRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/repository/FooRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/service/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/demo/service/FooController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java index 462291e0ac..88ff8c75f1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java @@ -1,12 +1,13 @@ package com.baeldung.boot; -import com.baeldung.session.exception.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.session.exception.Application; + @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @TestPropertySource("classpath:exception.properties") diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java index 1772739d20..9de1f56af0 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.boot.repository; -import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.DemoApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.demo.repository.FooRepository; import org.junit.Before; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 2fe072bb67..63b4734cf0 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.boot.repository; -import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.DemoApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.demo.repository.FooRepository; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 2e3326e6b1..ae20b15cb3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.boot.repository; import com.baeldung.boot.ApplicationIntegrationTest; import com.baeldung.demo.model.Foo; import com.baeldung.session.exception.repository.FooRepository; + import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java similarity index 95% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java index aaf4f1f780..3d72ec0140 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/demo/DemoApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.boot; +package com.baeldung.demo; import com.baeldung.demo.DemoApplication; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties b/spring-boot-modules/spring-boot-crud/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/exception-hibernate.properties rename to spring-boot-modules/spring-boot-crud/src/test/resources/exception-hibernate.properties diff --git a/spring-boot-modules/spring-boot/src/test/resources/exception.properties b/spring-boot-modules/spring-boot-crud/src/test/resources/exception.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/exception.properties rename to spring-boot-modules/spring-boot-crud/src/test/resources/exception.properties diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot-modules/spring-boot-di/src/main/resources/templates/displayallbeans.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/displayallbeans.html rename to spring-boot-modules/spring-boot-di/src/main/resources/templates/displayallbeans.html diff --git a/spring-boot-modules/spring-boot-mvc-3/README.md b/spring-boot-modules/spring-boot-mvc-3/README.md index fa24ac11ed..e4b0a73bda 100644 --- a/spring-boot-modules/spring-boot-mvc-3/README.md +++ b/spring-boot-modules/spring-boot-mvc-3/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [CharacterEncodingFilter In SpringBoot](https://www.baeldung.com/spring-boot-characterencodingfilter) - [HandlerInterceptors vs. Filters in Spring MVC](https://www.baeldung.com/spring-mvc-handlerinterceptor-vs-filter) - [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) -- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2) +- More articles: [[<-- Prev]](/spring-boot-modules/spring-boot-mvc-2)[[Next -->]](/spring-boot-modules/spring-boot-mvc-4) diff --git a/spring-boot-modules/spring-boot-mvc-4/README.md b/spring-boot-modules/spring-boot-mvc-4/README.md new file mode 100644 index 0000000000..68fcfa8b6b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-4/README.md @@ -0,0 +1,10 @@ +## Spring Boot MVC + +This module contains articles about Spring Web MVC in Spring Boot projects. + +### Relevant Articles: + +- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) +- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) +- [Configure a Spring Boot Web Application](https://www.baeldung.com/spring-boot-application-configuration) +- More articles: [[<-- Prev]](/spring-boot-modules/spring-boot-mvc-3) diff --git a/spring-boot-modules/spring-boot-mvc-4/pom.xml b/spring-boot-modules/spring-boot-mvc-4/pom.xml new file mode 100644 index 0000000000..7d4d6e3d0c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-4/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-boot-mvc-4 + spring-boot-mvc-4 + jar + Module For Spring Boot MVC Web + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + commons-io + commons-io + ${commons-io.version} + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/MyCustomErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/MyCustomErrorController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/controller/ErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/error/controller/ErrorController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/main/SpringBootApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/main/SpringBootApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/ApplicationMain.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/ApplicationMain.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/Constants.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/Constants.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/Constants.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertyLoader.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertyLoader.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertyLoader.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/UtilsApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/controller/UtilsController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/utils/controller/UtilsController.java diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot/src/main/resources/custom.properties b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/custom.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/custom.properties rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/custom.properties diff --git a/spring-boot-modules/spring-boot/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/logback.xml similarity index 55% rename from spring-boot-modules/spring-boot/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/logback.xml index 56af2d397e..7d900d8ea8 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/logback.xml +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/logback.xml @@ -7,12 +7,6 @@ - - - - - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/shutdown/shutdown.bat similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/shutdown/shutdown.bat rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/shutdown/shutdown.bat diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/other.html b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/other.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/other.html rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/other.html diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/utils.html b/spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/utils.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/utils.html rename to spring-boot-modules/spring-boot-mvc-4/src/main/resources/templates/utils.html diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/context.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/context.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/context.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/dispatcher.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/dispatcher.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/WEB-INF/web.xml diff --git a/spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/annotationservlet.jsp similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/annotationservlet.jsp rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/annotationservlet.jsp diff --git a/spring-boot-modules/spring-boot/src/main/webapp/index.jsp b/spring-boot-modules/spring-boot-mvc-4/src/main/webapp/index.jsp similarity index 100% rename from spring-boot-modules/spring-boot/src/main/webapp/index.jsp rename to spring-boot-modules/spring-boot-mvc-4/src/main/webapp/index.jsp diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-validation/README.md b/spring-boot-modules/spring-boot-validation/README.md index 8c3c8b9305..93b6e7d2d1 100644 --- a/spring-boot-modules/spring-boot-validation/README.md +++ b/spring-boot-modules/spring-boot-validation/README.md @@ -1,3 +1,4 @@ ### Relevant Articles - [Spring Validation in the Service Layer](https://www.baeldung.com/spring-service-layer-validation) +- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) diff --git a/spring-boot-modules/spring-boot-validation/pom.xml b/spring-boot-modules/spring-boot-validation/pom.xml index fa4e8439e6..639a62059d 100644 --- a/spring-boot-modules/spring-boot-validation/pom.xml +++ b/spring-boot-modules/spring-boot-validation/pom.xml @@ -22,6 +22,14 @@ org.hibernate.validator hibernate-validator + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/Application.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/controllers/UserController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/entities/User.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/entities/User.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/entities/User.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java rename to spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/beanvalidation/application/repositories/UserRepository.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/beanvalidation/application/UserControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot/.gitignore b/spring-boot-modules/spring-boot/.gitignore deleted file mode 100644 index da7c2c5c0a..0000000000 --- a/spring-boot-modules/spring-boot/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ -.settings/ -.classpath -.project - diff --git a/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties deleted file mode 100755 index a447c9fa81..0000000000 --- a/spring-boot-modules/spring-boot/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/README.md b/spring-boot-modules/spring-boot/README.md deleted file mode 100644 index fdc8093806..0000000000 --- a/spring-boot-modules/spring-boot/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Spring Boot - -This module contains articles about Spring Boot - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: - -- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) -- [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) -- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) -- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) -- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) diff --git a/spring-boot-modules/spring-boot/mvnw b/spring-boot-modules/spring-boot/mvnw deleted file mode 100755 index e96ccd5fbb..0000000000 --- a/spring-boot-modules/spring-boot/mvnw +++ /dev/null @@ -1,227 +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 Mingw, 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"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -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 "$@" diff --git a/spring-boot-modules/spring-boot/mvnw.cmd b/spring-boot-modules/spring-boot/mvnw.cmd deleted file mode 100755 index 6a6eec39ba..0000000000 --- a/spring-boot-modules/spring-boot/mvnw.cmd +++ /dev/null @@ -1,145 +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 set title of command window -title %0 -@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% diff --git a/spring-boot-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml deleted file mode 100644 index 3afccef925..0000000000 --- a/spring-boot-modules/spring-boot/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - 4.0.0 - spring-boot - 0.0.1-SNAPSHOT - spring-boot - war - This is simple boot application for Spring boot actuator test - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.ehcache - ehcache - - - org.hibernate - hibernate-ehcache - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-test - test - - - io.dropwizard.metrics - metrics-core - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter - - - com.jayway.jsonpath - json-path - test - - - com.google.guava - guava - ${guava.version} - - - org.apache.tomcat - tomcat-servlet-api - ${tomee-servlet-api.version} - provided - - - org.apache.activemq - artemis-server - - - com.rometools - rome - ${rome.version} - - - - - spring-boot - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-resources-plugin - - - @ - - false - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - - com.baeldung.intro.App - 8.5.11 - 1.9.0 - @ - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java deleted file mode 100644 index 928928c9a5..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.boot.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" }) -@PropertySource("classpath:persistence-generic-entity.properties") -@EnableTransactionManagement -public class H2JpaConfig { - - @Autowired - private Environment env; - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" }); - em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - em.setJpaProperties(additionalProperties()); - return em; - } - - @Bean - JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - - return hibernateProperties; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java deleted file mode 100644 index 7717294996..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.boot.domain; - -public enum Modes { - - ALPHA, BETA; -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java deleted file mode 100644 index 405cec3eac..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.buildproperties; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.PropertySource; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.buildproperties") -@PropertySource("classpath:build.properties") -//@PropertySource("classpath:build.yml") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java deleted file mode 100644 index 2a0d27188e..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/buildproperties/BuildInfoService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.buildproperties; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -@Service -public class BuildInfoService { - @Value("${application-description}") - private String applicationDescription; - - @Value("${application-version}") - private String applicationVersion; - - public String getApplicationDescription() { - return applicationDescription; - } - - public String getApplicationVersion() { - return applicationVersion; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java deleted file mode 100644 index 77cdf4ddb9..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/App.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.intro; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class App { - public static void main(String[] args) { - SpringApplication.run(App.class, args); - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java deleted file mode 100644 index 4797d6e593..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.intro.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - @GetMapping("/") - public String root() { - return "Index Page"; - } - - @GetMapping("/local") - public String local() { - return "/local"; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java deleted file mode 100644 index f131d17196..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/Contact.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.time.LocalDate; -import java.time.LocalDateTime; - -public class Contact { - - private String name; - private String address; - private String phone; - - @JsonFormat(pattern="yyyy-MM-dd") - private LocalDate birthday; - - @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") - private LocalDateTime lastUpdate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public LocalDate getBirthday() { - return birthday; - } - - public void setBirthday(LocalDate birthday) { - this.birthday = birthday; - } - - public LocalDateTime getLastUpdate() { - return lastUpdate; - } - - public void setLastUpdate(LocalDateTime lastUpdate) { - this.lastUpdate = lastUpdate; - } - - public Contact() { - } - - public Contact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) { - this.name = name; - this.address = address; - this.phone = phone; - this.birthday = birthday; - this.lastUpdate = lastUpdate; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java deleted file mode 100644 index 79037e1038..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactApp.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.jsondateformat; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ContactApp { - - public static void main(String[] args) { - SpringApplication.run(ContactApp.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java deleted file mode 100644 index 7a20ebfa51..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactAppConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; -import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; - -import java.time.format.DateTimeFormatter; - -@Configuration -public class ContactAppConfig { - - private static final String dateFormat = "yyyy-MM-dd"; - - private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss"; - - @Bean - @ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none") - public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() { - return new Jackson2ObjectMapperBuilderCustomizer() { - @Override - public void customize(Jackson2ObjectMapperBuilder builder) { - builder.simpleDateFormat(dateTimeFormat); - builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat))); - builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat))); - } - }; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java deleted file mode 100644 index 8894d82fc7..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactController.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.jsondateformat; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -@RestController -@RequestMapping(value = "/contacts") -public class ContactController { - - @GetMapping - public List getContacts() { - List contacts = new ArrayList<>(); - - Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - - contacts.add(contact1); - contacts.add(contact2); - contacts.add(contact3); - - return contacts; - } - - @GetMapping("/javaUtilDate") - public List getContactsWithJavaUtilDate() { - List contacts = new ArrayList<>(); - - ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date()); - ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date()); - ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date()); - - contacts.add(contact1); - contacts.add(contact2); - contacts.add(contact3); - - return contacts; - } - - @GetMapping("/plain") - public List getPlainContacts() { - List contacts = new ArrayList<>(); - - PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now()); - - contacts.add(contact1); - contacts.add(contact2); - contacts.add(contact3); - - return contacts; - } - - @GetMapping("/plainWithJavaUtilDate") - public List getPlainContactsWithJavaUtilDate() { - List contacts = new ArrayList<>(); - - PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date()); - PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date()); - PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date()); - - contacts.add(contact1); - contacts.add(contact2); - contacts.add(contact3); - - return contacts; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java deleted file mode 100644 index 5a1c508098..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/ContactWithJavaUtilDate.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.util.Date; - -public class ContactWithJavaUtilDate { - - private String name; - private String address; - private String phone; - - @JsonFormat(pattern="yyyy-MM-dd") - private Date birthday; - - @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") - private Date lastUpdate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public Date getBirthday() { - return birthday; - } - - public void setBirthday(Date birthday) { - this.birthday = birthday; - } - - public Date getLastUpdate() { - return lastUpdate; - } - - public void setLastUpdate(Date lastUpdate) { - this.lastUpdate = lastUpdate; - } - - public ContactWithJavaUtilDate() { - } - - public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { - this.name = name; - this.address = address; - this.phone = phone; - this.birthday = birthday; - this.lastUpdate = lastUpdate; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java deleted file mode 100644 index 7e9e53d205..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContact.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.jsondateformat; - -import java.time.LocalDate; -import java.time.LocalDateTime; - -public class PlainContact { - - private String name; - private String address; - private String phone; - - private LocalDate birthday; - - private LocalDateTime lastUpdate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public LocalDate getBirthday() { - return birthday; - } - - public void setBirthday(LocalDate birthday) { - this.birthday = birthday; - } - - public LocalDateTime getLastUpdate() { - return lastUpdate; - } - - public void setLastUpdate(LocalDateTime lastUpdate) { - this.lastUpdate = lastUpdate; - } - - public PlainContact() { - } - - public PlainContact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) { - this.name = name; - this.address = address; - this.phone = phone; - this.birthday = birthday; - this.lastUpdate = lastUpdate; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java deleted file mode 100644 index daefb15543..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/jsondateformat/PlainContactWithJavaUtilDate.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.util.Date; - -public class PlainContactWithJavaUtilDate { - - private String name; - private String address; - private String phone; - - @JsonFormat(pattern="yyyy-MM-dd") - private Date birthday; - - @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") - private Date lastUpdate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public Date getBirthday() { - return birthday; - } - - public void setBirthday(Date birthday) { - this.birthday = birthday; - } - - public Date getLastUpdate() { - return lastUpdate; - } - - public void setLastUpdate(Date lastUpdate) { - this.lastUpdate = lastUpdate; - } - - public PlainContactWithJavaUtilDate() { - } - - public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { - this.name = name; - this.address = address; - this.phone = phone; - this.birthday = birthday; - this.lastUpdate = lastUpdate; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java deleted file mode 100644 index cc5f27f38c..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer status; - - public User() { - } - - public User(String name, Integer status) { - this.name = name; - this.status = status; - } - - 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 Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java deleted file mode 100644 index 4dd863fb17..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.model.User; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Repository; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -@Repository("userRepository") -public interface UserRepository extends JpaRepository { - - int countByStatus(int status); - - Optional findOneByName(String name); - - @Async - CompletableFuture findOneByStatus(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java deleted file mode 100644 index 3efa619409..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleFeedView.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.rss; - -import com.rometools.rome.feed.rss.Channel; -import com.rometools.rome.feed.rss.Description; -import com.rometools.rome.feed.rss.Item; -import org.springframework.stereotype.Service; -import org.springframework.web.servlet.view.feed.AbstractRssFeedView; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -@Service("articleFeedView") -public class ArticleFeedView extends AbstractRssFeedView { - - protected Channel newFeed() { - Channel channel = new Channel("rss_2.0"); - channel.setLink("http://localhost:8080/rss"); - channel.setTitle("Article Feed"); - channel.setDescription("Article Feed Description"); - channel.setPubDate(new Date()); - return channel; - } - - @Override - protected List buildFeedItems(Map map, HttpServletRequest httpStRequest, HttpServletResponse httpStResponse) throws Exception { - List list = new ArrayList(); - - Item item1 = new Item(); - item1.setLink("http://www.baeldung.com/netty-exception-handling"); - item1.setTitle("Exceptions in Netty"); - Description description1 = new Description(); - description1.setValue("In this quick article, we’ll be looking at exception handling in Netty."); - item1.setDescription(description1); - item1.setPubDate(new Date()); - item1.setAuthor("Carlos"); - - Item item2 = new Item(); - item2.setLink("http://www.baeldung.com/cockroachdb-java"); - item2.setTitle("Guide to CockroachDB in Java"); - Description description2 = new Description(); - description2.setValue("This tutorial is an introductory guide to using CockroachDB with Java."); - item2.setDescription(description2); - item2.setPubDate(new Date()); - item2.setAuthor("Baeldung"); - - list.add(item1); - list.add(item2); - return list; - } -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java deleted file mode 100644 index daaeb8159b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.rss; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/rss", produces = "application/*") -public class ArticleRssController { - - @GetMapping - public String articleFeed() { - return "articleFeedView"; - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java deleted file mode 100644 index e067d3cfd1..0000000000 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/rss/RssApp.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.rss; - -import javax.annotation.security.RolesAllowed; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.rss") -public class RssApp { - - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(RssApp.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties deleted file mode 100644 index 270e86d443..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties +++ /dev/null @@ -1,4 +0,0 @@ -#server -server.port=9000 -server.servlet-path=/ -server.context-path=/ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.properties b/spring-boot-modules/spring-boot/src/main/resources/build.properties deleted file mode 100644 index 1612b8086d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/build.properties +++ /dev/null @@ -1,2 +0,0 @@ -application-description=@project.description@ -application-version=@project.version@ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/build.yml b/spring-boot-modules/spring-boot/src/main/resources/build.yml deleted file mode 100644 index 528d2e3440..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/build.yml +++ /dev/null @@ -1,2 +0,0 @@ -application-description: ^project.description^ -application-version: ^project.version^ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql deleted file mode 100644 index 3e702a759d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/data-expressions.sql +++ /dev/null @@ -1,3 +0,0 @@ -insert into contact_info_expression values ('email','[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?') -insert into contact_info_expression values ('phone','^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$') -insert into contact_info_expression values ('website','^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$') \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/data.sql b/spring-boot-modules/spring-boot/src/main/resources/data.sql deleted file mode 100644 index c44034c739..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/data.sql +++ /dev/null @@ -1,5 +0,0 @@ -insert into users values (1, 'Alex', 1); -insert into users values (2, 'Bob', 1); -insert into users values (3, 'John', 0); -insert into users values (4, 'Harry', 0); -insert into users values (5, 'Smith', 1); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/demo.properties b/spring-boot-modules/spring-boot/src/main/resources/demo.properties deleted file mode 100644 index 6b4cbeb7a0..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/demo.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.output.ansi.enabled=never -server.port=7070 diff --git a/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties deleted file mode 100644 index b19304cb1f..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/persistence-generic-entity.properties +++ /dev/null @@ -1,8 +0,0 @@ -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 -jdbc.user=sa -jdbc.pass=sa - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/public/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql b/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql deleted file mode 100644 index 59f6ab05eb..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/schema-expressions.sql +++ /dev/null @@ -1,5 +0,0 @@ -create table contact_info_expression( - expression_type varchar(50) not null, - pattern varchar(500) not null, - PRIMARY KEY ( expression_type ) -); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/schema.sql b/spring-boot-modules/spring-boot/src/main/resources/schema.sql deleted file mode 100644 index 4cd345c762..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/schema.sql +++ /dev/null @@ -1,8 +0,0 @@ -drop table if exists USERS; - -create table USERS( - ID int not null AUTO_INCREMENT, - NAME varchar(100) not null, - STATUS int, - PRIMARY KEY ( ID ) -); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html b/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html deleted file mode 100644 index 5a060d31da..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/customers.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -
-

- Hello, --name--. -

- - - - - - - - - - - - - - - - - -
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
- -
- - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error.html deleted file mode 100644 index bc517913b2..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Something went wrong!

- -

Our Engineers are on it.

-

Go Home

-
- - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/external.html b/spring-boot-modules/spring-boot/src/main/resources/templates/external.html deleted file mode 100644 index 2f9cc76961..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/external.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -
-
-

Customer Portal

-
-
-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam - erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras - arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit - amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non - id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit - amet varius mauris. Nulla eu eros pharetra, tristique dui quis, - vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec - at leo.

- -

Existing Customers

-
- Enter the intranet: customers -
-
- -
- - - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot/src/main/resources/templates/index.html deleted file mode 100644 index c1314558f6..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - WebJars Demo - - - -

Welcome Home

-

-
- × - Success! It is working as we expected. -
-
- - - - - - diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html b/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html deleted file mode 100644 index bab0c2982b..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/layout.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -Customer Portal - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java deleted file mode 100644 index cb056fe56d..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.buildproperties; - -import static org.junit.Assert.assertThat; - -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -class BuildInfoServiceIntegrationTest { - - @Autowired - private BuildInfoService service; - - @Test - void whenGetApplicationDescription_thenSuccess() { - assertThat(service.getApplicationDescription(), Matchers.is("This is simple boot application for Spring boot actuator test")); - assertThat(service.getApplicationVersion(), Matchers.is("0.0.1-SNAPSHOT")); - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java deleted file mode 100644 index 2785054153..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.intro; - -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -public class AppLiveTest { - - @Autowired - private MockMvc mvc; - - @Test - public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page"))); - } - - @Test - public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local"))); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java deleted file mode 100644 index 7be85b5e4f..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppUnitTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.text.ParseException; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class) -@TestPropertySource(properties = { - "spring.jackson.date-format=yyyy-MM-dd HH:mm:ss" -}) -public class ContactAppUnitTest { - - private final ObjectMapper mapper = new ObjectMapper(); - - @Autowired - TestRestTemplate restTemplate; - - @LocalServerPort - int port; - - String url; - - @Before - public void before() { - url=String.format("http://localhost:%s", port); - } - - @Test - public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - assertNotNull(birthdayDate); - assertNotNull(lastUpdateTime); - } - - @Test - public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts/javaUtilDate", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - assertNotNull(birthdayDate); - assertNotNull(lastUpdateTime); - } - - @Test - public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - assertNotNull(birthdayDate); - assertNotNull(lastUpdateTime); - } - - @Test(expected = DateTimeParseException.class) - public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts/plain", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java deleted file mode 100644 index 114f9bfc1a..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/jsondateformat/ContactAppWithObjectMapperCustomizerUnitTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jsondateformat; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class) -public class ContactAppWithObjectMapperCustomizerUnitTest { - - private final ObjectMapper mapper = new ObjectMapper(); - - @Autowired - TestRestTemplate restTemplate; - - @LocalServerPort - int port; - - String url; - - @Before - public void before() { - url=String.format("http://localhost:%s", port); - } - - @Test - public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - assertNotNull(birthdayDate); - assertNotNull(lastUpdateTime); - } - - @Test - public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException { - ResponseEntity response = restTemplate.getForEntity(url + "/contacts/plain", String.class); - - assertEquals(200, response.getStatusCodeValue()); - - List> respMap = mapper.readValue(response.getBody(), new TypeReference>>(){}); - - LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd")); - LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - assertNotNull(birthdayDate); - assertNotNull(lastUpdateTime); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index a1318949f3..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.boot.config.H2JpaConfig; -import com.baeldung.model.User; -import com.baeldung.repository.UserRepository; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = H2JpaConfig.class) -public class UserRepositoryIntegrationTest { - - private final String USER_NAME_ADAM = "Adam"; - private final Integer ACTIVE_STATUS = 1; - - @Autowired - private UserRepository userRepository; - - @Test - public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(false); - } - - @Test - public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - userRepository.save(user); - - Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - - assertThat(foundUser.isPresent()).isEqualTo(true); - - assertThat(foundUser - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - - assertThat(userByStatus - .get() - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/resources/README.md b/spring-boot-modules/spring-boot/src/test/resources/README.md deleted file mode 100644 index 51c95afd9d..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman) diff --git a/spring-boot-modules/spring-boot/src/test/resources/application.properties b/spring-boot-modules/spring-boot/src/test/resources/application.properties deleted file mode 100644 index 9ad65e1815..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -spring.mail.host=localhost -spring.mail.port=8025 -spring.mail.properties.mail.smtp.auth=false - - -# spring.datasource.x -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 -spring.datasource.username=sa -spring.datasource.password=sa - -# hibernate.X -spring.jpa.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.show_sql=true -spring.jpa.hibernate.hbm2ddl.auto=create-drop -spring.jpa.hibernate.cache.use_second_level_cache=true -spring.jpa.hibernate.cache.use_query_cache=true -spring.jpa.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory diff --git a/spring-boot-modules/spring-boot/src/test/resources/conversion.properties b/spring-boot-modules/spring-boot/src/test/resources/conversion.properties deleted file mode 100644 index 640442ec33..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/conversion.properties +++ /dev/null @@ -1,11 +0,0 @@ -###### time unit -conversion.timeInDefaultUnit=10 -conversion.timeInNano=9ns -conversion.timeInDays=2 - -###### data size -conversion.sizeInDefaultUnit=300 -conversion.sizeInGB=2GB -conversion.sizeInTB=4 - -conversion.employee=john,2000 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/resources/import.sql b/spring-boot-modules/spring-boot/src/test/resources/import.sql deleted file mode 100644 index 9095b9468c..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/import.sql +++ /dev/null @@ -1 +0,0 @@ ---insert into Foo values(1,'Foo_Name'); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json b/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json deleted file mode 100644 index f5409421a6..0000000000 --- a/spring-boot-modules/spring-boot/src/test/resources/org/baeldung/boot/expected.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "id":3, - "name":"Foo_Name_3" -} \ No newline at end of file From 4f6634745d703f6bdaba12a6ec8b1d9e68e654f8 Mon Sep 17 00:00:00 2001 From: Sameer Date: Fri, 15 Apr 2022 19:46:47 +0530 Subject: [PATCH 38/40] Spring Boot Properties Migrator Demo (#11975) * Spring Boot Properties Migrator Demo * updated demo properties (#1) Co-authored-by: s9m33r * Article/bael 5446 (#2) * updated demo properties * formatting Co-authored-by: s9m33r Co-authored-by: s9m33r --- spring-boot-modules/pom.xml | 1 + .../pom.xml | 57 +++++++++++++++++++ .../spring/boot/properties/migrator/Main.java | 11 ++++ .../src/main/resources/application-dev.yaml | 16 ++++++ .../src/main/resources/application.properties | 7 +++ 5 files changed, 92 insertions(+) create mode 100644 spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml create mode 100644 spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java create mode 100644 spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml create mode 100644 spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index a12ee55018..939add1147 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -64,6 +64,7 @@ spring-boot-properties spring-boot-properties-2 spring-boot-properties-3 + spring-boot-properties-migrator-demo spring-boot-property-exp spring-boot-runtime spring-boot-runtime-2 diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml new file mode 100644 index 0000000000..d44a8ce6f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + spring-boot-properties-migrator-demo + 1.0-SNAPSHOT + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../pom.xml + + + + + + + + + + + 8 + 8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-properties-migrator + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java new file mode 100644 index 0000000000..848b9680a0 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/java/com/baeldung/spring/boot/properties/migrator/Main.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.boot.properties.migrator; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Main { + public static void main(String[] args) { + SpringApplication.run(Main.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml new file mode 100644 index 0000000000..6eadac798b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application-dev.yaml @@ -0,0 +1,16 @@ +# Deprecated Properties for Demonstration +#spring: +# resources: +# cache: +# period: 31536000 +# chain: +# compressed: true +# html-application-cache: true + +spring: + web: + resources: + cache: + period: 31536000 + chain: + compressed: false diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..15199b7710 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-migrator-demo/src/main/resources/application.properties @@ -0,0 +1,7 @@ +# Deprecated Properties for Demonstration +#spring.resources.cache.period=31536000 +#spring.resources.chain.compressed=false +#spring.resources.chain.html-application-cache=false +spring.web.resources.cache.period=31536000 +spring.web.resources.chain.compressed=false +banner.image.location="myBanner.txt" From de77319b355da002c6cb5cc251f5481c3c29e90c Mon Sep 17 00:00:00 2001 From: Iulian Manda Date: Sun, 17 Apr 2022 14:16:25 +0300 Subject: [PATCH 39/40] BAEL-5115 Deduction-Based Polymorphism in Jackson 2.12 (#11732) * BAEL-5115 Deduction-Based Polymorphism in Jackson 2.12 * Fix pmd * Code review changes * Improvements * Code review * Code review * fix typo * Rename package * Apply formatter * Add old deduction * revert --- .../deductionbasedpolymorphism/Character.java | 12 +++ .../ControlledCharacter.java | 14 ++++ .../ImperialSpy.java | 5 ++ .../deductionbasedpolymorphism/King.java | 14 ++++ .../deductionbasedpolymorphism/Knight.java | 14 ++++ .../NamedCharacter.java | 14 ++++ .../CaseInsensitiveInferenceUnitTest.java | 33 +++++++++ .../ContainedInferenceUnitTest.java | 73 +++++++++++++++++++ .../JsonStringFormatterUtil.java | 9 +++ .../SimpleInferenceUnitTest.java | 61 ++++++++++++++++ 10 files changed, 249 insertions(+) create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java create mode 100644 jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java create mode 100644 jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java create mode 100644 jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java create mode 100644 jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java create mode 100644 jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java new file mode 100644 index 0000000000..6be7483cc2 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Character.java @@ -0,0 +1,12 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; + +@JsonTypeInfo(use = Id.DEDUCTION) +@JsonSubTypes({ @Type(ImperialSpy.class), @Type(King.class), @Type(Knight.class) }) +public interface Character { + +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java new file mode 100644 index 0000000000..9f6f03954e --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ControlledCharacter.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class ControlledCharacter { + + private Character character; + + public Character getCharacter() { + return character; + } + + public void setCharacter(Character character) { + this.character = character; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java new file mode 100644 index 0000000000..ff86966e38 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/ImperialSpy.java @@ -0,0 +1,5 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class ImperialSpy implements Character { + +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java new file mode 100644 index 0000000000..3270d92b3a --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/King.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class King extends NamedCharacter { + + private String land; + + public String getLand() { + return land; + } + + public void setLand(String land) { + this.land = land; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java new file mode 100644 index 0000000000..197d3b758b --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/Knight.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class Knight extends NamedCharacter { + + private String weapon; + + public String getWeapon() { + return weapon; + } + + public void setWeapon(String weapon) { + this.weapon = weapon; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java new file mode 100644 index 0000000000..15892f8659 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/deductionbasedpolymorphism/NamedCharacter.java @@ -0,0 +1,14 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class NamedCharacter implements Character { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java new file mode 100644 index 0000000000..cad9e73091 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/CaseInsensitiveInferenceUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class CaseInsensitiveInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) + .build(); + + @Test + void givenACaseInsensitiveKnight_whenMapping_thenExpectKnight() throws Exception { + String knightJson = formatJson("{'NaMe':'Ostrava, of Boletaria', 'WeaPON':'Rune Sword'}"); + + Character character = objectMapper.readValue(knightJson, Character.class); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight knight = (Knight) character; + assertEquals("Ostrava, of Boletaria", knight.getName()); + assertEquals("Rune Sword", knight.getWeapon()); + } + +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java new file mode 100644 index 0000000000..810051f2ab --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/ContainedInferenceUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class ContainedInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .build(); + + @Test + void givenAKnightControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKnight() throws Exception { + String controlledCharacterJson = formatJson("{'character': {'name': 'Ostrava, of Boletaria', 'weapon': 'Rune Sword'}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + Character character = controlledCharacter.getCharacter(); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight knight = (Knight) character; + assertEquals("Ostrava, of Boletaria", knight.getName()); + assertEquals("Rune Sword", knight.getWeapon()); + } + + @Test + void givenAKingControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKing() throws Exception { + String controlledCharacterJson = formatJson("{'character': {'name': 'King Allant', 'land': 'Boletaria'}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + Character character = controlledCharacter.getCharacter(); + + assertTrue(character instanceof King); + assertSame(character.getClass(), King.class); + King king = (King) character; + assertEquals("King Allant", king.getName()); + assertEquals("Boletaria", king.getLand()); + } + + @Test + void givenAnEmptySubtype_whenMapping_thenExpectImperialSpy() throws Exception { + String controlledCharacterJson = formatJson("{'character': {}}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertTrue(controlledCharacter.getCharacter() instanceof ImperialSpy); + } + + @Test + void givenANullCharacter_whenMapping_thenExpectNullCharacter() throws Exception { + String controlledCharacterJson = formatJson("{'character': null}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertNull(controlledCharacter.getCharacter()); + } + + @Test + void givenAAnAbsentCharacter_whenMapping_thenExpectNullCharacter() throws Exception { + String controlledCharacterJson = formatJson("{}"); + + ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class); + + assertNull(controlledCharacter.getCharacter()); + } +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java new file mode 100644 index 0000000000..948b264c45 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/JsonStringFormatterUtil.java @@ -0,0 +1,9 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +public class JsonStringFormatterUtil { + + public static String formatJson(String input) { + return input.replaceAll("'", "\""); + } + +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java new file mode 100644 index 0000000000..5e63e95289 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/deductionbasedpolymorphism/SimpleInferenceUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.jackson.deductionbasedpolymorphism; + +import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +class SimpleInferenceUnitTest { + + private final ObjectMapper objectMapper = JsonMapper.builder() + .build(); + + @Test + void givenAKnight_whenMapping_thenExpectAKnightType() throws Exception { + String knightJson = formatJson("{'name':'Ostrava, of Boletaria', 'weapon':'Rune Sword'}"); + + Character character = objectMapper.readValue(knightJson, Character.class); + + assertTrue(character instanceof Knight); + assertSame(character.getClass(), Knight.class); + Knight king = (Knight) character; + assertEquals("Ostrava, of Boletaria", king.getName()); + assertEquals("Rune Sword", king.getWeapon()); + } + + @Test + void givenAKing_whenMapping_thenExpectAKingType() throws Exception { + String kingJson = formatJson("{'name':'Old King Allant', 'land':'Boletaria'}"); + + Character character = objectMapper.readValue(kingJson, Character.class); + + assertTrue(character instanceof King); + assertSame(character.getClass(), King.class); + King king = (King) character; + assertEquals("Old King Allant", king.getName()); + assertEquals("Boletaria", king.getLand()); + } + + @Test + void givenAnEmptyObject_whenMapping_thenExpectAnImperialSpy() throws Exception { + String imperialSpyJson = "{}"; + + Character character = objectMapper.readValue(imperialSpyJson, Character.class); + + assertTrue(character instanceof ImperialSpy); + } + + @Test + void givenANullObject_whenMapping_thenExpectANullObject() throws Exception { + Character character = objectMapper.readValue("null", Character.class); + + assertNull(character); + } + +} From 49b61559523b7e17dc9be0a57446e758ae568116 Mon Sep 17 00:00:00 2001 From: etrandafir93 <75391049+etrandafir93@users.noreply.github.com> Date: Sun, 17 Apr 2022 14:23:51 +0200 Subject: [PATCH 40/40] BAEL-5440: hql distinct queries (#12007) * BAEL-5440: hql distinct queries * BAEL-5440: formated the code and renamed test class --- .../com/baeldung/hibernate/HibernateUtil.java | 4 + .../hibernate/distinct/entities/Comment.java | 28 +++++++ .../hibernate/distinct/entities/Post.java | 59 ++++++++++++++ .../entities/DistinctHqlQueriesUnitTest.java | 80 +++++++++++++++++++ 4 files changed, 171 insertions(+) create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java create mode 100644 persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 58724e690c..84b20197bd 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -13,6 +13,8 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.distinct.entities.Post; +import com.baeldung.hibernate.distinct.entities.Comment; import com.baeldung.hibernate.entities.DeptEmployee; import com.baeldung.hibernate.pojo.Student; @@ -41,6 +43,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Comment.class); + metadataSources.addAnnotatedClass(Post.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java new file mode 100644 index 0000000000..1d155b112e --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java @@ -0,0 +1,28 @@ +package com.baeldung.hibernate.distinct.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Comment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String text; + + public Comment() { + } + + public Comment(String text) { + this.text = text; + } + + @Override + public String toString() { + return "Comment{" + "id=" + id + ", text='" + text + '\'' + '}'; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java new file mode 100644 index 0000000000..d2608e614c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.distinct.entities; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; + +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String title; + + @OneToMany + @Cascade(CascadeType.ALL) + private List comments; + + public Post() { + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + @Override + public String toString() { + return "Post{" + "id=" + id + ", title='" + title + '\'' + ", comments=" + comments + '}'; + } +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java new file mode 100644 index 0000000000..799439a51b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.distinct.entities; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.annotations.QueryHints; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; + +public class DistinctHqlQueriesUnitTest { + + private Session session; + + @Before + public void setUp() throws IOException { + this.session = HibernateUtil.getSessionFactory() + .openSession(); + saveDummyData(); + } + + private void saveDummyData() { + Transaction trx = session.beginTransaction(); + session.createQuery("delete from Post") + .executeUpdate(); + + Post post = new Post(); + post.setTitle("Distinct Queries in HQL"); + post.setComments(Arrays.asList(new Comment("Great article!"), new Comment("Nice one :)"), new Comment("Keep up the good work!"))); + session.persist(post); + + trx.commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @Test + public void whenExecutingSelectQuery_thereWillBeDuplicates() { + String hql = "SELECT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .getResultList(); + + assertThat(posts).hasSize(3); + } + + @Test + public void whenExecutingSelectDistinctQuery_thereShouldBeNoDuplicates() { + String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .getResultList(); + + assertThat(posts).hasSize(1) + .allMatch(post -> post.getTitle() + .equals("Distinct Queries in HQL") && post.getComments() + .size() == 3); + } + + @Test + public void whenExecutingSelectDistinctQueryWithHint_thereShouldBeNoDuplicates() { + String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + List posts = session.createQuery(hql, Post.class) + .setHint(QueryHints.PASS_DISTINCT_THROUGH, false) + .getResultList(); + + assertThat(posts).hasSize(1) + .allMatch(post -> post.getTitle() + .equals("Distinct Queries in HQL") && post.getComments() + .size() == 3); + } +} \ No newline at end of file