From 6460e73eb67f514376005258d490ed742f93a60d Mon Sep 17 00:00:00 2001 From: Satyam Date: Tue, 2 Oct 2018 12:06:56 +0530 Subject: [PATCH 01/21] BAEL-2197: Initial Commit --- core-java-8/findItemsBasedOnValues/.gitignore | 1 + .../src/findItems/FindItemsBasedOnValues.java | 114 ++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 core-java-8/findItemsBasedOnValues/.gitignore create mode 100644 core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java diff --git a/core-java-8/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java new file mode 100644 index 0000000000..5fa15be86e --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -0,0 +1,114 @@ +package findItems; + +import static org.junit.Assert.*; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.Test; + +public class FindItemsBasedOnValues { + + static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy"); + + public static void main(String[] args) throws ParseException { + FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); + findItems.findItemsImpl(); + } + + @Test + public void findItemsImpl() throws ParseException { + List expectedList = new ArrayList(); + Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); + expectedList.add(expectedClient); + + List listOfCompanies = new ArrayList(); + List listOfClients = new ArrayList(); + populate(listOfCompanies, listOfClients); + + List filteredList = listOfClients.stream() + .filter(client -> listOfCompanies.stream() + .anyMatch(company -> company.getType() + .equals("eMart") && company.getProjectId() + .equals(client.getProjectId()) && company.getStart() + .after(client.getDate()) && company.getEnd() + .before(client.getDate()))) + .collect(Collectors.toList()); + + assertEquals(expectedClient.getProjectId(), filteredList.get(0) + .getProjectId()); + assertEquals(expectedClient.getDate(), filteredList.get(0) + .getDate()); + } + + private void populate(List companyList, List clientList) throws ParseException { + Company company1 = new Company(1001, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-01-2018"), "eMart"); + Company company2 = new Company(1002, DATE_FORMAT.parse("01-02-2018"), DATE_FORMAT.parse("01-04-2018"), "commerce"); + Company company3 = new Company(1003, DATE_FORMAT.parse("01-06-2018"), DATE_FORMAT.parse("01-02-2018"), "eMart"); + Company company4 = new Company(1004, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-06-2018"), "blog"); + + Collections.addAll(companyList, company1, company2, company3, company4); + + Client client1 = new Client(1001, DATE_FORMAT.parse("01-02-2018")); + Client client2 = new Client(1003, DATE_FORMAT.parse("01-04-2018")); + Client client3 = new Client(1005, DATE_FORMAT.parse("01-07-2018")); + Client client4 = new Client(1007, DATE_FORMAT.parse("01-08-2018")); + + Collections.addAll(clientList, client1, client2, client3, client4); + } +} + +class Company { + Long projectId; + Date start; + Date end; + String type; + + public Company(long projectId, Date start, Date end, String type) { + super(); + this.projectId = projectId; + this.start = start; + this.end = end; + this.type = type; + } + + public Long getProjectId() { + return projectId; + } + + public Date getStart() { + return start; + } + + public Date getEnd() { + return end; + } + + public String getType() { + return type; + } + +} + +class Client { + Long projectId; + Date date; + + public Client(long projectId, Date date) { + super(); + this.projectId = projectId; + this.date = date; + } + + public Long getProjectId() { + return projectId; + } + + public Date getDate() { + return date; + } + +} \ No newline at end of file From 7070aae38f951a23463abb3e2545bb7682ef387c Mon Sep 17 00:00:00 2001 From: Satyam Date: Wed, 3 Oct 2018 10:39:58 +0530 Subject: [PATCH 02/21] Updated Test method name --- .../src/findItems/FindItemsBasedOnValues.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java index 5fa15be86e..d6a320a8ec 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -16,11 +16,11 @@ public class FindItemsBasedOnValues { public static void main(String[] args) throws ParseException { FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.findItemsImpl(); + findItems.givenListOfCompanies_thenListOfClientsIsFilteredCorrectly(); } @Test - public void findItemsImpl() throws ParseException { + public void givenListOfCompanies_thenListOfClientsIsFilteredCorrectly() throws ParseException { List expectedList = new ArrayList(); Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); expectedList.add(expectedClient); From ef61b86af31c3d5c5186905fff2ec2046c483348 Mon Sep 17 00:00:00 2001 From: Satyam Date: Thu, 11 Oct 2018 20:55:55 +0530 Subject: [PATCH 03/21] BAEL-2197:Code rework --- .../src/findItems/FindItemsBasedOnValues.java | 111 +++++++----------- 1 file changed, 45 insertions(+), 66 deletions(-) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java index d6a320a8ec..a0dcdddd85 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -1,114 +1,93 @@ package findItems; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; + import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; -import java.util.Date; import java.util.List; import java.util.stream.Collectors; + import org.junit.Test; public class FindItemsBasedOnValues { - static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy"); + List EmplList = new ArrayList(); + List deptList = new ArrayList(); public static void main(String[] args) throws ParseException { FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.givenListOfCompanies_thenListOfClientsIsFilteredCorrectly(); + findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly(); } @Test - public void givenListOfCompanies_thenListOfClientsIsFilteredCorrectly() throws ParseException { - List expectedList = new ArrayList(); - Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); - expectedList.add(expectedClient); + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; - List listOfCompanies = new ArrayList(); - List listOfClients = new ArrayList(); - populate(listOfCompanies, listOfClients); + populate(EmplList, deptList); - List filteredList = listOfClients.stream() - .filter(client -> listOfCompanies.stream() - .anyMatch(company -> company.getType() - .equals("eMart") && company.getProjectId() - .equals(client.getProjectId()) && company.getStart() - .after(client.getDate()) && company.getEnd() - .before(client.getDate()))) + List filteredList = EmplList.stream() + .filter(empl -> deptList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) .collect(Collectors.toList()); - assertEquals(expectedClient.getProjectId(), filteredList.get(0) - .getProjectId()); - assertEquals(expectedClient.getDate(), filteredList.get(0) - .getDate()); + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); } - private void populate(List companyList, List clientList) throws ParseException { - Company company1 = new Company(1001, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-01-2018"), "eMart"); - Company company2 = new Company(1002, DATE_FORMAT.parse("01-02-2018"), DATE_FORMAT.parse("01-04-2018"), "commerce"); - Company company3 = new Company(1003, DATE_FORMAT.parse("01-06-2018"), DATE_FORMAT.parse("01-02-2018"), "eMart"); - Company company4 = new Company(1004, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-06-2018"), "blog"); + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); - Collections.addAll(companyList, company1, company2, company3, company4); + Collections.addAll(EmplList, employee1, employee2, employee3); - Client client1 = new Client(1001, DATE_FORMAT.parse("01-02-2018")); - Client client2 = new Client(1003, DATE_FORMAT.parse("01-04-2018")); - Client client3 = new Client(1005, DATE_FORMAT.parse("01-07-2018")); - Client client4 = new Client(1007, DATE_FORMAT.parse("01-08-2018")); + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); - Collections.addAll(clientList, client1, client2, client3, client4); + Collections.addAll(deptList, department1, department2, department3); } } -class Company { - Long projectId; - Date start; - Date end; - String type; +class Employee { + Integer employeeId; + String employeeName; - public Company(long projectId, Date start, Date end, String type) { + public Employee(Integer employeeId, String employeeName) { super(); - this.projectId = projectId; - this.start = start; - this.end = end; - this.type = type; + this.employeeId = employeeId; + this.employeeName = employeeName; } - public Long getProjectId() { - return projectId; + public Integer getEmployeeId() { + return employeeId; } - public Date getStart() { - return start; - } - - public Date getEnd() { - return end; - } - - public String getType() { - return type; + public String getEmployeeName() { + return employeeName; } } -class Client { - Long projectId; - Date date; +class Department { + Integer employeeId; + String department; - public Client(long projectId, Date date) { + public Department(Integer employeeId, String department) { super(); - this.projectId = projectId; - this.date = date; + this.employeeId = employeeId; + this.department = department; } - public Long getProjectId() { - return projectId; + public Integer getEmployeeId() { + return employeeId; } - public Date getDate() { - return date; + public String getDepartment() { + return department; } } \ No newline at end of file From 01819fe1bac8d3bf7dbd016a77a0f42a87ba16f5 Mon Sep 17 00:00:00 2001 From: Johan Janssen Date: Thu, 11 Oct 2018 21:40:30 +0200 Subject: [PATCH 04/21] BAEL-2263 Using JUnit 5 with Gradle --- gradle/junit5/build.gradle | 25 +++++++++++++ .../com/example/CalculatorJUnit4Test.java | 12 +++++++ .../com/example/CalculatorJUnit5Test.java | 36 +++++++++++++++++++ gradle/settings.gradle | 2 +- 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 gradle/junit5/build.gradle create mode 100644 gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java create mode 100644 gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java diff --git a/gradle/junit5/build.gradle b/gradle/junit5/build.gradle new file mode 100644 index 0000000000..5f056d8c23 --- /dev/null +++ b/gradle/junit5/build.gradle @@ -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' + } +} \ No newline at end of file diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java new file mode 100644 index 0000000000..4cf63642ee --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java @@ -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)); + } +} diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java new file mode 100644 index 0000000000..59fdb0f8ae --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java @@ -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); + }); + } +} diff --git a/gradle/settings.gradle b/gradle/settings.gradle index 38704681bd..f1d64de58a 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -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.' From fe8488a8d5e773e7e657a85c477bbfa7f3af68a0 Mon Sep 17 00:00:00 2001 From: Akash Pandey Date: Sat, 13 Oct 2018 01:20:33 +0530 Subject: [PATCH 05/21] Bael 2189: Convert Byte Array To/From hex String (#5396) * BAEL-2159: Mini Article on "Separate double into integer and decimal parts" * BAEL-2189: Tutorial to convert Byte Array to/from hex String. * BEAL-2189: Code review comments incorporated. * 1. Added validations for Non-Hex String characters in hex String. 2. Moved classes to algorithms module. 3. Renamed unit test class name ends with *UnitTest. * 1. Added validations for Non-Hex String characters in hex String. 2. Moved classes to algorithms module. 3. Renamed unit test class name ends with *UnitTest. * removed: redundant property added for local testing. --- algorithms/pom.xml | 6 + .../conversion/HexStringConverter.java | 110 +++++++++++++++ .../ByteArrayConverterUnitTest.java | 127 ++++++++++++++++++ 3 files changed, 243 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java diff --git a/algorithms/pom.xml b/algorithms/pom.xml index eda87d6c75..db4a1c2eff 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -17,6 +17,11 @@ commons-math3 ${commons-math3.version} + + commons-codec + commons-codec + ${commons-codec.version} + org.projectlombok lombok @@ -85,6 +90,7 @@ 3.7.0 1.0.1 3.9.0 + 1.11 \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java new file mode 100644 index 0000000000..d3e251d3fd --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java @@ -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()); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java new file mode 100644 index 0000000000..be61802705 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java @@ -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 }; + } + +} From 3c35e25015dd5e7b7943c8e77fab9b8345c37191 Mon Sep 17 00:00:00 2001 From: Rokon Uddin Ahmed Date: Sat, 13 Oct 2018 02:22:56 +0600 Subject: [PATCH 06/21] BAEL-9344 (#5435) * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md --- algorithms/README.md | 3 +++ aws/README.md | 2 +- core-java-9/README.md | 1 + core-java-collections/README.md | 3 +++ core-java-concurrency/README.md | 1 + core-java/README.md | 6 ++++++ core-kotlin/README.md | 2 ++ hibernate5/README.md | 1 + java-streams/README.md | 1 + java-strings/README.md | 2 ++ libraries-security/README.md | 3 +++ libraries/README.md | 2 ++ spring-5-mvc/README.md | 1 + spring-boot-bootstrap/README.md | 1 + spring-cloud/README.md | 2 ++ spring-core/README.md | 2 ++ spring-data-jpa/README.md | 1 + spring-security-mvc-boot/README.MD | 1 + testing-modules/spring-testing/README.md | 3 ++- 19 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 libraries-security/README.md diff --git a/algorithms/README.md b/algorithms/README.md index 9b3bbcdee5..9d347869bd 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -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) diff --git a/aws/README.md b/aws/README.md index d23937a419..2c61928095 100644 --- a/aws/README.md +++ b/aws/README.md @@ -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) diff --git a/core-java-9/README.md b/core-java-9/README.md index bf07cfcc86..38816471aa 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -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) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index d9d768961c..aef640634e 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -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) diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index d775d24dff..eeb9a83748 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -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) diff --git a/core-java/README.md b/core-java/README.md index a117d1843d..9e38dfc47d 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -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) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 7d8d5213d1..523f5b6e78 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -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) diff --git a/hibernate5/README.md b/hibernate5/README.md index b90f885c78..fbf46eed50 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -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) diff --git a/java-streams/README.md b/java-streams/README.md index 548d4b6a33..2550f08650 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -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) diff --git a/java-strings/README.md b/java-strings/README.md index b12fc75f30..ff833a5cda 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -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) diff --git a/libraries-security/README.md b/libraries-security/README.md new file mode 100644 index 0000000000..c42e91a888 --- /dev/null +++ b/libraries-security/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to ScribeJava](https://www.baeldung.com/scribejava) diff --git a/libraries/README.md b/libraries/README.md index c2c4b2718a..fcf687d806 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -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. diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index 7e83077f54..fa9d48ab72 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -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) diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 4b09f11714..08fdb1bdc9 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -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) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 805052e4db..16bc2d110a 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -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) diff --git a/spring-core/README.md b/spring-core/README.md index c0577b4ebc..e5c359c11b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -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) diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md index 8817020eec..44ce240da3 100644 --- a/spring-data-jpa/README.md +++ b/spring-data-jpa/README.md @@ -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: diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index 6bd9b9295c..6f01bfdc65 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -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) diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index aed330d260..e22c3e84e7 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -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) From 435af770b3a7538cb7debee70628aa64520546b9 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Sat, 13 Oct 2018 13:04:22 +0200 Subject: [PATCH 07/21] BAEL-2259 - Guide to EnumSet (#5423) * EnumSet * enumset operations * formatting --- .../java/com/baeldung/enumset/EnumSets.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java diff --git a/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java new file mode 100644 index 0000000000..7b93ed8737 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java @@ -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 allColors = EnumSet.allOf(Color.class); + System.out.println(allColors); + + EnumSet noColors = EnumSet.noneOf(Color.class); + System.out.println(noColors); + + EnumSet blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE); + System.out.println(blackAndWhite); + + EnumSet noBlackOrWhite = EnumSet.complementOf(blackAndWhite); + System.out.println(noBlackOrWhite); + + EnumSet range = EnumSet.range(Color.YELLOW, Color.BLUE); + System.out.println(range); + + EnumSet blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE)); + System.out.println(blackAndWhiteCopy); + + List colorsList = new ArrayList<>(); + colorsList.add(Color.RED); + EnumSet listCopy = EnumSet.copyOf(colorsList); + System.out.println(listCopy); + + EnumSet 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); + } + +} From 03e0627cffc0e8b674f0050951eebddeb5c2664f Mon Sep 17 00:00:00 2001 From: Kuba Date: Sat, 13 Oct 2018 17:02:22 +0200 Subject: [PATCH 08/21] BAEL-2200 Sample application for auto-configuration report. (#5335) * BAEL-2200 Sample application for auto-configuration report. * BAEL-2200 Sample application for auto-configuration report fixes. * Fix formatting. --- .../auto/configuration/AutoConfigurationDemo.java | 14 ++++++++++++++ .../src/main/resources/application.properties | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java new file mode 100644 index 0000000000..87a191554b --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -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(scanBasePackages = "com.baeldung.h2db.auto-configuration") +public class AutoConfigurationDemo { + + public static void main(String[] args) { + SpringApplication.run(AutoConfigurationDemo.class, args); + } + +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties index 0591cc9e0f..5e425a3550 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties +++ b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties @@ -4,4 +4,5 @@ spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create spring.h2.console.enabled=true -spring.h2.console.path=/h2-console \ No newline at end of file +spring.h2.console.path=/h2-console +debug=true \ No newline at end of file From b3a6a60100be49fea9925d1c17e8c02b5ff49119 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 13 Oct 2018 19:15:02 +0300 Subject: [PATCH 09/21] add txt files for zip --- core-java-io/src/main/resources/zipTest/test1.txt | 1 + core-java-io/src/main/resources/zipTest/test2.txt | 1 + 2 files changed, 2 insertions(+) create mode 100644 core-java-io/src/main/resources/zipTest/test1.txt create mode 100644 core-java-io/src/main/resources/zipTest/test2.txt diff --git a/core-java-io/src/main/resources/zipTest/test1.txt b/core-java-io/src/main/resources/zipTest/test1.txt new file mode 100644 index 0000000000..e88ded96ab --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test1.txt @@ -0,0 +1 @@ +Test1 \ No newline at end of file diff --git a/core-java-io/src/main/resources/zipTest/test2.txt b/core-java-io/src/main/resources/zipTest/test2.txt new file mode 100644 index 0000000000..da8f209890 --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test2.txt @@ -0,0 +1 @@ +Test2 \ No newline at end of file From ca4b6200a74a860fc0c4cc26a47c15215584d70c Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Sat, 13 Oct 2018 20:19:14 +0200 Subject: [PATCH 10/21] BAEL-2268 - Guide to JerseyTest (#5443) * BAEL-2268 - Guide to JerseyTest - second attempt without formatting changes * BAEL-2268 - Guide to JerseyTest - Add line break to end of file --- .../baeldung/jersey/server/model/Fruit.java | 5 +++ .../jersey/server/rest/FruitResource.java | 12 +++++++ .../GreetingsResourceIntegrationTest.java | 33 +++++++++++++++++++ .../rest/FruitResourceIntegrationTest.java | 27 +++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java index c55362487b..1a648290a3 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java @@ -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() + "]"; + } } diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java index ee34cdd3ca..88692dcc55 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java @@ -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; @@ -86,6 +88,16 @@ public class FruitResource { public void createFruit(@Valid Fruit fruit) { 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 diff --git a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java new file mode 100644 index 0000000000..8953f4161c --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java @@ -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); + } +} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java index 2eeb5710cb..376c8c1e75 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java @@ -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; @@ -63,6 +64,15 @@ public class FruitResourceIntegrationTest extends JerseyTest { assertEquals("Http Response should be 400 ", 400, response.getStatus()); 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() { @@ -102,6 +112,23 @@ public class FruitResourceIntegrationTest extends JerseyTest { .get(String.class); 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() { From 1820b2c37ff5d2167e34edd3d67754b3189226c2 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 13 Oct 2018 16:29:52 +0530 Subject: [PATCH 11/21] [BAEL-9514] - Added Junit 5 @DisplayName annotation example --- .../customtestname/CustomNameUnitTest.java | 17 +++++++ .../ParameterizedUnitTest.java | 48 +++++++++++++++++++ .../suite/SelectClassesSuiteUnitTest.java | 13 +++++ .../suite/SelectPackagesSuiteUnitTest.java | 11 +++++ .../suite/childpackage1/Class1UnitTest.java | 15 ++++++ .../suite/childpackage2/Class2UnitTest.java | 14 ++++++ 6 files changed, 118 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java new file mode 100644 index 0000000000..f04b825c89 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java @@ -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); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java new file mode 100644 index 0000000000..af9ad870b9 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java @@ -0,0 +1,48 @@ +package org.baeldung.java.parameterisedsource; + +import static org.junit.Assert.assertNotEquals; +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; + +import com.baeldung.enums.PizzaDeliveryStrategy; + +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 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); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java new file mode 100644 index 0000000000..220897eae7 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java @@ -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 { + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java new file mode 100644 index 0000000000..ae887ae43b --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java @@ -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 { + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java new file mode 100644 index 0000000000..78469cb971 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java @@ -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); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java new file mode 100644 index 0000000000..4463ecfad9 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java @@ -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); + } + +} From c9f2162f984a2f36f91406c1d2b9fa431b53fad3 Mon Sep 17 00:00:00 2001 From: Shreyash Date: Sun, 14 Oct 2018 11:34:09 +0530 Subject: [PATCH 12/21] Spring Data Reactive Redis examples Issue: BAEL-1868 --- .../log4j2/${sys:logging.folder.path} | 0 persistence-modules/spring-data-redis/pom.xml | 87 +++++++++++-------- .../redis/SpringRedisReactiveApplication.java | 13 +++ .../reactive/redis/config/RedisConfig.java | 56 ++++++++++++ .../data/reactive/redis/model/Employee.java | 21 +++++ .../spring/data/redis/config/RedisConfig.java | 8 +- .../RedisKeyCommandsIntegrationTest.java | 51 +++++++++++ .../RedisTemplateListOpsIntegrationTest.java | 49 +++++++++++ .../RedisTemplateValueOpsIntegrationTest.java | 71 +++++++++++++++ .../RedisMessageListenerIntegrationTest.java | 2 +- .../StudentRepositoryIntegrationTest.java | 2 +- pom.xml | 1 + 12 files changed, 318 insertions(+), 43 deletions(-) create mode 100755 logging-modules/log4j2/${sys:logging.folder.path} create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} new file mode 100755 index 0000000000..e69de29bb2 diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 5981bf41e0..bee3d683b8 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -7,17 +7,61 @@ jar + parent-boot-2 com.baeldung - parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 - org.springframework.data - spring-data-redis - ${spring-data-redis} + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + + + io.projectreactor + reactor-test + test + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test @@ -33,42 +77,12 @@ jar - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-test - ${spring.version} - test - - com.lordofthejars nosqlunit-redis ${nosqlunit.version} - - org.springframework.data - spring-data-commons - ${spring-data-commons.version} - com.github.kstyrc embedded-redis @@ -77,12 +91,13 @@ - 2.0.3.RELEASE 3.2.4 2.9.0 0.10.0 2.0.3.RELEASE 0.6 + 1.0.0 + 5.0.2 diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java new file mode 100644 index 0000000000..8b1f892f67 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java @@ -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); + } + +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java new file mode 100644 index 0000000000..d23d0092eb --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java @@ -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 reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Employee.class); + RedisSerializationContext.RedisSerializationContextBuilder builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); + RedisSerializationContext context = builder.value(serializer) + .build(); + return new ReactiveRedisTemplate<>(factory, context); + } + + @Bean + public ReactiveRedisTemplate 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(); + } +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java new file mode 100644 index 0000000000..9178f6e112 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java @@ -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; +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java index 62a7886f46..6fdb3c5bef 100644 --- a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -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") diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java new file mode 100644 index 0000000000..e48aa1e06a --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -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 keys = Flux.just("key1", "key2", "key3", "key4"); + + Flux generator = keys.map(String::getBytes) + .map(ByteBuffer::wrap) + .map(key -> SetCommand.set(key) + .value(key)); + + StepVerifier.create(stringCommands.set(generator)) + .expectNextCount(4L) + .verifyComplete(); + + Mono keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes())) + .flatMapMany(Flux::fromIterable) + .count(); + + StepVerifier.create(keyCount) + .expectNext(4L) + .verifyComplete(); + + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java new file mode 100644 index 0000000000..3ebeff87b1 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -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 redisTemplate; + + private ReactiveListOperations reactiveListOps; + + @Before + public void setup() { + reactiveListOps = redisTemplate.opsForList(); + } + + @Test + public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() { + Mono lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second") + .log("Pushed"); + + StepVerifier.create(lPush) + .expectNext(2L) + .verifyComplete(); + + Mono lPop = reactiveListOps.leftPop(LIST_NAME) + .log("Popped"); + + StepVerifier.create(lPop) + .expectNext("second") + .verifyComplete(); + } + +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java new file mode 100644 index 0000000000..9490568089 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -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 redisTemplate; + + private ReactiveValueOperations reactiveValueOps; + + @Before + public void setup() { + reactiveValueOps = redisTemplate.opsForValue(); + } + + @Test + public void givenEmployee_whenSet_thenSet() { + + Mono result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts")); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + } + + @Test + public void givenEmployeeId_whenGet_thenReturnsEmployee() { + + Mono fetchedEmployee = reactiveValueOps.get("123"); + + StepVerifier.create(fetchedEmployee) + .expectNext(new Employee("123", "Bill", "Accounts")) + .verifyComplete(); + } + + @Test + public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException { + + Mono result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1)); + + Mono fetchedEmployee = reactiveValueOps.get("129"); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + + Thread.sleep(2000L); + + StepVerifier.create(fetchedEmployee) + .expectNextCount(0L) + .verifyComplete(); + } + +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 5bc70069c5..99febb6430 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -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(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index 48832a8de9..43aadefc01 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -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(); } diff --git a/pom.xml b/pom.xml index 6c77ede1c2..28a6dd358e 100644 --- a/pom.xml +++ b/pom.xml @@ -451,6 +451,7 @@ spring-5 spring-5-data-reactive spring-5-reactive + spring-data-5-reactive/spring-5-data-reactive-redis spring-5-reactive-security spring-5-reactive-client spring-5-mvc From 79285e3cc60f28359c1429bc4ca15a4faf5a8a8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Carrasquel?= Date: Sun, 14 Oct 2018 01:33:39 -0500 Subject: [PATCH 13/21] BAEL-2234 Dates difference with ZonedDateTimes (#5445) --- .../test/java/com/baeldung/date/DateDiffUnitTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 58d192bfdb..92da22cc95 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -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(); From ee5fe8faab1b2bdc4c81d840a5545765e2f7260a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 15:13:39 +0530 Subject: [PATCH 14/21] [BAEL-9461] - Added code examples for difference between thenApply() and thenCompose() --- .../CompletableFutureLongRunningUnitTest.java | 20 +++++++++++++++++++ .../log4j2/${sys:logging.folder.path} | 0 2 files changed, 20 insertions(+) delete mode 100755 logging-modules/log4j2/${sys:logging.folder.path} diff --git a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 45d2ec68e4..d9cf8ae019 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -184,5 +184,25 @@ public class CompletableFutureLongRunningUnitTest { assertEquals("Hello World", future.get()); } + + @Test + public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException { + CompletableFuture finalResult = compute().thenApply(s -> s + 1); + assertTrue(finalResult.get() == 11); + } + + @Test + public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException { + CompletableFuture finalResult = compute().thenCompose(this::computeAnother); + assertTrue(finalResult.get() == 20); + } + + public CompletableFuture compute(){ + return CompletableFuture.supplyAsync(() -> 10); + } + + public CompletableFuture computeAnother(Integer i){ + return CompletableFuture.supplyAsync(() -> 10 + i); + } } \ No newline at end of file diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} deleted file mode 100755 index e69de29bb2..0000000000 From b5dcb13c41cae9374210dfe4c178b11a242a04de Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 18:13:40 +0530 Subject: [PATCH 15/21] [BAEL-9635] - Moved Junit vs TestNg junit code examples to junit-5 module from core-java --- .../customtestname/CustomNameUnitTest.java | 17 ------ .../ParameterizedUnitTest.java | 48 ----------------- .../suite/SelectClassesSuiteUnitTest.java | 13 ----- .../suite/SelectPackagesSuiteUnitTest.java | 11 ---- .../suite/childpackage1/Class1UnitTest.java | 15 ------ .../suite/childpackage2/Class2UnitTest.java | 14 ----- .../log4j2/${sys:logging.folder.path} | 0 pom.xml | 6 +++ .../baeldung/throwsexception/Calculator.java | 0 .../DivideByZeroException.java | 0 .../junit4vstestng/SortedUnitTest.java | 0 .../SummationServiceIntegrationTest.java | 0 .../SummationServiceIntegrationTest.java | 53 +++++++++++++++++++ .../throwsexception/CalculatorUnitTest.java | 0 14 files changed, 59 insertions(+), 118 deletions(-) delete mode 100644 core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java delete mode 100755 logging-modules/log4j2/${sys:logging.folder.path} rename {core-java => testing-modules/junit-5}/src/main/java/com/baeldung/throwsexception/Calculator.java (100%) rename {core-java => testing-modules/junit-5}/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java (100%) rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java (100%) rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java (100%) create mode 100644 testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java (100%) diff --git a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java deleted file mode 100644 index f04b825c89..0000000000 --- a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -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); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java deleted file mode 100644 index af9ad870b9..0000000000 --- a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.java.parameterisedsource; - -import static org.junit.Assert.assertNotEquals; -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; - -import com.baeldung.enums.PizzaDeliveryStrategy; - -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 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); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java deleted file mode 100644 index 220897eae7..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java +++ /dev/null @@ -1,13 +0,0 @@ -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 { - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java deleted file mode 100644 index ae887ae43b..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java +++ /dev/null @@ -1,11 +0,0 @@ -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 { - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java deleted file mode 100644 index 78469cb971..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java +++ /dev/null @@ -1,15 +0,0 @@ -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); - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java deleted file mode 100644 index 4463ecfad9..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -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); - } - -} diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} deleted file mode 100755 index e69de29bb2..0000000000 diff --git a/pom.xml b/pom.xml index 28a6dd358e..da1733d2b2 100644 --- a/pom.xml +++ b/pom.xml @@ -46,6 +46,12 @@ ${junit-jupiter.version} test + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + org.junit.jupiter junit-jupiter-api diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java similarity index 100% rename from core-java/src/main/java/com/baeldung/throwsexception/Calculator.java rename to testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java similarity index 100% rename from core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java rename to testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java new file mode 100644 index 0000000000..92e7a6f5db --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java @@ -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 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); + } +} diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java From 29cee792a889d72c211251ee31a5052bf118c7ac Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 20:02:51 +0530 Subject: [PATCH 16/21] [BAEL-9601] - Upgraded groovy-all version in libraries module --- libraries/pom.xml | 3 ++- logging-modules/log4j2/{${sys:logging.folder.path} => ${sys} | 0 2 files changed, 2 insertions(+), 1 deletion(-) rename logging-modules/log4j2/{${sys:logging.folder.path} => ${sys} (100%) mode change 100755 => 100644 diff --git a/libraries/pom.xml b/libraries/pom.xml index 91c54b6113..6bbe8e6f1c 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -358,6 +358,7 @@ org.codehaus.groovy groovy-all + pom ${groovy.version} @@ -922,7 +923,7 @@ 2.3.0 0.9.12 1.19 - 2.4.10 + 2.5.2 1.1.0 3.9.0 2.0.4 diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys old mode 100755 new mode 100644 similarity index 100% rename from logging-modules/log4j2/${sys:logging.folder.path} rename to logging-modules/log4j2/${sys From 38ddcc6477ca324e248173a102be6fd63276a7d9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 14 Oct 2018 19:26:46 +0300 Subject: [PATCH 17/21] rename test to manual --- ...{SystemsUtilsUnitTest.java => SystemsUtilsManualTest.java} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename libraries/src/test/java/com/baeldung/commons/lang3/test/{SystemsUtilsUnitTest.java => SystemsUtilsManualTest.java} (86%) diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java similarity index 86% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java rename to libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java index 0efe97f912..cb45ebc24d 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java @@ -6,8 +6,10 @@ 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() { assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre")); From 23b1323446c2c535ab8fdf3aef19761e0649bc98 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 14 Oct 2018 11:37:16 -0500 Subject: [PATCH 18/21] BAEL-2200: Spring Boot auto-configuration report (#5453) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * BAEL-2026 add link back to article * BAEL-2029: add link back to article * BAEL-1898: Add link back to article * BAEL-2102 and BAEL-2131 Add links back to articles * BAEL-2132 Add link back to article * BAEL-1980: add link back to article * BAEL-2200: Display auto-configuration report in Spring Boot --- .../baeldung/h2db/auto/configuration/AutoConfigurationDemo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java index 87a191554b..8d92e18754 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -4,7 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -@SpringBootApplication(scanBasePackages = "com.baeldung.h2db.auto-configuration") +@SpringBootApplication public class AutoConfigurationDemo { public static void main(String[] args) { From 285219c54c3ffe993e9bb9e7819d5b4cb9802de3 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Sun, 14 Oct 2018 19:08:11 +0200 Subject: [PATCH 19/21] Bael-2210 - Heap Sort (#5446) * implementing heap * Heap sort refactor --- .../main/java/com/baeldung/heapsort/Heap.java | 136 ++++++++++++++++++ .../com/baeldung/heapsort/HeapUnitTest.java | 36 +++++ 2 files changed, 172 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/heapsort/Heap.java create mode 100644 core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/heapsort/Heap.java b/core-java/src/main/java/com/baeldung/heapsort/Heap.java new file mode 100644 index 0000000000..95e0e1d8cd --- /dev/null +++ b/core-java/src/main/java/com/baeldung/heapsort/Heap.java @@ -0,0 +1,136 @@ +package com.baeldung.heapsort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Heap> { + + private List elements = new ArrayList<>(); + + public static > List sort(Iterable elements) { + Heap heap = of(elements); + + List result = new ArrayList<>(); + + while (!heap.isEmpty()) { + result.add(heap.pop()); + } + + return result; + } + + public static > Heap of(E... elements) { + return of(Arrays.asList(elements)); + } + + public static > Heap of(Iterable elements) { + Heap 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; + } + +} diff --git a/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java b/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java new file mode 100644 index 0000000000..cc3e49b6c9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java @@ -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 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 elements = Arrays.asList(3, 5, 1, 4, 2); + + // when + List sortedElements = Heap.sort(elements); + + // then + assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5)); + } + +} From edff9132ee617922b52a12be0d8b35c4e2ffd7d2 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 23:05:11 +0530 Subject: [PATCH 20/21] [BAEL-9635] - Added missing classes --- .../customtestname/CustomNameUnitTest.java | 17 +++++++ .../ParameterizedUnitTest.java | 45 +++++++++++++++++++ .../PizzaDeliveryStrategy.java | 6 +++ .../suite/SelectClassesSuiteUnitTest.java | 13 ++++++ .../suite/SelectPackagesSuiteUnitTest.java | 11 +++++ .../suite/childpackage1/Class1UnitTest.java | 15 +++++++ .../suite/childpackage2/Class2UnitTest.java | 14 ++++++ 7 files changed, 121 insertions(+) create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java new file mode 100644 index 0000000000..f04b825c89 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java @@ -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); + } +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java new file mode 100644 index 0000000000..8d09161176 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java @@ -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 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); + } +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java new file mode 100644 index 0000000000..ecfc7b4627 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java @@ -0,0 +1,6 @@ +package org.baeldung.java.parameterisedsource; + +public enum PizzaDeliveryStrategy { + EXPRESS, + NORMAL; +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java new file mode 100644 index 0000000000..220897eae7 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java @@ -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 { + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java new file mode 100644 index 0000000000..ae887ae43b --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java @@ -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 { + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java new file mode 100644 index 0000000000..78469cb971 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java @@ -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); + } + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java new file mode 100644 index 0000000000..4463ecfad9 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java @@ -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); + } + +} From 3d51a0f86aa42ffd32ba9233af1537be9ba2353a Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 14 Oct 2018 22:19:23 -0500 Subject: [PATCH 21/21] BAEL-2253 Update README (#5460) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * BAEL-2026 add link back to article * BAEL-2029: add link back to article * BAEL-1898: Add link back to article * BAEL-2102 and BAEL-2131 Add links back to articles * BAEL-2132 Add link back to article * BAEL-1980: add link back to article * BAEL-2200: Display auto-configuration report in Spring Boot * BAEL-2253: Add link back to article --- javaxval/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/javaxval/README.md b/javaxval/README.md index 3153546c7d..3a975022ad 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -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)