Merge branch 'eugenp:master' into master
This commit is contained in:
commit
88261b4340
@ -19,6 +19,11 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,316 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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;
|
||||
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingShiftOperator(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingShiftOperator(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingShiftOperator(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingShiftOperator(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingShiftOperator(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingShiftOperator(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertingByteArrayToDoubleUsingShiftOperator(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingByteBuffer(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingByteBuffer(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingByteBuffer(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingByteBuffer(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingByteBuffer(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingByteBuffer(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingByteBuffer(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingBigInteger(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingBigInteger(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingBigInteger(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingBigInteger(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingBigInteger(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingBigInteger(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingBigInteger(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingBigInteger(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertingByteArrayToIntUsingGuava(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingGuava(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingGuava(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingGuava(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingGuava(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingGuava(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingGuava(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingGuava(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingCommonsLang(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingCommonsLang(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingCommonsLang(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingCommonsLang(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingCommonsLang(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingCommonsLang(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingCommonsLang(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.accentsanddiacriticsremoval;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.text.Normalizer;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
class StringNormalizer {
|
||||
|
||||
static String removeAccentsWithApacheCommons(String input) {
|
||||
return StringUtils.stripAccents(input);
|
||||
}
|
||||
|
||||
static String removeAccents(String input) {
|
||||
return normalize(input).replaceAll("\\p{M}", "");
|
||||
}
|
||||
|
||||
static String unicodeValueOfNormalizedString(String input) {
|
||||
return toUnicode(normalize(input));
|
||||
}
|
||||
|
||||
private static String normalize(String input) {
|
||||
return input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD);
|
||||
}
|
||||
|
||||
private static String toUnicode(String input) {
|
||||
if (input.length() == 1) {
|
||||
return toUnicode(input.charAt(0));
|
||||
} else {
|
||||
StringJoiner stringJoiner = new StringJoiner(" ");
|
||||
for (char c : input.toCharArray()) {
|
||||
stringJoiner.add(toUnicode(c));
|
||||
}
|
||||
return stringJoiner.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private static String toUnicode(char input) {
|
||||
|
||||
String hex = Integer.toHexString(input);
|
||||
StringBuilder sb = new StringBuilder(hex);
|
||||
|
||||
while (sb.length() < 4) {
|
||||
sb.insert(0, "0");
|
||||
}
|
||||
sb.insert(0, "\\u");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.doublequotesremoval;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
public class DoubleQuotesRemovalUtils {
|
||||
|
||||
public static String removeWithSubString(String input) {
|
||||
if (input != null && input.length() >= 2 && input.charAt(0) == '\"'
|
||||
&& input.charAt(input.length() - 1) == '\"') {
|
||||
return input.substring(1, input.length() - 1);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
public static String removeWithReplaceAllSimple(String input) {
|
||||
if (input == null || input.isEmpty())
|
||||
return input;
|
||||
|
||||
return input.replaceAll("\"", "");
|
||||
}
|
||||
|
||||
public static String removeWithReplaceAllAdvanced(String input) {
|
||||
if (input == null || input.isEmpty())
|
||||
return input;
|
||||
|
||||
return input.replaceAll("^\"|\"$", "");
|
||||
}
|
||||
|
||||
public static String removeWithGuava(String input) {
|
||||
if (input == null || input.isEmpty())
|
||||
return input;
|
||||
|
||||
return CharMatcher.is('\"').trimFrom(input);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.accentsanddiacriticsremoval;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
|
||||
import java.text.Collator;
|
||||
|
||||
import static java.lang.Character.*;
|
||||
import static java.lang.String.valueOf;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CollatorUnitTest {
|
||||
|
||||
private final Collator collator = Collator.getInstance();
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
collator.setDecomposition(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccentedStringAndPrimaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
|
||||
Collator collator = Collator.getInstance();
|
||||
collator.setDecomposition(2);
|
||||
collator.setStrength(0);
|
||||
assertEquals(0, collator.compare("a", "a"));
|
||||
assertEquals(0, collator.compare("ä", "a"));
|
||||
assertEquals(0, collator.compare("A", "a"));
|
||||
assertEquals(1, collator.compare("b", "a"));
|
||||
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccentedStringAndSecondaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
|
||||
collator.setStrength(1);
|
||||
assertEquals(1, collator.compare("ä", "a"));
|
||||
assertEquals(1, collator.compare("b", "a"));
|
||||
assertEquals(0, collator.compare("A", "a"));
|
||||
assertEquals(0, collator.compare("a", "a"));
|
||||
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccentedStringAndTeriaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
|
||||
collator.setStrength(2);
|
||||
assertEquals(1, collator.compare("A", "a"));
|
||||
assertEquals(1, collator.compare("ä", "a"));
|
||||
assertEquals(1, collator.compare("b", "a"));
|
||||
assertEquals(0, collator.compare("a", "a"));
|
||||
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccentedStringAndIdenticalCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
|
||||
collator.setStrength(3);
|
||||
assertEquals(1, collator.compare("A", "a"));
|
||||
assertEquals(1, collator.compare("ä", "a"));
|
||||
assertEquals(1, collator.compare("b", "a"));
|
||||
assertEquals(-1, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
|
||||
assertEquals(0, collator.compare("a", "a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNondecomposableAccentedStringAndIdenticalCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
|
||||
collator.setStrength(0);
|
||||
assertEquals(1, collator.compare("ł", "l"));
|
||||
assertEquals(1, collator.compare("ø", "o"));
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.accentsanddiacriticsremoval;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.Normalizer;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StringNormalizerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNotNormalizedString_whenIsNormalized_thenReturnFalse() {
|
||||
assertFalse(Normalizer.isNormalized("āăąēîïĩíĝġńñšŝśûůŷ", Normalizer.Form.NFKD));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithDecomposableUnicodeCharacters_whenRemoveAccents_thenReturnASCIIString() {
|
||||
assertEquals("aaaeiiiiggnnsssuuy", StringNormalizer.removeAccents("āăąēîïĩíĝġńñšŝśûůŷ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithDecomposableUnicodeCharacters_whenRemoveAccentsWithApacheCommons_thenReturnASCIIString() {
|
||||
assertEquals("aaaeiiiiggnnsssuuy", StringNormalizer.removeAccentsWithApacheCommons("āăąēîïĩíĝġńñšŝśûůŷ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithNondecomposableUnicodeCharacters_whenRemoveAccents_thenReturnOriginalString() {
|
||||
assertEquals("łđħœ", StringNormalizer.removeAccents("łđħœ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithNondecomposableUnicodeCharacters_whenRemoveAccentsWithApacheCommons_thenReturnModifiedString() {
|
||||
assertEquals("lđħœ", StringNormalizer.removeAccentsWithApacheCommons("łđħœ"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithDecomposableUnicodeCharacters_whenUnicodeValueOfNormalizedString_thenReturnUnicodeValue() {
|
||||
assertEquals("\\u0066 \\u0069", StringNormalizer.unicodeValueOfNormalizedString("fi"));
|
||||
assertEquals("\\u0061 \\u0304", StringNormalizer.unicodeValueOfNormalizedString("ā"));
|
||||
assertEquals("\\u0069 \\u0308", StringNormalizer.unicodeValueOfNormalizedString("ï"));
|
||||
assertEquals("\\u006e \\u0301", StringNormalizer.unicodeValueOfNormalizedString("ń"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithNonDecomposableUnicodeCharacters_whenUnicodeValueOfNormalizedString_thenReturnOriginalValue() {
|
||||
assertEquals("\\u0142", StringNormalizer.unicodeValueOfNormalizedString("ł"));
|
||||
assertEquals("\\u0127", StringNormalizer.unicodeValueOfNormalizedString("ħ"));
|
||||
assertEquals("\\u0111", StringNormalizer.unicodeValueOfNormalizedString("đ"));
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.doublequotesremoval;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DoubleQuotesRemovalUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void given_EmptyString_ShouldReturn_EmptyString() {
|
||||
String input = "";
|
||||
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithSubString(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithGuava(input).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_DoubleQuotesOnly_ShouldReturn_EmptyString() {
|
||||
String input = "\"\"";
|
||||
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithSubString(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input).isEmpty());
|
||||
assertTrue(DoubleQuotesRemovalUtils.removeWithGuava(input).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_TextWithDoubleQuotes_ShouldReturn_TextOnly() {
|
||||
|
||||
String input = "\"Example of text for this test suit\"";
|
||||
String expectedResult = "Example of text for this test suit";
|
||||
|
||||
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithSubString(input));
|
||||
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input));
|
||||
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input));
|
||||
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithGuava(input));
|
||||
}
|
||||
|
||||
}
|
@ -5,7 +5,7 @@ spring.datasource.password=
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
spring.datasource.data=data-trans.sql
|
||||
spring.sql.init.data-locations=data-trans.sql
|
||||
|
||||
logging.level.org.hibernate.SQL=INFO
|
||||
logging.level.org.hibernate.type=INFO
|
||||
|
@ -5,7 +5,7 @@ spring.datasource.password=
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
spring.datasource.data=data-trans.sql
|
||||
spring.sql.init.data-locations=data-trans.sql
|
||||
|
||||
logging.level.org.hibernate.SQL=INFO
|
||||
logging.level.org.hibernate.type=INFO
|
||||
|
@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true
|
||||
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
|
||||
|
||||
spring.jpa.properties.hibernate.hbm2ddl.import_files=import_books.sql
|
||||
spring.datasource.data=import_*_users.sql
|
||||
spring.sql.init.data-locations=import_*_users.sql
|
@ -16,46 +16,15 @@
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-cassandra</artifactId>
|
||||
<version>${org.springframework.data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
<version>${spring-boot-starter-data-cassandra.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
@ -91,17 +60,10 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.datastax.cassandra</groupId>
|
||||
<artifactId>cassandra-driver-core</artifactId>
|
||||
<version>${cassandra-driver-core.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<org.springframework.data.version>1.3.2.RELEASE</org.springframework.data.version>
|
||||
<cassandra-driver-core.version>2.1.5</cassandra-driver-core.version>
|
||||
<spring-boot-starter-data-cassandra.version>1.3.2.RELEASE</spring-boot-starter-data-cassandra.version>
|
||||
<cassandra-unit-spring.version>2.1.9.2</cassandra-unit-spring.version>
|
||||
<cassandra-unit-shaded.version>2.1.9.2</cassandra-unit-shaded.version>
|
||||
<hector-core.version>2.0-0</hector-core.version>
|
||||
|
@ -1 +1 @@
|
||||
spring.datasource.initialization-mode=never
|
||||
spring.sql.init.mode=never
|
@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties = "spring.datasource.data=classpath:insert_users.sql")
|
||||
@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql")
|
||||
public class UserRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
||||
@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql")
|
||||
public class ArticleRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
@ -1 +1 @@
|
||||
spring.datasource.data=classpath:db/import_joins.sql
|
||||
spring.sql.init.data-locations=classpath:db/import_joins.sql
|
||||
|
@ -21,7 +21,7 @@ import com.baeldung.boot.domain.Location;
|
||||
import com.baeldung.boot.domain.Store;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
||||
@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql")
|
||||
public class JpaRepositoriesIntegrationTest {
|
||||
@Autowired
|
||||
private LocationRepository locationRepository;
|
||||
|
@ -4,3 +4,4 @@
|
||||
- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
|
||||
- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing)
|
||||
- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list)
|
||||
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||
|
@ -6,7 +6,6 @@
|
||||
- [Sorting with JPA](https://www.baeldung.com/jpa-sort)
|
||||
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
|
||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
|
||||
- More articles: [[next -->]](/spring-jpa-2)
|
||||
|
||||
|
@ -1,38 +0,0 @@
|
||||
package com.baeldung.jdbc.autogenkey.repository;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class MessageRepositoryJDBCTemplate {
|
||||
|
||||
@Autowired
|
||||
JdbcTemplate jdbcTemplate;
|
||||
|
||||
final String INSERT_MESSAGE_SQL = "insert into sys_message (message) values(?) ";
|
||||
|
||||
public long insert(final String message) {
|
||||
|
||||
KeyHolder keyHolder = new GeneratedKeyHolder();
|
||||
|
||||
jdbcTemplate.update(connection -> {
|
||||
PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
|
||||
ps.setString(1, message);
|
||||
return ps;
|
||||
}, keyHolder);
|
||||
|
||||
return (long) keyHolder.getKey();
|
||||
}
|
||||
|
||||
final String SELECT_BY_ID = "select message from sys_message where id = ?";
|
||||
|
||||
public String getMessageById(long id) {
|
||||
return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id });
|
||||
}
|
||||
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package com.baeldung.jdbc.autogenkey.repository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class MessageRepositorySimpleJDBCInsert {
|
||||
|
||||
SimpleJdbcInsert messageInsert;
|
||||
|
||||
@Autowired
|
||||
public MessageRepositorySimpleJDBCInsert(DataSource dataSource) {
|
||||
messageInsert = new SimpleJdbcInsert(dataSource).withTableName("sys_message").usingGeneratedKeyColumns("id");
|
||||
}
|
||||
|
||||
public long insert(String message) {
|
||||
Map<String, Object> parameters = new HashMap<String, Object>(1);
|
||||
parameters.put("message", message);
|
||||
Number newId = messageInsert.executeAndReturnKey(parameters);
|
||||
return (long) newId;
|
||||
}
|
||||
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
|
||||
spring.datasource.initialize=true
|
||||
spring.datasource.schema=classpath:autogenkey-schema.sql
|
@ -1,5 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS sys_message (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
message varchar(100) NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
@ -1,55 +0,0 @@
|
||||
package com.baeldung.jdbc.autogenkey;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
|
||||
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@Ignore
|
||||
public class GetAutoGenKeyByJDBCIntTest {
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@PropertySource("classpath:autogenkey-db.properties")
|
||||
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" })
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
|
||||
@Autowired
|
||||
MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert;
|
||||
|
||||
@Autowired
|
||||
MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate;
|
||||
|
||||
final String MESSAGE_CONTENT = "Test";
|
||||
|
||||
@Test
|
||||
public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() {
|
||||
long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT);
|
||||
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
|
||||
|
||||
assertEquals(MESSAGE_CONTENT, loadedMessage);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() {
|
||||
long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT);
|
||||
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
|
||||
|
||||
assertEquals(MESSAGE_CONTENT, loadedMessage);
|
||||
}
|
||||
|
||||
}
|
@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableAutoConfiguration
|
||||
public class KafkaProducerConsumerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableAutoConfiguration
|
||||
public class KafkaSslApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -8,5 +8,5 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
spring.h2.console.path=/myconsole
|
||||
spring.h2.console.enabled=true
|
||||
spring.datasource.initialize=true
|
||||
spring.datasource.schema=classpath:acl-schema.sql
|
||||
spring.datasource.data=classpath:acl-data.sql
|
||||
spring.sql.init.schema-locations=classpath:acl-schema.sql
|
||||
spring.sql.init.data-locations=classpath:acl-data.sql
|
@ -1,9 +1,8 @@
|
||||
spring.datasource.platform=mysql
|
||||
spring.sql.init.platform=mysql
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=pass
|
||||
|
||||
spring.datasource.initialization-mode=always
|
||||
spring.sql.init.mode=always
|
||||
spring.jpa.hibernate.ddl-auto=none
|
||||
|
||||
spring.profiles.active=mysql
|
||||
|
@ -1,7 +1,7 @@
|
||||
spring.datasource.platform=postgre
|
||||
spring.sql.init.platform=postgre
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=pass
|
||||
|
||||
spring.datasource.initialization-mode=always
|
||||
spring.sql.init.mode=always
|
||||
spring.jpa.hibernate.ddl-auto=none
|
||||
|
@ -175,6 +175,7 @@
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<!-- Maven plugins -->
|
||||
<maven-war-plugin.version>3.2.2</maven-war-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
@ -1,16 +1,18 @@
|
||||
package com.baeldung.web.interceptor;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
import java.util.Enumeration;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Enumeration;
|
||||
|
||||
public class LoggerInterceptor extends HandlerInterceptorAdapter {
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
|
||||
public class LoggerInterceptor implements HandlerInterceptor {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
|
||||
|
||||
@ -50,7 +52,8 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
|
||||
if (posted.length() > 1)
|
||||
posted.append("&");
|
||||
final String curr = (String) e.nextElement();
|
||||
posted.append(curr).append("=");
|
||||
posted.append(curr)
|
||||
.append("=");
|
||||
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
|
||||
posted.append("*****");
|
||||
} else {
|
||||
|
@ -8,10 +8,10 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
|
||||
public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
|
||||
public class SessionTimerInterceptor implements HandlerInterceptor {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class);
|
||||
|
||||
@ -30,7 +30,8 @@ public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
|
||||
request.setAttribute("executionTime", startTime);
|
||||
if (UserInterceptor.isUserLogged()) {
|
||||
session = request.getSession();
|
||||
log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession().getLastAccessedTime());
|
||||
log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession()
|
||||
.getLastAccessedTime());
|
||||
if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) {
|
||||
log.warn("Logging out, due to inactive session");
|
||||
SecurityContextHolder.clearContext();
|
||||
|
@ -1,18 +1,18 @@
|
||||
package com.baeldung.web.interceptor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.SmartView;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
public class UserInterceptor extends HandlerInterceptorAdapter {
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.SmartView;
|
||||
import org.springframework.web.servlet.View;
|
||||
|
||||
public class UserInterceptor implements HandlerInterceptor {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(UserInterceptor.class);
|
||||
|
||||
@ -44,7 +44,9 @@ public class UserInterceptor extends HandlerInterceptorAdapter {
|
||||
*/
|
||||
private void addToModelUserDetails(HttpSession session) {
|
||||
log.info("================= addToModelUserDetails ============================");
|
||||
String loggedUsername = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
String loggedUsername = SecurityContextHolder.getContext()
|
||||
.getAuthentication()
|
||||
.getName();
|
||||
session.setAttribute("username", loggedUsername);
|
||||
log.info("user(" + loggedUsername + ") session : " + session);
|
||||
log.info("================= addToModelUserDetails ============================");
|
||||
@ -56,7 +58,9 @@ public class UserInterceptor extends HandlerInterceptorAdapter {
|
||||
*/
|
||||
private void addToModelUserDetails(ModelAndView model) {
|
||||
log.info("================= addToModelUserDetails ============================");
|
||||
String loggedUsername = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
String loggedUsername = SecurityContextHolder.getContext()
|
||||
.getAuthentication()
|
||||
.getName();
|
||||
model.addObject("loggedUsername", loggedUsername);
|
||||
log.trace("session : " + model.getModel());
|
||||
log.info("================= addToModelUserDetails ============================");
|
||||
@ -76,7 +80,10 @@ public class UserInterceptor extends HandlerInterceptorAdapter {
|
||||
|
||||
public static boolean isUserLogged() {
|
||||
try {
|
||||
return !SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser");
|
||||
return !SecurityContextHolder.getContext()
|
||||
.getAuthentication()
|
||||
.getName()
|
||||
.equals("anonymousUser");
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
@ -30,8 +30,8 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<xstream.version>1.4.10</xstream.version>
|
||||
<jettison.version>1.3.8</jettison.version>
|
||||
<xstream.version>1.4.18</xstream.version>
|
||||
<jettison.version>1.4.1</jettison.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -7,7 +7,11 @@ import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
|
||||
public class SimpleXstreamInitializer {
|
||||
|
||||
public XStream getXstreamInstance() {
|
||||
return new XStream();
|
||||
XStream xstream = new XStream();
|
||||
xstream.allowTypesByWildcard(new String[]{
|
||||
"com.baeldung.**"
|
||||
});
|
||||
return xstream;
|
||||
}
|
||||
|
||||
public XStream getXstreamJettisonMappedInstance() {
|
||||
|
@ -21,6 +21,7 @@ public final class XStreamBasicsUnitTest {
|
||||
public void before() {
|
||||
xstream = new XStream();
|
||||
xstream.alias("person", Person.class);
|
||||
xstream.allowTypes(new Class<?>[] { Person.class });
|
||||
}
|
||||
|
||||
@Test
|
||||
|
Loading…
x
Reference in New Issue
Block a user