diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetAddBenchmark.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetAddBenchmark.java new file mode 100644 index 0000000000..a39ff832ce --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetAddBenchmark.java @@ -0,0 +1,56 @@ +package com.baeldung.listandset.benchmark; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@Warmup(iterations = 3, time = 10, timeUnit = TimeUnit.MILLISECONDS) +@Measurement(iterations = 3, time = 10, timeUnit = TimeUnit.MILLISECONDS) +public class ListAndSetAddBenchmark { + + public static void main(String[] args) throws IOException, RunnerException { + Options opt = new OptionsBuilder() + .include(ListAndSetAddBenchmark.class.getSimpleName()) + .forks(1) + .addProfiler("gc") + .build(); + new Runner(opt).run(); + + } + + @Benchmark + public void addElementToArrayList(Params param, Blackhole blackhole) { + param.arrayList.clear(); + for (int i = 0; i < param.addNumber; i++) { + blackhole.consume(param.arrayList.add(i)); + } + } + + @Benchmark + public void addElementToHashSet(Params param, Blackhole blackhole) { + param.hashSet.clear(); + for (int i = 0; i < param.addNumber; i++) { + blackhole.consume(param.hashSet.add(i)); + } + } + + @State(Scope.Benchmark) + public static class Params { + public int addNumber = 10000000; + + public List arrayList = new ArrayList<>(); + public Set hashSet = new HashSet<>(); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetContainsBenchmark.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetContainsBenchmark.java new file mode 100644 index 0000000000..ef19a81427 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/listandset/benchmark/ListAndSetContainsBenchmark.java @@ -0,0 +1,70 @@ +package com.baeldung.listandset.benchmark; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@Warmup(iterations = 3, time = 10, timeUnit = TimeUnit.MILLISECONDS) +@Measurement(iterations = 3, time = 10, timeUnit = TimeUnit.MILLISECONDS) +public class ListAndSetContainsBenchmark { + + public static void main(String[] args) throws IOException, RunnerException { + Options opt = new OptionsBuilder() + .include(ListAndSetContainsBenchmark.class.getSimpleName()) + .forks(1) + .addProfiler("gc") + .build(); + new Runner(opt).run(); + + } + + + + + @Benchmark + public void searchElementInArrayList(Params param, Blackhole blackhole) { + + blackhole.consume(param.arrayList.contains(param.searchElement)); + } + + @Benchmark + public void searchElementInHashSet(Params param, Blackhole blackhole) { + + blackhole.consume(param.hashSet.contains(param.searchElement)); + + } + + @State(Scope.Benchmark) + public static class Params { + @Param({"5000000"}) + public int searchElement; + + @Param({"10000000"}) + public int collectionSize; + + public List arrayList; + public Set hashSet; + + @Setup(Level.Iteration) + public void setup() { + arrayList = new ArrayList<>(); + hashSet = new HashSet<>(); + for (int i = 0; i < collectionSize; i++) { + arrayList.add(i); + hashSet.add(i); + } + } + } + +} diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listtojson/ListToJsonArrayUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listtojson/ListToJsonArrayUnitTest.java new file mode 100644 index 0000000000..b57ba0bbca --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listtojson/ListToJsonArrayUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.listtojson; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import org.json.JSONArray; +import org.junit.Assert; +import java.util.Arrays; +import org.junit.Test; +import java.util.List; + +public class ListToJsonArrayUnitTest { + public List list = Arrays.asList("Article 1", "Article 2", "Article 3"); + public String expectedJsonArray = "[\"Article 1\",\"Article 2\",\"Article 3\"]"; + +@Test +public void given_JavaList_whenUsingJacksonLibrary_thenOutJsonArray() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + String jsonArray = objectMapper.writeValueAsString(list); + Assert.assertEquals(expectedJsonArray, jsonArray); +} + + @Test + public void given_JavaList_whenUsingGsonLibrary_thenOutJsonArray() { + Gson gson = new Gson(); + String jsonArray = gson.toJson(list); + Assert.assertEquals(expectedJsonArray, jsonArray); + } + + @Test + public void given_JavaList_whenOrgJsonLibrary_thenOutJsonAray() { + JSONArray jsonArray = new JSONArray(list); + Assert.assertEquals(expectedJsonArray, jsonArray.toString()); + } + +} diff --git a/core-java-modules/core-java-string-operations-6/pom.xml b/core-java-modules/core-java-string-operations-6/pom.xml index 8b9eabbc63..ddbb5d0e40 100644 --- a/core-java-modules/core-java-string-operations-6/pom.xml +++ b/core-java-modules/core-java-string-operations-6/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-string-operations-6 core-java-string-operations-6 @@ -12,6 +12,14 @@ core-java-modules 0.0.1-SNAPSHOT + + + org.apache.commons + commons-lang3 + ${apache.commons-lang.version} + + + @@ -29,6 +37,7 @@ 11 11 + 3.12.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/checkcase/StringAllUpperOrLowercaseUnitTest.java b/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/checkcase/StringAllUpperOrLowercaseUnitTest.java new file mode 100644 index 0000000000..6dec5af29a --- /dev/null +++ b/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/checkcase/StringAllUpperOrLowercaseUnitTest.java @@ -0,0 +1,104 @@ +package com.baeldung.checkcase; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.Test; + +class CaseChecker { + + static boolean allUpper1(String input) { + return input.equals(input.toUpperCase()); + } + + static boolean allLower1(String input) { + return input.equals(input.toLowerCase()); + } + + static boolean allUpper2(String input) { + for (char c : input.toCharArray()) { + // don't write in this way: if (!Character.isUpperCase(c)) + if (Character.isLowerCase(c)) { + return false; + } + } + return true; + } + + static boolean allLower2(String input) { + for (char c : input.toCharArray()) { + // don't write in this way: if (!Character.isLowerCase(c)) + if (Character.isUpperCase(c)) { + return false; + } + } + return true; + } + + static boolean allUpper3(String input) { + return input.chars() + .noneMatch(Character::isLowerCase); + } + + static boolean allLower3(String input) { + return input.chars() + .noneMatch(Character::isUpperCase); + } +} + +public class StringAllUpperOrLowercaseUnitTest { + private static final String UPPER_INPUT = "1: COOL!"; + private static final String LOWER_INPUT = "2: cool!"; + private static final String MIXED_INPUT = "3: Cool!"; + + @Test + void whenComparingToConvertedString_thenGetExpectedResult() { + assertTrue(CaseChecker.allLower1(LOWER_INPUT)); + assertFalse(CaseChecker.allLower1(UPPER_INPUT)); + assertFalse(CaseChecker.allLower1(MIXED_INPUT)); + + assertFalse(CaseChecker.allUpper1(LOWER_INPUT)); + assertTrue(CaseChecker.allUpper1(UPPER_INPUT)); + assertFalse(CaseChecker.allUpper1(MIXED_INPUT)); + } + + @Test + void whenCheckCharInArray_thenGetExpectedResult() { + assertTrue(CaseChecker.allLower2(LOWER_INPUT)); + assertFalse(CaseChecker.allLower2(UPPER_INPUT)); + assertFalse(CaseChecker.allLower2(MIXED_INPUT)); + + assertFalse(CaseChecker.allUpper2(LOWER_INPUT)); + assertTrue(CaseChecker.allUpper2(UPPER_INPUT)); + assertFalse(CaseChecker.allUpper2(MIXED_INPUT)); + } + + @Test + void whenUsingStream_thenGetExpectedResult() { + assertTrue(CaseChecker.allLower3(LOWER_INPUT)); + assertFalse(CaseChecker.allLower3(UPPER_INPUT)); + assertFalse(CaseChecker.allLower3(MIXED_INPUT)); + + assertFalse(CaseChecker.allUpper3(LOWER_INPUT)); + assertTrue(CaseChecker.allUpper3(UPPER_INPUT)); + assertFalse(CaseChecker.allUpper3(MIXED_INPUT)); + } + + @Test + void whenUsingApacheCommons_thenGetExpectedResult() { + assertFalse(StringUtils.isAllLowerCase(LOWER_INPUT)); + assertFalse(StringUtils.isAllLowerCase(UPPER_INPUT)); + assertFalse(StringUtils.isAllLowerCase(MIXED_INPUT)); + + assertFalse(StringUtils.isAllLowerCase("a b")); + assertTrue(StringUtils.isAllLowerCase("ab")); + + assertFalse(StringUtils.isAllUpperCase(LOWER_INPUT)); + assertFalse(StringUtils.isAllUpperCase(UPPER_INPUT)); + assertFalse(StringUtils.isAllUpperCase(MIXED_INPUT)); + + assertFalse(StringUtils.isAllUpperCase("A B")); + assertTrue(StringUtils.isAllUpperCase("AB")); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java index 11e776123a..fb38ae4018 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java @@ -12,10 +12,8 @@ public class Citizen { public Citizen() { } - public Citizen(EncryptedCitizen encryptedCitizen) { - if (encryptedCitizen != null) { - this.name = encryptedCitizen.getName(); - } + public Citizen(String name) { + this.name = name; } public String getName() { diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java index c7ca5566a9..b8d7f413ce 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java @@ -13,8 +13,8 @@ public class EncryptedCitizen { public EncryptedCitizen() { } - public EncryptedCitizen(Citizen citizen) { - this.name = citizen.getName(); + public EncryptedCitizen(String name) { + this.name = name; } public String getName() { diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java index c93b00f3f8..094483bbdf 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java @@ -39,7 +39,7 @@ public class CitizenService { if (encryptionConfig.isAutoEncryption()) { return mongo.save(citizen); } else { - EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen); + EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen.getName()); encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM)); encryptedCitizen.setBirthYear(encrypt(citizen.getBirthYear(), RANDOM_ALGORITHM)); @@ -77,19 +77,10 @@ public class CitizenService { } } - public Binary encrypt(Object value, String algorithm) { - if (value == null) + public Binary encrypt(BsonValue bsonValue, String algorithm) { + if (bsonValue == null) return null; - BsonValue bsonValue; - if (value instanceof Integer) { - bsonValue = new BsonInt32((Integer) value); - } else if (value instanceof String) { - bsonValue = new BsonString((String) value); - } else { - throw new IllegalArgumentException("unsupported type: " + value.getClass()); - } - EncryptOptions options = new EncryptOptions(algorithm); options.keyId(encryptionConfig.getDataKeyId()); @@ -97,6 +88,20 @@ public class CitizenService { return new Binary(encryptedValue.getType(), encryptedValue.getData()); } + public Binary encrypt(String value, String algorithm) { + if (value == null) + return null; + + return encrypt(new BsonString(value), algorithm); + } + + public Binary encrypt(Integer value, String algorithm) { + if (value == null) + return null; + + return encrypt(new BsonInt32(value), algorithm); + } + public BsonValue decryptProperty(Binary value) { if (value == null) return null; @@ -108,7 +113,7 @@ public class CitizenService { if (encrypted == null) return null; - Citizen citizen = new Citizen(encrypted); + Citizen citizen = new Citizen(encrypted.getName()); BsonValue decryptedBirthYear = decryptProperty(encrypted.getBirthYear()); if (decryptedBirthYear != null) { diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index a9970e85c0..d513822ea3 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -28,6 +28,7 @@ spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-java-2 + spring-mvc-java-3 spring-mvc-velocity spring-mvc-views spring-mvc-webflow diff --git a/spring-web-modules/spring-mvc-java-3/README.md b/spring-web-modules/spring-mvc-java-3/README.md new file mode 100644 index 0000000000..7d843af9ea --- /dev/null +++ b/spring-web-modules/spring-mvc-java-3/README.md @@ -0,0 +1 @@ +### Relevant Articles: diff --git a/spring-web-modules/spring-mvc-java-3/pom.xml b/spring-web-modules/spring-mvc-java-3/pom.xml new file mode 100644 index 0000000000..3a49a5f9af --- /dev/null +++ b/spring-web-modules/spring-mvc-java-3/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + spring-mvc-java-3 + 0.1-SNAPSHOT + spring-mvc-java-3 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + javax.servlet + javax.servlet-api + + + org.springframework + spring-webmvc + + + + + spring-mvc-java-3 + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/filters/CacheRequestContentFilter.java b/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/filters/CacheRequestContentFilter.java new file mode 100644 index 0000000000..907ec24700 --- /dev/null +++ b/spring-web-modules/spring-mvc-java-3/src/main/java/com/baeldung/filters/CacheRequestContentFilter.java @@ -0,0 +1,23 @@ +package com.baeldung.filters; + +import org.springframework.web.util.ContentCachingRequestWrapper; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@WebFilter(urlPatterns = "/*") +public class CacheRequestContentFilter implements Filter { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { + if (request instanceof HttpServletRequest) { + String contentType = request.getContentType(); + if (contentType == null || !contentType.contains("multipart/form-data")) { + request = new ContentCachingRequestWrapper((HttpServletRequest) request); + } + } + chain.doFilter(request, response); + } +} diff --git a/spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/filters/HttpRequestUnitTest.java b/spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/filters/HttpRequestUnitTest.java new file mode 100644 index 0000000000..cd369d9118 --- /dev/null +++ b/spring-web-modules/spring-mvc-java-3/src/test/java/com/baeldung/filters/HttpRequestUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.filters; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import javax.servlet.Filter; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +public class HttpRequestUnitTest { + + @Test + public void givenHttpServletRequest_whenCalling_getReaderAfter_getInputStream_thenThrowIllegalStateException() throws IOException { + HttpServletRequest request = new MockHttpServletRequest(); + try (ServletInputStream ignored = request.getInputStream()) { + IllegalStateException exception = assertThrows(IllegalStateException.class, request::getReader); + assertEquals("Cannot call getReader() after getInputStream() has already been called for the current request", + exception.getMessage()); + } + } + + @Test + public void givenServletRequest_whenDoFilter_thenCanCallBoth() throws ServletException, IOException { + MockHttpServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse res = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + + Filter filter = new CacheRequestContentFilter(); + filter.doFilter(req, res, chain); + + ServletRequest request = chain.getRequest(); + assertTrue(request instanceof ContentCachingRequestWrapper); + + // now we can call both getInputStream() and getReader() + request.getInputStream(); + request.getReader(); + } + +} diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 25e9fd51a2..fe7ec0fe7a 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -1,7 +1,7 @@ - + 4.0.0 mockito-2 diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Helper.java b/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Helper.java new file mode 100644 index 0000000000..dd8e04065b --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Helper.java @@ -0,0 +1,9 @@ +package com.baeldung.wantedbutnotinvocked; + +class Helper { + + String getBaeldungString() { + return "Baeldung"; + } + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Main.java b/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Main.java new file mode 100644 index 0000000000..31134000d2 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/wantedbutnotinvocked/Main.java @@ -0,0 +1,14 @@ +package com.baeldung.wantedbutnotinvocked; + +class Main { + + Helper helper = new Helper(); + + String methodUnderTest(int i) { + if (i > 5) { + return helper.getBaeldungString(); + } + return "Hello"; + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/wantedbutnotinvocked/MainUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/wantedbutnotinvocked/MainUnitTest.java new file mode 100644 index 0000000000..6927b13a06 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/wantedbutnotinvocked/MainUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.wantedbutnotinvocked; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +class MainUnitTest { + + @Mock + Helper helper; + + @InjectMocks + Main main = new Main(); + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void givenValueUpperThan5_WhenMethodUnderTest_ThenDelegatesToHelperClass() { + main.methodUnderTest(7); + Mockito.verify(helper) + .getBaeldungString(); + } + + // Uncomment the next line to see the error + // @Test + void givenValueLowerThan5_WhenMethodUnderTest_ThenDelegatesToGetBaeldungString() { + main.methodUnderTest(3); + Mockito.verify(helper) + .getBaeldungString(); + } + +}