Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-10-15 14:39:42 +03:00
commit aebb463186
69 changed files with 1292 additions and 49 deletions

View File

@ -28,3 +28,6 @@
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)

View File

@ -17,6 +17,11 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@ -85,6 +90,7 @@
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>
</project>

View File

@ -0,0 +1,110 @@
package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
public class HexStringConverter {
/**
* Create a byte Array from String of hexadecimal digits using Character conversion
* @param hexString - Hexadecimal digits as String
* @return Desired byte Array
*/
public byte[] decodeHexString(String hexString) {
if (hexString.length() % 2 == 1) {
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
}
return bytes;
}
/**
* Create a String of hexadecimal digits from a byte Array using Character conversion
* @param byteArray - The byte Array
* @return Desired String of hexadecimal digits in lower case
*/
public String encodeHexString(byte[] byteArray) {
StringBuffer hexStringBuffer = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
hexStringBuffer.append(byteToHex(byteArray[i]));
}
return hexStringBuffer.toString();
}
public String byteToHex(byte num) {
char[] hexDigits = new char[2];
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
hexDigits[1] = Character.forDigit((num & 0xF), 16);
return new String(hexDigits);
}
public byte hexToByte(String hexString) {
int firstDigit = toDigit(hexString.charAt(0));
int secondDigit = toDigit(hexString.charAt(1));
return (byte) ((firstDigit << 4) + secondDigit);
}
private int toDigit(char hexChar) {
int digit = Character.digit(hexChar, 16);
if(digit == -1) {
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
}
return digit;
}
public String encodeUsingBigIntegerToString(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return bigInteger.toString(16);
}
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
}
public byte[] decodeUsingBigInteger(String hexString) {
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
if (byteArray[0] == 0) {
byte[] output = new byte[byteArray.length - 1];
System.arraycopy(byteArray, 1, output, 0, output.length);
return output;
}
return byteArray;
}
public String encodeUsingDataTypeConverter(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes);
}
public byte[] decodeUsingDataTypeConverter(String hexString) {
return DatatypeConverter.parseHexBinary(hexString);
}
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
return Hex.encodeHexString(bytes);
}
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
return Hex.decodeHex(hexString);
}
public String encodeUsingGuava(byte[] bytes) {
return BaseEncoding.base16()
.encode(bytes);
}
public byte[] decodeUsingGuava(String hexString) {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
}

View File

@ -0,0 +1,127 @@
package com.baeldung.algorithms.conversion;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.conversion.HexStringConverter;
public class ByteArrayConverterUnitTest {
private HexStringConverter hexStringConverter;
@Before
public void setup() {
hexStringConverter = new HexStringConverter();
}
@Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
if(hexString.charAt(0) == '0') {
hexString = hexString.substring(1);
}
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeHexString(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output);
}
@Test(expected=IllegalArgumentException.class)
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
hexStringConverter.hexToByte("fg");
}
@Test
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingGuava(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
assertArrayEquals(bytes, output);
}
@Test
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
assertArrayEquals(bytes, output);
}
private String getSampleHexString() {
return "0af50c0e2d10";
}
private byte[] getSampleBytes() {
return new byte[] { 10, -11, 12, 14, 45, 16 };
}
}

View File

@ -9,4 +9,4 @@
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java)

View File

@ -0,0 +1 @@
/bin/

View File

@ -0,0 +1,93 @@
package findItems;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class FindItemsBasedOnValues {
List<Employee> EmplList = new ArrayList<Employee>();
List<Department> deptList = new ArrayList<Department>();
public static void main(String[] args) throws ParseException {
FindItemsBasedOnValues findItems = new FindItemsBasedOnValues();
findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly();
}
@Test
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
Integer expectedId = 1002;
populate(EmplList, deptList);
List<Employee> filteredList = EmplList.stream()
.filter(empl -> deptList.stream()
.anyMatch(dept -> dept.getDepartment()
.equals("sales") && empl.getEmployeeId()
.equals(dept.getEmployeeId())))
.collect(Collectors.toList());
assertEquals(expectedId, filteredList.get(0)
.getEmployeeId());
}
private void populate(List<Employee> EmplList, List<Department> deptList) {
Employee employee1 = new Employee(1001, "empl1");
Employee employee2 = new Employee(1002, "empl2");
Employee employee3 = new Employee(1003, "empl3");
Collections.addAll(EmplList, employee1, employee2, employee3);
Department department1 = new Department(1002, "sales");
Department department2 = new Department(1003, "marketing");
Department department3 = new Department(1004, "sales");
Collections.addAll(deptList, department1, department2, department3);
}
}
class Employee {
Integer employeeId;
String employeeName;
public Employee(Integer employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
public Integer getEmployeeId() {
return employeeId;
}
public String getEmployeeName() {
return employeeName;
}
}
class Department {
Integer employeeId;
String department;
public Department(Integer employeeId, String department) {
super();
this.employeeId = employeeId;
this.department = department;
}
public Integer getEmployeeId() {
return employeeId;
}
public String getDepartment() {
return department;
}
}

View File

@ -26,3 +26,4 @@
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)

View File

@ -52,3 +52,6 @@
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)

View File

@ -0,0 +1,45 @@
package com.baeldung.enumset;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
public class EnumSets {
public enum Color {
RED, YELLOW, GREEN, BLUE, BLACK, WHITE
}
public static void main(String[] args) {
EnumSet<Color> allColors = EnumSet.allOf(Color.class);
System.out.println(allColors);
EnumSet<Color> noColors = EnumSet.noneOf(Color.class);
System.out.println(noColors);
EnumSet<Color> blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE);
System.out.println(blackAndWhite);
EnumSet<Color> noBlackOrWhite = EnumSet.complementOf(blackAndWhite);
System.out.println(noBlackOrWhite);
EnumSet<Color> range = EnumSet.range(Color.YELLOW, Color.BLUE);
System.out.println(range);
EnumSet<Color> blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE));
System.out.println(blackAndWhiteCopy);
List<Color> colorsList = new ArrayList<>();
colorsList.add(Color.RED);
EnumSet<Color> listCopy = EnumSet.copyOf(colorsList);
System.out.println(listCopy);
EnumSet<Color> set = EnumSet.noneOf(Color.class);
set.add(Color.RED);
set.add(Color.YELLOW);
set.contains(Color.RED);
set.forEach(System.out::println);
set.remove(Color.RED);
}
}

View File

@ -29,3 +29,4 @@
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)

View File

@ -185,4 +185,24 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello World", future.get());
}
@Test
public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenApply(s -> s + 1);
assertTrue(finalResult.get() == 11);
}
@Test
public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenCompose(this::computeAnother);
assertTrue(finalResult.get() == 20);
}
public CompletableFuture<Integer> compute(){
return CompletableFuture.supplyAsync(() -> 10);
}
public CompletableFuture<Integer> computeAnother(Integer i){
return CompletableFuture.supplyAsync(() -> 10 + i);
}
}

View File

@ -0,0 +1 @@
Test1

View File

@ -0,0 +1 @@
Test2

View File

@ -150,3 +150,9 @@
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [Java Switch Statement](https://www.baeldung.com/java-switch)

View File

@ -0,0 +1,136 @@
package com.baeldung.heapsort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Heap<E extends Comparable<E>> {
private List<E> elements = new ArrayList<>();
public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) {
Heap<E> heap = of(elements);
List<E> result = new ArrayList<>();
while (!heap.isEmpty()) {
result.add(heap.pop());
}
return result;
}
public static <E extends Comparable<E>> Heap<E> of(E... elements) {
return of(Arrays.asList(elements));
}
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
Heap<E> result = new Heap<>();
for (E element : elements) {
result.add(element);
}
return result;
}
public void add(E e) {
elements.add(e);
int elementIndex = elements.size() - 1;
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
int parentIndex = parentIndex(elementIndex);
swap(elementIndex, parentIndex);
elementIndex = parentIndex;
}
}
public E pop() {
if (isEmpty()) {
throw new IllegalStateException("You cannot pop from an empty heap");
}
E result = elementAt(0);
int lasElementIndex = elements.size() - 1;
swap(0, lasElementIndex);
elements.remove(lasElementIndex);
int elementIndex = 0;
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
int smallerChildIndex = smallerChildIndex(elementIndex);
swap(elementIndex, smallerChildIndex);
elementIndex = smallerChildIndex;
}
return result;
}
public boolean isEmpty() {
return elements.isEmpty();
}
private boolean isRoot(int index) {
return index == 0;
}
private int smallerChildIndex(int index) {
int leftChildIndex = leftChildIndex(index);
int rightChildIndex = rightChildIndex(index);
if (!isValidIndex(rightChildIndex)) {
return leftChildIndex;
}
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
return leftChildIndex;
}
return rightChildIndex;
}
private boolean isLeaf(int index) {
return !isValidIndex(leftChildIndex(index));
}
private boolean isCorrectParent(int index) {
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
}
private boolean isCorrectChild(int index) {
return isCorrect(parentIndex(index), index);
}
private boolean isCorrect(int parentIndex, int childIndex) {
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
return true;
}
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
}
private boolean isValidIndex(int index) {
return index < elements.size();
}
private void swap(int index1, int index2) {
E element1 = elementAt(index1);
E element2 = elementAt(index2);
elements.set(index1, element2);
elements.set(index2, element1);
}
private E elementAt(int index) {
return elements.get(index);
}
private int parentIndex(int index) {
return (index - 1) / 2;
}
private int leftChildIndex(int index) {
return 2 * index + 1;
}
private int rightChildIndex(int index) {
return 2 * index + 2;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.heapsort;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class HeapUnitTest {
@Test
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
// given
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
// when
int head = heap.pop();
// then
assertThat(head).isEqualTo(1);
}
@Test
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
// given
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);
// when
List<Integer> sortedElements = Heap.sort(elements);
// then
assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5));
}
}

View File

@ -37,3 +37,5 @@
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)

View File

@ -0,0 +1,25 @@
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
// Only necessary for JUnit 3 and 4 tests
testCompileOnly 'junit:junit:4.12'
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1'
}
repositories {
jcenter()
}
test {
useJUnitPlatform {
includeTags 'fast'
excludeTags 'slow'
}
}

View File

@ -0,0 +1,12 @@
package com.example;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorJUnit4Test {
@Test
public void testAdd() {
assertEquals(42, Integer.sum(19, 23));
}
}

View File

@ -0,0 +1,36 @@
package com.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;;
public class CalculatorJUnit5Test {
@Tag("fast")
@Test
public void testAdd() {
assertEquals(42, Integer.sum(19, 23));
}
@Tag("slow")
@Test
public void testAddMaxInteger() {
assertEquals(2147483646, Integer.sum(2147183646, 300000));
}
@Tag("fast")
@Test
public void testAddZero() {
assertEquals(21, Integer.sum(21, 0));
}
@Tag("fast")
@Test
public void testDivide() {
assertThrows(ArithmeticException.class, () -> {
Integer.divideUnsigned(42, 0);
});
}
}

View File

@ -5,6 +5,6 @@ include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
include 'junit5'
println 'This will be executed during the initialization phase.'

View File

@ -16,3 +16,4 @@
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)

View File

@ -51,6 +51,15 @@ public class DateDiffUnitTest {
assertEquals(diff, 6);
}
@Test
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6);
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
assertEquals(diff, 6);
}
@Test
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();

View File

@ -13,3 +13,4 @@
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)

View File

@ -31,3 +31,5 @@
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance)

View File

@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
- [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints)
- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)

View File

@ -54,4 +54,9 @@ public class Fruit {
public void setSerial(String serial) {
this.serial = serial;
}
@Override
public String toString() {
return "Fruit [name: " + getName() + " colour: " + getColour() + "]";
}
}

View File

@ -16,6 +16,8 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.server.mvc.ErrorTemplate;
import org.glassfish.jersey.server.mvc.Template;
@ -87,6 +89,16 @@ public class FruitResource {
SimpleStorageService.storeFruit(fruit);
}
@POST
@Path("/created")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewFruit(@Valid Fruit fruit) {
String result = "Fruit saved : " + fruit;
return Response.status(Status.CREATED.getStatusCode())
.entity(result)
.build();
}
@GET
@Valid
@Produces(MediaType.APPLICATION_JSON)

View File

@ -0,0 +1,33 @@
package com.baeldung.jersey.server;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
public class GreetingsResourceIntegrationTest extends JerseyTest {
@Override
protected Application configure() {
return new ResourceConfig(Greetings.class);
}
@Test
public void givenGetHiGreeting_whenCorrectRequest_thenResponseIsOkAndContainsHi() {
Response response = target("/greetings/hi").request()
.get();
assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
assertEquals("Content of ressponse is: ", "hi", content);
}
}

View File

@ -10,6 +10,7 @@ import javax.ws.rs.core.Application;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
@ -64,6 +65,15 @@ public class FruitResourceIntegrationTest extends JerseyTest {
assertThat(response.readEntity(String.class), containsString("Fruit colour must not be null"));
}
@Test
public void givenCreateFruit_whenJsonIsCorrect_thenResponseCodeIsCreated() {
Response response = target("fruit/created").request()
.post(Entity.json("{\"name\":\"strawberry\",\"weight\":20}"));
assertEquals("Http Response should be 201 ", Status.CREATED.getStatusCode(), response.getStatus());
assertThat(response.readEntity(String.class), containsString("Fruit saved : Fruit [name: strawberry colour: null]"));
}
@Test
public void givenUpdateFruit_whenFormContainsBadSerialParam_thenResponseCodeIsBadRequest() {
Form form = new Form();
@ -103,6 +113,23 @@ public class FruitResourceIntegrationTest extends JerseyTest {
assertThat(json, containsString("{\"name\":\"strawberry\",\"weight\":20}"));
}
@Test
public void givenFruitExists_whenSearching_thenResponseContainsFruitEntity() {
Fruit fruit = new Fruit();
fruit.setName("strawberry");
fruit.setWeight(20);
Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE));
assertEquals("Http Response should be 204 ", 204, response.getStatus());
final Fruit entity = target("fruit/search/strawberry").request()
.get(Fruit.class);
assertEquals("Fruit name: ", "strawberry", entity.getName());
assertEquals("Fruit weight: ", Integer.valueOf(20), entity.getWeight());
}
@Test
public void givenFruit_whenFruitIsInvalid_thenReponseContainsCustomExceptions() {
final Response response = target("fruit/exception").request()

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Guide to ScribeJava](https://www.baeldung.com/scribejava)

View File

@ -81,6 +81,8 @@
- [Guide to Resilience4j](http://www.baeldung.com/resilience4j)
- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml)
- [Guide to JMapper](http://www.baeldung.com/jmapper)
- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3)
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -358,6 +358,7 @@
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<type>pom</type>
<version>${groovy.version}</version>
</dependency>
<dependency>
@ -922,7 +923,7 @@
<quartz.version>2.3.0</quartz.version>
<jool.version>0.9.12</jool.version>
<jmh.version>1.19</jmh.version>
<groovy.version>2.4.10</groovy.version>
<groovy.version>2.5.2</groovy.version>
<noexception.version>1.1.0</noexception.version>
<logging-interceptor.version>3.9.0</logging-interceptor.version>
<yarg.version>2.0.4</yarg.version>

View File

@ -6,7 +6,9 @@ import org.apache.commons.lang3.SystemUtils;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SystemsUtilsUnitTest {
public class SystemsUtilsManualTest {
// the paths depend on the OS and installed version of Java
@Test
public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() {

View File

View File

@ -7,17 +7,61 @@
<packaging>jar</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-spring-5</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis}</version>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -33,42 +77,12 @@
<type>jar</type>
</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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-redis</artifactId>
<version>${nosqlunit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data-commons.version}</version>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
@ -77,12 +91,13 @@
</dependencies>
<properties>
<spring-data-redis>2.0.3.RELEASE</spring-data-redis>
<cglib.version>3.2.4</cglib.version>
<jedis.version>2.9.0</jedis.version>
<nosqlunit.version>0.10.0</nosqlunit.version>
<spring-data-commons.version>2.0.3.RELEASE</spring-data-commons.version>
<embedded-redis.version>0.6</embedded-redis.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.jupiter.version>5.0.2</junit.jupiter.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.data.reactive.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisReactiveApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisReactiveApplication.class, args);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.spring.data.reactive.redis.config;
import com.baeldung.spring.data.reactive.redis.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PreDestroy;
@Configuration
public class RedisConfig {
@Autowired
RedisConnectionFactory factory;
@Bean
public ReactiveRedisTemplate<String, Employee> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Employee> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Employee> context = builder.value(serializer)
.build();
return new ReactiveRedisTemplate<>(factory, context);
}
@Bean
public ReactiveRedisTemplate<String, String> reactiveRedisTemplateString(ReactiveRedisConnectionFactory connectionFactory) {
return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string());
}
@Bean
public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.keyCommands();
}
@Bean
public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.stringCommands();
}
@PreDestroy
public void cleanRedis() {
factory.getConnection()
.flushDb();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.spring.data.reactive.redis.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Employee implements Serializable {
private static final long serialVersionUID = 1603714798906422731L;
private String id;
private String name;
private String department;
}

View File

@ -1,6 +1,8 @@
package com.baeldung.spring.data.redis.config;
import org.springframework.beans.factory.annotation.Value;
import com.baeldung.spring.data.redis.queue.MessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ -13,10 +15,6 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import com.baeldung.spring.data.redis.queue.MessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
@Configuration
@ComponentScan("com.baeldung.spring.data.redis")
@EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo")

View File

@ -0,0 +1,51 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.nio.ByteBuffer;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
public class RedisKeyCommandsIntegrationTest {
@Autowired
private ReactiveKeyCommands keyCommands;
@Autowired
private ReactiveStringCommands stringCommands;
@Test
public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() {
Flux<String> keys = Flux.just("key1", "key2", "key3", "key4");
Flux<SetCommand> generator = keys.map(String::getBytes)
.map(ByteBuffer::wrap)
.map(key -> SetCommand.set(key)
.value(key));
StepVerifier.create(stringCommands.set(generator))
.expectNextCount(4L)
.verifyComplete();
Mono<Long> keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes()))
.flatMapMany(Flux::fromIterable)
.count();
StepVerifier.create(keyCount)
.expectNext(4L)
.verifyComplete();
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveListOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
public class RedisTemplateListOpsIntegrationTest {
private static final String LIST_NAME = "demo_list";
@Autowired
private ReactiveRedisTemplate<String, String> redisTemplate;
private ReactiveListOperations<String, String> reactiveListOps;
@Before
public void setup() {
reactiveListOps = redisTemplate.opsForList();
}
@Test
public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() {
Mono<Long> lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second")
.log("Pushed");
StepVerifier.create(lPush)
.expectNext(2L)
.verifyComplete();
Mono<String> lPop = reactiveListOps.leftPop(LIST_NAME)
.log("Popped");
StepVerifier.create(lPop)
.expectNext("second")
.verifyComplete();
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import com.baeldung.spring.data.reactive.redis.model.Employee;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
public class RedisTemplateValueOpsIntegrationTest {
@Autowired
private ReactiveRedisTemplate<String, Employee> redisTemplate;
private ReactiveValueOperations<String, Employee> reactiveValueOps;
@Before
public void setup() {
reactiveValueOps = redisTemplate.opsForValue();
}
@Test
public void givenEmployee_whenSet_thenSet() {
Mono<Boolean> result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts"));
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
}
@Test
public void givenEmployeeId_whenGet_thenReturnsEmployee() {
Mono<Employee> fetchedEmployee = reactiveValueOps.get("123");
StepVerifier.create(fetchedEmployee)
.expectNext(new Employee("123", "Bill", "Accounts"))
.verifyComplete();
}
@Test
public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException {
Mono<Boolean> result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1));
Mono<Employee> fetchedEmployee = reactiveValueOps.get("129");
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
Thread.sleep(2000L);
StepVerifier.create(fetchedEmployee)
.expectNextCount(0L)
.verifyComplete();
}
}

View File

@ -31,7 +31,7 @@ public class RedisMessageListenerIntegrationTest {
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new redis.embedded.RedisServer(6379);
redisServer = new redis.embedded.RedisServer(6380);
redisServer.start();
}

View File

@ -32,7 +32,7 @@ public class StudentRepositoryIntegrationTest {
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new redis.embedded.RedisServer(6379);
redisServer = new redis.embedded.RedisServer(6380);
redisServer.start();
}

View File

@ -46,6 +46,12 @@
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
@ -451,6 +457,7 @@
<module>spring-5</module>
<module>spring-5-data-reactive</module>
<module>spring-5-reactive</module>
<module>spring-data-5-reactive/spring-5-data-reactive-redis</module>
<module>spring-5-reactive-security</module>
<module>spring-5-reactive-client</module>
<module>spring-5-mvc</module>

View File

@ -2,3 +2,4 @@
- [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin)
- [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams)
- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy)
- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao)

View File

@ -3,3 +3,4 @@
- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent)
- [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar)
- [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry)
- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine)

View File

@ -0,0 +1,14 @@
package com.baeldung.h2db.auto.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class AutoConfigurationDemo {
public static void main(String[] args) {
SpringApplication.run(AutoConfigurationDemo.class, args);
}
}

View File

@ -5,3 +5,4 @@ spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
debug=true

View File

@ -28,3 +28,5 @@
- [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task)
- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube)
- [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration)
- [An Intro to Spring Cloud Vault](https://www.baeldung.com/spring-cloud-vault)
- [Netflix Archaius with Various Database Configurations](https://www.baeldung.com/netflix-archaius-database-configurations)

View File

@ -20,3 +20,5 @@
- [Controlling Bean Creation Order with @DependsOn Annotation](http://www.baeldung.com/spring-depends-on)
- [Spring Autowiring of Generic Types](https://www.baeldung.com/spring-autowire-generics)
- [Spring Application Context Events](https://www.baeldung.com/spring-context-events)
- [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency)
- [What is a Spring Bean?](https://www.baeldung.com/spring-bean)

View File

@ -14,6 +14,7 @@
- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa)
- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date)
- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd)
- [Spring Data CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:

View File

@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com
- [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role)
- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security)
- [Spring Security Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range)
- [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters)

View File

@ -0,0 +1,53 @@
package com.baeldung.junit5vstestng;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SummationServiceIntegrationTest {
private static List<Integer> numbers;
@BeforeAll
public static void initialize() {
numbers = new ArrayList<>();
}
@AfterAll
public static void tearDown() {
numbers = null;
}
@BeforeEach
public void runBeforeEachTest() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@AfterEach
public void runAfterEachTest() {
numbers.clear();
}
@Test
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung.java.customtestname;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class CustomNameUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
@DisplayName("Test Method to check that the inputs are not nullable")
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
}

View File

@ -0,0 +1,45 @@
package org.baeldung.java.parameterisedsource;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.EnumSet;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
public class ParameterizedUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
@ParameterizedTest
@EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"})
void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) {
assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit));
}
@ParameterizedTest
@MethodSource("wordDataProvider")
void givenMethodSource_TestInputStream(String argument) {
assertNotNull(argument);
}
static Stream<String> wordDataProvider() {
return Stream.of("foo", "bar");
}
@ParameterizedTest
@CsvSource({ "1, Car", "2, House", "3, Train" })
void givenCSVSource_TestContent(int id, String word) {
assertNotNull(id);
assertNotNull(word);
}
}

View File

@ -0,0 +1,6 @@
package org.baeldung.java.parameterisedsource;
public enum PizzaDeliveryStrategy {
EXPRESS,
NORMAL;
}

View File

@ -0,0 +1,13 @@
package org.baeldung.java.suite;
import org.baeldung.java.suite.childpackage1.Class1UnitTest;
import org.baeldung.java.suite.childpackage2.Class2UnitTest;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectClasses({Class1UnitTest.class, Class2UnitTest.class})
public class SelectClassesSuiteUnitTest {
}

View File

@ -0,0 +1,11 @@
package org.baeldung.java.suite;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" })
public class SelectPackagesSuiteUnitTest {
}

View File

@ -0,0 +1,15 @@
package org.baeldung.java.suite.childpackage1;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class1UnitTest {
@Test
public void testCase_InClass1UnitTest() {
assertTrue(true);
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.java.suite.childpackage2;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class2UnitTest {
@Test
public void testCase_InClass2UnitTest() {
assertTrue(true);
}
}

View File

@ -1,3 +1,4 @@
### Relevant Articles:
* [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean)
- [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean)
- [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source)