diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java
index 703e6abf7a..7faccbb125 100644
--- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java
+++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java
@@ -1,6 +1,7 @@
package com.baeldung.cassecuredapp.controllers;
-import org.apache.log4j.Logger;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
@@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
@Controller
public class AuthController {
- private Logger logger = Logger.getLogger(AuthController.class);
+ private Logger logger = LogManager.getLogger(AuthController.class);
@GetMapping("/logout")
public String logout(
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index f5506f095e..17d330b3b8 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -1,258 +1,276 @@
-
- 4.0.0
- com.baeldung
- core-java-8
- 0.1.0-SNAPSHOT
- jar
-
- core-java-8
-
-
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
-
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
-
- log4j
- log4j
- 1.2.17
-
-
-
- commons-codec
- commons-codec
- ${commons-codec.version}
-
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
-
-
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
-
-
- com.jayway.awaitility
- awaitility
- ${avaitility.version}
- test
-
-
-
-
-
- core-java-8
-
-
- src/main/resources
- true
-
-
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
-
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
-
-
-
-
-
-
- json
-
-
-
-
-
-
-
-
-
-
-
- 21.0
- 3.5
- 3.6.1
- 2.5
- 4.1
- 4.01
- 1.10
- 1.16.12
-
-
- 3.6.1
- 1.7.0
-
-
+
+ 4.0.0
+ com.baeldung
+ core-java-8
+ 0.1.0-SNAPSHOT
+ jar
+
+ core-java-8
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+
+ log4j
+ log4j
+ 1.2.17
+
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+
+ org.openjdk.jmh
+ jmh-core
+ 1.19
+
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ 1.19
+
+
+
+ org.openjdk.jmh
+ jmh-generator-bytecode
+ 1.19
+
+
+
+
+
+ core-java-8
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ true
+ libs/
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+ ${project.basedir}
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+ jar-with-dependencies
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+
+
+
+ shade
+
+
+ true
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
+
+ com.jolira
+ onejar-maven-plugin
+
+
+
+ org.baeldung.executable.ExecutableMavenJar
+ true
+ ${project.build.finalName}-onejar.${project.packaging}
+
+
+ one-jar
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ spring-boot
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+
+
+
+ 21.0
+ 3.5
+ 3.6.1
+ 2.5
+ 4.1
+ 4.01
+ 1.10
+ 1.16.12
+
+
+ 3.6.1
+ 1.7.0
+
+
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java b/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
new file mode 100644
index 0000000000..2a42a166fa
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
@@ -0,0 +1,45 @@
+package com.baeldung.counter;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Mode;
+
+import com.baeldung.counter.CounterUtil.MutableInteger;
+
+@Fork(value = 1, warmups = 3)
+@BenchmarkMode(Mode.All)
+public class CounterStatistics {
+
+ private static final Map counterMap = new HashMap<>();
+ private static final Map counterWithMutableIntMap = new HashMap<>();
+ private static final Map counterWithIntArrayMap = new HashMap<>();
+ private static final Map counterWithLongWrapperMap = new HashMap<>();
+
+ @Benchmark
+ public void wrapperAsCounter() {
+ CounterUtil.counterWithWrapperObject(counterMap);
+ }
+
+ @Benchmark
+ public void lambdaExpressionWithWrapper() {
+ CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
+ }
+
+ @Benchmark
+ public void mutableIntegerAsCounter() {
+ CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
+ }
+
+ @Benchmark
+ public void primitiveArrayAsCounter() {
+ CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
+ }
+
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.Main.main(args);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java b/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java
new file mode 100644
index 0000000000..657b510452
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.counter;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import com.baeldung.counter.CounterUtil.MutableInteger;
+
+public class CounterTest {
+
+ @Test
+ public void whenMapWithWrapperAsCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithWrapperObject(counterMap);
+
+ assertEquals(3, counterMap.get("China")
+ .intValue());
+ assertEquals(2, counterMap.get("India")
+ .intValue());
+ }
+
+ @Test
+ public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithLambdaAndWrapper(counterMap);
+
+ assertEquals(3l, counterMap.get("China")
+ .longValue());
+ assertEquals(2l, counterMap.get("India")
+ .longValue());
+ }
+
+ @Test
+ public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithMutableInteger(counterMap);
+ assertEquals(3, counterMap.get("China")
+ .getCount());
+ assertEquals(2, counterMap.get("India")
+ .getCount());
+ }
+
+ @Test
+ public void whenMapWithPrimitiveArray_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithPrimitiveArray(counterMap);
+ assertEquals(3, counterMap.get("China")[0]);
+ assertEquals(2, counterMap.get("India")[0]);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java b/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
new file mode 100644
index 0000000000..647fbfb0cc
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
@@ -0,0 +1,61 @@
+package com.baeldung.counter;
+
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class CounterUtil {
+
+ private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
+
+ public static void counterWithWrapperObject(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
+ }
+ }
+
+ public static void counterWithLambdaAndWrapper(Map counterMap) {
+ counterMap.putAll(Stream.of(COUNTRY_NAMES)
+ .parallel()
+ .collect(Collectors.groupingBy(k -> k, Collectors.counting())));
+ }
+
+ public static class MutableInteger {
+ int count;
+
+ public MutableInteger(int count) {
+ this.count = count;
+ }
+
+ public void increment() {
+ this.count++;
+ }
+
+ public int getCount() {
+ return this.count;
+ }
+ }
+
+ public static void counterWithMutableInteger(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ MutableInteger oldValue = counterMap.get(country);
+ if (oldValue != null) {
+ oldValue.increment();
+ } else {
+ counterMap.put(country, new MutableInteger(1));
+ }
+ }
+ }
+
+ public static void counterWithPrimitiveArray(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ int[] oldCounter = counterMap.get(country);
+ if (oldCounter != null) {
+ oldCounter[0] += 1;
+ } else {
+ counterMap.put(country, new int[] { 1 });
+ }
+ }
+ }
+
+}
diff --git a/core-java-9/compile-httpclient.bat b/core-java-9/compile-httpclient.bat
new file mode 100644
index 0000000000..9d845784cf
--- /dev/null
+++ b/core-java-9/compile-httpclient.bat
@@ -0,0 +1,3 @@
+javac --module-path mods -d mods/com.baeldung.httpclient^
+ src/modules/com.baeldung.httpclient/module-info.java^
+ src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
\ No newline at end of file
diff --git a/core-java-9/run-httpclient.bat b/core-java-9/run-httpclient.bat
new file mode 100644
index 0000000000..60b1eb7f68
--- /dev/null
+++ b/core-java-9/run-httpclient.bat
@@ -0,0 +1 @@
+java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java b/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
new file mode 100644
index 0000000000..de08c2164e
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
@@ -0,0 +1,84 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package com.baeldung.httpclient;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+import jdk.incubator.http.HttpClient;
+import jdk.incubator.http.HttpRequest;
+import jdk.incubator.http.HttpRequest.BodyProcessor;
+import jdk.incubator.http.HttpResponse;
+import jdk.incubator.http.HttpResponse.BodyHandler;
+
+/**
+ *
+ * @author pkaria
+ */
+public class HttpClientExample {
+
+ public static void main(String[] args) throws Exception {
+ httpGetRequest();
+ httpPostRequest();
+ asynchronousRequest();
+ asynchronousMultipleRequests();
+ }
+
+ public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
+ HttpClient client = HttpClient.newHttpClient();
+ URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
+ HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
+ .headers("Accept-Enconding", "gzip, deflate").build();
+ HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString());
+ String responseBody = response.body();
+ int responseStatusCode = response.statusCode();
+ System.out.println(responseBody);
+ }
+
+ public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
+ HttpClient client = HttpClient
+ .newBuilder()
+ .build();
+ HttpRequest request = HttpRequest
+ .newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
+ .POST(BodyProcessor.fromString("Sample Post Request"))
+ .build();
+ HttpResponse response
+ = client.send(request, HttpResponse.BodyHandler.asString());
+ String responseBody = response.body();
+ System.out.println(responseBody);
+ }
+
+ public static void asynchronousRequest() throws URISyntaxException {
+ HttpClient client = HttpClient.newHttpClient();
+ URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
+ HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
+ CompletableFuture> futureResponse = client.sendAsync(request,
+ HttpResponse.BodyHandler.asString());
+ }
+
+ public static void asynchronousMultipleRequests() throws URISyntaxException {
+ List targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
+ HttpClient client = HttpClient.newHttpClient();
+ List> futures = targets
+ .stream()
+ .map(target -> client
+ .sendAsync(
+ HttpRequest.newBuilder(target)
+ .GET()
+ .build(),
+ BodyHandler.asFile(Paths.get("base", target.getPath())))
+ .thenApply(response -> response.body())
+ .thenApply(path -> path.toFile()))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.httpclient/module-info.java b/core-java-9/src/modules/com.baeldung.httpclient/module-info.java
new file mode 100644
index 0000000000..205c9ea725
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.httpclient/module-info.java
@@ -0,0 +1,3 @@
+module com.baeldung.httpclient {
+ requires jdk.incubator.httpclient;
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java
index 17b71aa35b..7e2bf590fd 100644
--- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java
@@ -9,7 +9,6 @@ import java.util.List;
import java.util.concurrent.*;
import static junit.framework.TestCase.assertTrue;
-import static org.junit.Assert.fail;
public class WaitingForThreadsToFinishTest {
@@ -40,16 +39,13 @@ public class WaitingForThreadsToFinishTest {
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
- WORKER_THREAD_POOL.submit(new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(1000);
- latch.countDown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- Thread.currentThread().interrupt();
- }
+ WORKER_THREAD_POOL.submit(() -> {
+ try {
+ Thread.sleep(1000);
+ latch.countDown();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Thread.currentThread().interrupt();
}
});
}
@@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
try {
- WORKER_THREAD_POOL.submit(new Callable() {
- @Override
- public String call() throws Exception {
- fail("This thread should have been rejected !");
- Thread.sleep(1000000);
- return null;
- }
+ WORKER_THREAD_POOL.submit((Callable) () -> {
+ Thread.sleep(1000000);
+ return null;
});
} catch (RejectedExecutionException ex) {
//
diff --git a/core-java/README.md b/core-java/README.md
index 1feee4126e..8287a21d1e 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -120,4 +120,5 @@
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
+- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
diff --git a/core-java/customers.xml b/core-java/customers.xml
new file mode 100644
index 0000000000..b52dc27633
--- /dev/null
+++ b/core-java/customers.xml
@@ -0,0 +1,95 @@
+
+
+
+ SELECT * FROM customers
+ 1008
+
+ true
+ 1000
+ 0
+ 2
+
+
+
+ 0
+ 0
+ 0
+ true
+ ResultSet.TYPE_SCROLL_INSENSITIVE
+ false
+ customers
+ jdbc:h2:mem:testdb
+
+ com.sun.rowset.providers.RIOptimisticProvider
+ Oracle Corporation
+ 1.0
+ 2
+ 1
+
+
+
+ 2
+
+ 1
+ false
+ true
+ false
+ 0
+ true
+ true
+ 11
+ ID
+ ID
+ PUBLIC
+ 10
+ 0
+ CUSTOMERS
+ TESTDB
+ 4
+ INTEGER
+
+
+ 2
+ false
+ true
+ false
+ 0
+ true
+ true
+ 50
+ NAME
+ NAME
+ PUBLIC
+ 50
+ 0
+ CUSTOMERS
+ TESTDB
+ 12
+ VARCHAR
+
+
+
+
+ 1
+ Customer1
+
+
+ 2
+ Customer2
+
+
+ 3
+ Customer3
+
+
+ 4
+ Customer4
+
+
+ 5
+ Customer5
+
+
+
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 2c4cbfc37b..068a772c43 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,479 +1,496 @@
- 4.0.0
- com.baeldung
- core-java
- 0.1.0-SNAPSHOT
- jar
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ core-java
+ 0.1.0-SNAPSHOT
+ jar
- core-java
+ core-java
-
+
-
-
- net.sourceforge.collections
- collections-generic
- ${collections-generic.version}
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
-
- org.decimal4j
- decimal4j
- ${decimal4j.version}
-
-
-
- org.bouncycastle
- bcprov-jdk15on
- ${bouncycastle.version}
-
-
-
- org.unix4j
- unix4j-command
- ${unix4j.version}
-
-
-
- com.googlecode.grep4j
- grep4j
- ${grep4j.version}
-
-
-
-
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
-
-
-
- log4j
- log4j
- 1.2.17
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
-
-
-
- org.hamcrest
- hamcrest-all
- 1.3
- test
-
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
-
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
-
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
- com.jayway.awaitility
- awaitility
- ${avaitility.version}
- test
-
-
-
- commons-codec
- commons-codec
- ${commons-codec.version}
-
-
-
- org.javamoney
- moneta
- 1.1
-
-
-
- org.owasp.esapi
- esapi
- 2.1.0.1
-
-
-
- com.codepoetics
- protonpack
- ${protonpack.version}
-
-
- one.util
- streamex
- ${streamex.version}
-
-
- io.vavr
- vavr
- ${vavr.version}
-
-
- org.openjdk.jmh
- jmh-core
- 1.19
-
-
- org.openjdk.jmh
- jmh-generator-annprocess
- 1.19
-
+
- org.springframework
- spring-web
- 4.3.4.RELEASE
+ net.sourceforge.collections
+ collections-generic
+ ${collections-generic.version}
+
+
+ com.google.guava
+ guava
+ ${guava.version}
-
-
- core-java
-
-
- src/main/resources
- true
-
-
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
-
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- **/*LiveTest.java
- **/*IntegrationTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
-
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
-
-
+
+ org.decimal4j
+ decimal4j
+ ${decimal4j.version}
+
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
+
+ org.bouncycastle
+ bcprov-jdk15on
+ ${bouncycastle.version}
+
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
+
+ org.unix4j
+ unix4j-command
+ ${unix4j.version}
+
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
+
+ com.googlecode.grep4j
+ grep4j
+ ${grep4j.version}
+
+
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
+
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
+
+
+ log4j
+ log4j
+ 1.2.17
+
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
-
- org.codehaus.mojo
- exec-maven-plugin
- 1.6.0
-
- java
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
- -Xmx300m
- -XX:+UseParallelGC
- -classpath
-
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
-
-
+
+
+
+ org.hamcrest
+ hamcrest-all
+ 1.3
+ test
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
+
+
+ org.javamoney
+ moneta
+ 1.1
+
+
+
+ org.owasp.esapi
+ esapi
+ 2.1.0.1
+
+
+ com.h2database
+ h2
+ 1.4.196
+ runtime
+
+
+ com.sun.messaging.mq
+ fscontext
+ ${fscontext.version}
+
+
+ com.codepoetics
+ protonpack
+ ${protonpack.version}
+
+
+ one.util
+ streamex
+ ${streamex.version}
+
+
+ io.vavr
+ vavr
+ ${vavr.version}
+
+
+ org.openjdk.jmh
+ jmh-core
+ 1.19
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ 1.19
+
+
+ org.springframework
+ spring-web
+ 4.3.4.RELEASE
+
+
+
+ org.springframework.boot
+ spring-boot-starter
+ 1.5.8.RELEASE
+
+
+
+
+
+ core-java
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*LiveTest.java
+ **/*IntegrationTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ true
+ libs/
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+ ${project.basedir}
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+ jar-with-dependencies
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+
+
+
+ shade
+
+
+ true
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
+
+
+ com.jolira
+ onejar-maven-plugin
+
+
+
+ org.baeldung.executable.ExecutableMavenJar
+ true
+ ${project.build.finalName}-onejar.${project.packaging}
+
+
+ one-jar
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ spring-boot
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+ java
+ com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
+
+ -Xmx300m
+ -XX:+UseParallelGC
+ -classpath
+
+ com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
+
+
+
-
+
-
+
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
-
-
-
-
-
-
- json
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
-
-
- run-benchmarks
-
- none
-
- exec
-
-
- test
- java
-
- -classpath
-
- org.openjdk.jmh.Main
- .*
-
-
-
-
-
-
-
-
-
+
+
+ run-benchmarks
+
+ none
+
+ exec
+
+
+ test
+ java
+
+ -classpath
+
+ org.openjdk.jmh.Main
+ .*
+
+
+
+
+
+
+
+
+
-
-
- 2.8.5
+
+
+ 2.8.5
-
- 1.7.21
- 1.1.7
+
+ 1.7.21
+ 1.1.7
-
- 23.0
- 3.5
- 1.55
- 1.10
- 3.6.1
- 1.0.3
- 2.5
- 4.1
- 4.01
- 0.4
- 1.8.7
- 1.16.12
- 4.6-b01
- 1.13
- 0.6.5
- 0.9.0
-
-
- 1.3
- 4.12
- 2.8.9
- 3.6.1
- 1.7.0
+
+ 22.0
+ 3.5
+ 1.55
+ 1.10
+ 3.6.1
+ 1.0.3
+ 2.5
+ 4.1
+ 4.01
+ 0.4
+ 1.8.7
+ 1.16.12
+ 4.6-b01
+ 1.13
+ 0.6.5
+ 0.9.0
-
- 3.6.0
- 2.19.1
-
-
\ No newline at end of file
+
+ 1.3
+ 4.12
+ 2.8.9
+ 3.6.1
+ 1.7.0
+
+
+ 3.6.0
+ 2.19.1
+
+
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
new file mode 100644
index 0000000000..9cfcff468e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
@@ -0,0 +1,51 @@
+package com.baeldung.jdbcrowset;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import javax.sql.rowset.JdbcRowSet;
+import javax.sql.rowset.RowSetFactory;
+import javax.sql.rowset.RowSetProvider;
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@EnableAutoConfiguration
+public class DatabaseConfiguration {
+
+
+ public static Connection geth2Connection() throws Exception {
+ Class.forName("org.h2.Driver");
+ System.out.println("Driver Loaded.");
+ String url = "jdbc:h2:mem:testdb";
+ return DriverManager.getConnection(url, "sa", "");
+ }
+
+ public static void initDatabase(Statement stmt) throws SQLException{
+ int iter = 1;
+ while(iter<=5){
+ String customer = "Customer"+iter;
+ String sql ="INSERT INTO customers(id, name) VALUES ("+iter+ ",'"+customer+"');";
+ System.out.println("here is sql statmeent for execution: " + sql);
+ stmt.executeUpdate(sql);
+ iter++;
+ }
+
+ int iterb = 1;
+ while(iterb<=5){
+ String associate = "Associate"+iter;
+ String sql = "INSERT INTO associates(id, name) VALUES("+iterb+",'"+associate+"');";
+ System.out.println("here is sql statement for associate:"+ sql);
+ stmt.executeUpdate(sql);
+ iterb++;
+ }
+
+
+ }
+
+
+
+}
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java b/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
new file mode 100644
index 0000000000..7d5bb759f5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
@@ -0,0 +1,24 @@
+package com.baeldung.jdbcrowset;
+
+import javax.sql.RowSetEvent;
+import javax.sql.RowSetListener;
+
+public class ExampleListener implements RowSetListener {
+
+
+ public void cursorMoved(RowSetEvent event) {
+ System.out.println("ExampleListener alerted of cursorMoved event");
+ System.out.println(event.toString());
+ }
+
+ public void rowChanged(RowSetEvent event) {
+ System.out.println("ExampleListener alerted of rowChanged event");
+ System.out.println(event.toString());
+ }
+
+ public void rowSetChanged(RowSetEvent event) {
+ System.out.println("ExampleListener alerted of rowSetChanged event");
+ System.out.println(event.toString());
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java b/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
new file mode 100644
index 0000000000..14e738f72d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
@@ -0,0 +1,46 @@
+package com.baeldung.jdbcrowset;
+
+import java.sql.SQLException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.sql.RowSet;
+import javax.sql.rowset.Predicate;
+
+public class FilterExample implements Predicate {
+
+ private Pattern pattern;
+
+ public FilterExample(String regexQuery) {
+ if (regexQuery != null && !regexQuery.isEmpty()) {
+ pattern = Pattern.compile(regexQuery);
+ }
+ }
+
+ public boolean evaluate(RowSet rs) {
+ try {
+ if (!rs.isAfterLast()) {
+ String name = rs.getString("name");
+ System.out.println(String.format(
+ "Searching for pattern '%s' in %s", pattern.toString(),
+ name));
+ Matcher matcher = pattern.matcher(name);
+ return matcher.matches();
+ } else
+ return false;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+ public boolean evaluate(Object value, int column) throws SQLException {
+ throw new UnsupportedOperationException("This operation is unsupported.");
+ }
+
+ public boolean evaluate(Object value, String columnName)
+ throws SQLException {
+ throw new UnsupportedOperationException("This operation is unsupported.");
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
new file mode 100644
index 0000000000..72c462ac42
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
@@ -0,0 +1,139 @@
+package com.baeldung.jdbcrowset;
+
+import java.io.FileOutputStream;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import com.sun.rowset.*;
+
+import javax.sql.rowset.CachedRowSet;
+import javax.sql.rowset.FilteredRowSet;
+import javax.sql.rowset.JdbcRowSet;
+import javax.sql.rowset.JoinRowSet;
+import javax.sql.rowset.RowSetFactory;
+import javax.sql.rowset.RowSetProvider;
+import javax.sql.rowset.WebRowSet;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class JdbcRowsetApplication {
+
+ public static void main(String[] args) throws Exception {
+ SpringApplication.run(JdbcRowsetApplication.class, args);
+ Statement stmt = null;
+ try {
+ Connection conn = DatabaseConfiguration.geth2Connection();
+
+ String drop = "DROP TABLE IF EXISTS customers, associates;";
+ String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
+ String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
+
+ stmt = conn.createStatement();
+ stmt.executeUpdate(drop);
+ stmt.executeUpdate(schema);
+ stmt.executeUpdate(schemapartb);
+ // insert data
+ DatabaseConfiguration.initDatabase(stmt);
+ // JdbcRowSet Example
+ String sql = "SELECT * FROM customers";
+ JdbcRowSet jdbcRS;
+ jdbcRS = new JdbcRowSetImpl(conn);
+ jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
+ jdbcRS.setCommand(sql);
+ jdbcRS.execute();
+ jdbcRS.addRowSetListener(new ExampleListener());
+
+ while (jdbcRS.next()) {
+ // each call to next, generates a cursorMoved event
+ System.out.println("id=" + jdbcRS.getString(1));
+ System.out.println("name=" + jdbcRS.getString(2));
+ }
+
+ // CachedRowSet Example
+ String username = "sa";
+ String password = "";
+ String url = "jdbc:h2:mem:testdb";
+ CachedRowSet crs = new CachedRowSetImpl();
+ crs.setUsername(username);
+ crs.setPassword(password);
+ crs.setUrl(url);
+ crs.setCommand(sql);
+ crs.execute();
+ crs.addRowSetListener(new ExampleListener());
+ while (crs.next()) {
+ if (crs.getInt("id") == 1) {
+ System.out.println("CRS found customer1 and will remove the record.");
+ crs.deleteRow();
+ break;
+ }
+ }
+
+ // WebRowSet example
+ WebRowSet wrs = new WebRowSetImpl();
+ wrs.setUsername(username);
+ wrs.setPassword(password);
+ wrs.setUrl(url);
+ wrs.setCommand(sql);
+ wrs.execute();
+ FileOutputStream ostream = new FileOutputStream("customers.xml");
+ wrs.writeXml(ostream);
+
+ // JoinRowSet example
+ CachedRowSetImpl customers = new CachedRowSetImpl();
+ customers.setUsername(username);
+ customers.setPassword(password);
+ customers.setUrl(url);
+ customers.setCommand(sql);
+ customers.execute();
+
+ CachedRowSetImpl associates = new CachedRowSetImpl();
+ associates.setUsername(username);
+ associates.setPassword(password);
+ associates.setUrl(url);
+ String associatesSQL = "SELECT * FROM associates";
+ associates.setCommand(associatesSQL);
+ associates.execute();
+
+ JoinRowSet jrs = new JoinRowSetImpl();
+ final String ID = "id";
+ final String NAME = "name";
+ jrs.addRowSet(customers, ID);
+ jrs.addRowSet(associates, ID);
+ jrs.last();
+ System.out.println("Total rows: " + jrs.getRow());
+ jrs.beforeFirst();
+ while (jrs.next()) {
+
+ String string1 = jrs.getString(ID);
+ String string2 = jrs.getString(NAME);
+ System.out.println("ID: " + string1 + ", NAME: " + string2);
+ }
+
+ // FilteredRowSet example
+ RowSetFactory rsf = RowSetProvider.newFactory();
+ FilteredRowSet frs = rsf.createFilteredRowSet();
+ frs.setCommand("select * from customers");
+ frs.execute(conn);
+ frs.setFilter(new FilterExample("^[A-C].*"));
+
+ ResultSetMetaData rsmd = frs.getMetaData();
+ int columncount = rsmd.getColumnCount();
+ while (frs.next()) {
+ for (int i = 1; i <= columncount; i++) {
+ System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
+ }
+ }
+
+ } catch (SQLException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java b/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java
deleted file mode 100644
index a9911538b0..0000000000
--- a/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.nestedclass;
-
-public class Enclosing {
-
- public static class Nested {
-
- public void test() {
- System.out.println("Calling test...");
- }
- }
-}
diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Outer.java b/core-java/src/main/java/com/baeldung/nestedclass/Outer.java
deleted file mode 100644
index ebd6d27293..0000000000
--- a/core-java/src/main/java/com/baeldung/nestedclass/Outer.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.nestedclass;
-
-public class Outer {
-
- public class Inner {
-
- public void test() {
- System.out.println("Calling test...");
- }
- }
-}
diff --git a/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java b/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java
deleted file mode 100644
index 586e2d12b4..0000000000
--- a/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.baeldung.nestedclass;
-
-abstract class SimpleAbstractClass {
- abstract void run();
-}
\ No newline at end of file
diff --git a/core-java/src/main/resources/countries.properties b/core-java/src/main/resources/countries.properties
index 3c1f53aded..e743b5a40b 100644
--- a/core-java/src/main/resources/countries.properties
+++ b/core-java/src/main/resources/countries.properties
@@ -1,3 +1,3 @@
-UK
-US
-Germany
+UK
+US
+Germany
diff --git a/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java
new file mode 100644
index 0000000000..94911baac9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java
@@ -0,0 +1,116 @@
+package com.baeldung.array;
+
+import org.junit.Test;
+
+import java.util.*;
+
+public class SearchArrayTest {
+
+
+ @Test
+ public void searchArrayAllocNewCollections() {
+
+ int count = 1000;
+
+ String[] strings = seedArray(count);
+
+ long startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ searchList(strings, "W");
+ }
+ long duration = System.nanoTime() - startTime;
+ System.out.println("SearchList: " + duration / 10000);
+
+ startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ searchSet(strings,"S");
+ }
+ duration = System.nanoTime() - startTime;
+ System.out.println("SearchSet: " + duration / 10000);
+
+ startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ searchLoop(strings, "T");
+ }
+ duration = System.nanoTime() - startTime;
+ System.out.println("SearchLoop: " + duration / 10000);
+ }
+
+ @Test
+ public void searchArrayReuseCollections() {
+
+ int count = 10000;
+ String[] strings = seedArray(count);
+
+ List asList = Arrays.asList(strings);
+ Set asSet = new HashSet<>(Arrays.asList(strings));
+
+ long startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ asList.contains("W");
+ }
+ long duration = System.nanoTime() - startTime;
+ System.out.println("List: " + duration / 10000);
+
+ startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ asSet.contains("S");
+ }
+ duration = System.nanoTime() - startTime;
+ System.out.println("Set: " + duration / 10000);
+
+ startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ searchLoop(strings, "T");
+ }
+ duration = System.nanoTime() - startTime;
+ System.out.println("Loop: " + duration / 10000);
+
+ }
+
+
+ @Test
+ public void searchArrayBinarySearch() {
+
+ int count = 10000;
+ String[] strings = seedArray(count);
+ Arrays.sort(strings);
+
+ long startTime = System.nanoTime();
+ for (int i = 0; i < count; i++) {
+ Arrays.binarySearch(strings, "A");
+ }
+ long duration = System.nanoTime() - startTime;
+ System.out.println("Binary search: " + duration / 10000);
+
+ }
+
+ private boolean searchList(String[] strings, String searchString) {
+ return Arrays.asList(strings).contains(searchString);
+ }
+
+ private boolean searchSet(String[] strings, String searchString) {
+ Set set = new HashSet<>(Arrays.asList(strings));
+ return set.contains(searchString);
+ }
+
+ private boolean searchLoop(String[] strings, String searchString) {
+ for (String s : strings) {
+ if (s.equals(searchString))
+ return true;
+ }
+ return false;
+ }
+
+ private String[] seedArray(int length) {
+
+ String[] strings = new String[length];
+ Random random = new Random();
+ for (int i = 0; i < length; i++)
+ {
+ strings[i] = String.valueOf(random.nextInt());
+ }
+ return strings;
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/collection/WhenUsingHashSet.java b/core-java/src/test/java/com/baeldung/collection/WhenUsingHashSet.java
new file mode 100644
index 0000000000..7dc47ee8c2
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/collection/WhenUsingHashSet.java
@@ -0,0 +1,93 @@
+package com.baeldung.collection;
+
+import java.util.ConcurrentModificationException;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class WhenUsingHashSet {
+
+ @Test
+ public void whenAddingElement_shouldAddElement() {
+ Set hashset = new HashSet<>();
+ Assert.assertTrue(hashset.add("String Added"));
+ }
+
+ @Test
+ public void whenCheckingForElement_shouldSearchForElement() {
+ Set hashsetContains = new HashSet<>();
+ hashsetContains.add("String Added");
+ Assert.assertTrue(hashsetContains.contains("String Added"));
+ }
+
+ @Test
+ public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
+ Set hashSetSize = new HashSet<>();
+ hashSetSize.add("String Added");
+ Assert.assertEquals(1, hashSetSize.size());
+ }
+
+ @Test
+ public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
+ Set emptyHashSet = new HashSet<>();
+ Assert.assertTrue(emptyHashSet.isEmpty());
+ }
+
+ @Test
+ public void whenRemovingElement_shouldRemoveElement() {
+ Set removeFromHashSet = new HashSet<>();
+ removeFromHashSet.add("String Added");
+ Assert.assertTrue(removeFromHashSet.remove("String Added"));
+ }
+
+ @Test
+ public void whenClearingHashSet_shouldClearHashSet() {
+ Set clearHashSet = new HashSet<>();
+ clearHashSet.add("String Added");
+ clearHashSet.clear();
+ Assert.assertTrue(clearHashSet.isEmpty());
+ }
+
+ @Test
+ public void whenIteratingHashSet_shouldIterateHashSet() {
+ Set hashset = new HashSet<>();
+ hashset.add("First");
+ hashset.add("Second");
+ hashset.add("Third");
+ Iterator itr = hashset.iterator();
+ while (itr.hasNext()) {
+ System.out.println(itr.next());
+ }
+ }
+
+ @Test(expected = ConcurrentModificationException.class)
+ public void whenModifyingHashSetWhileIterating_shouldThrowException() {
+ Set hashset = new HashSet<>();
+ hashset.add("First");
+ hashset.add("Second");
+ hashset.add("Third");
+ Iterator itr = hashset.iterator();
+ while (itr.hasNext()) {
+ itr.next();
+ hashset.remove("Second");
+ }
+ }
+
+ @Test
+ public void whenRemovingElementUsingIterator_shouldRemoveElement() {
+ Set hashset = new HashSet<>();
+ hashset.add("First");
+ hashset.add("Second");
+ hashset.add("Third");
+ Iterator itr = hashset.iterator();
+ while (itr.hasNext()) {
+ String element = itr.next();
+ if (element.equals("Second"))
+ itr.remove();
+ }
+ Assert.assertEquals(2, hashset.size());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java
new file mode 100644
index 0000000000..cb455c213a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java
@@ -0,0 +1,157 @@
+package com.baeldung.jdbcrowset;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import javax.sql.rowset.CachedRowSet;
+import javax.sql.rowset.FilteredRowSet;
+import javax.sql.rowset.JdbcRowSet;
+import javax.sql.rowset.JoinRowSet;
+import javax.sql.rowset.RowSetFactory;
+import javax.sql.rowset.RowSetProvider;
+import javax.sql.rowset.WebRowSet;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.sun.rowset.CachedRowSetImpl;
+import com.sun.rowset.JdbcRowSetImpl;
+import com.sun.rowset.JoinRowSetImpl;
+import com.sun.rowset.WebRowSetImpl;
+
+public class JdbcRowSetTest {
+ Statement stmt = null;
+ String username = "sa";
+ String password = "";
+ String url = "jdbc:h2:mem:testdb";
+ String sql = "SELECT * FROM customers";
+
+ @Before
+ public void setup() throws Exception {
+ Connection conn = DatabaseConfiguration.geth2Connection();
+
+ String drop = "DROP TABLE IF EXISTS customers, associates;";
+ String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
+ String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
+ stmt = conn.createStatement();
+ stmt.executeUpdate(drop);
+ stmt.executeUpdate(schema);
+ stmt.executeUpdate(schemapartb);
+ DatabaseConfiguration.initDatabase(stmt);
+
+ }
+
+ // JdbcRowSet Example
+ @Test
+ public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
+
+ String sql = "SELECT * FROM customers";
+ JdbcRowSet jdbcRS;
+ Connection conn = DatabaseConfiguration.geth2Connection();
+ jdbcRS = new JdbcRowSetImpl(conn);
+ jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
+ jdbcRS.setCommand(sql);
+ jdbcRS.execute();
+ jdbcRS.addRowSetListener(new ExampleListener());
+
+ while (jdbcRS.next()) {
+ // each call to next, generates a cursorMoved event
+ System.out.println("id=" + jdbcRS.getString(1));
+ System.out.println("name=" + jdbcRS.getString(2));
+ }
+
+ }
+
+ // CachedRowSet Example
+ @Test
+ public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
+
+ CachedRowSet crs = new CachedRowSetImpl();
+ crs.setUsername(username);
+ crs.setPassword(password);
+ crs.setUrl(url);
+ crs.setCommand(sql);
+ crs.execute();
+ crs.addRowSetListener(new ExampleListener());
+ while (crs.next()) {
+ if (crs.getInt("id") == 1) {
+ System.out.println("CRS found customer1 and will remove the record.");
+ crs.deleteRow();
+ break;
+ }
+ }
+ }
+
+ // WebRowSet example
+ @Test
+ public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
+
+ WebRowSet wrs = new WebRowSetImpl();
+ wrs.setUsername(username);
+ wrs.setPassword(password);
+ wrs.setUrl(url);
+ wrs.setCommand(sql);
+ wrs.execute();
+ FileOutputStream ostream = new FileOutputStream("customers.xml");
+ wrs.writeXml(ostream);
+ }
+
+ // JoinRowSet example
+ @Test
+ public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
+
+ CachedRowSetImpl customers = new CachedRowSetImpl();
+ customers.setUsername(username);
+ customers.setPassword(password);
+ customers.setUrl(url);
+ customers.setCommand(sql);
+ customers.execute();
+
+ CachedRowSetImpl associates = new CachedRowSetImpl();
+ associates.setUsername(username);
+ associates.setPassword(password);
+ associates.setUrl(url);
+ String associatesSQL = "SELECT * FROM associates";
+ associates.setCommand(associatesSQL);
+ associates.execute();
+
+ JoinRowSet jrs = new JoinRowSetImpl();
+ final String ID = "id";
+ final String NAME = "name";
+ jrs.addRowSet(customers, ID);
+ jrs.addRowSet(associates, ID);
+ jrs.last();
+ System.out.println("Total rows: " + jrs.getRow());
+ jrs.beforeFirst();
+ while (jrs.next()) {
+
+ String string1 = jrs.getString(ID);
+ String string2 = jrs.getString(NAME);
+ System.out.println("ID: " + string1 + ", NAME: " + string2);
+ }
+ }
+
+ // FilteredRowSet example
+ @Test
+ public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
+ RowSetFactory rsf = RowSetProvider.newFactory();
+ FilteredRowSet frs = rsf.createFilteredRowSet();
+ frs.setCommand("select * from customers");
+ Connection conn = DatabaseConfiguration.geth2Connection();
+ frs.execute(conn);
+ frs.setFilter(new FilterExample("^[A-C].*"));
+
+ ResultSetMetaData rsmd = frs.getMetaData();
+ int columncount = rsmd.getColumnCount();
+ while (frs.next()) {
+ for (int i = 1; i <= columncount; i++) {
+ System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
+ }
+ }
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java
index 9590eabfef..f82f9ddaa7 100644
--- a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java
+++ b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java
@@ -1,11 +1,38 @@
package com.baeldung.loops;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
+ private static List list = new ArrayList<>();
+ private static Set set = new HashSet<>();
+ private static Map map = new HashMap<>();
+
+ @BeforeClass
+ public static void setUp() {
+ list.add("One");
+ list.add("Two");
+ list.add("Three");
+
+ set.add("Four");
+ set.add("Five");
+ set.add("Six");
+
+ map.put("One", 1);
+ map.put("Two", 2);
+ map.put("Three", 3);
+ }
@Test
public void shouldRunForLoop() {
@@ -34,4 +61,47 @@ public class WhenUsingLoops {
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
+
+ @Test
+ public void whenUsingSimpleFor_shouldIterateList() {
+ for (int i = 0; i < list.size(); i++) {
+ System.out.println(list.get(i));
+ }
+ }
+
+ @Test
+ public void whenUsingEnhancedFor_shouldIterateList() {
+ for (String item : list) {
+ System.out.println(item);
+ }
+ }
+
+ @Test
+ public void whenUsingEnhancedFor_shouldIterateSet() {
+ for (String item : set) {
+ System.out.println(item);
+ }
+ }
+
+ @Test
+ public void whenUsingEnhancedFor_shouldIterateMap() {
+ for (Entry entry : map.entrySet()) {
+ System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
+ }
+ }
+
+ @Test
+ public void whenUsingSimpleFor_shouldRunLabelledLoop() {
+ aa: for (int i = 1; i <= 3; i++) {
+ if (i == 1)
+ continue;
+ bb: for (int j = 1; j <= 3; j++) {
+ if (i == 2 && j == 2) {
+ break aa;
+ }
+ System.out.println(i + " " + j);
+ }
+ }
+ }
+
}
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInner.java
similarity index 72%
rename from core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java
rename to core-java/src/test/java/com/baeldung/nestedclass/AnonymousInner.java
index 394c0bb57a..9fa8ee9cd5 100644
--- a/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java
+++ b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInner.java
@@ -2,10 +2,14 @@ package com.baeldung.nestedclass;
import org.junit.Test;
-public class AnonymousInnerTest {
+abstract class SimpleAbstractClass {
+ abstract void run();
+}
+
+public class AnonymousInner {
@Test
- public void whenRunAnonymousClass_thenCorrect() {
+ public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/Enclosing.java b/core-java/src/test/java/com/baeldung/nestedclass/Enclosing.java
new file mode 100644
index 0000000000..3db33cde9b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/nestedclass/Enclosing.java
@@ -0,0 +1,21 @@
+package com.baeldung.nestedclass;
+
+import org.junit.Test;
+
+public class Enclosing {
+
+ private static int x = 1;
+
+ public static class StaticNested {
+
+ private void run() {
+ System.out.println("x = " + x);
+ }
+ }
+
+ @Test
+ public void test() {
+ Enclosing.StaticNested nested = new Enclosing.StaticNested();
+ nested.run();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java
deleted file mode 100644
index e9cb119ac2..0000000000
--- a/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.baeldung.nestedclass;
-
-import org.junit.Test;
-
-public class InnerClassTest {
-
- @Test
- public void givenInnerClassWhenInstantiating_thenCorrect() {
- Outer outer = new Outer();
- Outer.Inner inner = outer.new Inner();
- inner.test();
- }
-}
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java
deleted file mode 100644
index dad19161ad..0000000000
--- a/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.baeldung.nestedclass;
-
-import org.junit.Test;
-
-public class LocalClassTest {
-
- @Test
- public void whenTestingLocalClass_thenCorrect() {
- NewEnclosing newEnclosing = new NewEnclosing();
- newEnclosing.run();
- }
-}
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java
deleted file mode 100644
index 16c883689a..0000000000
--- a/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.baeldung.nestedclass;
-
-import org.junit.Test;
-
-public class NestedClassTest {
-
- @Test
- public void whenInstantiatingStaticNestedClass_thenCorrect() {
- Enclosing.Nested nested = new Enclosing.Nested();
- nested.test();
- }
-}
diff --git a/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java b/core-java/src/test/java/com/baeldung/nestedclass/NewEnclosing.java
similarity index 59%
rename from core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java
rename to core-java/src/test/java/com/baeldung/nestedclass/NewEnclosing.java
index c7e04e8600..deeb72de0c 100644
--- a/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java
+++ b/core-java/src/test/java/com/baeldung/nestedclass/NewEnclosing.java
@@ -1,10 +1,11 @@
package com.baeldung.nestedclass;
+import org.junit.Test;
+
public class NewEnclosing {
- void run() {
+ private void run() {
class Local {
-
void run() {
System.out.println("Welcome to Baeldung!");
}
@@ -12,4 +13,10 @@ public class NewEnclosing {
Local local = new Local();
local.run();
}
+
+ @Test
+ public void test() {
+ NewEnclosing newEnclosing = new NewEnclosing();
+ newEnclosing.run();
+ }
}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java b/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java
new file mode 100644
index 0000000000..a3a723b30e
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java
@@ -0,0 +1,30 @@
+package com.baeldung.nestedclass;
+
+import org.junit.Test;
+
+public class NewOuter {
+
+ int a = 1;
+ static int b = 2;
+
+ public class InnerClass {
+ int a = 3;
+ static final int b = 4;
+
+ public void run() {
+ System.out.println("a = " + a);
+ System.out.println("b = " + b);
+ System.out.println("NewOuterTest.this.a = " + NewOuter.this.a);
+ System.out.println("NewOuterTest.b = " + NewOuter.b);
+ System.out.println("NewOuterTest.this.b = " + NewOuter.this.b);
+ }
+ }
+
+ @Test
+ public void test() {
+ NewOuter outer = new NewOuter();
+ NewOuter.InnerClass inner = outer.new InnerClass();
+ inner.run();
+
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java
deleted file mode 100644
index e883687d33..0000000000
--- a/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.baeldung.nestedclass;
-
-import static org.junit.Assert.assertEquals;
-import org.junit.Test;
-
-public class NewOuterTest {
-
- int a = 1;
- static int b = 2;
-
- public class InnerClass {
- int a = 3;
- static final int b = 4;
-
- @Test
- public void whenShadowing_thenCorrect() {
- assertEquals(3, a);
- assertEquals(4, b);
- assertEquals(1, NewOuterTest.this.a);
- assertEquals(2, NewOuterTest.b);
- assertEquals(2, NewOuterTest.this.b);
- }
- }
-
- @Test
- public void shadowingTest() {
- NewOuterTest outer = new NewOuterTest();
- NewOuterTest.InnerClass inner = outer.new InnerClass();
- inner.whenShadowing_thenCorrect();
-
- }
-}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/nestedclass/Outer.java b/core-java/src/test/java/com/baeldung/nestedclass/Outer.java
new file mode 100644
index 0000000000..d5e46670c9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/nestedclass/Outer.java
@@ -0,0 +1,20 @@
+package com.baeldung.nestedclass;
+
+import org.junit.Test;
+
+public class Outer {
+
+ public class Inner {
+
+ public void run() {
+ System.out.println("Calling test...");
+ }
+ }
+
+ @Test
+ public void test() {
+ Outer outer = new Outer();
+ Outer.Inner inner = outer.new Inner();
+ inner.run();
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt
new file mode 100644
index 0000000000..09ce898860
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt
@@ -0,0 +1,51 @@
+package com.baeldung.kotlin
+
+import org.junit.Assert
+import org.junit.Test
+
+class ExtensionMethods {
+ @Test
+ fun simpleExtensionMethod() {
+ fun String.escapeForXml() : String {
+ return this
+ .replace("&", "&")
+ .replace("<", "<")
+ .replace(">", ">")
+ }
+
+ Assert.assertEquals("Nothing", "Nothing".escapeForXml())
+ Assert.assertEquals("<Tag>", "".escapeForXml())
+ Assert.assertEquals("a&b", "a&b".escapeForXml())
+ }
+
+ @Test
+ fun genericExtensionMethod() {
+ fun T.concatAsString(b: T) : String {
+ return this.toString() + b.toString()
+ }
+
+ Assert.assertEquals("12", "1".concatAsString("2"))
+ Assert.assertEquals("12", 1.concatAsString(2))
+ // This doesn't compile
+ // Assert.assertEquals("12", 1.concatAsString(2.0))
+ }
+
+ @Test
+ fun infixExtensionMethod() {
+ infix fun Number.toPowerOf(exponent: Number): Double {
+ return Math.pow(this.toDouble(), exponent.toDouble())
+ }
+
+ Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
+ Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
+ }
+
+ @Test
+ fun operatorExtensionMethod() {
+ operator fun List.times(by: Int): List {
+ return this.map { it * by }
+ }
+
+ Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
+ }
+}
diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml
index a9aba47f12..f8dbf5657e 100644
--- a/guava-modules/guava-18/pom.xml
+++ b/guava-modules/guava-18/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml
index 2345212eba..4a23bf7aec 100644
--- a/guava-modules/guava-19/pom.xml
+++ b/guava-modules/guava-19/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml
index 94bb66e76a..f5432fb7df 100644
--- a/guava-modules/guava-21/pom.xml
+++ b/guava-modules/guava-21/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml
index 8543d1dae3..3b0b2fcd88 100644
--- a/hibernate5/pom.xml
+++ b/hibernate5/pom.xml
@@ -17,12 +17,15 @@
UTF-8
3.6.0
-
+ 5.2.12.Final
+ 6.0.6
+ 2.2.3
+
org.hibernate
hibernate-core
- 5.2.12.Final
+ ${hibernate.version}
junit
@@ -40,6 +43,21 @@
h2
1.4.194
+
+ org.hibernate
+ hibernate-spatial
+ ${hibernate.version}
+
+
+ mysql
+ mysql-connector-java
+ ${mysql.version}
+
+
+ ch.vorburger.mariaDB4j
+ mariaDB4j
+ ${mariaDB4j.version}
+
hibernate5
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
index c3bf8c2aa9..f1fc22d29a 100644
--- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -5,6 +5,7 @@ import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
+import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
@@ -23,6 +24,7 @@ import com.baeldung.hibernate.pojo.inheritance.Person;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
+import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
@@ -36,8 +38,14 @@ import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
+ private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
+ return getSessionFactory(null);
+ }
+
+ public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
+ PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
@@ -70,6 +78,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
+ metadataSources.addAnnotatedClass(PointEntity.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
@@ -86,12 +95,11 @@ public class HibernateUtil {
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
- .getContextClassLoader()
- .getResource("hibernate.properties");
+ .getContextClassLoader()
+ .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
-
}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java
new file mode 100644
index 0000000000..223f5dcbde
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java
@@ -0,0 +1,41 @@
+package com.baeldung.hibernate.pojo;
+
+import com.vividsolutions.jts.geom.Point;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+@Entity
+public class PointEntity {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ private Point point;
+
+ public PointEntity() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Point getPoint() {
+ return point;
+ }
+
+ public void setPoint(Point point) {
+ this.point = point;
+ }
+
+ @Override
+ public String toString() {
+ return "PointEntity{" + "id=" + id + ", point=" + point + '}';
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java
new file mode 100644
index 0000000000..a5c7b329fc
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java
@@ -0,0 +1,97 @@
+package com.baeldung.hibernate;
+
+import com.baeldung.hibernate.pojo.PointEntity;
+import com.vividsolutions.jts.geom.Geometry;
+import com.vividsolutions.jts.geom.Point;
+import com.vividsolutions.jts.io.ParseException;
+import com.vividsolutions.jts.io.WKTReader;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.Query;
+import java.io.IOException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import static org.junit.Assert.assertTrue;
+
+public class HibernateSpatialTest {
+
+ private Session session;
+ private Transaction transaction;
+
+ @Before
+ public void setUp() throws IOException {
+ session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
+ .openSession();
+ transaction = session.beginTransaction();
+ }
+
+ @After
+ public void tearDown() {
+ transaction.rollback();
+ session.close();
+ }
+
+ @Test
+ public void shouldConvertWktToGeometry() throws ParseException {
+ Geometry geometry = wktToGeometry("POINT (2 5)");
+ assertEquals("Point", geometry.getGeometryType());
+ assertTrue(geometry instanceof Point);
+ }
+
+ @Test
+ public void shouldInsertAndSelectPoints() throws ParseException {
+ PointEntity entity = new PointEntity();
+ entity.setPoint((Point) wktToGeometry("POINT (1 1)"));
+
+ session.persist(entity);
+ PointEntity fromDb = session.find(PointEntity.class, entity.getId());
+ assertEquals("POINT (1 1)", fromDb.getPoint().toString());
+ }
+
+ @Test
+ public void shouldSelectDisjointPoints() throws ParseException {
+ insertPoint("POINT (1 2)");
+ insertPoint("POINT (3 4)");
+ insertPoint("POINT (5 6)");
+
+ Point point = (Point) wktToGeometry("POINT (3 4)");
+ Query query = session.createQuery("select p from PointEntity p "
+ + "where disjoint(p.point, :point) = true", PointEntity.class);
+ query.setParameter("point", point);
+ assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
+ assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
+ }
+
+ @Test
+ public void shouldSelectAllPointsWithinPolygon() throws ParseException {
+ insertPoint("POINT (1 1)");
+ insertPoint("POINT (1 2)");
+ insertPoint("POINT (3 4)");
+ insertPoint("POINT (5 6)");
+
+ Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true",
+ PointEntity.class);
+ query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))"));
+ assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
+ .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)");
+ }
+
+ private void insertPoint(String point) throws ParseException {
+ PointEntity entity = new PointEntity();
+ entity.setPoint((Point) wktToGeometry(point));
+ session.persist(entity);
+ }
+
+ private Geometry wktToGeometry(String wellKnownText) throws ParseException {
+ WKTReader fromText = new WKTReader();
+ Geometry geom = null;
+ geom = fromText.read(wellKnownText);
+ return geom;
+ }
+}
diff --git a/hibernate5/src/test/resources/hibernate-spatial.properties b/hibernate5/src/test/resources/hibernate-spatial.properties
new file mode 100644
index 0000000000..e85cd49cc3
--- /dev/null
+++ b/hibernate5/src/test/resources/hibernate-spatial.properties
@@ -0,0 +1,10 @@
+hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
+hibernate.connection.driver_class=com.mysql.jdbc.Driver
+hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
+hibernate.connection.username=root
+hibernate.connection.password=pass
+hibernate.connection.pool_size=5
+hibernate.show_sql=true
+hibernate.format_sql=true
+hibernate.max_fetch_depth=5
+hibernate.hbm2ddl.auto=create-drop
\ No newline at end of file
diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx
new file mode 100644
index 0000000000..09e71a4d4e
Binary files /dev/null and b/libraries/helloWorld.docx differ
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 546fe8a6d8..27d867b68b 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -711,4 +711,4 @@
3.8.4
2.5.5
-
+
\ No newline at end of file
diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml
index 918e052a15..5551585372 100644
--- a/logging-modules/log-mdc/pom.xml
+++ b/logging-modules/log-mdc/pom.xml
@@ -12,7 +12,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/logging-modules/log4j/pom.xml b/logging-modules/log4j/pom.xml
index a3bfb0a33a..6a3fbde393 100644
--- a/logging-modules/log4j/pom.xml
+++ b/logging-modules/log4j/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml
index 58bc4b74e7..48608fbc80 100644
--- a/logging-modules/log4j2/pom.xml
+++ b/logging-modules/log4j2/pom.xml
@@ -9,7 +9,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/logging-modules/logback/README.md b/logging-modules/logback/README.md
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml
new file mode 100644
index 0000000000..8169134442
--- /dev/null
+++ b/logging-modules/logback/pom.xml
@@ -0,0 +1,35 @@
+
+
+
+ 4.0.0
+
+ logback
+ logback
+ 0.1-SNAPSHOT
+
+
+ UTF-8
+ 1.2.3
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
+
+
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+
+
+
diff --git a/logging-modules/logback/src/main/java/com/baeldung/logback/Example.java b/logging-modules/logback/src/main/java/com/baeldung/logback/Example.java
new file mode 100644
index 0000000000..e3d09dc321
--- /dev/null
+++ b/logging-modules/logback/src/main/java/com/baeldung/logback/Example.java
@@ -0,0 +1,14 @@
+package com.baeldung.logback;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Example {
+
+ private static final Logger logger = LoggerFactory.getLogger(Example.class);
+
+ public static void main(String[] args) {
+ logger.info("Example log from {}", Example.class.getSimpleName());
+ }
+
+}
diff --git a/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java b/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java
new file mode 100644
index 0000000000..99cc6488e5
--- /dev/null
+++ b/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java
@@ -0,0 +1,37 @@
+package com.baeldung.logback;
+
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.AppenderBase;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class MapAppender extends AppenderBase {
+
+ private final Map eventMap = new HashMap<>();
+
+ private String prefix;
+
+ @Override
+ protected void append(final ILoggingEvent event) {
+ if (prefix == null || "".equals(prefix)) {
+ addError("Prefix is not set for MapAppender.");
+ return;
+ }
+
+ eventMap.put(prefix + System.currentTimeMillis(), event);
+ }
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public void setPrefix(final String prefix) {
+ this.prefix = prefix;
+ }
+
+ public Map getEventMap() {
+ return eventMap;
+ }
+
+}
diff --git a/logging-modules/logback/src/main/resources/logback.xml b/logging-modules/logback/src/main/resources/logback.xml
new file mode 100644
index 0000000000..37ae2adbb0
--- /dev/null
+++ b/logging-modules/logback/src/main/resources/logback.xml
@@ -0,0 +1,18 @@
+
+
+
+ test
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java
new file mode 100644
index 0000000000..20366a229d
--- /dev/null
+++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.logback;
+
+import ch.qos.logback.classic.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertEquals;
+
+public class MapAppenderIntegrationTest {
+
+ private Logger rootLogger;
+
+ @Before
+ public void setUp() throws Exception {
+ rootLogger = (Logger) LoggerFactory.getLogger("ROOT");
+ }
+
+ @Test
+ public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception {
+ rootLogger.info("Test from {}", this.getClass().getSimpleName());
+ MapAppender appender = (MapAppender) rootLogger.getAppender("map");
+ assertEquals(appender.getEventMap().size(), 1);
+ }
+
+ @Test
+ public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() throws Exception {
+ rootLogger.info("Test from {}", this.getClass().getSimpleName());
+ MapAppender appender = (MapAppender) rootLogger.getAppender("badMap");
+ assertEquals(appender.getEventMap().size(), 0);
+ }
+
+}
diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java
new file mode 100644
index 0000000000..a5a938a923
--- /dev/null
+++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.logback;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.BasicStatusManager;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class MapAppenderTest {
+
+ private LoggerContext ctx;
+
+ private MapAppender mapAppender = new MapAppender();
+
+ private LoggingEvent event;
+
+ @Before
+ public void setUp() throws Exception {
+ ctx = new LoggerContext();
+ ctx.setName("test context");
+ ctx.setStatusManager(new BasicStatusManager());
+ mapAppender.setContext(ctx);
+ mapAppender.setPrefix("prefix");
+ event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]);
+ ctx.start();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ ctx.stop();
+ mapAppender.stop();
+ }
+
+ @Test
+ public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception {
+ mapAppender.setPrefix(null);
+ mapAppender.append(event);
+ assertTrue(mapAppender.getEventMap().isEmpty());
+ }
+
+ @Test
+ public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception {
+ mapAppender.setPrefix("");
+ mapAppender.append(event);
+ assertTrue(mapAppender.getEventMap().isEmpty());
+ }
+
+ @Test
+ public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception {
+ mapAppender.append(event);
+ assertEquals(mapAppender.getEventMap().size(), 1);
+ mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix")));
+ }
+
+}
diff --git a/logging-modules/logback/src/test/resources/logback-test.xml b/logging-modules/logback/src/test/resources/logback-test.xml
new file mode 100644
index 0000000000..8254e6ac80
--- /dev/null
+++ b/logging-modules/logback/src/test/resources/logback-test.xml
@@ -0,0 +1,14 @@
+
+
+
+ test
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml
index faaabb9e2e..81e072c3a7 100644
--- a/persistence-modules/java-cassandra/pom.xml
+++ b/persistence-modules/java-cassandra/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml
index aab48921a6..9784b2c5a8 100644
--- a/persistence-modules/java-mongodb/pom.xml
+++ b/persistence-modules/java-mongodb/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml
index 020c2516a2..a574ba497c 100644
--- a/persistence-modules/liquibase/pom.xml
+++ b/persistence-modules/liquibase/pom.xml
@@ -6,7 +6,7 @@
parent-modules
com.baeldung
1.0.0-SNAPSHOT
- ../
+ ../../
4.0.0
diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml
index 27f383e0c6..c2943875f1 100644
--- a/persistence-modules/querydsl/pom.xml
+++ b/persistence-modules/querydsl/pom.xml
@@ -15,7 +15,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml
index ef081a2c69..4321b491eb 100644
--- a/persistence-modules/redis/pom.xml
+++ b/persistence-modules/redis/pom.xml
@@ -15,7 +15,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/solr/pom.xml b/persistence-modules/solr/pom.xml
index 2fd0bdd721..966bd8755b 100644
--- a/persistence-modules/solr/pom.xml
+++ b/persistence-modules/solr/pom.xml
@@ -12,7 +12,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml
index 607d7b90ba..1358210a45 100644
--- a/persistence-modules/spring-data-cassandra/pom.xml
+++ b/persistence-modules/spring-data-cassandra/pom.xml
@@ -13,7 +13,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml
index 9108865b4c..3f7fcd03e5 100644
--- a/persistence-modules/spring-data-gemfire/pom.xml
+++ b/persistence-modules/spring-data-gemfire/pom.xml
@@ -12,7 +12,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml
index 0055850ec3..bdd51e9659 100644
--- a/persistence-modules/spring-data-neo4j/pom.xml
+++ b/persistence-modules/spring-data-neo4j/pom.xml
@@ -10,7 +10,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml
index b184d7e369..6cb49f11cf 100644
--- a/persistence-modules/spring-data-redis/pom.xml
+++ b/persistence-modules/spring-data-redis/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml
index 0759c1dbc0..e24d8314ba 100644
--- a/persistence-modules/spring-data-solr/pom.xml
+++ b/persistence-modules/spring-data-solr/pom.xml
@@ -12,7 +12,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml
index 8eee819572..f1873a84d3 100644
--- a/persistence-modules/spring-hibernate-3/pom.xml
+++ b/persistence-modules/spring-hibernate-3/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml
index f1f3d10347..23cf9a4d44 100644
--- a/persistence-modules/spring-hibernate-5/pom.xml
+++ b/persistence-modules/spring-hibernate-5/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
+ ../../
@@ -57,6 +57,11 @@
jta
${jta.version}
+
+ org.hibernate
+ hibernate-search-orm
+ ${hibernatesearch.version}
+
org.apache.tomcat
@@ -184,6 +189,7 @@
5.2.10.Final
+ 5.8.2.Final
8.0.7-dmr
9.0.0.M26
1.1
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java
new file mode 100644
index 0000000000..6bbd2625fc
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java
@@ -0,0 +1,76 @@
+package com.baeldung.hibernatesearch;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.JpaVendorAdapter;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.persistence.EntityManagerFactory;
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@EnableTransactionManagement
+@Configuration
+@PropertySource({ "classpath:persistence-h2.properties" })
+@EnableJpaRepositories(basePackages = { "com.baeldung.hibernatesearch" })
+@ComponentScan({ "com.baeldung.hibernatesearch" })
+public class HibernateSearchConfig {
+
+ @Autowired
+ private Environment env;
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
+ em.setDataSource(dataSource());
+ em.setPackagesToScan(new String[] { "com.baeldung.hibernatesearch.model" });
+
+ JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ em.setJpaVendorAdapter(vendorAdapter);
+ em.setJpaProperties(additionalProperties());
+
+ return em;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
+ JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(emf);
+
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ Properties additionalProperties() {
+ Properties properties = new Properties();
+ properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto")));
+ properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect")));
+ return properties;
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/ProductSearchDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/ProductSearchDao.java
new file mode 100644
index 0000000000..210c1c58b3
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/ProductSearchDao.java
@@ -0,0 +1,195 @@
+package com.baeldung.hibernatesearch;
+
+import com.baeldung.hibernatesearch.model.Product;
+import org.apache.lucene.search.Query;
+import org.hibernate.search.engine.ProjectionConstants;
+import org.hibernate.search.jpa.FullTextEntityManager;
+import org.hibernate.search.jpa.FullTextQuery;
+import org.hibernate.search.jpa.Search;
+import org.hibernate.search.query.dsl.QueryBuilder;
+import org.springframework.stereotype.Repository;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import java.util.List;
+
+@Repository
+public class ProductSearchDao {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ public List searchProductNameByKeywordQuery(String text) {
+
+ Query keywordQuery = getQueryBuilder()
+ .keyword()
+ .onField("productName")
+ .matching(text)
+ .createQuery();
+
+ List results = getJpaQuery(keywordQuery).getResultList();
+
+ return results;
+ }
+
+ public List searchProductNameByFuzzyQuery(String text) {
+
+ Query fuzzyQuery = getQueryBuilder()
+ .keyword()
+ .fuzzy()
+ .withEditDistanceUpTo(2)
+ .withPrefixLength(0)
+ .onField("productName")
+ .matching(text)
+ .createQuery();
+
+ List results = getJpaQuery(fuzzyQuery).getResultList();
+
+ return results;
+ }
+
+ public List searchProductNameByWildcardQuery(String text) {
+
+ Query wildcardQuery = getQueryBuilder()
+ .keyword()
+ .wildcard()
+ .onField("productName")
+ .matching(text)
+ .createQuery();
+
+ List results = getJpaQuery(wildcardQuery).getResultList();
+
+ return results;
+ }
+
+ public List searchProductDescriptionByPhraseQuery(String text) {
+
+ Query phraseQuery = getQueryBuilder()
+ .phrase()
+ .withSlop(1)
+ .onField("description")
+ .sentence(text)
+ .createQuery();
+
+ List results = getJpaQuery(phraseQuery).getResultList();
+
+ return results;
+ }
+
+ public List searchProductNameAndDescriptionBySimpleQueryStringQuery(String text) {
+
+ Query simpleQueryStringQuery = getQueryBuilder()
+ .simpleQueryString()
+ .onFields("productName", "description")
+ .matching(text)
+ .createQuery();
+
+ List results = getJpaQuery(simpleQueryStringQuery).getResultList();
+
+ return results;
+ }
+
+ public List searchProductNameByRangeQuery(int low, int high) {
+
+ Query rangeQuery = getQueryBuilder()
+ .range()
+ .onField("memory")
+ .from(low)
+ .to(high)
+ .createQuery();
+
+ List results = getJpaQuery(rangeQuery).getResultList();
+
+ return results;
+ }
+
+ public List