Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu 2019-07-06 23:27:06 +03:00 committed by GitHub
commit 3d5931b0ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 1878 additions and 366 deletions

View File

@ -22,6 +22,7 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<icu.version>64.2</icu.version>
<assertj.version>3.12.2</assertj.version>
</properties>
<dependencies>
@ -30,6 +31,12 @@
<artifactId>icu4j</artifactId>
<version>${icu.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,164 @@
package com.baeldung.bifunction;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class BiFunctionalInterfacesUnitTest {
@Test
public void givenStreamValues_whenMappedToNewValues() {
List<String> mapped = Stream.of("hello", "world")
.map(word -> word + "!")
.collect(Collectors.toList());
assertThat(mapped).containsExactly("hello!", "world!");
}
@Test
public void givenStreamValues_whenReducedWithPrefixingOperation() {
String result = Stream.of("hello", "world")
.reduce("", (a, b) -> b + "-" + a);
assertThat(result).isEqualTo("world-hello-");
}
@Test
public void givenStreamValues_whenReducedWithPrefixingLambda_thenHasNoTrailingDash() {
String result = Stream.of("hello", "world")
.reduce("", (a, b) -> combineWithoutTrailingDash(a, b));
assertThat(result).isEqualTo("world-hello");
}
private String combineWithoutTrailingDash(String a, String b) {
if (a.isEmpty()) {
return b;
}
return b + "-" + a;
}
@Test
public void givenStreamValues_whenReducedWithPrefixingMethodReference_thenHasNoTrailingDash() {
String result = Stream.of("hello", "world")
.reduce("", this::combineWithoutTrailingDash);
assertThat(result).isEqualTo("world-hello");
}
@Test
public void givenTwoLists_whenCombined() {
List<String> list1 = Arrays.asList("a", "b", "c");
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<String> result = new ArrayList<>();
for (int i=0; i < list1.size(); i++) {
result.add(list1.get(i) + list2.get(i));
}
assertThat(result).containsExactly("a1", "b2", "c3");
}
@Test
public void givenTwoLists_whenCombinedWithGeneralPurposeCombiner() {
List<String> list1 = Arrays.asList("a", "b", "c");
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<String> result = listCombiner(list1, list2, (a, b) -> a + b);
assertThat(result).containsExactly("a1", "b2", "c3");
}
private static <T, U, R> List<R> listCombiner(List<T> list1,
List<U> list2,
BiFunction<T, U, R> combiner) {
List<R> result = new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
result.add(combiner.apply(list1.get(i), list2.get(i)));
}
return result;
}
@Test
public void givenTwoLists_whenComparedWithCombiningFunction() {
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
// algorithm to determine if the value in list1 > value in list 2
List<Boolean> result = listCombiner(list1, list2, (a, b) -> a > b);
assertThat(result).containsExactly(true, true, false);
}
@Test
public void givenTwoLists_whenComparedWithCombiningFunctionByMethodReference() {
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
// algorithm to determine if the value in list1 > value in list 2
List<Boolean> result = listCombiner(list1, list2, this::firstIsGreaterThanSecond);
assertThat(result).containsExactly(true, true, false);
}
private boolean firstIsGreaterThanSecond(Double a, Float b) {
return a > b;
}
@Test
public void givenTwoLists_whenComparedForEqualityByCombiningFunction() {
List<Float> list1 = Arrays.asList(0.1f, 0.2f, 4f);
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
List<Boolean> result = listCombiner(list1, list2, (a, b) -> a.equals(b));
assertThat(result).containsExactly(true, true, true);
}
@Test
public void givenTwoLists_whenComparedForEqualityByCombiningFunctionWithMethodReference() {
List<Float> list1 = Arrays.asList(0.1f, 0.2f, 4f);
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
List<Boolean> result = listCombiner(list1, list2, Float::equals);
assertThat(result).containsExactly(true, true, true);
}
@Test
public void givenTwoLists_whenComparedWithCombiningFunctionWithCompareTo() {
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
List<Double> list2 = Arrays.asList(0.1d, 0.2d, 4d);
List<Integer> result = listCombiner(list1, list2, Double::compareTo);
assertThat(result).containsExactly(1, 1, -1);
}
/**
* Allows you to to pass in a lambda or method reference and then
* get access to the BiFunction it is meant to become
*/
private static <T, U, R> BiFunction<T, U, R> asBiFunction(BiFunction<T, U, R> function) {
return function;
}
@Test
public void givenTwoLists_whenComparedWithCombiningFunctionWithComposedBiFunction() {
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
List<Double> list2 = Arrays.asList(0.1d, 0.2d, 4d);
List<Boolean> result = listCombiner(list1, list2,
asBiFunction(Double::compareTo)
.andThen(i -> i > 0));
assertThat(result).containsExactly(true, true, false);
}
}

View File

@ -389,7 +389,7 @@
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>

View File

@ -1,49 +0,0 @@
package com.baeldung.array;
import java.util.Arrays;
import java.util.Scanner;
public class JaggedArray {
int[][] shortHandFormInitialization() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
return jaggedArr;
}
int[][] declarationAndThenInitialization() {
int[][] jaggedArr = new int[3][];
jaggedArr[0] = new int[] { 1, 2 };
jaggedArr[1] = new int[] { 3, 4, 5 };
jaggedArr[2] = new int[] { 6, 7, 8, 9 };
return jaggedArr;
}
int[][] declarationAndThenInitializationUsingUserInputs() {
int[][] jaggedArr = new int[3][];
jaggedArr[0] = new int[2];
jaggedArr[1] = new int[3];
jaggedArr[2] = new int[4];
initializeElements(jaggedArr);
return jaggedArr;
}
void initializeElements(int[][] jaggedArr) {
Scanner sc = new Scanner(System.in);
for (int outer = 0; outer < jaggedArr.length; outer++) {
for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
jaggedArr[outer][inner] = sc.nextInt();
}
}
}
void printElements(int[][] jaggedArr) {
for (int index = 0; index < jaggedArr.length; index++) {
System.out.println(Arrays.toString(jaggedArr[index]));
}
}
int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
return jaggedArr[index];
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.array;
import java.util.Arrays;
import java.util.Scanner;
public class MultiDimensionalArray {
int[][] shortHandFormInitialization() {
int[][] multiDimensionalArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
return multiDimensionalArray;
}
int[][] declarationAndThenInitialization() {
int[][] multiDimensionalArray = new int[3][];
multiDimensionalArray[0] = new int[] { 1, 2 };
multiDimensionalArray[1] = new int[] { 3, 4, 5 };
multiDimensionalArray[2] = new int[] { 6, 7, 8, 9 };
return multiDimensionalArray;
}
int[][] declarationAndThenInitializationUsingUserInputs() {
int[][] multiDimensionalArray = new int[3][];
multiDimensionalArray[0] = new int[2];
multiDimensionalArray[1] = new int[3];
multiDimensionalArray[2] = new int[4];
initializeElements(multiDimensionalArray);
return multiDimensionalArray;
}
void initializeElements(int[][] multiDimensionalArray) {
Scanner sc = new Scanner(System.in);
for (int outer = 0; outer < multiDimensionalArray.length; outer++) {
for (int inner = 0; inner < multiDimensionalArray[outer].length; inner++) {
multiDimensionalArray[outer][inner] = sc.nextInt();
}
}
}
void initialize2DArray(int[][] multiDimensionalArray) {
for (int[] array : multiDimensionalArray) {
Arrays.fill(array, 7);
}
}
void printElements(int[][] multiDimensionalArray) {
for (int index = 0; index < multiDimensionalArray.length; index++) {
System.out.println(Arrays.toString(multiDimensionalArray[index]));
}
}
int[] getElementAtGivenIndex(int[][] multiDimensionalArray, int index) {
return multiDimensionalArray[index];
}
int[] findLengthOfElements(int[][] multiDimensionalArray) {
int[] arrayOfLengths = new int[multiDimensionalArray.length];
for (int i = 0; i < multiDimensionalArray.length; i++) {
arrayOfLengths[i] = multiDimensionalArray[i].length;
}
return arrayOfLengths;
}
Integer[] findLengthOfElements(Integer[][] multiDimensionalArray) {
return Arrays.stream(multiDimensionalArray)
.map(array -> array.length)
.toArray(Integer[]::new);
}
int[][] copy2DArray(int[][] arrayOfArrays) {
int[][] copied2DArray = new int[arrayOfArrays.length][];
for (int i = 0; i < arrayOfArrays.length; i++) {
int[] array = arrayOfArrays[i];
copied2DArray[i] = Arrays.copyOf(array, array.length);
}
return copied2DArray;
}
Integer[][] copy2DArray(Integer[][] arrayOfArrays) {
return Arrays.stream(arrayOfArrays)
.map(array -> Arrays.copyOf(array, array.length))
.toArray(Integer[][]::new);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.array;
import org.apache.commons.lang3.ArrayUtils;
public class RemoveElementFromAnArray {
public int[] removeAnElementWithAGivenIndex(int[] array, int index) {
return ArrayUtils.remove(array, index);
}
public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) {
return ArrayUtils.removeAll(array, indicies);
}
public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) {
return ArrayUtils.removeElement(array, element);
}
public int[] removeAllGivenElements(int[] array, int... elements) {
return ArrayUtils.removeElements(array, elements);
}
public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) {
return ArrayUtils.removeAllOccurences(array, element);
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.array;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.junit.Test;
public class JaggedArrayUnitTest {
private JaggedArray obj = new JaggedArray();
@Test
public void whenInitializedUsingShortHandForm_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
System.setIn(is);
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
System.setIn(System.in);
}
@Test
public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0));
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1));
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2));
}
@Test
public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
obj.printElements(jaggedArr);
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out);
}
}

View File

@ -0,0 +1,86 @@
package com.baeldung.array;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.junit.Test;
public class MultiDimensionalArrayUnitTest {
private MultiDimensionalArray obj = new MultiDimensionalArray();
@Test
public void whenInitializedUsingShortHandForm_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
System.setIn(is);
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
System.setIn(System.in);
}
@Test
public void givenMultiDimensionalArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(multiDimensionalArr, 0));
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(multiDimensionalArr, 1));
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(multiDimensionalArr, 2));
}
@Test
public void givenMultiDimensionalArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
obj.printElements(multiDimensionalArr);
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out);
}
@Test
public void givenMultiDimensionalArray_whenUsingArraysFill_thenVerifyInitialize2DArray() {
int[][] multiDimensionalArr = new int[3][];
multiDimensionalArr[0] = new int[2];
multiDimensionalArr[1] = new int[3];
multiDimensionalArr[2] = new int[4];
obj.initialize2DArray(multiDimensionalArr);
assertArrayEquals(new int[][] {{7,7}, {7,7,7}, {7,7,7,7}}, multiDimensionalArr);
}
@Test
public void givenMultiDimensionalArray_whenUsingIteration_thenVerifyFindLengthOfElements() {
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new int[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr));
}
@Test
public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyFindLengthOfElements() {
Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new Integer[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr));
}
@Test
public void givenMultiDimensionalArray_whenUsingArraysCopyOf_thenVerifyCopy2DArray() {
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr));
}
@Test
public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyCopy2DArray() {
Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr));
}
}

View File

@ -0,0 +1,85 @@
package com.baeldung.array;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
class RemoveElementFromAnArrayUnitTest {
private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray();
private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 };
@Test
void testRemoveAnElementWithAGivenIndex() {
int index = 2;
int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index]));
}
@Test
void testRemoveAllElementsWithGivenIndices() {
int first = 0;
int last = inputArray.length - 1;
int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last]));
}
@Test
void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() {
int index = 2;
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAnElementWithAGivenIndex(null, index);
});
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAllElementsWithGivenIndices(null, index);
});
}
@Test
void testRemoveFirstOccurrenceOfGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element);
int indexInInputArray = ArrayUtils.indexOf(inputArray, element);
int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element);
assertFalse(indexInInputArray == indexInModifiedArray);
}
@Test
void testRemoveAllGivenElements() {
int duplicateElement = 40;
int[] elements = new int[] { duplicateElement, 10, 50 };
int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements);
assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement));
assertFalse(ArrayUtils.contains(modifiedArray, elements[1]));
assertFalse(ArrayUtils.contains(modifiedArray, elements[2]));
}
@Test
void testRemoveAllOccurrencesOfAGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element);
assertFalse(ArrayUtils.contains(modifiedArray, element));
}
@Test
void testRemoveElement_WhenArrayIsNull_ReturnsNull() {
int element = 20;
assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element));
assertEquals(null, sut.removeAllGivenElements(null, element));
assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.random;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.DoubleStream;
public interface SecureRandomDemo {
public static void generateSecureRandomValues() {
SecureRandom sr = new SecureRandom();
int randomInt = sr.nextInt();
long randomLong = sr.nextLong();
float randomFloat = sr.nextFloat();
double randomDouble = sr.nextDouble();
boolean randomBoolean = sr.nextBoolean();
IntStream randomIntStream = sr.ints();
LongStream randomLongStream = sr.longs();
DoubleStream randomDoubleStream = sr.doubles();
byte[] values = new byte[124];
sr.nextBytes(values);
}
public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException {
if (algorithm == null || algorithm.isEmpty()) {
return new SecureRandom();
}
return SecureRandom.getInstance(algorithm);
}
}

View File

@ -20,6 +20,13 @@
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<!-- test scoped -->
<dependency>

View File

@ -0,0 +1,5 @@
package com.baeldung.date.validation;
public interface DateValidator {
boolean isValid(String dateStr);
}

View File

@ -0,0 +1,11 @@
package com.baeldung.date.validation;
import org.apache.commons.validator.GenericValidator;
public class DateValidatorUsingApacheValidator implements DateValidator {
@Override
public boolean isValid(String dateStr) {
return GenericValidator.isDate(dateStr, "yyyy-MM-dd", true);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.date.validation;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateValidatorUsingDateFormat implements DateValidator {
private String dateFormat;
public DateValidatorUsingDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public boolean isValid(String dateStr) {
DateFormat sdf = new SimpleDateFormat(this.dateFormat);
sdf.setLenient(false);
try {
sdf.parse(dateStr);
} catch (ParseException e) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.date.validation;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class DateValidatorUsingDateTimeFormatter implements DateValidator {
private DateTimeFormatter dateFormatter;
public DateValidatorUsingDateTimeFormatter(DateTimeFormatter dateFormatter) {
this.dateFormatter = dateFormatter;
}
@Override
public boolean isValid(String dateStr) {
try {
this.dateFormatter.parse(dateStr);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.date.validation;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class DateValidatorUsingLocalDate implements DateValidator {
private DateTimeFormatter dateFormatter;
public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) {
this.dateFormatter = dateFormatter;
}
@Override
public boolean isValid(String dateStr) {
try {
LocalDate.parse(dateStr, this.dateFormatter);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.date.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.validator.GenericValidator;
import org.junit.Test;
public class DateValidatorUsingApacheValidatorUnitTest {
@Test
public void whenValidDatePassed_ThenTrue() {
assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true));
}
@Test
public void whenInvalidDatePassed_ThenFalse() {
assertFalse(GenericValidator.isDate("2019-02-29", "yyyy-MM-dd", true));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.date.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DateValidatorUsingDateFormatUnitTest {
@Test
public void givenValidator_whenValidDatePassed_ThenTrue() {
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy");
assertTrue(validator.isValid("02/28/2019"));
}
@Test
public void givenValidator_whenInvalidDatePassed_ThenFalse() {
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy");
assertFalse(validator.isValid("02/30/2019"));
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.date.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
import org.junit.Test;
public class DateValidatorUsingDateTimeFormatterUnitTest {
@Test
public void givenValidator_whenValidDatePassed_ThenTrue() {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US)
.withResolverStyle(ResolverStyle.STRICT);
DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter);
assertTrue(validator.isValid("2019-02-28"));
}
@Test
public void givenValidator_whenInValidDatePassed_ThenFalse() {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US)
.withResolverStyle(ResolverStyle.STRICT);
DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter);
assertFalse(validator.isValid("2019-02-30"));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.date.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
public class DateValidatorUsingLocalDateUnitTest {
@Test
public void givenValidator_whenValidDatePassed_ThenTrue() {
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter);
assertTrue(validator.isValid("20190228"));
}
@Test
public void givenValidator_whenInValidDatePassed_ThenFalse() {
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter);
assertFalse(validator.isValid("20190230"));
}
}

View File

@ -3,3 +3,4 @@
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)

View File

@ -57,6 +57,26 @@
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
@ -86,7 +106,7 @@
<properties>
<commons-lang3.version>3.8.1</commons-lang3.version>
<icu4j.version>61.1</icu4j.version>
<guava.version>27.0.1-jre</guava.version>
<guava.version>28.0-jre</guava.version>
<commons-text.version>1.4</commons-text.version>
</properties>

View File

@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class EmptyStringCheck {
boolean isEmptyString(String string) {
return string == null || string.isEmpty();
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class Java5EmptyStringCheck {
boolean isEmptyString(String string) {
return string == null || string.length() == 0;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class PlainJavaBlankStringCheck {
boolean isBlankString(String string) {
return string == null || string.trim().isEmpty();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.string.emptystrings;
import javax.validation.constraints.Pattern;
class SomeClassWithValidations {
@Pattern(regexp = "\\A(?!\\s*\\Z).+")
private String someString;
SomeClassWithValidations setSomeString(String someString) {
this.someString = someString;
return this;
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.string.multiline;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
public class MultiLineString {
String newLine = System.getProperty("line.separator");
public String stringConcatenation() {
return "Get busy living"
.concat(newLine)
.concat("or")
.concat(newLine)
.concat("get busy dying.")
.concat(newLine)
.concat("--Stephen King");
}
public String stringJoin() {
return String.join(newLine,
"Get busy living",
"or",
"get busy dying.",
"--Stephen King");
}
public String stringBuilder() {
return new StringBuilder()
.append("Get busy living")
.append(newLine)
.append("or")
.append(newLine)
.append("get busy dying.")
.append(newLine)
.append("--Stephen King")
.toString();
}
public String stringWriter() {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.println("Get busy living");
printWriter.println("or");
printWriter.println("get busy dying.");
printWriter.println("--Stephen King");
return stringWriter.toString();
}
public String guavaJoiner() {
return Joiner.on(newLine).join(ImmutableList.of("Get busy living",
"or",
"get busy dying.",
"--Stephen King"));
}
public String loadFromFile() throws IOException {
return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt")));
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.string.reverse;
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
public static String reverse(String input) {
if (input == null) {
return null;
}
String output = "";
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
return output;
}
public static String reverseUsingStringBuilder(String input) {
if (input == null) {
return null;
}
StringBuilder output = new StringBuilder(input).reverse();
return output.toString();
}
public static String reverseUsingApacheCommons(String input) {
return StringUtils.reverse(input);
}
public static String reverseTheOrderOfWords(String sentence) {
if (sentence == null) {
return null;
}
StringBuilder output = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
output.append(words[i]);
output.append(" ");
}
return output.toString()
.trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
}

View File

@ -0,0 +1,4 @@
Get busy living
or
get busy dying.
--Stephen King

View File

@ -0,0 +1,22 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import com.baeldung.string.multiline.MultiLineString;
public class MultiLineStringUnitTest {
@Test
public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException {
MultiLineString ms = new MultiLineString();
assertEquals(ms.stringConcatenation(), ms.stringJoin());
assertEquals(ms.stringJoin(), ms.stringBuilder());
assertEquals(ms.stringBuilder(), ms.guavaJoiner());
assertEquals(ms.guavaJoiner(), ms.loadFromFile());
}
}

View File

@ -0,0 +1,142 @@
package com.baeldung.string.emptystrings;
import static org.hamcrest.Matchers.iterableWithSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.Strings;
public class EmptyStringsUnitTest {
private String emptyString = "";
private String blankString = " \n\t ";
private String nonEmptyString = " someString ";
/*
* EmptyStringCheck
*/
@Test
public void givenSomeEmptyString_thenEmptyStringCheckIsEmptyStringReturnsTrue() {
assertTrue(new EmptyStringCheck().isEmptyString(emptyString));
}
@Test
public void givenSomeNonEmptyString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
assertFalse(new EmptyStringCheck().isEmptyString(nonEmptyString));
}
@Test
public void givenSomeBlankString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
assertFalse(new EmptyStringCheck().isEmptyString(blankString));
}
/*
* Java5EmptyStringCheck
*/
@Test
public void givenSomeEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsTrue() {
assertTrue(new Java5EmptyStringCheck().isEmptyString(emptyString));
}
@Test
public void givenSomeNonEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
assertFalse(new Java5EmptyStringCheck().isEmptyString(nonEmptyString));
}
@Test
public void givenSomeBlankString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
assertFalse(new Java5EmptyStringCheck().isEmptyString(blankString));
}
/*
* PlainJavaBlankStringCheck
*/
@Test
public void givenSomeEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
assertTrue(new PlainJavaBlankStringCheck().isBlankString(emptyString));
}
@Test
public void givenSomeNonEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsFalse() {
assertFalse(new PlainJavaBlankStringCheck().isBlankString(nonEmptyString));
}
@Test
public void givenSomeBlankString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
assertTrue(new PlainJavaBlankStringCheck().isBlankString(blankString));
}
/*
* Apache Commons Lang StringUtils
*/
@Test
public void givenSomeEmptyString_thenStringUtilsIsBlankReturnsTrue() {
assertTrue(StringUtils.isBlank(emptyString));
}
@Test
public void givenSomeNonEmptyString_thenStringUtilsIsBlankReturnsFalse() {
assertFalse(StringUtils.isBlank(nonEmptyString));
}
@Test
public void givenSomeBlankString_thenStringUtilsIsBlankReturnsTrue() {
assertTrue(StringUtils.isBlank(blankString));
}
/*
* Google Guava Strings
*/
@Test
public void givenSomeEmptyString_thenStringsIsNullOrEmptyStringReturnsTrue() {
assertTrue(Strings.isNullOrEmpty(emptyString));
}
@Test
public void givenSomeNonEmptyString_thenStringsIsNullOrEmptyStringReturnsFalse() {
assertFalse(Strings.isNullOrEmpty(nonEmptyString));
}
@Test
public void givenSomeBlankString_thenStringsIsNullOrEmptyStringReturnsFalse() {
assertFalse(Strings.isNullOrEmpty(blankString));
}
/*
* Bean Validation
*/
private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
private Validator validator = factory.getValidator();
@Test
public void givenSomeEmptyString_thenBeanValidationReturnsViolations() {
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(emptyString);
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
assertThat(violations, iterableWithSize(1));
}
@Test
public void givenSomeNonEmptyString_thenBeanValidationValidatesWithoutViolations() {
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(nonEmptyString);
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
assertThat(violations, iterableWithSize(0));
}
@Test
public void givenSomeBlankString_thenBeanValidationReturnsViolations() {
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(blankString);
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
assertThat(violations, iterableWithSize(1));
}
}

View File

@ -9,11 +9,11 @@ public class SubstringRepetitionUnitTest {
private String validString = "aa";
private String validStringTwo = "ababab";
private String validStringThree = "aabcaabcaabcaabc";
private String validStringThree = "baeldungbaeldung";
private String invalidString = "aca";
private String invalidStringTwo = "ababa";
private String invalidStringThree = "abcdab";
private String invalidStringThree = "baeldungnonrepeatedbaeldung";
@Test
public void givenValidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsTrue() {

View File

@ -0,0 +1,70 @@
package com.baeldung.string.reverse;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReverseStringExamplesUnitTest {
private static final String STRING_INPUT = "cat";
private static final String STRING_INPUT_REVERSED = "tac";
private static final String SENTENCE = "The quick brown fox jumps over the lazy dog";
private static final String REVERSED_WORDS_SENTENCE = "dog lazy the over jumps fox brown quick The";
@Test
public void whenReverseIsCalled_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverse(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverse(null);
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned() throws Exception {
String reversed = ReverseStringExamples.reverseUsingStringBuilder(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverseUsingStringBuilder(null);
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() throws Exception {
String reversed = ReverseStringExamples.reverseUsingApacheCommons(STRING_INPUT);
String reversedNull = ReverseStringExamples.reverseUsingApacheCommons(null);
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
assertEquals(null, reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverseTheOrderOfWords(SENTENCE);
String reversedNull = ReverseStringExamples.reverseTheOrderOfWords(null);
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
assertEquals(null, reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@Test
public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() {
String reversed = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(SENTENCE);
String reversedNull = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(null);
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
assertEquals(null, reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
}

View File

@ -1,70 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries2</artifactId>
<name>libraries2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>parallel-collectors</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>${classgraph.version}</version>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-test</artifactId>
<version>${jbpm.version}</version>
</dependency>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>${picocli.version}</version>
</dependency>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries2</artifactId>
<name>libraries2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.mapdb</groupId>
<artifactId>mapdb</artifactId>
<version>${mapdb.version}</version>
</dependency>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>parallel-collectors</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>${classgraph.version}</version>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-test</artifactId>
<version>${jbpm.version}</version>
</dependency>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>${picocli.version}</version>
</dependency>
<dependency>
<groupId>org.ejml</groupId>
<artifactId>ejml-all</artifactId>
<version>${ejml.version}</version>
</dependency>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native</artifactId>
<version>${nd4j.version}</version>
</dependency>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native</artifactId>
<version>${nd4j.version}</version>
</dependency>
<dependency>
<groupId>org.la4j</groupId>
<artifactId>la4j</artifactId>
@ -75,87 +76,85 @@
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle-map</artifactId>
<version>${chronicle.map.version}</version>
<exclusions>
<exclusion>
<groupId>com.sun.java</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Dependencies for response decoder with okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.14.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle-map</artifactId>
<version>${chronicle.map.version}</version>
<exclusions>
<exclusion>
<groupId>com.sun.java</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Dependencies for response decoder with okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.14.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>edu.uci.ics</groupId>
<artifactId>crawler4j</artifactId>
<version>${crawler4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
<version>4.1.2</version>
</dependency>
<!-- Benchmarking -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.2</assertj.version>
<classgraph.version>4.8.28</classgraph.version>
<jbpm.version>6.0.0.Final</jbpm.version>
<picocli.version>3.9.6</picocli.version>
<chronicle.map.version>3.17.2</chronicle.map.version>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
<version>4.1.2</version>
</dependency>
<!-- Benchmarking -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.mesos</groupId>
<artifactId>mesos</artifactId>
<version>${mesos.library.version}</version>
</dependency>
</dependencies>
<properties>
<mapdb.version>3.0.7</mapdb.version>
<assertj.version>3.6.2</assertj.version>
<classgraph.version>4.8.28</classgraph.version>
<jbpm.version>6.0.0.Final</jbpm.version>
<picocli.version>3.9.6</picocli.version>
<chronicle.map.version>3.17.2</chronicle.map.version>
<crawler4j.version>4.4.0</crawler4j.version>
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
<ejml.version>0.38</ejml.version>
<nd4j.version>1.0.0-beta4</nd4j.version>
<colt.version>1.2.0</colt.version>
<la4j.version>0.6.0</la4j.version>
<jmh.version>1.19</jmh.version>
</properties>
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
<ejml.version>0.38</ejml.version>
<nd4j.version>1.0.0-beta4</nd4j.version>
<colt.version>1.2.0</colt.version>
<la4j.version>0.6.0</la4j.version>
<jmh.version>1.19</jmh.version>
<mesos.library.version>0.28.3</mesos.library.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.mesos;
import com.baeldung.mesos.schedulers.HelloWorldScheduler;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.CommandInfo;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.FrameworkInfo;
public class HelloWorldMain {
public static void main(String[] args) {
String path = System.getProperty("user.dir")
+ "/target/libraries2-1.0.0-SNAPSHOT.jar";
CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build();
String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor";
CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri)
.build();
ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder()
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor"))
.setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build();
FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000)
.setUser("")
.setName("Hello World Framework (Java)");
frameworkBuilder.setPrincipal("test-framework-java");
MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]);
int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver.stop();
System.exit(status);
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.mesos.executors;
import org.apache.mesos.Executor;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.MesosExecutorDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.TaskInfo;
public class HelloWorldExecutor implements Executor {
@Override
public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) {
}
@Override
public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) {
}
@Override
public void disconnected(ExecutorDriver driver) {
}
@Override
public void launchTask(ExecutorDriver driver, TaskInfo task) {
Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_RUNNING).build();
driver.sendStatusUpdate(status);
String myStatus = "Hello Framework";
driver.sendFrameworkMessage(myStatus.getBytes());
System.out.println("Hello World!!!");
status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
.setState(Protos.TaskState.TASK_FINISHED).build();
driver.sendStatusUpdate(status);
}
@Override
public void killTask(ExecutorDriver driver, Protos.TaskID taskId) {
}
@Override
public void frameworkMessage(ExecutorDriver driver, byte[] data) {
}
@Override
public void shutdown(ExecutorDriver driver) {
}
@Override
public void error(ExecutorDriver driver, String message) {
}
public static void main(String[] args) {
MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor());
System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1);
}
}

View File

@ -0,0 +1,100 @@
package com.baeldung.mesos.schedulers;
import com.google.protobuf.ByteString;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.OfferID;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.util.ArrayList;
import java.util.List;
public class HelloWorldScheduler implements Scheduler {
private int launchedTasks = 0;
private final ExecutorInfo helloWorldExecutor;
public HelloWorldScheduler(ExecutorInfo helloWorldExecutor) {
this.helloWorldExecutor = helloWorldExecutor;
}
@Override
public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) {
}
@Override
public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) {
}
@Override
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> list) {
for (Offer offer : list) {
List<TaskInfo> tasks = new ArrayList<TaskInfo>();
Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build();
System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java");
TaskInfo printHelloWorld = TaskInfo
.newBuilder()
.setName("printHelloWorld " + taskId.getValue())
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addResources(
Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(1)))
.addResources(
Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(128)))
.setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build();
List<OfferID> offerIDS = new ArrayList<>();
offerIDS.add(offer.getId());
tasks.add(printHelloWorld);
schedulerDriver.declineOffer(offer.getId());
schedulerDriver.launchTasks(offerIDS, tasks);
}
}
@Override
public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) {
}
@Override
public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) {
}
@Override
public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) {
}
@Override
public void disconnected(SchedulerDriver schedulerDriver) {
}
@Override
public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) {
}
@Override
public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) {
}
@Override
public void error(SchedulerDriver schedulerDriver, String s) {
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import java.util.NavigableSet;
import static junit.framework.Assert.assertEquals;
public class CollectionsUnitTest {
@Test
public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() {
DB db = DBMaker.memoryDB().make();
NavigableSet<String> set = db.
treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
String myString = "Baeldung!";
set.add(myString);
set.add(myString);
assertEquals(1, set.size());
db.close();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.mapdb;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.mapdb.*;
import java.io.IOException;
import static junit.framework.Assert.assertEquals;
public class HTreeMapUnitTest {
@Test
public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() {
DB db = DBMaker.memoryDB().make();
HTreeMap<String, String> hTreeMap = db
.hashMap("myTreMap")
.keySerializer(Serializer.STRING)
.valueSerializer(Serializer.STRING)
.create();
hTreeMap.put("key1", "value1");
hTreeMap.put("key2", "value2");
assertEquals(2, hTreeMap.size());
//add another value with the same key
hTreeMap.put("key1", "value3");
assertEquals(2, hTreeMap.size());
assertEquals("value3", hTreeMap.get("key1"));
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import java.util.concurrent.ConcurrentMap;
import static junit.framework.Assert.assertEquals;
public class HelloBaeldungUnitTest {
@Test
public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.memoryDB().make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
@Test
public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.fileDB("file.db").make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import static junit.framework.Assert.assertEquals;
public class InMemoryModesUnitTest {
@Test
public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.heapDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDirectDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.Serializer;
import org.mapdb.SortedTableMap;
import org.mapdb.volume.MappedFileVol;
import org.mapdb.volume.Volume;
import static junit.framework.Assert.assertEquals;
public class SortedTableMapUnitTest {
private static final String VOLUME_LOCATION = "sortedTableMapVol.db";
@Test
public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() {
//create memory mapped volume, readonly false
Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false);
//create sink to feed the map with data
SortedTableMap.Sink<Integer, String> sink =
SortedTableMap.create(
vol,
Serializer.INTEGER,
Serializer.STRING
).createFromSink();
//add content
for(int i = 0; i < 100; i++){
sink.put(i, "Value " + Integer.toString(i));
}
sink.create();
//now open in read-only mode
Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true);
SortedTableMap<Integer, String> sortedTableMap = SortedTableMap.open(
openVol,
Serializer.INTEGER,
Serializer.STRING
);
assertEquals(100, sortedTableMap.size());
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.mapdb;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import java.util.NavigableSet;
import static junit.framework.Assert.assertEquals;
public class TransactionsUnitTest {
@Test
public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() {
DB db = DBMaker.memoryDB().transactionEnable().make();
NavigableSet<String> set = db
.treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
set.add("One");
set.add("Two");
db.commit();
assertEquals(2, set.size());
set.add("Three");
assertEquals(3, set.size());
db.rollback();
assertEquals(2, set.size());
db.close();
}
}

View File

@ -19,6 +19,9 @@
<version>${typesafe-akka.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-testkit_2.12</artifactId>
@ -837,6 +840,7 @@
<h2.version>1.4.196</h2.version>
<jnats.version>1.0</jnats.version>
<httpclient.version>4.5.3</httpclient.version>
<jackson.version>2.9.7</jackson.version>
<neuroph.version>2.92</neuroph.version>

View File

@ -1147,7 +1147,7 @@
<module>java-rmi</module>
<module>java-spi</module>
<module>java-streams</module>
<module>java-streams-2</module>
<!-- <module>java-streams-2</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>java-strings</module>
<module>java-strings-2</module>
<module>java-vavr-stream</module>

View File

@ -0,0 +1,8 @@
package com.baeldung.components;
import org.springframework.stereotype.Component;
@Component
public class AccountService {
}

View File

@ -0,0 +1,16 @@
package com.baeldung.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Autowired
private AccountService accountService;
public AccountService getAccountService() {
return accountService;
}
}

View File

@ -0,0 +1,15 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package="com.baeldung.components" />
<bean id="accountService" class="com.baeldung.components.AccountService"></bean>
<bean id="userService" class="com.baeldung.components.UserService">
<!-- If we have <context:annotation-config/> on top, then we don't need to set the properties(dependencies) in XML. -->
<!-- <property name="accountService" ref="accountService"></property> -->
</bean>
</beans>

View File

@ -0,0 +1,23 @@
package com.baeldung;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.components.AccountService;
import com.baeldung.components.UserService;
public class SpringXMLConfigurationIntegrationTest {
@Test
public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
UserService userService = context.getBean(UserService.class);
AccountService accountService = context.getBean(AccountService.class);
Assert.assertNotNull(userService);
Assert.assertNotNull(accountService);
Assert.assertNotNull(userService.getAccountService());
}
}

View File

@ -6,4 +6,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing)
- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test)
- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level)
- [Override properties in Spring]

View File

@ -1,5 +1,2 @@
# test properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
# override properties
example.firstProperty=profile
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

View File

@ -1,7 +1,3 @@
# security
spring.security.user.name=john
spring.security.user.password=123
# override properties
example.firstProperty=file
example.secondProperty=file
spring.security.user.password=123

View File

@ -1,57 +1,12 @@
package org.baeldung.custom.config;
import org.baeldung.custom.security.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@ComponentScan("org.baeldung.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and().formLogin().permitAll()
.and().csrf().disable();
;
// @formatter:on
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
public class SecurityConfig {
@Bean
public PasswordEncoder encoder() {

View File

@ -3,14 +3,16 @@ package org.baeldung.custom.web;
import org.baeldung.custom.persistence.dao.OrganizationRepository;
import org.baeldung.custom.persistence.model.Foo;
import org.baeldung.custom.persistence.model.Organization;
import org.baeldung.custom.security.MyUserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ -23,14 +25,14 @@ public class MainController {
// @PostAuthorize("hasPermission(returnObject, 'read')")
@PreAuthorize("hasPermission(#id, 'Foo', 'read')")
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
@GetMapping("/foos/{id}")
@ResponseBody
public Foo findById(@PathVariable final long id) {
return new Foo("Sample");
}
@PreAuthorize("hasPermission(#foo, 'write')")
@RequestMapping(method = RequestMethod.POST, value = "/foos")
@PostMapping("/foos")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo create(@RequestBody final Foo foo) {
@ -40,7 +42,7 @@ public class MainController {
//
@PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')")
@RequestMapping(method = RequestMethod.GET, value = "/foos")
@GetMapping("/foos")
@ResponseBody
public Foo findFooByName(@RequestParam final String name) {
return new Foo(name);
@ -49,10 +51,18 @@ public class MainController {
//
@PreAuthorize("isMember(#id)")
@RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}")
@GetMapping("/organizations/{id}")
@ResponseBody
public Organization findOrgById(@PathVariable final long id) {
return organizationRepository.findById(id).orElse(null);
return organizationRepository.findById(id)
.orElse(null);
}
@PreAuthorize("hasPermission(#id, 'Foo', 'read')")
@GetMapping("/user")
@ResponseBody
public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) {
return principal;
}
}

View File

@ -1,76 +1,89 @@
package org.baeldung.web;
import static org.junit.Assert.assertEquals;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.http.HttpHeaders;
import org.baeldung.custom.Application;
import org.baeldung.custom.config.MvcConfig;
import org.baeldung.custom.config.SecurityConfig;
import org.baeldung.custom.persistence.dao.UserRepository;
import org.baeldung.custom.persistence.model.User;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.baeldung.custom.persistence.model.Foo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
@WebAppConfiguration
import com.fasterxml.jackson.databind.ObjectMapper;
@SpringBootTest(classes = { Application.class })
@AutoConfigureMockMvc
public class CustomUserDetailsServiceIntegrationTest {
private static final String USERNAME = "user";
private static final String PASSWORD = "pass";
private static final String USERNAME2 = "user2";
@Autowired
private UserRepository myUserRepository;
@Autowired
private AuthenticationProvider authenticationProvider;
@Autowired
private PasswordEncoder passwordEncoder;
//
private MockMvc mvc;
@Test
public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() {
User user = new User();
user.setUsername(USERNAME);
user.setPassword(passwordEncoder.encode(PASSWORD));
myUserRepository.save(user);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD);
Authentication authentication = authenticationProvider.authenticate(auth);
assertEquals(authentication.getName(), USERNAME);
@WithUserDetails("john")
public void givenUserWithReadPermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception {
this.mvc.perform(get("/user").with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user.privileges[0].name").value("FOO_READ_PRIVILEGE"))
.andExpect(jsonPath("$.user.organization.name").value("FirstOrg"))
.andExpect(jsonPath("$.user.username").value("john"));
}
@Test(expected = BadCredentialsException.class)
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
User user = new User();
user.setUsername(USERNAME);
user.setPassword(passwordEncoder.encode(PASSWORD));
myUserRepository.save(user);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
authenticationProvider.authenticate(auth);
@Test
@WithUserDetails("tom")
public void givenUserWithWritePermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception {
this.mvc.perform(get("/user").with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user.privileges").isArray())
.andExpect(jsonPath("$.user.organization.name").value("SecondOrg"))
.andExpect(jsonPath("$.user.username").value("tom"));
}
//
@Test
@WithUserDetails("john")
public void givenUserWithReadPermissions_whenRequestFoo_thenRetrieveSampleFoo() throws Exception {
this.mvc.perform(get("/foos/1").with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Sample"));
}
@After
public void tearDown() {
myUserRepository.removeUserByUsername(USERNAME);
@Test
@WithAnonymousUser
public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception {
this.mvc.perform(get("/foos/1").with(csrf()))
.andExpect(status().isUnauthorized());
}
@Test
@WithUserDetails("john")
public void givenUserWithReadPermissions_whenCreateNewFoo_thenForbiddenStatusRetrieved() throws Exception {
this.mvc.perform(post("/foos").with(csrf())
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.content(asJsonString(new Foo())))
.andExpect(status().isForbidden());
}
@Test
@WithUserDetails("tom")
public void givenUserWithWritePermissions_whenCreateNewFoo_thenOkStatusRetrieved() throws Exception {
this.mvc.perform(post("/foos").with(csrf())
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.content(asJsonString(new Foo())))
.andExpect(status().isCreated());
}
private static String asJsonString(final Object obj) throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
}
}

View File

@ -9,7 +9,7 @@ class ReplaceUnderscoresGeneratorUnitTest {
class when_doing_something {
@Test
void then_should_happen_something() {
void then_something_should_happen() {
}
@Test

View File

@ -5,3 +5,4 @@
- [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils)
- [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation)
- [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized)
- [Override properties in Spring]()

View File

@ -26,7 +26,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>LATEST</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -0,0 +1,2 @@
# override properties
example.firstProperty=profile

View File

@ -0,0 +1,3 @@
# override properties
example.firstProperty=file
example.secondProperty=file