) map.get("key1"))
+ .containsExactly("value1", "value2", "value3");
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/map/MapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapUnitTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/java/map/MapUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java/map/MapUnitTest.java
diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java
diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java
diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/weakhashmap/WeakHashMapUnitTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/weakhashmap/WeakHashMapUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/collections/README.md b/core-java-collections/src/test/java/org/baeldung/java/collections/README.md
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/collections/README.md
rename to core-java-collections/src/test/java/org/baeldung/java/collections/README.md
diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListJUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/lists/ListJUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/lists/ListJUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/lists/ListJUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java b/core-java-collections/src/test/java/org/baeldung/java/lists/ListToSTring.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java
rename to core-java-collections/src/test/java/org/baeldung/java/lists/ListToSTring.java
diff --git a/core-java/src/test/java/org/baeldung/java/lists/README.md b/core-java-collections/src/test/java/org/baeldung/java/lists/README.md
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/lists/README.md
rename to core-java-collections/src/test/java/org/baeldung/java/lists/README.md
diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml
index bf858047e9..7e162abc64 100644
--- a/core-java-concurrency/pom.xml
+++ b/core-java-concurrency/pom.xml
@@ -5,67 +5,50 @@
core-java-concurrency
0.1.0-SNAPSHOT
jar
-
core-java-concurrency
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
-
-
-
- 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.assertj
assertj-core
${assertj.version}
test
-
com.jayway.awaitility
awaitility
${avaitility.version}
test
-
-
+
core-java-concurrency
@@ -92,7 +75,6 @@
-
org.apache.maven.plugins
maven-jar-plugin
@@ -141,7 +123,7 @@
true
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
org.baeldung.executable.ExecutableMavenJar
@@ -181,46 +163,9 @@
-
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
-
-
-
-
-
-
- json
-
-
-
-
-
-
-
-
-
21.0
3.5
@@ -228,10 +173,9 @@
2.5
4.1
4.01
-
3.6.1
1.7.0
-
+
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
similarity index 93%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java
rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
index e9b2e164ae..4eead471f8 100644
--- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
@@ -9,7 +9,7 @@ import java.util.stream.IntStream;
import org.junit.Test;
-public class ThreadSafeCounterTest {
+public class ThreadSafeCounterIntegrationTest {
@Test
public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException {
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java
similarity index 95%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java
rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java
index 3ca69d8847..2d8b91d846 100644
--- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java
@@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
-public class DaemonThreadTest {
+public class DaemonThreadUnitTest {
@Test
@Ignore
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java
similarity index 96%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java
rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java
index 9c56fa64be..553b8c9906 100644
--- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java
@@ -9,7 +9,7 @@ import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
-public class BaeldungSychronizedBlockTest {
+public class BaeldungSychronizedBlockUnitTest {
@Test
public void givenMultiThread_whenBlockSync() throws InterruptedException {
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java
similarity index 97%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java
rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java
index ba7c1f0a7b..32648729d5 100644
--- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java
@@ -10,7 +10,7 @@ import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
-public class BaeldungSynchronizeMethodsTest {
+public class BaeldungSynchronizeMethodsUnitTest {
@Test
@Ignore
diff --git a/core-java-io/README.md b/core-java-io/README.md
index 52485acfd5..011282af12 100644
--- a/core-java-io/README.md
+++ b/core-java-io/README.md
@@ -22,4 +22,9 @@
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
-- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
\ No newline at end of file
+- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
+- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
+- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
+- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
+- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
+- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml
index 03fd5799c9..a98b489d9d 100644
--- a/core-java-io/pom.xml
+++ b/core-java-io/pom.xml
@@ -1,92 +1,78 @@
-
+
4.0.0
com.baeldung
core-java-io
0.1.0-SNAPSHOT
jar
-
core-java-io
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-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
+ ${log4j.version}
org.slf4j
@@ -116,23 +102,19 @@
${lombok.version}
provided
-
-
org.hamcrest
hamcrest-all
- 1.3
+ ${hamcrest-all.version}
test
-
junit
junit
${junit.version}
test
-
org.hamcrest
hamcrest-core
@@ -145,14 +127,12 @@
${org.hamcrest.version}
test
-
org.assertj
assertj-core
${assertj.version}
test
-
org.mockito
mockito-core
@@ -165,25 +145,21 @@
${avaitility.version}
test
-
commons-codec
commons-codec
${commons-codec.version}
-
org.javamoney
moneta
- 1.1
+ ${moneta.version}
-
org.owasp.esapi
esapi
- 2.1.0.1
+ ${esapi.version}
-
com.sun.messaging.mq
fscontext
@@ -207,19 +183,25 @@
org.openjdk.jmh
jmh-core
- 1.19
+ ${jmh-core.version}
org.openjdk.jmh
jmh-generator-annprocess
- 1.19
+ ${jmh-generator-annprocess.version}
org.hsqldb
hsqldb
- 2.4.0
+ ${hsqldb.version}
runtime
+
+
+ org.asynchttpclient
+ async-http-client
+ ${async-http-client.version}
+
@@ -230,15 +212,15 @@
true
-
-
+
org.apache.maven.plugins
maven-surefire-plugin
**/*LiveTest.java
**/*IntegrationTest.java
+ **/*IntTest.java
**/*LongRunningUnitTest.java
**/*ManualTest.java
@@ -260,11 +242,10 @@
-
org.codehaus.mojo
exec-maven-plugin
- 1.6.0
+ ${exec-maven-plugin.version}
java
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
@@ -272,25 +253,21 @@
-Xmx300m
-XX:+UseParallelGC
-classpath
-
+
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
org.apache.maven.plugins
maven-javadoc-plugin
- 3.0.0-M1
+ ${maven-javadoc-plugin.version}
- 1.8
- 1.8
+ ${maven.compiler.source}
+ ${maven.compiler.target}
-
-
-
@@ -313,6 +290,7 @@
**/*IntegrationTest.java
+ **/*IntTest.java
@@ -340,7 +318,7 @@
java
-classpath
-
+
org.openjdk.jmh.Main
.*
@@ -389,5 +367,13 @@
3.7.0
2.19.1
+ 1.8
+ 1.8
+ 3.0.0-M1
+ 2.4.0
+ 2.1.0.1
+ 1.19
+ 2.4.5
+
\ No newline at end of file
diff --git a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java
new file mode 100644
index 0000000000..c7dd154023
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java
@@ -0,0 +1,89 @@
+package com.baeldung.download;
+
+import org.apache.commons.io.FileUtils;
+import org.asynchttpclient.*;
+
+import java.io.*;
+import java.net.*;
+import java.nio.channels.Channels;
+import java.nio.channels.FileChannel;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.concurrent.ExecutionException;
+
+public class FileDownload {
+
+ public static void downloadWithJavaIO(String url, String localFilename) {
+
+ try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) {
+
+ byte dataBuffer[] = new byte[1024];
+ int bytesRead;
+ while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
+ fileOutputStream.write(dataBuffer, 0, bytesRead);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void downloadWithJava7IO(String url, String localFilename) {
+
+ try (InputStream in = new URL(url).openStream()) {
+ Files.copy(in, Paths.get(localFilename), StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void downloadWithJavaNIO(String fileURL, String localFilename) throws IOException {
+
+ URL url = new URL(fileURL);
+ try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
+ FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) {
+
+ fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
+ }
+ }
+
+ public static void downloadWithApacheCommons(String url, String localFilename) {
+
+ int CONNECT_TIMEOUT = 10000;
+ int READ_TIMEOUT = 10000;
+ try {
+ FileUtils.copyURLToFile(new URL(url), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException {
+
+ FileOutputStream stream = new FileOutputStream(localFilename);
+ AsyncHttpClient client = Dsl.asyncHttpClient();
+
+ client.prepareGet(url)
+ .execute(new AsyncCompletionHandler() {
+
+ @Override
+ public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
+ stream.getChannel()
+ .write(bodyPart.getBodyByteBuffer());
+ return State.CONTINUE;
+ }
+
+ @Override
+ public FileOutputStream onCompleted(Response response) throws Exception {
+ return stream;
+ }
+ })
+ .get();
+
+ stream.getChannel().close();
+ client.close();
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java
new file mode 100644
index 0000000000..55ff485e40
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java
@@ -0,0 +1,62 @@
+package com.baeldung.download;
+
+import java.io.*;
+import java.net.*;
+
+public class ResumableDownload {
+
+ public static long downloadFile(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
+
+ File outputFile = new File(saveAsFileName);
+ URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
+ .openConnection();
+ return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
+ }
+
+ private static long transferDataAndGetBytesDownloaded(URLConnection downloadFileConnection, File outputFile) throws IOException {
+
+ long bytesDownloaded = 0;
+ try (InputStream is = downloadFileConnection.getInputStream(); OutputStream os = new FileOutputStream(outputFile, true)) {
+
+ byte[] buffer = new byte[1024];
+
+ int bytesCount;
+ while ((bytesCount = is.read(buffer)) > 0) {
+ os.write(buffer, 0, bytesCount);
+ bytesDownloaded += bytesCount;
+ }
+ }
+ return bytesDownloaded;
+ }
+
+ public static long downloadFileWithResume(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
+ File outputFile = new File(saveAsFileName);
+
+ URLConnection downloadFileConnection = addFileResumeFunctionality(downloadUrl, outputFile);
+ return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
+ }
+
+ private static URLConnection addFileResumeFunctionality(String downloadUrl, File outputFile) throws IOException, URISyntaxException, ProtocolException, ProtocolException {
+ long existingFileSize = 0L;
+ URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
+ .openConnection();
+
+ if (outputFile.exists() && downloadFileConnection instanceof HttpURLConnection) {
+ HttpURLConnection httpFileConnection = (HttpURLConnection) downloadFileConnection;
+
+ HttpURLConnection tmpFileConn = (HttpURLConnection) new URI(downloadUrl).toURL()
+ .openConnection();
+ tmpFileConn.setRequestMethod("HEAD");
+ long fileLength = tmpFileConn.getContentLengthLong();
+ existingFileSize = outputFile.length();
+
+ if (existingFileSize < fileLength) {
+ httpFileConnection.setRequestProperty("Range", "bytes=" + existingFileSize + "-" + fileLength);
+ } else {
+ throw new IOException("File Download already completed.");
+ }
+ }
+ return downloadFileConnection;
+ }
+
+}
diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java
similarity index 96%
rename from core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java
rename to core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java
index 6d96d2fc0b..4603644bf5 100644
--- a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java
+++ b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java
@@ -18,7 +18,7 @@ import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
-public class FileCopierTest {
+public class FileCopierIntegrationTest {
File original = new File("src/test/resources/original.txt");
@Before
diff --git a/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java
new file mode 100644
index 0000000000..81ac391958
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java
@@ -0,0 +1,91 @@
+package com.baeldung.download;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.concurrent.ExecutionException;
+
+import javax.xml.bind.DatatypeConverter;
+
+import org.junit.After;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class FileDownloadIntegrationTest {
+
+ static String FILE_URL = "http://ovh.net/files/1Mio.dat";
+ static String FILE_NAME = "file.dat";
+ static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116";
+
+ @Test
+ public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
+
+ FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ @Test
+ public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
+
+ FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ @Test
+ public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
+
+ FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ @Test
+ public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException {
+
+ FileDownload.downloadWithAHC(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ @Test
+ public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
+
+ FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ @Test
+ public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException {
+
+ ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME);
+ assertTrue(checkMd5Hash(FILE_NAME));
+ }
+
+ private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException {
+
+ MessageDigest md = MessageDigest.getInstance("MD5");
+ md.update(Files.readAllBytes(Paths.get(filename)));
+ byte[] digest = md.digest();
+ String myChecksum = DatatypeConverter.printHexBinary(digest);
+
+ return myChecksum.equalsIgnoreCase(FILE_MD5_HASH);
+ }
+
+ @BeforeClass
+ public static void setup() throws IOException {
+ if (Files.exists(Paths.get(FILE_NAME))) {
+ Files.delete(Paths.get(FILE_NAME));
+ }
+ }
+
+ @After
+ public void cleanup() throws IOException {
+ if (Files.exists(Paths.get(FILE_NAME))) {
+ Files.delete(Paths.get(FILE_NAME));
+ }
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java
similarity index 98%
rename from core-java-io/src/test/java/com/baeldung/file/FilesTest.java
rename to core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java
index a35cda8b23..f5c5c3dd3a 100644
--- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java
+++ b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java
@@ -24,7 +24,7 @@ import org.junit.Test;
import com.baeldung.util.StreamUtils;
-public class FilesTest {
+public class FilesManualTest {
public static final String fileName = "src/main/resources/countries.properties";
@@ -77,6 +77,6 @@ public class FilesTest {
bw.newLine();
bw.close();
- assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
}
\ No newline at end of file
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
index b56841117e..a96232d66c 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
@@ -1,6 +1,7 @@
package org.baeldung.java.io;
import org.junit.Test;
+import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -105,8 +106,9 @@ public class JavaReadFromFileUnitTest {
}
@Test
+ @Ignore // TODO
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
- final String expected_value = "�空";
+ final String expected_value = "青空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine();
reader.close();
diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml
index 04c2454872..8662884095 100644
--- a/core-java-sun/pom.xml
+++ b/core-java-sun/pom.xml
@@ -4,89 +4,74 @@
core-java-sun
0.1.0-SNAPSHOT
jar
-
core-java-sun
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-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
+ ${log4j.version}
org.slf4j
@@ -116,23 +101,19 @@
${lombok.version}
provided
-
-
org.hamcrest
hamcrest-all
- 1.3
+ ${hamcrest-all.version}
test
-
junit
junit
${junit.version}
test
-
org.hamcrest
hamcrest-core
@@ -145,14 +126,12 @@
${org.hamcrest.version}
test
-
org.assertj
assertj-core
${assertj.version}
test
-
org.mockito
mockito-core
@@ -165,25 +144,21 @@
${avaitility.version}
test
-
commons-codec
commons-codec
${commons-codec.version}
-
org.javamoney
moneta
- 1.1
+ ${moneta.version}
-
org.owasp.esapi
esapi
- 2.1.0.1
+ ${esapi.version}
-
com.sun.messaging.mq
fscontext
@@ -207,22 +182,22 @@
org.openjdk.jmh
jmh-core
- 1.19
+ ${jmh-core.version}
org.openjdk.jmh
jmh-generator-annprocess
- 1.19
+ ${jmh-generator.version}
org.springframework
spring-web
- 4.3.4.RELEASE
+ ${spring-web.version}
com.sun
tools
- 1.8.0
+ ${sun-tools.version}
system
${java.home}/../lib/tools.jar
@@ -236,7 +211,6 @@
true
-
org.apache.maven.plugins
@@ -254,7 +228,6 @@
-
org.apache.maven.plugins
maven-jar-plugin
@@ -268,7 +241,6 @@
-
org.apache.maven.plugins
maven-assembly-plugin
@@ -292,7 +264,6 @@
-
org.apache.maven.plugins
maven-shade-plugin
@@ -312,7 +283,6 @@
-
com.jolira
onejar-maven-plugin
@@ -329,7 +299,6 @@
-
org.springframework.boot
spring-boot-maven-plugin
@@ -345,11 +314,10 @@
-
org.codehaus.mojo
exec-maven-plugin
- 1.6.0
+ ${exec-maven-plugin.version}
java
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
@@ -357,15 +325,12 @@
-Xmx300m
-XX:+UseParallelGC
-classpath
-
+
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
-
-
@@ -388,6 +353,7 @@
**/*IntegrationTest.java
+ **/*IntTest.java
@@ -415,7 +381,7 @@
java
-classpath
-
+
org.openjdk.jmh.Main
.*
@@ -456,7 +422,6 @@
1.3
- 4.12
2.8.9
3.6.1
1.7.0
@@ -464,5 +429,8 @@
3.7.0
2.19.1
+ 1.8.0
+ 4.3.4.RELEASE
+
\ No newline at end of file
diff --git a/core-java/README.md b/core-java/README.md
index b9d87be785..8800e2b862 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -3,21 +3,14 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
-- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
-- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
-- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
-- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
-- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Java – Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double)
- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
-- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
-- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
@@ -29,7 +22,6 @@
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Grep in Java](http://www.baeldung.com/grep-in-java)
-- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
@@ -38,28 +30,19 @@
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
-- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
-- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
-- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
-- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
-- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
-- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
-- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
-- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
-- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
@@ -71,7 +54,6 @@
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
- [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
-- [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
@@ -87,28 +69,22 @@
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
-- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
-- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
-- [Singletons in Java](http://www.baeldung.com/java-singleton)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
-- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
-- [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)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
-- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
@@ -122,33 +98,66 @@
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
- [Varargs in Java](http://www.baeldung.com/java-varargs)
-- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
- [Polymorphism in Java](http://www.baeldung.com/java-polymorphism)
- [Recursion In Java](http://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
-- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
-- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
-- [How to TDD a List Implementation](http://jira.baeldung.com/browse/BAEL-1537)
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
-- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
-- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
-- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
-
+- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
+- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
+- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
+- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
+- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
+- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
+- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
+- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
+- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
+- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
+- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
+- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
+- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
+- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
+- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
+- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
+- [Sending Emails with Java](http://www.baeldung.com/java-email)
+- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
+- [Java KeyStore API](http://www.baeldung.com/java-keystore)
+- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
+- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
+- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
+- [Using Java Assertions](http://www.baeldung.com/java-assert)
+- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
+- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
+- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
+- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
+- [NaN in Java](http://www.baeldung.com/java-not-a-number)
+- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
+- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
+- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
+- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
+- [Singletons in Java](http://www.baeldung.com/java-singleton)
+- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
+- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
+- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
+- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
+- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
+- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
+- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
+- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index f7bf9ed12a..cad458596b 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -5,78 +5,53 @@
core-java
0.1.0-SNAPSHOT
jar
-
core-java
-
+
+
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-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
@@ -87,12 +62,11 @@
gson
${gson.version}
-
log4j
log4j
- 1.2.17
+ ${log4j.version}
org.slf4j
@@ -122,23 +96,19 @@
${lombok.version}
provided
-
-
org.hamcrest
hamcrest-all
- 1.3
+ ${hamcrest-all.version}
test
-
junit
junit
${junit.version}
test
-
org.hamcrest
hamcrest-core
@@ -151,45 +121,33 @@
${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
+ ${javamoney.moneta.version}
-
org.owasp.esapi
esapi
- 2.1.0.1
+ ${esapi.version}
-
com.sun.messaging.mq
fscontext
@@ -213,27 +171,37 @@
org.openjdk.jmh
jmh-core
- 1.19
+ ${jmh-core.version}
org.openjdk.jmh
jmh-generator-annprocess
- 1.19
+ ${jmh-generator-annprocess.version}
-
- org.springframework
- spring-web
- 4.3.4.RELEASE
-
-
- org.springframework.boot
- spring-boot-starter
- 1.5.8.RELEASE
-
- com.h2database
- h2
- 1.4.197
+ org.springframework
+ spring-web
+ ${springframework.spring-web.version}
+
+
+ org.springframework.boot
+ spring-boot-starter
+ ${springframework.boot.spring-boot-starter.version}
+
+
+ com.h2database
+ h2
+ ${h2database.version}
+
+
+ javax.mail
+ mail
+ ${javax.mail.version}
+
+
+ com.ibm.icu
+ icu4j
+ ${icu4j.version}
@@ -254,6 +222,7 @@
**/*LiveTest.java
**/*IntegrationTest.java
+ **/*IntTest.java
**/*LongRunningUnitTest.java
**/*ManualTest.java
@@ -281,6 +250,7 @@
org.apache.maven.plugins
maven-jar-plugin
+ ${maven-jar-plugin.version}
@@ -319,6 +289,7 @@
org.apache.maven.plugins
maven-shade-plugin
+ ${maven-shade-plugin.version}
@@ -340,6 +311,7 @@
com.jolira
onejar-maven-plugin
+ ${onejar-maven-plugin.version}
@@ -357,6 +329,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -373,7 +346,7 @@
org.codehaus.mojo
exec-maven-plugin
- 1.6.0
+ ${exec-maven-plugin.version}
java
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
@@ -386,20 +359,17 @@
-
+
org.apache.maven.plugins
maven-javadoc-plugin
- 3.0.0-M1
+ ${maven-javadoc-plugin.version}
1.8
- 1.8
+ 1.8
-
-
-
@@ -422,6 +392,7 @@
**/*IntegrationTest.java
+ **/*IntTest.java
@@ -439,7 +410,7 @@
run-benchmarks
-
+
none
exec
@@ -470,17 +441,15 @@
1.7.21
1.1.7
+ 1.2.17
- 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
@@ -488,16 +457,31 @@
1.13
0.6.5
0.9.0
-
+
1.3
- 4.12
2.8.9
3.6.1
- 1.7.0
3.7.0
2.19.1
+ 4.3.4.RELEASE
+ 1.5.8.RELEASE
+ 1.1
+ 1.3
+ 1.4.197
+ 2.1.0.1
+ 1.19
+ 1.19
+ 3.0.0-M1
+ 1.6.0
+ 1.5.0-b01
+ 3.0.2
+ 1.4.4
+ 3.1.1
+ 2.0.3.RELEASE
+ 61.1
+
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java
new file mode 100644
index 0000000000..9a64c1d4c4
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java
@@ -0,0 +1,9 @@
+package com.baeldung.accessmodifiers;
+
+public class Public {
+ public Public() {
+ SuperPublic.publicMethod(); // Available everywhere.
+ SuperPublic.protectedMethod(); // Available in the same package or subclass.
+ SuperPublic.defaultMethod(); // Available in the same package.
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java
new file mode 100644
index 0000000000..545f48c9ca
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java
@@ -0,0 +1,9 @@
+package com.baeldung.accessmodifiers;
+
+public class SubClass extends SuperPublic {
+ public SubClass() {
+ SuperPublic.publicMethod(); // Available everywhere.
+ SuperPublic.protectedMethod(); // Available in the same package or subclass.
+ SuperPublic.defaultMethod(); // Available in the same package.
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java
new file mode 100644
index 0000000000..7c9554f2c7
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java
@@ -0,0 +1,39 @@
+package com.baeldung.accessmodifiers;
+
+//Only public or default access modifiers are permitted
+public class SuperPublic {
+ // Always available from anywhere
+ static public void publicMethod() {
+ System.out.println(SuperPublic.class.getName() + " publicMethod()");
+ }
+
+ // Available within the same package
+ static void defaultMethod() {
+ System.out.println(SuperPublic.class.getName() + " defaultMethod()");
+ }
+
+ // Available within the same package and subclasses
+ static protected void protectedMethod() {
+ System.out.println(SuperPublic.class.getName() + " protectedMethod()");
+ }
+
+ // Available within the same class only
+ static private void privateMethod() {
+ System.out.println(SuperPublic.class.getName() + " privateMethod()");
+ }
+
+ // Method in the same class = has access to all members within the same class
+ private void anotherPrivateMethod() {
+ privateMethod();
+ defaultMethod();
+ protectedMethod();
+ publicMethod(); // Available in the same class only.
+ }
+}
+
+// Only public or default access modifiers are permitted
+class SuperDefault {
+ public void publicMethod() {
+ System.out.println(this.getClass().getName() + " publicMethod()");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java
new file mode 100644
index 0000000000..32eea36854
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java
@@ -0,0 +1,9 @@
+package com.baeldung.accessmodifiers.another;
+
+import com.baeldung.accessmodifiers.SuperPublic;
+
+public class AnotherPublic {
+ public AnotherPublic() {
+ SuperPublic.publicMethod(); // Available everywhere.
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java
new file mode 100644
index 0000000000..3d9dc3f119
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java
@@ -0,0 +1,10 @@
+package com.baeldung.accessmodifiers.another;
+
+import com.baeldung.accessmodifiers.SuperPublic;
+
+public class AnotherSubClass extends SuperPublic {
+ public AnotherSubClass() {
+ SuperPublic.publicMethod(); // Available everywhere.
+ SuperPublic.protectedMethod(); // Available in subclass. Let's note different package.
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java
new file mode 100644
index 0000000000..3932e6f990
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java
@@ -0,0 +1,9 @@
+package com.baeldung.accessmodifiers.another;
+
+import com.baeldung.accessmodifiers.SuperPublic;
+
+public class AnotherSuperPublic {
+ public AnotherSuperPublic() {
+ SuperPublic.publicMethod(); // Available everywhere. Let's note different package.
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java
index 977587a06a..f35064b783 100644
--- a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java
+++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java
@@ -9,7 +9,7 @@ public class ArrayBenchmarkRunner {
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
- .include(SearchArrayTest.class.getSimpleName()).threads(1)
+ .include(SearchArrayUnitTest.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
diff --git a/core-java/src/main/java/com/baeldung/array/JaggedArray.java b/core-java/src/main/java/com/baeldung/array/JaggedArray.java
new file mode 100644
index 0000000000..36cfc88b95
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/array/JaggedArray.java
@@ -0,0 +1,49 @@
+package com.baeldung.array;
+
+import java.util.Arrays;
+import java.util.Scanner;
+
+public class JaggedArray {
+
+ int[][] shortHandFormInitialization() {
+ int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
+ return jaggedArr;
+ }
+
+ int[][] declarationAndThenInitialization() {
+ int[][] jaggedArr = new int[3][];
+ jaggedArr[0] = new int[] { 1, 2 };
+ jaggedArr[1] = new int[] { 3, 4, 5 };
+ jaggedArr[2] = new int[] { 6, 7, 8, 9 };
+ return jaggedArr;
+ }
+
+ int[][] declarationAndThenInitializationUsingUserInputs() {
+ int[][] jaggedArr = new int[3][];
+ jaggedArr[0] = new int[2];
+ jaggedArr[1] = new int[3];
+ jaggedArr[2] = new int[4];
+ initializeElements(jaggedArr);
+ return jaggedArr;
+ }
+
+ void initializeElements(int[][] jaggedArr) {
+ Scanner sc = new Scanner(System.in);
+ for (int outer = 0; outer < jaggedArr.length; outer++) {
+ for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
+ jaggedArr[outer][inner] = sc.nextInt();
+ }
+ }
+ }
+
+ void printElements(int[][] jaggedArr) {
+ for (int index = 0; index < jaggedArr.length; index++) {
+ System.out.println(Arrays.toString(jaggedArr[index]));
+ }
+ }
+
+ int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
+ return jaggedArr[index];
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java
similarity index 98%
rename from core-java/src/main/java/com/baeldung/array/SearchArrayTest.java
rename to core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java
index 199ebdf036..bed58356cb 100644
--- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java
+++ b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java
@@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
-public class SearchArrayTest {
+public class SearchArrayUnitTest {
@State(Scope.Benchmark)
public static class SearchData {
diff --git a/core-java/src/main/java/com/baeldung/assertion/Assertion.java b/core-java/src/main/java/com/baeldung/assertion/Assertion.java
new file mode 100644
index 0000000000..795728757c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/assertion/Assertion.java
@@ -0,0 +1,26 @@
+package com.baeldung.assertion;
+
+/**
+ * Simple demonstration of using Java assert keyword.
+ */
+public class Assertion {
+
+ public static void main(String[] args) {
+ Assertion assertion = new Assertion();
+ assertion.setup();
+ }
+
+ public void setup() {
+ Object conn = getConnection();
+ assert conn != null : "Connection is null";
+
+ // continue with other setup ...
+ }
+
+ // Simulate failure to get a connection; using Object
+ // to avoid dependencies on JDBC or some other heavy
+ // 3rd party library
+ public Object getConnection() {
+ return null;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java b/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java
new file mode 100644
index 0000000000..a5c704345f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java
@@ -0,0 +1,26 @@
+package com.baeldung.console;
+
+import java.io.Console;
+
+public class ConsoleConsoleClass {
+
+ public static void main(String[] args) {
+ Console console = System.console();
+
+ if (console == null) {
+ System.out.print("No console available");
+ return;
+ }
+
+ String progLanguauge = console.readLine("Enter your favourite programming language: ");
+ console.printf(progLanguauge + " is very interesting!");
+
+ char[] pass = console.readPassword("To finish, enter password: ");
+
+ if ("BAELDUNG".equals(pass.toString().toUpperCase()))
+ console.printf("Good! Regards!");
+ else
+ console.printf("Nice try. Regards.");
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java b/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java
new file mode 100644
index 0000000000..7b7a7a4ade
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java
@@ -0,0 +1,76 @@
+package com.baeldung.console;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public class ConsoleScannerClass {
+
+ public static void main(String[] args) {
+ System.out.println("Please enter your name and surname: ");
+
+ Scanner scanner = new Scanner(System.in);
+
+ String nameSurname = scanner.nextLine();
+
+ System.out.println("Please enter your gender: ");
+
+ char gender = scanner.next().charAt(0);
+
+ System.out.println("Please enter your age: ");
+
+ int age = scanner.nextInt();
+
+ System.out.println("Please enter your height in meters: ");
+
+ double height = scanner.nextDouble();
+
+ System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung.");
+
+ System.out.print("Have a good");
+ System.out.print(" one!");
+
+ System.out.println("\nPlease enter number of years of experience as a developer: ");
+
+ BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
+
+ int i = 0;
+
+ try {
+ i = Integer.parseInt(buffReader.readLine());
+ } catch (NumberFormatException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
+
+ int sum = 0, count = 0;
+
+ System.out.println("Please enter your college degrees. To finish, enter baeldung website url");
+
+ while (scanner.hasNextInt()) {
+ int nmbr = scanner.nextInt();
+ sum += nmbr;
+ count++;
+ }
+ int mean = sum / count;
+
+ System.out.println("Your average degree is " + mean);
+
+ if (scanner.hasNext(Pattern.compile("www.baeldung.com")))
+ System.out.println("Correct!");
+ else
+ System.out.println("Baeldung website url is www.baeldung.com");
+
+ if (scanner != null)
+ scanner.close();
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/customexception/FileManager.java b/core-java/src/main/java/com/baeldung/customexception/FileManager.java
new file mode 100644
index 0000000000..b6f4d960aa
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/customexception/FileManager.java
@@ -0,0 +1,43 @@
+package com.baeldung.customexception;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.Scanner;
+
+public class FileManager {
+
+ public static String getFirstLine(String fileName) throws IncorrectFileNameException {
+ try (Scanner file = new Scanner(new File(fileName))) {
+ if (file.hasNextLine()) {
+ return file.nextLine();
+ } else {
+ throw new IllegalArgumentException("Non readable file");
+ }
+ } catch (FileNotFoundException err) {
+ if (!isCorrectFileName(fileName)) {
+ throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
+ }
+ // Logging etc
+ } catch (IllegalArgumentException err) {
+ if (!containsExtension(fileName)) {
+ throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
+ }
+ // Other error cases and logging
+ }
+ return "Default First Line";
+ }
+
+ private static boolean containsExtension(String fileName) {
+ if (fileName.contains(".txt") || fileName.contains(".doc"))
+ return true;
+ return false;
+ }
+
+ private static boolean isCorrectFileName(String fileName) {
+ if (fileName.equals("wrongFileName.txt"))
+ return false;
+ else
+ return true;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java
new file mode 100644
index 0000000000..c6dc6d6964
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java
@@ -0,0 +1,9 @@
+package com.baeldung.customexception;
+
+public class IncorrectFileExtensionException extends RuntimeException{
+ private static final long serialVersionUID = 1L;
+
+ public IncorrectFileExtensionException(String errorMessage, Throwable err) {
+ super(errorMessage, err);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java
new file mode 100644
index 0000000000..a804cadb84
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java
@@ -0,0 +1,9 @@
+package com.baeldung.customexception;
+
+public class IncorrectFileNameException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ public IncorrectFileNameException(String errorMessage, Throwable err) {
+ super(errorMessage, err);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/date/DateWithoutTime.java b/core-java/src/main/java/com/baeldung/date/DateWithoutTime.java
new file mode 100644
index 0000000000..fed9141597
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/date/DateWithoutTime.java
@@ -0,0 +1,30 @@
+package com.baeldung.date;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.LocalDate;
+import java.util.Calendar;
+import java.util.Date;
+
+public class DateWithoutTime {
+
+ public static Date getDateWithoutTimeUsingCalendar() {
+ Calendar calendar = Calendar.getInstance();
+ calendar.set(Calendar.HOUR_OF_DAY, 0);
+ calendar.set(Calendar.MINUTE, 0);
+ calendar.set(Calendar.SECOND, 0);
+ calendar.set(Calendar.MILLISECOND, 0);
+
+ return calendar.getTime();
+ }
+
+ public static Date getDateWithoutTimeUsingFormat() throws ParseException {
+ SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
+ return formatter.parse(formatter.format(new Date()));
+ }
+
+ public static LocalDate getLocalDate() {
+ return LocalDate.now();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/core-java/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java
new file mode 100644
index 0000000000..a6cef94377
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java
@@ -0,0 +1,28 @@
+package com.baeldung.datetime;
+
+import java.util.Calendar;
+import java.util.Date;
+
+public class DateExtractYearMonthDayIntegerValues {
+
+ int getYear(Date date) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(date);
+
+ return calendar.get(Calendar.YEAR);
+ }
+
+ int getMonth(Date date) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(date);
+
+ return calendar.get(Calendar.MONTH);
+ }
+
+ int getDay(Date date) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(date);
+
+ return calendar.get(Calendar.DAY_OF_MONTH);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/core-java/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java
new file mode 100644
index 0000000000..b40e10f6ad
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java
@@ -0,0 +1,18 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+
+public class LocalDateExtractYearMonthDayIntegerValues {
+
+ int getYear(LocalDate localDate) {
+ return localDate.getYear();
+ }
+
+ int getMonth(LocalDate localDate) {
+ return localDate.getMonthValue();
+ }
+
+ int getDay(LocalDate localDate) {
+ return localDate.getDayOfMonth();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/core-java/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java
new file mode 100644
index 0000000000..404a62d2f4
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java
@@ -0,0 +1,18 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+
+public class LocalDateTimeExtractYearMonthDayIntegerValues {
+
+ int getYear(LocalDateTime localDateTime) {
+ return localDateTime.getYear();
+ }
+
+ int getMonth(LocalDateTime localDateTime) {
+ return localDateTime.getMonthValue();
+ }
+
+ int getDay(LocalDateTime localDateTime) {
+ return localDateTime.getDayOfMonth();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/core-java/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java
new file mode 100644
index 0000000000..e686b05493
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java
@@ -0,0 +1,18 @@
+package com.baeldung.datetime;
+
+import java.time.OffsetDateTime;
+
+public class OffsetDateTimeExtractYearMonthDayIntegerValues {
+
+ int getYear(OffsetDateTime offsetDateTime) {
+ return offsetDateTime.getYear();
+ }
+
+ int getMonth(OffsetDateTime offsetDateTime) {
+ return offsetDateTime.getMonthValue();
+ }
+
+ int getDay(OffsetDateTime offsetDateTime) {
+ return offsetDateTime.getDayOfMonth();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/core-java/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java
new file mode 100644
index 0000000000..3e790b2b3f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java
@@ -0,0 +1,18 @@
+package com.baeldung.datetime;
+
+import java.time.ZonedDateTime;
+
+public class ZonedDateTimeExtractYearMonthDayIntegerValues {
+
+ int getYear(ZonedDateTime zonedDateTime) {
+ return zonedDateTime.getYear();
+ }
+
+ int getMonth(ZonedDateTime zonedDateTime) {
+ return zonedDateTime.getMonthValue();
+ }
+
+ int getDay(ZonedDateTime zonedDateTime) {
+ return zonedDateTime.getDayOfMonth();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java
deleted file mode 100644
index 897bb71f38..0000000000
--- a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.baeldung.designpatterns.creational.abstractfactory;
-
-public interface Color {
- String getColor();
-}
diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java
deleted file mode 100644
index 8364e546b0..0000000000
--- a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.baeldung.designpatterns.creational.factory;
-
-public interface Polygon {
- String getType();
-}
diff --git a/core-java/src/main/java/com/baeldung/extension/Extension.java b/core-java/src/main/java/com/baeldung/extension/Extension.java
new file mode 100644
index 0000000000..e30084f1cb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/extension/Extension.java
@@ -0,0 +1,23 @@
+package com.baeldung.extension;
+
+import com.google.common.io.Files;
+import org.apache.commons.io.FilenameUtils;
+
+import java.util.Optional;
+
+public class Extension {
+ //Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
+ public String getExtensionByApacheCommonLib(String filename) {
+ return FilenameUtils.getExtension(filename);
+ }
+
+ public Optional getExtensionByStringHandling(String filename) {
+ return Optional.ofNullable(filename)
+ .filter(f -> f.contains("."))
+ .map(f -> f.substring(filename.lastIndexOf(".") + 1));
+ }
+
+ public String getExtensionByGuava(String filename) {
+ return Files.getFileExtension(filename);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java
new file mode 100644
index 0000000000..412d105581
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java
@@ -0,0 +1,18 @@
+package com.baeldung.immutableobjects;
+
+public final class Currency {
+
+ private final String value;
+
+ private Currency(String currencyValue) {
+ value = currencyValue;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static Currency of(String value) {
+ return new Currency(value);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Money.java b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java
new file mode 100644
index 0000000000..b509d2e797
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java
@@ -0,0 +1,20 @@
+package com.baeldung.immutableobjects;
+
+// 4. Immutability in Java
+public final class Money {
+ private final double amount;
+ private final Currency currency;
+
+ public Money(double amount, Currency currency) {
+ this.amount = amount;
+ this.currency = currency;
+ }
+
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public double getAmount() {
+ return amount;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java
new file mode 100644
index 0000000000..fd608b424c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java
@@ -0,0 +1,16 @@
+package com.baeldung.keyword;
+
+import com.baeldung.keyword.superkeyword.SuperSub;
+import com.baeldung.keyword.thiskeyword.KeywordUnitTest;
+
+/**
+ * Created by Gebruiker on 5/14/2018.
+ */
+public class KeywordDemo {
+
+ public static void main(String[] args) {
+ KeywordUnitTest keyword = new KeywordUnitTest();
+
+ SuperSub child = new SuperSub("message from the child class");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java
new file mode 100644
index 0000000000..a5304fcef9
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java
@@ -0,0 +1,20 @@
+package com.baeldung.keyword.superkeyword;
+
+/**
+ * Created by Gebruiker on 5/14/2018.
+ */
+public class SuperBase {
+
+ String message = "super class";
+
+ public SuperBase() {
+ }
+
+ public SuperBase(String message) {
+ this.message = message;
+ }
+
+ public void printMessage() {
+ System.out.println(message);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java
new file mode 100644
index 0000000000..83bc04ad0f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java
@@ -0,0 +1,26 @@
+package com.baeldung.keyword.superkeyword;
+
+/**
+ * Created by Gebruiker on 5/15/2018.
+ */
+public class SuperSub extends SuperBase {
+
+ String message = "child class";
+
+ public SuperSub(String message) {
+ super(message);
+ }
+
+ public SuperSub() {
+ super.printMessage();
+ printMessage();
+ }
+
+ public void getParentMessage() {
+ System.out.println(super.message);
+ }
+
+ public void printMessage() {
+ System.out.println(message);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java
new file mode 100644
index 0000000000..35fd7358af
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.keyword.thiskeyword;
+
+public class KeywordUnitTest {
+
+ private String name;
+ private int age;
+
+ public KeywordUnitTest() {
+ this("John", 27);
+ this.printMessage();
+ printInstance(this);
+ }
+
+ public KeywordUnitTest(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public void printMessage() {
+ System.out.println("invoked by this");
+ }
+
+ public void printInstance(KeywordUnitTest thisKeyword) {
+ System.out.println(thisKeyword);
+ }
+
+ public KeywordUnitTest getCurrentInstance() {
+ return this;
+ }
+
+ class ThisInnerClass {
+
+ boolean isInnerClass = true;
+
+ public ThisInnerClass() {
+ KeywordUnitTest thisKeyword = KeywordUnitTest.this;
+ String outerString = KeywordUnitTest.this.name;
+ System.out.println(this.isInnerClass);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "KeywordTest{" +
+ "name='" + name + '\'' +
+ ", age=" + age +
+ '}';
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/loops/InfiniteLoops.java b/core-java/src/main/java/com/baeldung/loops/InfiniteLoops.java
new file mode 100644
index 0000000000..0706c85db8
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/loops/InfiniteLoops.java
@@ -0,0 +1,23 @@
+package com.baeldung.loops;
+
+public class InfiniteLoops {
+
+ public void infiniteLoopUsingWhile() {
+ while (true) {
+ System.out.println("Infinite loop using while");
+ }
+ }
+
+ public void infiniteLoopUsingFor() {
+ for (;;) {
+ System.out.println("Infinite loop using for");
+ }
+ }
+
+ public void infiniteLoopUsingDoWhile() {
+ do {
+ System.out.println("Infinite loop using do-while");
+ } while (true);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/mail/EmailService.java b/core-java/src/main/java/com/baeldung/mail/EmailService.java
new file mode 100644
index 0000000000..e775b9f708
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/mail/EmailService.java
@@ -0,0 +1,80 @@
+package com.baeldung.mail;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.util.Properties;
+import javax.mail.*;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+
+public class EmailService {
+
+ private String host = "";
+ private int port = 0;
+ private String username = "";
+ private String password = "";
+
+
+ public EmailService(String host, int port, String username, String password) {
+
+ this.host = host;
+ this.port = port;
+ this.username = username;
+ this.password = password;
+
+ sendMail();
+ }
+
+ private void sendMail() {
+
+ Properties prop = new Properties();
+ prop.put("mail.smtp.auth", true);
+ prop.put("mail.smtp.starttls.enable", "true");
+ prop.put("mail.smtp.host", host);
+ prop.put("mail.smtp.port", port);
+ prop.put("mail.smtp.ssl.trust", host);
+
+ Session session = Session.getInstance(prop, new Authenticator() {
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication(username, password);
+ }
+ });
+
+ try {
+
+ Message message = new MimeMessage(session);
+ message.setFrom(new InternetAddress("from@gmail.com"));
+ message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
+ message.setSubject("Mail Subject");
+
+ String msg = "This is my first email using JavaMailer";
+
+ MimeBodyPart mimeBodyPart = new MimeBodyPart();
+ mimeBodyPart.setContent(msg, "text/html");
+
+ MimeBodyPart attachmentBodyPart = new MimeBodyPart();
+ attachmentBodyPart.attachFile(new File("pom.xml"));
+
+ Multipart multipart = new MimeMultipart();
+ multipart.addBodyPart(mimeBodyPart);
+ multipart.addBodyPart(attachmentBodyPart);
+
+ message.setContent(multipart);
+
+ Transport.send(message);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void main(String ... args) {
+ new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed");
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/manifest/AppExample.java b/core-java/src/main/java/com/baeldung/manifest/AppExample.java
new file mode 100644
index 0000000000..cb15323b22
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/manifest/AppExample.java
@@ -0,0 +1,8 @@
+package com.baeldung.manifest;
+
+public class AppExample {
+
+ public static void main(String[] args){
+ System.out.println("AppExample executed!");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java
new file mode 100644
index 0000000000..21e14b96e0
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java
@@ -0,0 +1,83 @@
+package com.baeldung.manifest;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+public class ExecuteJarFile {
+
+ private static final String DELIMITER = " ";
+ private static final String WORK_PATH = "src/main/java/com/baeldung/manifest";
+ private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF";
+ private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample";
+
+ private static final String COMPILE_COMMAND = "javac -d . AppExample.java";
+ private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class";
+ private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class";
+ private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar";
+
+ public static void main(String[] args) {
+ System.out.println(executeJarWithoutManifestAttribute());
+ System.out.println(executeJarWithManifestAttribute());
+ }
+
+ public static String executeJarWithoutManifestAttribute() {
+ return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND);
+ }
+
+ public static String executeJarWithManifestAttribute() {
+ createManifestFile();
+ return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND);
+ }
+
+ private static void createManifestFile() {
+ BufferedWriter writer;
+ try {
+ writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH));
+ writer.write(MAIN_MANIFEST_ATTRIBUTE);
+ writer.newLine();
+ writer.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static String executeJar(String createJarCommand) {
+ executeCommand(COMPILE_COMMAND);
+ executeCommand(createJarCommand);
+ return executeCommand(EXECUTE_JAR_COMMAND);
+ }
+
+ private static String executeCommand(String command) {
+ String output = null;
+ try {
+ output = collectOutput(runProcess(command));
+ } catch (Exception ex) {
+ System.out.println(ex);
+ }
+ return output;
+ }
+
+ private static String collectOutput(Process process) throws IOException {
+ StringBuffer output = new StringBuffer();
+ BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ String line = "";
+ while ((line = outputReader.readLine()) != null) {
+ output.append(line + "\n");
+ }
+ return output.toString();
+ }
+
+ private static Process runProcess(String command) throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER));
+ builder.directory(new File(WORK_PATH).getAbsoluteFile());
+ builder.redirectErrorStream(true);
+ Process process = builder.start();
+ process.waitFor();
+ return process;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/nan/NaNExample.java b/core-java/src/main/java/com/baeldung/nan/NaNExample.java
new file mode 100644
index 0000000000..d54a749d3f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/nan/NaNExample.java
@@ -0,0 +1,81 @@
+package com.baeldung.nan;
+
+/**
+ * Sample usage of NaN.
+ *
+ */
+public class NaNExample {
+
+ public static void main(String[] args) {
+ NaNExample naNExample = new NaNExample();
+ naNExample.demo();
+ }
+
+ void demo() {
+ undefined_operations_produce_NaN();
+ operations_with_no_real_results_produce_NaN();
+ operations_with_NaN_produce_NaN();
+ comparison_with_NaN();
+ check_if_a_value_is_NaN();
+ assign_NaN_to_missing_values();
+ }
+
+ void undefined_operations_produce_NaN() {
+ System.out.println("Undefined Operations Produce NaN");
+ final double ZERO = 0;
+ System.out.println("ZERO / ZERO = " + (ZERO / ZERO));
+ System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY));
+ System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO));
+ System.out.println();
+ }
+
+ void operations_with_no_real_results_produce_NaN() {
+ System.out.println("Operations with no real results produce NaN");
+ System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1));
+ System.out.println("LOG OF -1 = " + Math.log(-1));
+ System.out.println();
+ }
+
+ void operations_with_NaN_produce_NaN() {
+ System.out.println("Operations with NaN produce NaN");
+ System.out.println("2 + NaN = " + (2 + Double.NaN));
+ System.out.println("2 - NaN = " + (2 - Double.NaN));
+ System.out.println("2 * NaN = " + (2 * Double.NaN));
+ System.out.println("2 / NaN = " + (2 / Double.NaN));
+ System.out.println();
+ }
+
+ void assign_NaN_to_missing_values() {
+ System.out.println("Assign NaN to Missing values");
+ double salaryRequired = Double.NaN;
+ System.out.println(salaryRequired);
+ System.out.println();
+ }
+
+ void comparison_with_NaN() {
+ System.out.println("Comparison with NaN");
+ final double NAN = Double.NaN;
+ System.out.println("NaN == 1 = " + (NAN == 1));
+ System.out.println("NaN > 1 = " + (NAN > 1));
+ System.out.println("NaN < 1 = " + (NAN < 1));
+ System.out.println("NaN != 1 = " + (NAN != 1));
+ System.out.println("NaN == NaN = " + (NAN == NAN));
+ System.out.println("NaN > NaN = " + (NAN > NAN));
+ System.out.println("NaN < NaN = " + (NAN < NAN));
+ System.out.println("NaN != NaN = " + (NAN != NAN));
+ System.out.println();
+ }
+
+ void check_if_a_value_is_NaN() {
+ System.out.println("Check if a value is NaN");
+ double x = 1;
+ System.out.println(x + " is NaN = " + (x != x));
+ System.out.println(x + " is NaN = " + (Double.isNaN(x)));
+
+ x = Double.NaN;
+ System.out.println(x + " is NaN = " + (x != x));
+ System.out.println(x + " is NaN = " + (Double.isNaN(x)));
+ System.out.println();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java
index 32d3051327..c3cc567eaa 100755
--- a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java
+++ b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java
@@ -1,10 +1,12 @@
package com.baeldung.numberofdigits;
-import static com.baeldung.designpatterns.util.LogerUtil.LOG;
+import org.apache.log4j.Logger;
public class NumberOfDigitsDriver {
private static NumberOfDigits numberOfDigits;
+ private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
+
static {
numberOfDigits = new NumberOfDigits();
}
diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java
new file mode 100644
index 0000000000..0e1746fc38
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java
@@ -0,0 +1,27 @@
+package com.baeldung.parameterpassing;
+
+public class NonPrimitives {
+ public static void main(String[] args) {
+ FooClass a = new FooClass(1);
+ FooClass b = new FooClass(1);
+
+ System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num);
+ modify(a, b);
+ System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num);
+ }
+
+ public static void modify(FooClass a1, FooClass b1) {
+ a1.num++;
+
+ b1 = new FooClass(1);
+ b1.num++;
+ }
+}
+
+class FooClass {
+ public int num;
+
+ public FooClass(int num) {
+ this.num = num;
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java
new file mode 100644
index 0000000000..f63229d7de
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java
@@ -0,0 +1,17 @@
+package com.baeldung.parameterpassing;
+
+public class Primitives {
+ public static void main(String[] args) {
+ int x = 1;
+ int y = 2;
+
+ System.out.printf("Before Modification: x = %d and y = %d ", x, y);
+ modify(x, y);
+ System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y);
+ }
+
+ public static void modify(int x1, int y1) {
+ x1 = 5;
+ y1 = 10;
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java b/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java
new file mode 100644
index 0000000000..46ed5fd99f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java
@@ -0,0 +1,9 @@
+package com.baeldung.scope.method;
+
+
+public class BaseMethodClass {
+
+ public static void printMessage() {
+ System.out.println("base static method");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java b/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java
new file mode 100644
index 0000000000..1d0cff2d6b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java
@@ -0,0 +1,9 @@
+package com.baeldung.scope.method;
+
+
+public class ChildMethodClass extends BaseMethodClass {
+
+ public static void printMessage() {
+ System.out.println("child static method");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java b/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java
new file mode 100644
index 0000000000..7e0b3ed146
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java
@@ -0,0 +1,8 @@
+package com.baeldung.scope.method;
+
+public class MethodHidingDemo {
+
+ public static void main(String[] args) {
+ ChildMethodClass.printMessage();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java
new file mode 100644
index 0000000000..5730e5e282
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java
@@ -0,0 +1,13 @@
+package com.baeldung.scope.variable;
+
+/**
+ * Created by Gebruiker on 5/7/2018.
+ */
+public class ChildVariable extends ParentVariable {
+
+ String instanceVariable = "child variable";
+
+ public void printInstanceVariable() {
+ System.out.println(instanceVariable);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java
new file mode 100644
index 0000000000..8243fdb249
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java
@@ -0,0 +1,23 @@
+package com.baeldung.scope.variable;
+
+/**
+ * Created by Gebruiker on 5/6/2018.
+ */
+public class HideVariable {
+
+ private String message = "this is instance variable";
+
+ HideVariable() {
+ String message = "constructor local variable";
+ System.out.println(message);
+ }
+
+ public void printLocalVariable() {
+ String message = "method local variable";
+ System.out.println(message);
+ }
+
+ public void printInstanceVariable() {
+ System.out.println(this.message);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java
new file mode 100644
index 0000000000..7f116b955e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java
@@ -0,0 +1,13 @@
+package com.baeldung.scope.variable;
+
+/**
+ * Created by Gebruiker on 5/7/2018.
+ */
+public class ParentVariable {
+
+ String instanceVariable = "parent variable";
+
+ public void printInstanceVariable() {
+ System.out.println(instanceVariable);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java b/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java
new file mode 100644
index 0000000000..1ad71bd966
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java
@@ -0,0 +1,18 @@
+package com.baeldung.scope.variable;
+
+/**
+ * Created by Gebruiker on 5/6/2018.
+ */
+public class VariableHidingDemo {
+ public static void main(String[] args) {
+ HideVariable variable = new HideVariable();
+ variable.printLocalVariable();
+ variable.printInstanceVariable();
+
+ ParentVariable parentVariable = new ParentVariable();
+ ParentVariable childVariable = new ChildVariable();
+
+ parentVariable.printInstanceVariable();
+ childVariable.printInstanceVariable();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java b/core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java
new file mode 100644
index 0000000000..0fdda86f2a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java
@@ -0,0 +1,68 @@
+package com.baeldung.string;
+
+import com.ibm.icu.lang.UCharacter;
+import com.ibm.icu.text.BreakIterator;
+import org.apache.commons.lang.WordUtils;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+public class TitleCaseConverter {
+
+ private static final String WORD_SEPARATOR = " ";
+
+ public static String convertToTitleCaseIteratingChars(String text) {
+ if (text == null || text.isEmpty()) {
+ return text;
+ }
+
+ StringBuilder converted = new StringBuilder();
+
+ boolean convertNext = true;
+ for (char ch : text.toCharArray()) {
+ if (Character.isSpaceChar(ch)) {
+ convertNext = true;
+ } else if (convertNext) {
+ ch = Character.toTitleCase(ch);
+ convertNext = false;
+ } else {
+ ch = Character.toLowerCase(ch);
+ }
+ converted.append(ch);
+ }
+
+ return converted.toString();
+ }
+
+ public static String convertToTitleCaseSplitting(String text) {
+ if (text == null || text.isEmpty()) {
+ return text;
+ }
+
+ return Arrays
+ .stream(text.split(WORD_SEPARATOR))
+ .map(word -> word.isEmpty()
+ ? word
+ : Character.toTitleCase(word.charAt(0)) + word
+ .substring(1)
+ .toLowerCase())
+ .collect(Collectors.joining(WORD_SEPARATOR));
+ }
+
+ public static String convertToTitleCaseIcu4j(String text) {
+ if (text == null || text.isEmpty()) {
+ return text;
+ }
+
+ return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance());
+ }
+
+ public static String convertToTileCaseWordUtilsFull(String text) {
+ return WordUtils.capitalizeFully(text);
+ }
+
+ public static String convertToTileCaseWordUtils(String text) {
+ return WordUtils.capitalize(text);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java b/core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java
new file mode 100644
index 0000000000..4ae1f5aa83
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java
@@ -0,0 +1,75 @@
+package com.baeldung.stringisnumeric;
+
+import java.util.concurrent.TimeUnit;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.State;
+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;
+
+
+public class Benchmarking {
+ public static void main(String[] args) throws RunnerException {
+ Options opt = new OptionsBuilder()
+ .include(Benchmarking.class.getSimpleName())
+ .forks(1)
+ .build();
+
+ new Runner(opt).run();
+ }
+
+ @State(Scope.Thread)
+ public static class ExecutionPlan {
+ public String number = Integer.toString(Integer.MAX_VALUE);
+ public boolean isNumber = false;
+ public IsNumeric isNumeric= new IsNumeric();
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingCoreJava(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingRegularExpressions(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingNumberUtils_isParsable(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingStringUtils_isNumeric(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.NANOSECONDS)
+ public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
+ plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java b/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java
new file mode 100644
index 0000000000..c438071e42
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java
@@ -0,0 +1,35 @@
+package com.baeldung.stringisnumeric;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+
+public class IsNumeric {
+ public boolean usingCoreJava(String strNum) {
+ try {
+ double d = Double.parseDouble(strNum);
+ } catch (NumberFormatException | NullPointerException nfe) {
+ return false;
+ }
+ return true;
+ }
+
+ public boolean usingRegularExpressions(String strNum) {
+ return strNum.matches("-?\\d+(\\.\\d+)?");
+ }
+
+ public boolean usingNumberUtils_isCreatable(String strNum) {
+ return NumberUtils.isCreatable(strNum);
+ }
+
+ public boolean usingNumberUtils_isParsable(String strNum) {
+ return NumberUtils.isParsable(strNum);
+ }
+
+ public boolean usingStringUtils_isNumeric(String strNum) {
+ return StringUtils.isNumeric(strNum);
+ }
+
+ public boolean usingStringUtils_isNumericSpace(String strNum) {
+ return StringUtils.isNumericSpace(strNum);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java b/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java
new file mode 100644
index 0000000000..c0a6edae50
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java
@@ -0,0 +1,34 @@
+package com.baeldung.stringisnumeric;
+
+import org.apache.log4j.Logger;
+
+public class IsNumericDriver {
+ private static IsNumeric isNumeric;
+ private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
+ static {
+ isNumeric =new IsNumeric();
+
+ }
+
+ public static void main(String[] args) {
+ LOG.info("Testing all methods...");
+
+ boolean res = isNumeric.usingCoreJava("1001");
+ LOG.info("Using Core Java : " + res);
+
+ res = isNumeric.usingRegularExpressions("1001");
+ LOG.info("Using Regular Expressions : " + res);
+
+ res =isNumeric.usingNumberUtils_isCreatable("1001");
+ LOG.info("Using NumberUtils.isCreatable : " + res);
+
+ res =isNumeric.usingNumberUtils_isParsable("1001");
+ LOG.info("Using NumberUtils.isParsable : " + res);
+
+ res =isNumeric.usingStringUtils_isNumeric("1001");
+ LOG.info("Using StringUtils.isNumeric : " + res);
+
+ res =isNumeric.usingStringUtils_isNumericSpace("1001");
+ LOG.info("Using StringUtils.isNumericSpace : " + res);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java
rename to core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java
index 7265fa20e5..5e764da174 100644
--- a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java
+++ b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
-public class ArrayInitializerTest {
+public class ArrayInitializerUnitTest {
@Test
public void whenInitializeArrayInLoop_thenCorrect() {
diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java
similarity index 90%
rename from core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java
rename to core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java
index ec916af092..4493f3fbf5 100644
--- a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java
+++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
-public class Find2ndLargestInArrayTest {
+public class Find2ndLargestInArrayUnitTest {
@Test
public void givenAnIntArray_thenFind2ndLargestElement() {
int[] array = { 1, 3, 24, 16, 87, 20 };
diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java
rename to core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java
index ba9188fa7b..887f50ebcc 100644
--- a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java
+++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
-public class FindElementInArrayTest {
+public class FindElementInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
int[] array = { 1, 3, 4, 8, 19, 20 };
diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java
new file mode 100644
index 0000000000..a4dd7e25c3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.array;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+
+import org.junit.Test;
+
+public class JaggedArrayUnitTest {
+
+ private JaggedArray obj = new JaggedArray();
+
+ @Test
+ public void whenInitializedUsingShortHandForm_thenCorrect() {
+ assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
+ }
+
+ @Test
+ public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
+ assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
+ }
+
+ @Test
+ public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
+ InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
+ System.setIn(is);
+ assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
+ System.setIn(System.in);
+ }
+
+ @Test
+ public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
+ int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
+ assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0));
+ assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1));
+ assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2));
+ }
+
+ @Test
+ public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
+ int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
+ ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ obj.printElements(jaggedArr);
+ assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
+ System.setOut(System.out);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java
rename to core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java
index 208075cb57..0f38316ce3 100644
--- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java
+++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
-public class SumAndAverageInArrayTest {
+public class SumAndAverageInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindSum() {
int[] array = { 1, 3, 4, 8, 19, 20 };
diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java
new file mode 100644
index 0000000000..9e6d3d6131
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java
@@ -0,0 +1,153 @@
+package com.baeldung.arrays;
+
+import static org.junit.Assert.*;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+public class ArraysUnitTest {
+ private String[] intro;
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Before
+ public void setup() {
+ intro = new String[] { "once", "upon", "a", "time" };
+ }
+
+ @Test
+ public void whenCopyOfRange_thenAbridgedArray() {
+ String[] abridgement = Arrays.copyOfRange(intro, 0, 3);
+
+ assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement);
+ assertFalse(Arrays.equals(intro, abridgement));
+ }
+
+ @Test
+ public void whenCopyOf_thenNullElement() {
+ String[] revised = Arrays.copyOf(intro, 3);
+ String[] expanded = Arrays.copyOf(intro, 5);
+
+ assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
+ assertNull(expanded[4]);
+ }
+
+ @Test
+ public void whenFill_thenAllMatch() {
+ String[] stutter = new String[3];
+ Arrays.fill(stutter, "once");
+
+ assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el)));
+ }
+
+ @Test
+ public void whenEqualsContent_thenMatch() {
+ assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
+ assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro));
+ }
+
+ @Test
+ public void whenNestedArrays_thenDeepEqualsPass() {
+ String[] end = { "the", "end" };
+ Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+ Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+
+ assertTrue(Arrays.deepEquals(story, copy));
+ assertFalse(Arrays.equals(story, copy));
+ }
+
+ @Test
+ public void whenSort_thenArraySorted() {
+ String[] sorted = Arrays.copyOf(intro, 4);
+ Arrays.sort(sorted);
+
+ assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted);
+ }
+
+ @Test
+ public void whenBinarySearch_thenFindElements() {
+ String[] sorted = Arrays.copyOf(intro, 4);
+ Arrays.sort(sorted);
+ int exact = Arrays.binarySearch(sorted, "time");
+ int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);
+
+ assertEquals("time", sorted[exact]);
+ assertEquals(2, exact);
+ assertEquals(exact, caseInsensitive);
+ }
+
+ @Test
+ public void whenNullElement_thenArraysHashCodeNotEqual() {
+ int beforeChange = Arrays.hashCode(intro);
+ int before = intro.hashCode();
+ intro[3] = null;
+ int after = intro.hashCode();
+ int afterChange = Arrays.hashCode(intro);
+
+ assertNotEquals(beforeChange, afterChange);
+ assertEquals(before, after);
+ }
+
+ @Test
+ public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() {
+ Object[] looping = new Object[] { intro, intro };
+ int deepHashBefore = Arrays.deepHashCode(looping);
+ int hashBefore = Arrays.hashCode(looping);
+
+ intro[3] = null;
+
+ int hashAfter = Arrays.hashCode(looping);
+ int deepHashAfter = Arrays.deepHashCode(looping);
+
+ assertEquals(hashAfter, hashBefore);
+ assertNotEquals(deepHashAfter, deepHashBefore);
+ }
+
+ @Test
+ public void whenStreamBadIndex_thenException() {
+ assertEquals(Arrays.stream(intro).count(), 4);
+
+ exception.expect(ArrayIndexOutOfBoundsException.class);
+ Arrays.stream(intro, 2, 1).count();
+ }
+
+ @Test
+ public void whenSetAllToUpper_thenAppliedToAllElements() {
+ String[] longAgo = new String[4];
+ Arrays.setAll(longAgo, i -> intro[i].toUpperCase());
+
+ assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" });
+ }
+
+ @Test
+ public void whenToString_thenFormattedArrayString() {
+ assertEquals("[once, upon, a, time]", Arrays.toString(intro));
+ }
+
+ @Test
+ public void whenNestedArrayDeepString_thenFormattedArraysString() {
+ String[] end = { "the", "end" };
+ Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
+
+ assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story));
+ }
+
+ @Test
+ public void whenAsList_thenImmutableArray() {
+ List rets = Arrays.asList(intro);
+
+ assertTrue(rets.contains("upon"));
+ assertTrue(rets.contains("time"));
+ assertEquals(rets.size(), 4);
+
+ exception.expect(UnsupportedOperationException.class);
+ rets.add("the");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java
similarity index 92%
rename from core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java
rename to core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java
index 103681894e..8ab1695395 100644
--- a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java
+++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
-public class AsciiArtTest {
+public class AsciiArtIntegrationTest {
@Test
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java
rename to core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java
index 1980497cd3..2a2f3be2a9 100644
--- a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java
+++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java
@@ -9,7 +9,7 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
-public class BreakContinueTest {
+public class BreakContinueUnitTest {
@Test
public void whenUnlabeledBreak_ThenEqual() {
diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/casting/CastingTest.java
rename to core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java
index dd95e0dd80..41eaa5dc1b 100644
--- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java
+++ b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java
@@ -5,7 +5,7 @@ import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
-public class CastingTest {
+public class CastingUnitTest {
@Test
public void whenPrimitiveConverted_thenValueChanged() {
diff --git a/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java
new file mode 100644
index 0000000000..d1cfe7df19
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.chararraypassword;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class PasswordStoreExamplesUnitTest {
+
+ String stringPassword = "password";
+ char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
+
+ @Test
+ public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() {
+ String originalHashCode = Integer.toHexString(stringPassword.hashCode());
+
+ stringPassword = "********";
+ String changedHashCode = Integer.toHexString(stringPassword.hashCode());
+
+ assertThat(originalHashCode).isNotEqualTo(changedHashCode);
+ assertThat(stringPassword).isNotEqualTo("password");
+ }
+
+ @Test
+ public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() {
+ String originalHashCode = Integer.toHexString(stringPassword.hashCode());
+
+ stringPassword = "********";
+ stringPassword = "password";
+ String reassignedHashCode = Integer.toHexString(stringPassword.hashCode());
+
+ assertThat(originalHashCode).isEqualTo(reassignedHashCode);
+ assertThat(stringPassword).isEqualTo("password");
+ }
+
+ @Test
+ public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() {
+ String originalHashCode = Integer.toHexString(stringPassword.hashCode());
+
+ String newString = "********";
+ stringPassword.replace(stringPassword, newString);
+
+ String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode());
+
+ assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace);
+ assertThat(stringPassword).isEqualTo("password");
+ }
+
+ @Test
+ public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() {
+ String originalHashCode = Integer.toHexString(charPassword.hashCode());
+
+ Arrays.fill(charPassword, '*');
+ String changedHashCode = Integer.toHexString(charPassword.hashCode());
+
+ assertThat(originalHashCode).isEqualTo(changedHashCode);
+ assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'});
+ }
+
+ @Test
+ public void whenCallingToStringOfString_ThenValuesEqual() {
+ assertThat(stringPassword.toString()).isEqualTo("password");
+ }
+
+ @Test
+ public void whenCallingToStringOfCharArray_ThenValuesNotEqual() {
+ assertThat(charPassword.toString()).isNotEqualTo("password");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java
rename to core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
index 9f3c751805..ec35885b84 100644
--- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java
+++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java
@@ -5,7 +5,7 @@ import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-public class CustomClassLoaderTest {
+public class CustomClassLoaderUnitTest {
@Test
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
diff --git a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java
rename to core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java
index f44a5cef09..f0d69f4326 100644
--- a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java
+++ b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java
@@ -4,7 +4,7 @@ import org.junit.Test;
import static org.junit.Assert.*;
-public class PrintClassLoaderTest {
+public class PrintClassLoaderUnitTest {
@Test(expected = ClassNotFoundException.class)
public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception {
PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance();
diff --git a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java
similarity index 84%
rename from core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java
rename to core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java
index 8714d084ab..b076b0324a 100644
--- a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java
+++ b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java
@@ -2,7 +2,7 @@ package com.baeldung.classnotfoundexception;
import org.junit.Test;
-public class ClassNotFoundExceptionTest {
+public class ClassNotFoundExceptionUnitTest {
@Test(expected = ClassNotFoundException.class)
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
diff --git a/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java
new file mode 100644
index 0000000000..230698f719
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.customexception;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.File;
+
+import org.junit.Test;
+
+public class IncorrectFileExtensionExceptionUnitTest {
+
+ @Test
+ public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException {
+ assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line");
+ }
+
+ @Test(expected = IncorrectFileExtensionException.class)
+ public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
+ StringBuffer sBuffer = new StringBuffer();
+ sBuffer.append("src");
+ sBuffer.append(File.separator);
+ sBuffer.append("test");
+ sBuffer.append(File.separator);
+ sBuffer.append("resources");
+ sBuffer.append(File.separator);
+ sBuffer.append("correctFileNameWithoutProperExtension");
+ FileManager.getFirstLine(sBuffer.toString());
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java
new file mode 100644
index 0000000000..acb05eb763
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.customexception;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class IncorrectFileNameExceptionUnitTest {
+
+ @Test(expected = IncorrectFileNameException.class)
+ public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException {
+ FileManager.getFirstLine("wrongFileName.txt");
+ }
+
+ @Test
+ public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
+ assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line");
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/core-java/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java
new file mode 100644
index 0000000000..63a4395a38
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java
@@ -0,0 +1,92 @@
+package com.baeldung.date;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.text.ParseException;
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.util.Calendar;
+import java.util.Date;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class DateWithoutTimeUnitTest {
+
+ private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
+
+ @Test
+ public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() {
+ Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar();
+
+ // first check the time is set to 0
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(dateWithoutTime);
+
+ assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
+ assertEquals(0, calendar.get(Calendar.MINUTE));
+ assertEquals(0, calendar.get(Calendar.SECOND));
+ assertEquals(0, calendar.get(Calendar.MILLISECOND));
+
+ // we get the day of the date
+ int day = calendar.get(Calendar.DAY_OF_MONTH);
+
+ // if we add the mills of one day minus 1 we should get the same day
+ calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
+ assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
+
+ // if we add one full day in millis we should get a different day
+ calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
+ assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
+ }
+
+ @Test
+ public void whenGettingDateWithoutTimeUsingFormat_thenReturnDateWithoutTime() throws ParseException {
+ Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingFormat();
+
+ // first check the time is set to 0
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(dateWithoutTime);
+
+ assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
+ assertEquals(0, calendar.get(Calendar.MINUTE));
+ assertEquals(0, calendar.get(Calendar.SECOND));
+ assertEquals(0, calendar.get(Calendar.MILLISECOND));
+
+ // we get the day of the date
+ int day = calendar.get(Calendar.DAY_OF_MONTH);
+
+ // if we add the mills of one day minus 1 we should get the same day
+ calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
+ assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
+
+ // if we add one full day in millis we should get a different day
+ calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
+ assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
+ }
+
+ @Test
+ public void whenGettingLocalDate_thenReturnDateWithoutTime() {
+ // get the local date
+ LocalDate localDate = DateWithoutTime.getLocalDate();
+
+ // get the millis of our LocalDate
+ long millisLocalDate = localDate
+ .atStartOfDay()
+ .toInstant(OffsetDateTime
+ .now()
+ .getOffset())
+ .toEpochMilli();
+
+ Calendar calendar = Calendar.getInstance();
+ // if we add the millis of one day minus 1 we should get the same day
+ calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY - 1);
+ assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
+
+ // if we add one full day in millis we should get a different day
+ calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY);
+ assertNotEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH));
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java
new file mode 100644
index 0000000000..3b1fcfa6c5
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java
@@ -0,0 +1,45 @@
+package com.baeldung.datetime;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class DateExtractYearMonthDayIntegerValuesUnitTest {
+
+ DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
+
+ Date date;
+
+ @Before
+ public void setup() throws ParseException
+ {
+ date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
+ }
+
+ @Test
+ public void whenGetYear_thenCorrectYear()
+ {
+ int actualYear=extractYearMonthDateIntegerValues.getYear(date);
+ assertThat(actualYear,is(2018));
+ }
+
+ @Test
+ public void whenGetMonth_thenCorrectMonth()
+ {
+ int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
+ assertThat(actualMonth,is(02));
+ }
+
+ @Test
+ public void whenGetDay_thenCorrectDay()
+ {
+ int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
+ assertThat(actualDayOfMonth,is(01));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java
new file mode 100644
index 0000000000..05de6ed0b9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.time.LocalDate;
+
+import org.junit.Test;
+
+public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
+
+ LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
+
+ LocalDate localDate=LocalDate.parse("2007-12-03");
+
+ @Test
+ public void whenGetYear_thenCorrectYear()
+ {
+ int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
+ assertThat(actualYear,is(2007));
+ }
+
+ @Test
+ public void whenGetMonth_thenCorrectMonth()
+ {
+ int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
+ assertThat(actualMonth,is(12));
+ }
+
+ @Test
+ public void whenGetDay_thenCorrectDay()
+ {
+ int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
+ assertThat(actualDayOfMonth,is(03));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
new file mode 100644
index 0000000000..70544ea970
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.time.LocalDateTime;
+
+import org.junit.Test;
+
+public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
+
+ LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
+
+ LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
+
+ @Test
+ public void whenGetYear_thenCorrectYear()
+ {
+ int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
+ assertThat(actualYear,is(2007));
+ }
+
+ @Test
+ public void whenGetMonth_thenCorrectMonth()
+ {
+ int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
+ assertThat(actualMonth,is(12));
+ }
+
+ @Test
+ public void whenGetDay_thenCorrectDay()
+ {
+ int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
+ assertThat(actualDayOfMonth,is(03));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
new file mode 100644
index 0000000000..efb01c49a5
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.time.OffsetDateTime;
+
+import org.junit.Test;
+
+public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
+
+ OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
+
+ OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
+
+ @Test
+ public void whenGetYear_thenCorrectYear()
+ {
+ int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
+ assertThat(actualYear,is(2007));
+ }
+
+ @Test
+ public void whenGetMonth_thenCorrectMonth()
+ {
+ int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
+ assertThat(actualMonth,is(12));
+ }
+
+ @Test
+ public void whenGetDay_thenCorrectDay()
+ {
+ int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
+ assertThat(actualDayOfMonth,is(03));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
new file mode 100644
index 0000000000..a9ed3d2b74
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.time.ZonedDateTime;
+
+import org.junit.Test;
+
+public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
+
+ ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
+
+ ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
+
+ @Test
+ public void whenGetYear_thenCorrectYear()
+ {
+ int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
+ assertThat(actualYear,is(2007));
+ }
+
+ @Test
+ public void whenGetMonth_thenCorrectMonth()
+ {
+ int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
+ assertThat(actualMonth,is(12));
+ }
+
+ @Test
+ public void whenGetDay_thenCorrectDay()
+ {
+ int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
+ assertThat(actualDayOfMonth,is(03));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java
rename to core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java
index 8acd4e023e..6c3393c254 100644
--- a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java
+++ b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java
@@ -11,7 +11,7 @@ import java.util.Locale;
import org.junit.Test;
-public class DecimalFormatExamplesTest {
+public class DecimalFormatExamplesUnitTest {
double d = 1234567.89;
diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java
rename to core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java
index 8fec58f111..77b38419a9 100644
--- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java
+++ b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java
@@ -13,7 +13,7 @@ import java.util.TimeZone;
import org.junit.Ignore;
import org.junit.Test;
-public class DaylightSavingTimeExamplesTest {
+public class DaylightSavingTimeExamplesUnitTest {
@Test
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java
rename to core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java
index 78847033ac..07ab859e09 100644
--- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java
+++ b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java
@@ -11,7 +11,7 @@ import java.util.TimeZone;
import org.junit.Test;
-public class DaylightSavingTimeJavaTimeExamplesTest {
+public class DaylightSavingTimeJavaTimeExamplesUnitTest {
@Test
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
diff --git a/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java
new file mode 100644
index 0000000000..680eea0cae
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.extension;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Optional;
+
+public class ExtensionUnitTest {
+ private Extension extension = new Extension();
+
+ @Test
+ public void getExtension_whenApacheCommonIO_thenExtensionIsTrue() {
+ String expectedExtension = "txt";
+ String actualExtension = extension.getExtensionByApacheCommonLib("jarvis.txt");
+ Assert.assertEquals(expectedExtension, actualExtension);
+ }
+
+ @Test
+ public void getExtension_whenStringHandle_thenExtensionIsTrue() {
+ String expectedExtension = "java";
+ Optional actualExtension = extension.getExtensionByStringHandling("Demo.java");
+ Assert.assertEquals(expectedExtension, actualExtension.get());
+ }
+
+ @Test
+ public void getExtension_whenGuava_thenExtensionIsTrue() {
+ String expectedExtension = "class";
+ String actualExtension = extension.getExtensionByGuava("baeldung/Demo.class");
+ Assert.assertEquals(expectedExtension, actualExtension);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java
similarity index 95%
rename from core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java
rename to core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java
index 60950fae7a..49857f355a 100644
--- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java
+++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java
@@ -8,7 +8,7 @@ import java.util.Map;
import static org.junit.Assert.assertTrue;
-public class ApplicationTest {
+public class ApplicationUnitTest {
@Test
public void main_NoInputState_TextPrintedToConsole() throws Exception {
diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java
rename to core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java
index e356b4beef..44ea7efed1 100644
--- a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java
+++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java
@@ -5,7 +5,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-public class UserTest {
+public class UserUnitTest {
private User user;
private User comparisonUser;
diff --git a/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java
new file mode 100644
index 0000000000..01dfeac050
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.immutableobjects;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ImmutableObjectsUnitTest {
+
+ @Test
+ public void whenCallingStringReplace_thenStringDoesNotMutate() {
+ // 2. What's an Immutable Object?
+ final String name = "baeldung";
+ final String newName = name.replace("dung", "----");
+
+ assertEquals("baeldung", name);
+ assertEquals("bael----", newName);
+ }
+
+ public void whenReassignFinalValue_thenCompilerError() {
+ // 3. The final Keyword in Java (1)
+ final String name = "baeldung";
+ // name = "bael...";
+ }
+
+ @Test
+ public void whenAddingElementToList_thenSizeChange() {
+ // 3. The final Keyword in Java (2)
+ final List strings = new ArrayList<>();
+ assertEquals(0, strings.size());
+ strings.add("baeldung");
+ assertEquals(1, strings.size());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java
similarity index 85%
rename from core-java/src/test/java/com/baeldung/inheritance/AppTest.java
rename to core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java
index 1235761aba..1c3c2fff35 100644
--- a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java
+++ b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java
@@ -6,14 +6,14 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
-public class AppTest extends TestCase {
+public class AppUnitTest extends TestCase {
- public AppTest(String testName) {
+ public AppUnitTest(String testName) {
super( testName );
}
public static Test suite() {
- return new TestSuite(AppTest.class);
+ return new TestSuite(AppUnitTest.class);
}
@SuppressWarnings("static-access")
diff --git a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java
similarity index 95%
rename from core-java/src/test/java/com/baeldung/initializationguide/UserTest.java
rename to core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java
index 8d352ba706..f74384e6f7 100644
--- a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java
+++ b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java
@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
-public class UserTest {
+public class UserUnitTest {
@Test
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
diff --git a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java
rename to core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java
index b19ed76189..65d7c860a8 100644
--- a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java
+++ b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java
@@ -7,7 +7,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
-public class InnerInterfaceTests {
+public class InnerInterfaceUnitTest {
@Test
public void whenCustomerListJoined_thenReturnsJoinedNames() {
Customer.List customerList = new CommaSeparatedCustomers();
diff --git a/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java
new file mode 100644
index 0000000000..e83ba7afc8
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java
@@ -0,0 +1,159 @@
+package com.baeldung.java.clock;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ClockUnitTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class);
+
+ @Test
+ public void givenClock_withSytemUTC_retrievesInstant() {
+
+ Clock clockUTC = Clock.systemUTC();
+
+ assertEquals(clockUTC.getZone(), ZoneOffset.UTC);
+ assertEquals(clockUTC.instant().equals(null), false);
+
+ LOGGER.debug("UTC instant :: " + clockUTC.instant());
+ }
+
+ @Test
+ public void givenClock_withSytem_retrievesInstant() {
+
+ Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta"));
+
+ assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta"));
+ assertEquals(clockSystem.instant().equals(null), false);
+
+ LOGGER.debug("System zone :: " + clockSystem.getZone());
+ }
+
+ @Test
+ public void givenClock_withSytemDefaultZone_retrievesInstant() {
+
+ Clock clockSystemDefault = Clock.systemDefaultZone();
+
+ assertEquals(clockSystemDefault.getZone().equals(null), false);
+ assertEquals(clockSystemDefault.instant().equals(null), false);
+
+ LOGGER.debug("System Default instant :: " + clockSystemDefault.instant());
+ }
+
+ @Test
+ public void givenClock_withSytemUTC_retrievesTimeInMillis() {
+
+ Clock clockMillis = Clock.systemDefaultZone();
+
+ assertEquals(clockMillis.instant().equals(null), false);
+ assertTrue(clockMillis.millis() > 0);
+
+ LOGGER.debug("System Default millis :: " + clockMillis.millis());
+ }
+
+ @Test
+ public void givenClock_usingOffset_retrievesFutureDate() {
+
+ Clock baseClock = Clock.systemDefaultZone();
+
+ // result clock will be later than baseClock
+ Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72));
+
+ assertEquals(futureClock.instant().equals(null), false);
+ assertTrue(futureClock.millis() > baseClock.millis());
+
+ LOGGER.debug("Future Clock instant :: " + futureClock.instant());
+ }
+
+ @Test
+ public void givenClock_usingOffset_retrievesPastDate() {
+ Clock baseClock = Clock.systemDefaultZone();
+
+ // result clock will be later than baseClock
+ Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72));
+
+ assertEquals(pastClock.instant().equals(null), false);
+ assertTrue(pastClock.millis() < baseClock.millis());
+
+ LOGGER.debug("Past Clock instant :: " + pastClock.instant());
+ }
+
+ @Test
+ public void givenClock_usingTick_retrievesInstant() {
+ Clock clockDefaultZone = Clock.systemDefaultZone();
+ Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300));
+
+ assertEquals(clockDefaultZone.instant().equals(null), false);
+ assertEquals(clocktick.instant().equals(null), false);
+ assertTrue(clockDefaultZone.millis() > clocktick.millis());
+
+ LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant());
+ LOGGER.debug("Clock tick instant: " + clocktick.instant());
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void givenClock_usingTickDurationNegative_throwsException() {
+
+ Clock clockDefaultZone = Clock.systemDefaultZone();
+ Clock.tick(clockDefaultZone, Duration.ofSeconds(-300));
+
+ }
+
+ @Test
+ public void givenClock_usingTickSeconds_retrievesInstant() {
+ ZoneId zoneId = ZoneId.of("Asia/Calcutta");
+ Clock tickSeconds = Clock.tickSeconds(zoneId);
+
+ assertEquals(tickSeconds.instant().equals(null), false);
+ LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant());
+
+ tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100));
+ assertEquals(tickSeconds.instant().equals(null), false);
+ }
+
+ @Test
+ public void givenClock_usingTickMinutes_retrievesInstant() {
+
+ Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta"));
+
+ assertEquals(tickMinutes.instant().equals(null), false);
+ LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant());
+
+ tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5));
+ assertEquals(tickMinutes.instant().equals(null), false);
+ }
+
+ @Test
+ public void givenClock_usingWithZone_retrievesInstant() {
+
+ ZoneId zoneSingapore = ZoneId.of("Asia/Singapore");
+ Clock clockSingapore = Clock.system(zoneSingapore);
+
+ assertEquals(clockSingapore.instant().equals(null), false);
+ LOGGER.debug("clockSingapore instant : " + clockSingapore.instant());
+
+ ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta");
+ Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta);
+ assertEquals(clockCalcutta.instant().equals(null), false);
+ LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant());
+ }
+
+ @Test
+ public void givenClock_usingGetZone_retrievesZoneId() {
+
+ Clock clockDefaultZone = Clock.systemDefaultZone();
+ ZoneId zone = clockDefaultZone.getZone();
+
+ assertEquals(zone.getId().equals(null), false);
+ LOGGER.debug("Default zone instant : " + clockDefaultZone.instant());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java
rename to core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java
index 9a231a9a3d..43ebdee688 100644
--- a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java
+++ b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java
@@ -7,7 +7,7 @@ import static org.junit.Assert.assertEquals;
/**
* The class presents various ways of finding the name of currently executed method.
*/
-public class CurrentlyExecutedMethodFinderTest {
+public class CurrentlyExecutedMethodFinderUnitTest {
@Test
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java
similarity index 95%
rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java
rename to core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java
index c429039e3d..0c312ff613 100644
--- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java
+++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java
@@ -23,8 +23,8 @@ import org.slf4j.LoggerFactory;
import com.baeldung.javanetworking.uriurl.URLDemo;
@FixMethodOrder
-public class URIDemoTest {
- private final Logger log = LoggerFactory.getLogger(URIDemoTest.class);
+public class URIDemoLiveTest {
+ private final Logger log = LoggerFactory.getLogger(URIDemoLiveTest.class);
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
static String URISCHEME = "https";
diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java
rename to core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java
index 47cbf539a5..15f53ed878 100644
--- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java
+++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java
@@ -21,8 +21,8 @@ import org.slf4j.LoggerFactory;
import com.baeldung.javanetworking.uriurl.URLDemo;
@FixMethodOrder
-public class URLDemoTest {
- private final Logger log = LoggerFactory.getLogger(URLDemoTest.class);
+public class URLDemoLiveTest {
+ private final Logger log = LoggerFactory.getLogger(URLDemoLiveTest.class);
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
static String URLPROTOCOL = "https";
diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java b/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java
rename to core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
index 90f2ea133f..c905482f55 100644
--- a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java
+++ b/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
@@ -15,7 +15,7 @@ import java.sql.PreparedStatement;
import java.sql.Statement;
@RunWith(MockitoJUnitRunner.class)
-public class BatchProcessingTest {
+public class BatchProcessingLiveTest {
@InjectMocks
diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
similarity index 99%
rename from core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java
rename to core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
index cb455c213a..ebfb4df102 100644
--- a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java
+++ b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
@@ -24,7 +24,7 @@ import com.sun.rowset.JdbcRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.WebRowSetImpl;
-public class JdbcRowSetTest {
+public class JdbcRowSetLiveTest {
Statement stmt = null;
String username = "sa";
String password = "";
diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java
similarity index 87%
rename from core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java
rename to core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java
index 5095217efc..3e02309636 100644
--- a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java
+++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java
@@ -5,6 +5,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class })
-public class SuiteTest {
+public class SuiteUnitTest {
}
diff --git a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java
similarity index 99%
rename from core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java
rename to core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java
index ff1d337597..cb2a9f1c49 100644
--- a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java
+++ b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java
@@ -33,7 +33,7 @@ import java.util.Date;
/**
* Created by adi on 4/14/18.
*/
-public class JavaKeyStoreTest {
+public class JavaKeyStoreUnitTest {
private JavaKeyStore keyStore;
diff --git a/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java
new file mode 100644
index 0000000000..a5a499c98c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.manifest;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class ExecuteJarFileUnitTest {
+
+ private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n";
+ private static final String SUCCESS_MESSAGE = "AppExample executed!\n";
+
+ @Test
+ public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() {
+ String output = ExecuteJarFile.executeJarWithoutManifestAttribute();
+ assertEquals(ERROR_MESSAGE, output);
+ }
+
+ @Test
+ public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() {
+ String output = ExecuteJarFile.executeJarWithManifestAttribute();
+ assertEquals(SUCCESS_MESSAGE, output);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java
similarity index 91%
rename from core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java
rename to core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java
index 788fbd7047..786e5af312 100644
--- a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java
+++ b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
-public class BigDecimalImplTest {
+public class BigDecimalImplUnitTest {
@Test
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java
similarity index 91%
rename from core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java
rename to core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java
index aa8eaa9909..4c45f69090 100644
--- a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java
+++ b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java
@@ -5,7 +5,7 @@ import org.junit.Test;
import java.math.BigInteger;
-public class BigIntegerImplTest {
+public class BigIntegerImplUnitTest {
@Test
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
diff --git a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java
rename to core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java
index 2066f13c6d..6812a8f588 100644
--- a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java
+++ b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java
@@ -5,7 +5,7 @@ import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
-public class FloatingPointArithmeticTest {
+public class FloatingPointArithmeticUnitTest {
@Test
public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/maths/RoundTest.java
rename to core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java
index 5ce9523e21..f3c8e6e97a 100644
--- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java
+++ b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java
@@ -8,7 +8,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-public class RoundTest {
+public class RoundUnitTest {
private double value = 2.03456d;
private int places = 2;
private double delta = 0.0d;
diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
index fe2747bcee..04d2886a82 100644
--- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
+++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
@@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest {
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
- .set("pattern", "00000.00 �")
+ .set("pattern", "00000.00 US Dollar")
.build());
String customFormatted = customFormat.format(oneDollar);
diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java
similarity index 85%
rename from core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java
rename to core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java
index aa11aaa788..ccc8c1f69c 100644
--- a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java
+++ b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java
@@ -2,7 +2,7 @@ package com.baeldung.noclassdeffounderror;
import org.junit.Test;
-public class NoClassDefFoundErrorTest {
+public class NoClassDefFoundErrorUnitTest {
@Test(expected = NoClassDefFoundError.class)
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java
new file mode 100644
index 0000000000..62f891d11b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.parameterpassing;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class NonPrimitivesUnitTest {
+ @Test
+ public void whenModifyingObjects_thenOriginalObjectChanged() {
+ Foo a = new Foo(1);
+ Foo b = new Foo(1);
+
+ // Before Modification
+ Assert.assertEquals(a.num, 1);
+ Assert.assertEquals(b.num, 1);
+
+ modify(a, b);
+
+ // After Modification
+ Assert.assertEquals(a.num, 2);
+ Assert.assertEquals(b.num, 1);
+ }
+
+ public static void modify(Foo a1, Foo b1) {
+ a1.num++;
+
+ b1 = new Foo(1);
+ b1.num++;
+ }
+}
+
+class Foo {
+ public int num;
+
+ public Foo(int num) {
+ this.num = num;
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java
new file mode 100644
index 0000000000..496cd1d205
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.parameterpassing;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class PrimitivesUnitTest {
+ @Test
+ public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
+
+ int x = 1;
+ int y = 2;
+
+ // Before Modification
+ Assert.assertEquals(x, 1);
+ Assert.assertEquals(y, 2);
+
+ modify(x, y);
+
+ // After Modification
+ Assert.assertEquals(x, 1);
+ Assert.assertEquals(y, 2);
+ }
+
+ public static void modify(int x1, int y1) {
+ x1 = 5;
+ y1 = 10;
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java
similarity index 94%
rename from core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java
rename to core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java
index c65be24240..6c560c9c37 100644
--- a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java
+++ b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.recursion;
import org.junit.Assert;
import org.junit.Test;
-public class RecursionExampleTest {
+public class RecursionExampleUnitTest {
RecursionExample recursion = new RecursionExample();
diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java
rename to core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java
index bba867f50f..77cdd0279d 100644
--- a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java
+++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java
@@ -7,7 +7,7 @@ import java.util.List;
import static org.junit.Assert.assertTrue;
-public class BaeldungReflectionUtilsTest {
+public class BaeldungReflectionUtilsUnitTest {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java
rename to core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java
index 47c9cfc621..d903a02589 100644
--- a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java
+++ b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java
@@ -10,7 +10,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
-public class EscapingCharsTest {
+public class EscapingCharsUnitTest {
@Test
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
String strInput = "foof";
diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
index 7f165cec86..9abe8a927c 100644
--- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java
@@ -104,7 +104,7 @@ public class NashornUnitTest {
public void loadExamples() throws ScriptException {
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
- Assert.assertEquals(6.0, loadResult);
+ Assert.assertEquals(6, ((Double) loadResult).intValue());
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java
similarity index 90%
rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java
rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java
index cd31f545b9..8d8e4f14fe 100644
--- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java
+++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java
@@ -4,7 +4,7 @@ import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
-public class SneakyRunnableTest {
+public class SneakyRunnableUnitTest {
@Test
public void whenCallSneakyRunnableMethod_thenThrowException() {
diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java
similarity index 91%
rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java
rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java
index e033ca062d..da1b2e617b 100644
--- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java
+++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java
@@ -4,7 +4,7 @@ import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
-public class SneakyThrowsTest {
+public class SneakyThrowsUnitTest {
@Test
public void whenCallSneakyMethod_thenThrowSneakyException() {
diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
index 70c6e88c49..103824b6aa 100644
--- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
@@ -1,21 +1,29 @@
package com.baeldung.socket;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.util.concurrent.Executors;
+
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import java.util.concurrent.Executors;
-
-import static org.junit.Assert.assertEquals;
-
public class EchoIntegrationTest {
- private static final Integer PORT = 4444;
+ private static int port;
@BeforeClass
- public static void start() throws InterruptedException {
+ public static void start() throws InterruptedException, IOException {
+
+ // Take an available port
+ ServerSocket s = new ServerSocket(0);
+ port = s.getLocalPort();
+ s.close();
+
Executors.newSingleThreadExecutor()
- .submit(() -> new EchoServer().start(PORT));
+ .submit(() -> new EchoServer().start(port));
Thread.sleep(500);
}
@@ -23,7 +31,7 @@ public class EchoIntegrationTest {
@Before
public void init() {
- client.startConnection("127.0.0.1", PORT);
+ client.startConnection("127.0.0.1", port);
}
@After
diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java
index 4367ed26a2..2bded156c5 100644
--- a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java
@@ -1,31 +1,39 @@
package com.baeldung.socket;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.util.concurrent.Executors;
+
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import java.util.concurrent.Executors;
-
-import static org.junit.Assert.assertEquals;
-
public class GreetServerIntegrationTest {
private GreetClient client;
- private static final Integer PORT = 6666;
+ private static int port;
@BeforeClass
- public static void start() throws InterruptedException {
+ public static void start() throws InterruptedException, IOException {
+
+ // Take an available port
+ ServerSocket s = new ServerSocket(0);
+ port = s.getLocalPort();
+ s.close();
+
Executors.newSingleThreadExecutor()
- .submit(() -> new GreetServer().start(PORT));
+ .submit(() -> new GreetServer().start(port));
Thread.sleep(500);
}
@Before
public void init() {
client = new GreetClient();
- client.startConnection("127.0.0.1", PORT);
+ client.startConnection("127.0.0.1", port);
}
diff --git a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java
index 6ebc0946c5..62e2dd44ae 100644
--- a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java
+++ b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java
@@ -1,26 +1,35 @@
package com.baeldung.socket;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
+import java.io.IOException;
+import java.net.ServerSocket;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
public class SocketEchoMultiIntegrationTest {
- private static final Integer PORT = 5555;
+ private static int port;
@BeforeClass
- public static void start() throws InterruptedException {
- Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT));
+ public static void start() throws InterruptedException, IOException {
+
+ // Take an available port
+ ServerSocket s = new ServerSocket(0);
+ port = s.getLocalPort();
+ s.close();
+
+ Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port));
Thread.sleep(500);
}
@Test
public void givenClient1_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", PORT);
+ client.startConnection("127.0.0.1", port);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
@@ -34,7 +43,7 @@ public class SocketEchoMultiIntegrationTest {
@Test
public void givenClient2_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", PORT);
+ client.startConnection("127.0.0.1", port);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
@@ -47,7 +56,7 @@ public class SocketEchoMultiIntegrationTest {
@Test
public void givenClient3_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient();
- client.startConnection("127.0.0.1", PORT);
+ client.startConnection("127.0.0.1", port);
String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world");
String terminate = client.sendMessage(".");
diff --git a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/string/PalindromeTest.java
rename to core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java
index bc6fee2cd9..49f2542f39 100644
--- a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java
+++ b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.string;
import static org.junit.Assert.*;
import org.junit.Test;
-public class PalindromeTest {
+public class PalindromeUnitTest {
private String[] words = {
"Anna",
diff --git a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
similarity index 99%
rename from core-java/src/test/java/com/baeldung/string/StringComparisonTest.java
rename to core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
index 5869676004..539f66d9b4 100644
--- a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java
+++ b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
@@ -7,7 +7,7 @@ import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
-public class StringComparisonTest {
+public class StringComparisonUnitTest {
@Test
public void whenUsingComparisonOperator_ThenComparingStrings(){
diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java
similarity index 99%
rename from core-java/src/test/java/com/baeldung/string/StringTest.java
rename to core-java/src/test/java/com/baeldung/string/StringUnitTest.java
index e88b2d7c2c..0d4fd6eff9 100644
--- a/core-java/src/test/java/com/baeldung/string/StringTest.java
+++ b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java
@@ -12,7 +12,7 @@ import java.util.regex.PatternSyntaxException;
import org.junit.Test;
-public class StringTest {
+public class StringUnitTest {
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
diff --git a/core-java/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java b/core-java/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java
new file mode 100644
index 0000000000..2272565cd3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.string;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class TitleCaseConverterUnitTest {
+
+ private static final String TEXT = "tHis IS a tiTLe";
+ private static final String TEXT_EXPECTED = "This Is A Title";
+ private static final String TEXT_EXPECTED_NOT_FULL = "THis IS A TiTLe";
+
+ private static final String TEXT_OTHER_DELIMITERS = "tHis, IS a tiTLe";
+ private static final String TEXT_EXPECTED_OTHER_DELIMITERS = "This, Is A Title";
+ private static final String TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL = "THis, IS A TiTLe";
+
+ @Test
+ public void whenConvertingToTitleCaseIterating_thenStringConverted() {
+ assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT));
+ }
+
+ @Test
+ public void whenConvertingToTitleCaseSplitting_thenStringConverted() {
+ assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseSplitting(TEXT));
+ }
+
+ @Test
+ public void whenConvertingToTitleCaseUsingWordUtilsFull_thenStringConverted() {
+ assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT));
+ }
+
+ @Test
+ public void whenConvertingToTitleCaseUsingWordUtils_thenStringConvertedOnlyFirstCharacter() {
+ assertEquals(TEXT_EXPECTED_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT));
+ }
+
+ @Test
+ public void whenConvertingToTitleCaseUsingIcu4j_thenStringConverted() {
+ assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT));
+ }
+
+ @Test
+ public void whenConvertingToTitleCaseWithDifferentDelimiters_thenDelimitersKept() {
+ assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT_OTHER_DELIMITERS));
+ assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseSplitting(TEXT_OTHER_DELIMITERS));
+ assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT_OTHER_DELIMITERS));
+ assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT_OTHER_DELIMITERS));
+ assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT_OTHER_DELIMITERS));
+ }
+
+ @Test
+ public void givenNull_whenConvertingToTileCase_thenReturnNull() {
+ assertEquals(null, TitleCaseConverter.convertToTitleCaseIteratingChars(null));
+ assertEquals(null, TitleCaseConverter.convertToTitleCaseSplitting(null));
+ assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtilsFull(null));
+ assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtils(null));
+ assertEquals(null, TitleCaseConverter.convertToTitleCaseIcu4j(null));
+ }
+
+ @Test
+ public void givenEmptyString_whenConvertingToTileCase_thenReturnEmptyString() {
+ assertEquals("", TitleCaseConverter.convertToTitleCaseIteratingChars(""));
+ assertEquals("", TitleCaseConverter.convertToTitleCaseSplitting(""));
+ assertEquals("", TitleCaseConverter.convertToTileCaseWordUtilsFull(""));
+ assertEquals("", TitleCaseConverter.convertToTileCaseWordUtils(""));
+ assertEquals("", TitleCaseConverter.convertToTitleCaseIcu4j(""));
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
similarity index 99%
rename from core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java
rename to core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
index ad4f5dce7e..648fdaf65a 100644
--- a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java
+++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
@@ -8,7 +8,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class StringFormatterExampleTests {
+public class StringFormatterExampleUnitTest {
@Test
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric.zip b/core-java/src/test/java/com/baeldung/stringisnumeric.zip
new file mode 100644
index 0000000000..b8a7b9b35a
Binary files /dev/null and b/core-java/src/test/java/com/baeldung/stringisnumeric.zip differ
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java
new file mode 100644
index 0000000000..808d3c45b0
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.stringisnumeric;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class CoreJavaIsNumericUnitTest {
+ public static boolean isNumeric(String strNum) {
+ try {
+ double d = Double.parseDouble(strNum);
+ } catch (NumberFormatException | NullPointerException nfe) {
+ return false;
+ }
+ return true;
+ }
+
+ @Test
+ public void whenUsingCoreJava_thenTrue() {
+ // Valid Numbers
+ assertThat(isNumeric("22")).isTrue();
+ assertThat(isNumeric("5.05")).isTrue();
+ assertThat(isNumeric("-200")).isTrue();
+ assertThat(isNumeric("10.0d")).isTrue();
+ assertThat(isNumeric(" 22 ")).isTrue();
+
+ // Invalid Numbers
+ assertThat(isNumeric(null)).isFalse();
+ assertThat(isNumeric("")).isFalse();
+ assertThat(isNumeric("abc")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java
new file mode 100644
index 0000000000..467d58837a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.stringisnumeric;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.commons.lang3.math.NumberUtils;
+import org.junit.Test;
+
+public class NumberUtilsIsCreatableUnitTest {
+ @Test
+ public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
+ // Valid Numbers
+ assertThat(NumberUtils.isCreatable("22")).isTrue();
+ assertThat(NumberUtils.isCreatable("5.05")).isTrue();
+ assertThat(NumberUtils.isCreatable("-200")).isTrue();
+ assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
+ assertThat(NumberUtils.isCreatable("1000L")).isTrue();
+ assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
+ assertThat(NumberUtils.isCreatable("07")).isTrue();
+ assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
+
+ // Invalid Numbers
+ assertThat(NumberUtils.isCreatable(null)).isFalse();
+ assertThat(NumberUtils.isCreatable("")).isFalse();
+ assertThat(NumberUtils.isCreatable("abc")).isFalse();
+ assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
+ assertThat(NumberUtils.isCreatable("09")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java
new file mode 100644
index 0000000000..141a761158
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.stringisnumeric;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.commons.lang3.math.NumberUtils;
+import org.junit.Test;
+
+public class NumberUtilsIsParsableUnitTest {
+ @Test
+ public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
+ // Valid Numbers
+ assertThat(NumberUtils.isParsable("22")).isTrue();
+ assertThat(NumberUtils.isParsable("-23")).isTrue();
+ assertThat(NumberUtils.isParsable("2.2")).isTrue();
+ assertThat(NumberUtils.isParsable("09")).isTrue();
+
+ // Invalid Numbers
+ assertThat(NumberUtils.isParsable(null)).isFalse();
+ assertThat(NumberUtils.isParsable("")).isFalse();
+ assertThat(NumberUtils.isParsable("6.2f")).isFalse();
+ assertThat(NumberUtils.isParsable("9.8d")).isFalse();
+ assertThat(NumberUtils.isParsable("22L")).isFalse();
+ assertThat(NumberUtils.isParsable("0xFF")).isFalse();
+ assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java
new file mode 100644
index 0000000000..c3aa43ac94
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.stringisnumeric;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class RegularExpressionsUnitTest {
+ public static boolean isNumeric(String strNum) {
+ return strNum.matches("-?\\d+(\\.\\d+)?");
+ }
+
+ @Test
+ public void whenUsingRegularExpressions_thenTrue() {
+ // Valid Numbers
+ assertThat(isNumeric("22")).isTrue();
+ assertThat(isNumeric("5.05")).isTrue();
+ assertThat(isNumeric("-200")).isTrue();
+
+ // Invalid Numbers
+ assertThat(isNumeric("abc")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java
new file mode 100644
index 0000000000..135780d9ad
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java
@@ -0,0 +1,23 @@
+package com.baeldung.stringisnumeric;
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class StringUtilsIsNumericSpaceUnitTest {
+ @Test
+ public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
+ // Valid Numbers
+ assertThat(StringUtils.isNumericSpace("123")).isTrue();
+ assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
+ assertThat(StringUtils.isNumericSpace("")).isTrue();
+ assertThat(StringUtils.isNumericSpace(" ")).isTrue();
+ assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
+
+ // Invalid Numbers
+ assertThat(StringUtils.isNumericSpace(null)).isFalse();
+ assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
+ assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
+ assertThat(StringUtils.isNumericSpace("-123")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java b/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java
new file mode 100644
index 0000000000..b667dda906
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.stringisnumeric;
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class StringUtilsIsNumericUnitTest {
+ @Test
+ public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
+ // Valid Numbers
+ assertThat(StringUtils.isNumeric("123")).isTrue();
+ assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
+ assertThat(StringUtils.isNumeric("१२३")).isTrue();
+
+ // Invalid Numbers
+ assertThat(StringUtils.isNumeric(null)).isFalse();
+ assertThat(StringUtils.isNumeric("")).isFalse();
+ assertThat(StringUtils.isNumeric(" ")).isFalse();
+ assertThat(StringUtils.isNumeric("12 3")).isFalse();
+ assertThat(StringUtils.isNumeric("ab2c")).isFalse();
+ assertThat(StringUtils.isNumeric("12.3")).isFalse();
+ assertThat(StringUtils.isNumeric("-123")).isFalse();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java
similarity index 90%
rename from core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java
rename to core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java
index 587cd4ef20..ef083dd25e 100644
--- a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java
+++ b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
-public class DateTimeServiceTest {
+public class DateTimeServiceUnitTest {
@Test
public void givenClass_whenCalledMethods_thenNotNullInResult() {
diff --git a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java
similarity index 87%
rename from core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java
rename to core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java
index 3722fea88f..5e4db747be 100644
--- a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java
+++ b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
-public class EnvironmentVariablesTest {
+public class EnvironmentVariablesUnitTest {
@Test
public void givenEnvVars_whenReadPath_thenGetValueinResult() {
diff --git a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java
similarity index 95%
rename from core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java
rename to core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java
index f54e3702c8..bf715f3ac3 100644
--- a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java
+++ b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
-public class SystemArrayCopyTest {
+public class SystemArrayCopyUnitTest {
@Test
public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() {
diff --git a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java
similarity index 91%
rename from core-java/src/test/java/com/baeldung/system/SystemNanoTest.java
rename to core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java
index bf6590da0a..cd9543212e 100644
--- a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java
+++ b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java
@@ -3,7 +3,7 @@ package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
-public class SystemNanoTest {
+public class SystemNanoUnitTest {
@Test
public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() {
diff --git a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java
rename to core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java
index 4fca27f96c..4940e39238 100644
--- a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java
+++ b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import java.util.Properties;
-public class SystemPropertiesTest {
+public class SystemPropertiesUnitTest {
@Test
public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() {
diff --git a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java
similarity index 93%
rename from core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java
rename to core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java
index 77901f6524..27a6dd43c6 100644
--- a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java
+++ b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java
@@ -5,7 +5,7 @@ import org.junit.Ignore;
import org.junit.Test;
@Ignore
-public class WhenDetectingOSTest {
+public class WhenDetectingOSUnitTest {
private DetectOS os = new DetectOS();
diff --git a/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java b/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java
new file mode 100644
index 0000000000..85cff51eb3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.thread.join;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.logging.Logger;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Demonstrates Thread.join behavior.
+ *
+ */
+public class ThreadJoinUnitTest {
+
+ final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
+
+ class SampleThread extends Thread {
+ public int processingCount = 0;
+
+ SampleThread(int processingCount) {
+ this.processingCount = processingCount;
+ LOGGER.info("Thread " + this.getName() + " created");
+ }
+
+ @Override
+ public void run() {
+ LOGGER.info("Thread " + this.getName() + " started");
+ while (processingCount > 0) {
+ try {
+ Thread.sleep(1000); // Simulate some work being done by thread
+ } catch (InterruptedException e) {
+ LOGGER.info("Thread " + this.getName() + " interrupted.");
+ }
+ processingCount--;
+ LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
+ }
+ LOGGER.info("Thread " + this.getName() + " exiting");
+ }
+ }
+
+ @Test
+ public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
+ Thread t1 = new SampleThread(0);
+ LOGGER.info("Invoking join.");
+ t1.join();
+ LOGGER.info("Returned from join");
+ LOGGER.info("Thread state is" + t1.getState());
+ assertFalse(t1.isAlive());
+ }
+
+ @Test
+ public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
+ throws InterruptedException {
+ Thread t2 = new SampleThread(1);
+ t2.start();
+ LOGGER.info("Invoking join.");
+ t2.join();
+ LOGGER.info("Returned from join");
+ assertFalse(t2.isAlive());
+ }
+
+ @Test
+ public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
+ throws InterruptedException {
+ Thread t3 = new SampleThread(10);
+ t3.start();
+ t3.join(1000);
+ assertTrue(t3.isAlive());
+ }
+
+ @Test
+ @Ignore
+ public void givenThreadTerminated_checkForEffect_notGuaranteed()
+ throws InterruptedException {
+ SampleThread t4 = new SampleThread(10);
+ t4.start();
+ //not guaranteed to stop even if t4 finishes.
+ do {
+
+ } while (t4.processingCount > 0);
+ }
+
+ @Test
+ public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
+ throws InterruptedException {
+ SampleThread t4 = new SampleThread(10);
+ t4.start();
+ do {
+ t4.join(100);
+ } while (t4.processingCount > 0);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java
rename to core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java
index c75813baba..56c77f923f 100644
--- a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java
+++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java
@@ -5,7 +5,7 @@ import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class ThreadLocalRandomTest {
+public class ThreadLocalRandomIntegrationTest {
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
diff --git a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
similarity index 96%
rename from core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java
rename to core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
index fa3c425156..eea3068253 100644
--- a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java
+++ b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
@@ -7,7 +7,7 @@ import java.util.Properties;
import static org.junit.Assert.assertEquals;
-public class PropertiesLoaderTest {
+public class PropertiesLoaderUnitTest {
@Test
public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException {
diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java
similarity index 97%
rename from core-java/src/test/java/com/baeldung/varargs/FormatterTest.java
rename to core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java
index 509c8764d2..e9018afd62 100644
--- a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java
+++ b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java
@@ -5,7 +5,7 @@ import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-public class FormatterTest {
+public class FormatterUnitTest {
private final static String FORMAT = "%s %s %s";
diff --git a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java
similarity index 91%
rename from core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java
rename to core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java
index 2b36786abf..161c053cea 100644
--- a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java
+++ b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java
@@ -5,7 +5,7 @@ import java.util.List;
import org.junit.Test;
-public class RawTypesTest {
+public class RawTypesUnitTest {
@Test
public void shouldCreateListUsingRawTypes() {
@SuppressWarnings("rawtypes")
diff --git a/core-java/src/test/resources/correctFileNameWithoutProperExtension b/core-java/src/test/resources/correctFileNameWithoutProperExtension
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/core-kotlin/README.md b/core-kotlin/README.md
index d6bd41a111..7fcdc68429 100644
--- a/core-kotlin/README.md
+++ b/core-kotlin/README.md
@@ -24,3 +24,9 @@
- [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions)
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)
- [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file)
+- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation)
+- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
+- [Writing to a File in Kotlin](http://www.baeldung.com/kotlin-write-file)
+- [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions)
+- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek)
+- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson)
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index b5aeb264e1..1dd804eedd 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -2,7 +2,6 @@
4.0.0
-
core-kotlin
1.0-SNAPSHOT
jar
@@ -26,12 +25,6 @@
commons-math3
${commons-math3.version}
-
- org.junit.jupiter
- junit-jupiter-engine
- ${junit.jupiter.version}
- test
-
org.junit.platform
junit-platform-runner
@@ -51,7 +44,7 @@
khttp
khttp
- 0.1.0
+ ${khttp.version}
org.jetbrains.kotlin
@@ -70,6 +63,24 @@
kotlinx-coroutines-core
${kotlinx.version}
+
+ org.jetbrains.spek
+ spek-api
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-subject-extension
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-junit-platform-engine
+ 1.1.5
+ test
+
com.nhaarman
mockito-kotlin
@@ -87,13 +98,18 @@
${assertj.version}
test
+
+ com.beust
+ klaxon
+ ${klaxon.version}
+
- kotlin-maven-plugin
org.jetbrains.kotlin
+ kotlin-maven-plugin
${kotlin-maven-plugin.version}
@@ -125,11 +141,11 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.7.0
+ ${maven-compiler-plugin.version}
- 1.8
- 1.8
-
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
@@ -161,7 +177,7 @@
maven-failsafe-plugin
- 2.19.1
+ ${maven-failsafe-plugin.version}
org.junit.platform
@@ -189,21 +205,24 @@
UTF-8
- 1.2.31
- 1.2.31
- 1.2.31
- 1.2.31
- 0.15
+ 1.2.41
+ 1.2.41
+ 1.2.41
+ 1.2.41
+ 0.22.5
1.5.0
4.1.0
-
+ 3.0.4
+ 2.21.0
+ 0.1.0
3.6.1
-
- 5.0.0
- 1.0.0
- 4.12.0
+ 5.2.0
+ 1.2.0
+ 5.2.0
4.12
- 3.9.1
+ 3.10.0
+ 1.8
+ 1.8
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt
new file mode 100644
index 0000000000..69cfce5601
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt
@@ -0,0 +1,23 @@
+package com.baeldung.enums
+
+enum class CardType(val color: String) : ICardLimit {
+ SILVER("gray") {
+ override fun getCreditLimit() = 100000
+ override fun calculateCashbackPercent() = 0.25f
+ },
+ GOLD("yellow") {
+ override fun getCreditLimit() = 200000
+ override fun calculateCashbackPercent(): Float = 0.5f
+ },
+ PLATINUM("black") {
+ override fun getCreditLimit() = 300000
+ override fun calculateCashbackPercent() = 0.75f
+ };
+
+ companion object {
+ fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color }
+ fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
+ }
+
+ abstract fun calculateCashbackPercent(): Float
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt
new file mode 100644
index 0000000000..7994822a52
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt
@@ -0,0 +1,5 @@
+package com.baeldung.enums
+
+interface ICardLimit {
+ fun getCreditLimit(): Int
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt
new file mode 100644
index 0000000000..6dc9b95f1f
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt
@@ -0,0 +1,19 @@
+package com.baeldung.filesystem
+
+import java.io.File
+
+class FileWriter {
+
+ fun writeFileUsingPrintWriter(fileName: String, fileContent: String) =
+ File(fileName).printWriter().use { out -> out.print(fileContent) }
+
+ fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) =
+ File(fileName).bufferedWriter().use { out -> out.write(fileContent) }
+
+ fun writeFileDirectly(fileName: String, fileContent: String) =
+ File(fileName).writeText(fileContent)
+
+ fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) =
+ File(fileName).writeBytes(fileContent.toByteArray())
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt
new file mode 100644
index 0000000000..cc46c65f96
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt
@@ -0,0 +1,9 @@
+package com.baeldung.klaxon
+
+import com.beust.klaxon.Json
+
+class CustomProduct(
+ @Json(name = "productName")
+ val name: String,
+ @Json(ignored = true)
+ val id: Int)
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt
new file mode 100644
index 0000000000..09bcbc8722
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt
@@ -0,0 +1,3 @@
+package com.baeldung.klaxon
+
+class Product(val name: String)
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt
new file mode 100644
index 0000000000..1f30f26ce9
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt
@@ -0,0 +1,3 @@
+package com.baeldung.klaxon
+
+data class ProductData(val name: String, val capacityInGb: Int)
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/lambda/Lambda.kt b/core-kotlin/src/main/kotlin/com/baeldung/lambda/Lambda.kt
new file mode 100644
index 0000000000..f35f9cdac2
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/lambda/Lambda.kt
@@ -0,0 +1,84 @@
+package com.baeldung.lambda
+
+fun inferredType(input: Int): Int {
+ val square = { number: Int -> number * number }
+
+ return square(input)
+}
+
+fun intToBiggerString(argument: Int): String {
+
+ val magnitude100String = { input: Int ->
+ val magnitude = input * 100
+ magnitude.toString()
+ }
+
+ return magnitude100String(argument)
+}
+
+fun manyLambda(nums: Array): List {
+ val newList = nums.map { intToBiggerString(it) }
+
+ return newList
+}
+
+fun empty() {
+ val noReturn: (Int) -> Unit = { num -> println(num) }
+
+ noReturn(5)
+}
+
+fun invokeLambda(lambda: (Double) -> Boolean): Boolean {
+ return lambda(4.329)
+}
+
+fun extendString(arg: String, num: Int): String {
+ val another: String.(Int) -> String = { this + it }
+
+ return arg.another(num)
+}
+
+fun getCalculationLambda(): (Int) -> Any {
+ val calculateGrade = { grade: Int ->
+ when (grade) {
+ in 0..40 -> "Fail"
+ in 41..70 -> "Pass"
+ in 71..100 -> "Distinction"
+ else -> false
+ }
+ }
+
+ return calculateGrade
+}
+
+fun getCalculationLambdaWithReturn(): (Int) -> String {
+ val calculateGrade: Int.() -> String = lambda@{
+ if (this < 0 || this > 100) {
+ return@lambda "Error"
+ } else if (this < 40) {
+ return@lambda "Fail"
+ } else if (this < 70) {
+ return@lambda "Pass"
+ }
+
+ "Distinction"
+ }
+
+ return calculateGrade
+}
+
+fun getCalculationAnonymousFunction(): (Int) -> String {
+ val calculateGrade = fun(grade: Int): String {
+ if (grade < 0 || grade > 100) {
+ return "Error"
+ } else if (grade < 40) {
+ return "Fail"
+ } else if (grade < 70) {
+ return "Pass"
+ }
+
+ return "Distinction"
+ }
+
+ return calculateGrade
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt b/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt
new file mode 100644
index 0000000000..4b2d863618
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt
@@ -0,0 +1,115 @@
+package com.baeldung.stringtemplates
+
+/**
+ * Example of a useful function defined in Kotlin String class
+ */
+fun padExample(): String {
+ return "Hello".padEnd(10, '!')
+}
+
+/**
+ * Example of a simple string template usage
+ */
+fun simpleTemplate(n: Int): String {
+ val message = "n = $n"
+ return message
+}
+
+/**
+ * Example of a string template with a simple expression
+ */
+fun templateWithExpression(n: Int): String {
+ val message = "n + 1 = ${n + 1}"
+ return message
+}
+
+/**
+ * Example of a string template with expression containing some logic
+ */
+fun templateWithLogic(n: Int): String {
+ val message = "$n is ${if (n > 0) "positive" else "not positive"}"
+ return message
+}
+
+/**
+ * Example of nested string templates
+ */
+fun nestedTemplates(n: Int): String {
+ val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}"
+ return message
+}
+
+/**
+ * Example of joining array's element into a string with a default separator
+ */
+fun templateJoinArray(): String {
+ val numbers = listOf(1, 1, 2, 3, 5, 8)
+ val message = "first Fibonacci numbers: ${numbers.joinToString()}"
+ return message
+}
+
+/**
+ * Example of escaping the dollar sign
+ */
+fun notAStringTemplate(): String {
+ val message = "n = \$n"
+ return message
+}
+
+/**
+ * Example of a simple triple quoted string
+ */
+fun showFilePath(): String {
+ val path = """C:\Repository\read.me"""
+ return path
+}
+
+/**
+ * Example of a multiline string
+ */
+fun showMultiline(): String {
+ val receipt = """Item 1: $1.00
+Item 2: $0.50"""
+ return receipt
+}
+
+/**
+ * Example of a multiline string with indentation
+ */
+fun showMultilineIndent(): String {
+ val receipt = """Item 1: $1.00
+ >Item 2: $0.50""".trimMargin(">")
+ return receipt
+}
+
+/**
+ * Example of a triple quoted string with a not-working escape sequence
+ */
+fun showTripleQuotedWrongEscape(): String {
+ val receipt = """Item 1: $1.00\nItem 2: $0.50"""
+ return receipt
+}
+
+/**
+ * Example of a triple quoted string with a correctly working escape sequence
+ */
+
+fun showTripleQuotedCorrectEscape(): String {
+ val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50"""
+ return receipt
+}
+
+fun main(args: Array) {
+ println(padExample())
+ println(simpleTemplate(10))
+ println(templateWithExpression(5))
+ println(templateWithLogic(7))
+ println(nestedTemplates(-5))
+ println(templateJoinArray())
+ println(notAStringTemplate())
+ println(showFilePath())
+ println(showMultiline())
+ println(showMultilineIndent())
+ println(showTripleQuotedWrongEscape())
+ println(showTripleQuotedCorrectEscape())
+}
diff --git a/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java b/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java
new file mode 100644
index 0000000000..1e68d8af4c
--- /dev/null
+++ b/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.lambda;
+
+import kotlin.jvm.functions.Function1;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Created by Paul Jervis on 24/04/2018.
+ */
+class LambdaKotlinTest {
+
+ @Test
+ void givenJava6_whenUsingAnonnymousClass_thenReturnLambdaResult() {
+ assertTrue(LambdaKt.invokeLambda(new Function1() {
+ @Override
+ public Boolean invoke(Double c) {
+ return c >= 0;
+ }
+ }));
+ }
+
+ @Test
+ void givenJava8_whenUsingLambda_thenReturnLambdaResult() {
+ assertTrue(LambdaKt.invokeLambda(c -> c >= 0));
+ }
+
+ @Test
+ void givenJava8_whenCallingMethodWithStringExtension_thenImplementExtension() {
+ String actual = LambdaKt.extendString("Word", 90);
+ String expected = "Word90";
+
+ assertEquals(expected, actual);
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt
new file mode 100644
index 0000000000..525faebd55
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt
@@ -0,0 +1,84 @@
+package com.baeldung.enums
+
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+
+internal class CardTypeUnitTest {
+
+ @Test
+ fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
+ assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent())
+ }
+
+ @Test
+ fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
+ assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent())
+ }
+
+ @Test
+ fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
+ assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent())
+ }
+
+ @Test
+ fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() {
+ assertEquals(100000, CardType.SILVER.getCreditLimit())
+ }
+
+ @Test
+ fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() {
+ assertEquals(200000, CardType.GOLD.getCreditLimit())
+ }
+
+ @Test
+ fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() {
+ assertEquals(300000, CardType.PLATINUM.getCreditLimit())
+ }
+
+ @Test
+ fun givenSilverCardType_whenCheckColor_thenReturnColor() {
+ assertEquals("gray", CardType.SILVER.color)
+ }
+
+ @Test
+ fun givenGoldCardType_whenCheckColor_thenReturnColor() {
+ assertEquals("yellow", CardType.GOLD.color)
+ }
+
+ @Test
+ fun givenPlatinumCardType_whenCheckColor_thenReturnColor() {
+ assertEquals("black", CardType.PLATINUM.color)
+ }
+
+ @Test
+ fun whenGetCardTypeByColor_thenSilverCardType() {
+ Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray"))
+ }
+
+ @Test
+ fun whenGetCardTypeByColor_thenGoldCardType() {
+ Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow"))
+ }
+
+ @Test
+ fun whenGetCardTypeByColor_thenPlatinumCardType() {
+ Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenSilverCardType() {
+ Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenGoldCardType() {
+ Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold"))
+ }
+
+ @Test
+ fun whenGetCardTypeByName_thenPlatinumCardType() {
+ Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum"))
+ }
+
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt
new file mode 100644
index 0000000000..91c66a4fee
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt
@@ -0,0 +1,43 @@
+package com.baeldung.filesystem
+
+import org.junit.jupiter.api.Test
+import java.io.File
+import kotlin.test.assertEquals
+
+internal class FileWriterTest {
+
+ private val fileName = "src/test/resources/Kotlin.out"
+
+ private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly"
+
+ private val fileWriter = FileWriter()
+
+ @Test
+ fun whenWrittenWithPrintWriter_thenCorrect() {
+ fileWriter.writeFileUsingPrintWriter(fileName, fileContent)
+
+ assertEquals(fileContent, File(fileName).readText())
+ }
+
+ @Test
+ fun whenWrittenWithBufferedWriter_thenCorrect() {
+ fileWriter.writeFileUsingBufferedWriter(fileName, fileContent)
+
+ assertEquals(fileContent, File(fileName).readText())
+ }
+
+ @Test
+ fun whenWrittenDirectly_thenCorrect() {
+ fileWriter.writeFileDirectly(fileName, fileContent)
+
+ assertEquals(fileContent, File(fileName).readText())
+ }
+
+ @Test
+ fun whenWrittenDirectlyAsBytes_thenCorrect() {
+ fileWriter.writeFileDirectlyAsBytes(fileName, fileContent)
+
+ assertEquals(fileContent, File(fileName).readText())
+ }
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt
new file mode 100644
index 0000000000..2a7d44a163
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt
@@ -0,0 +1,163 @@
+package com.baeldung.klaxon
+
+import com.beust.klaxon.JsonArray
+import com.beust.klaxon.JsonObject
+import com.beust.klaxon.JsonReader
+import com.beust.klaxon.Klaxon
+import com.beust.klaxon.Parser
+import com.beust.klaxon.PathMatcher
+import org.assertj.core.api.Assertions.assertThat
+import org.assertj.core.api.SoftAssertions.assertSoftly
+import org.junit.Assert
+import org.junit.jupiter.api.Test
+import java.io.StringReader
+import java.util.regex.Pattern
+
+class KlaxonUnitTest {
+
+ @Test
+ fun giveProduct_whenSerialize_thenGetJsonString() {
+ val product = Product("HDD")
+ val result = Klaxon().toJsonString(product)
+
+ assertThat(result).isEqualTo("""{"name" : "HDD"}""")
+ }
+
+ @Test
+ fun giveJsonString_whenDeserialize_thenGetProduct() {
+ val result = Klaxon().parse("""
+ {
+ "name" : "RAM"
+ }
+ """)
+
+ assertThat(result?.name).isEqualTo("RAM")
+ }
+
+ @Test
+ fun giveCustomProduct_whenSerialize_thenGetJsonString() {
+ val product = CustomProduct("HDD", 1)
+ val result = Klaxon().toJsonString(product)
+
+ assertThat(result).isEqualTo("""{"productName" : "HDD"}""")
+ }
+
+ @Test
+ fun giveJsonArray_whenStreaming_thenGetProductArray() {
+ val jsonArray = """
+ [
+ { "name" : "HDD", "capacityInGb" : 512 },
+ { "name" : "RAM", "capacityInGb" : 16 }
+ ]"""
+ val expectedArray = arrayListOf(ProductData("HDD", 512),
+ ProductData("RAM", 16))
+ val klaxon = Klaxon()
+ val productArray = arrayListOf()
+ JsonReader(StringReader(jsonArray)).use { reader ->
+ reader.beginArray {
+ while (reader.hasNext()) {
+ val product = klaxon.parse(reader)
+ productArray.add(product!!)
+ }
+ }
+ }
+
+ assertThat(productArray).hasSize(2).isEqualTo(expectedArray)
+ }
+
+ @Test
+ fun giveJsonString_whenParser_thenGetJsonObject() {
+ val jsonString = StringBuilder("""
+ {
+ "name" : "HDD",
+ "capacityInGb" : 512,
+ "sizeInInch" : 2.5
+ }
+ """)
+ val parser = Parser()
+ val json = parser.parse(jsonString) as JsonObject
+
+ assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5)
+ }
+
+ @Suppress("UNCHECKED_CAST")
+ @Test
+ fun giveJsonStringArray_whenParser_thenGetJsonArray() {
+ val jsonString = StringBuilder("""
+ [
+ { "name" : "SDD" },
+ { "madeIn" : "Taiwan" },
+ { "warrantyInYears" : 5 }
+ ]""")
+ val parser = Parser()
+ val json = parser.parse(jsonString) as JsonArray
+
+ assertSoftly({ softly ->
+ softly.assertThat(json).hasSize(3)
+ softly.assertThat(json[0]["name"]).isEqualTo("SDD")
+ softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan")
+ softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5)
+ })
+ }
+
+ @Test
+ fun givenJsonString_whenStreaming_thenProcess() {
+ val jsonString = """
+ {
+ "name" : "HDD",
+ "madeIn" : "Taiwan",
+ "warrantyInYears" : 5
+ "hasStock" : true
+ "capacitiesInTb" : [ 1, 2 ],
+ "features" : { "cacheInMb" : 64, "speedInRpm" : 7200 }
+ }"""
+
+ JsonReader(StringReader(jsonString)).use { reader ->
+ reader.beginObject {
+ while (reader.hasNext()) {
+ val readName = reader.nextName()
+ when (readName) {
+ "name" -> assertThat(reader.nextString()).isEqualTo("HDD")
+ "madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan")
+ "warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5)
+ "hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true)
+ "capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2)
+ "features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200)
+ else -> Assert.fail("Unexpected name: $readName")
+ }
+ }
+ }
+ }
+
+ }
+
+ @Test
+ fun givenDiskInventory_whenRegexMatches_thenGetTypes() {
+ val jsonString = """
+ {
+ "inventory" : {
+ "disks" : [
+ {
+ "type" : "HDD",
+ "sizeInGb" : 1000
+ },
+ {
+ "type" : "SDD",
+ "sizeInGb" : 512
+ }
+ ]
+ }
+ }"""
+ val pathMatcher = object : PathMatcher {
+ override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path)
+
+ override fun onMatch(path: String, value: Any) {
+ when (path) {
+ "$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD")
+ "$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD")
+ }
+ }
+ }
+ Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString))
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt
new file mode 100644
index 0000000000..0d0e7b724d
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt
@@ -0,0 +1,32 @@
+package com.baeldung.kotlin.reflection
+
+import org.junit.Ignore
+import org.junit.Test
+import org.slf4j.LoggerFactory
+
+@Ignore
+class JavaReflectionTest {
+ private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
+
+ @Test
+ fun listJavaClassMethods() {
+ Exception::class.java.methods
+ .forEach { method -> LOG.info("Method: {}", method) }
+ }
+
+ @Test
+ fun listKotlinClassMethods() {
+ JavaReflectionTest::class.java.methods
+ .forEach { method -> LOG.info("Method: {}", method) }
+ }
+
+ @Test
+ fun listKotlinDataClassMethods() {
+ data class ExampleDataClass(val name: String, var enabled: Boolean)
+
+ ExampleDataClass::class.java.methods
+ .forEach { method -> LOG.info("Method: {}", method) }
+ }
+
+
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt
new file mode 100644
index 0000000000..56183b50be
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt
@@ -0,0 +1,69 @@
+package com.baeldung.kotlin.reflection
+
+import org.junit.Assert
+import org.junit.Ignore
+import org.junit.Test
+import org.slf4j.LoggerFactory
+import java.math.BigDecimal
+import kotlin.reflect.full.*
+
+class KClassTest {
+ private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
+
+ @Test
+ fun testKClassDetails() {
+ val stringClass = String::class
+ Assert.assertEquals("kotlin.String", stringClass.qualifiedName)
+ Assert.assertFalse(stringClass.isData)
+ Assert.assertFalse(stringClass.isCompanion)
+ Assert.assertFalse(stringClass.isAbstract)
+ Assert.assertTrue(stringClass.isFinal)
+ Assert.assertFalse(stringClass.isSealed)
+
+ val listClass = List::class
+ Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName)
+ Assert.assertFalse(listClass.isData)
+ Assert.assertFalse(listClass.isCompanion)
+ Assert.assertTrue(listClass.isAbstract)
+ Assert.assertFalse(listClass.isFinal)
+ Assert.assertFalse(listClass.isSealed)
+ }
+
+ @Test
+ fun testGetRelated() {
+ LOG.info("Companion Object: {}", TestSubject::class.companionObject)
+ LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance)
+ LOG.info("Object Instance: {}", TestObject::class.objectInstance)
+
+ Assert.assertSame(TestObject, TestObject::class.objectInstance)
+ }
+
+ @Test
+ fun testNewInstance() {
+ val listClass = ArrayList::class
+
+ val list = listClass.createInstance()
+ Assert.assertTrue(list is ArrayList)
+ }
+
+ @Test
+ @Ignore
+ fun testMembers() {
+ val bigDecimalClass = BigDecimal::class
+
+ LOG.info("Constructors: {}", bigDecimalClass.constructors)
+ LOG.info("Functions: {}", bigDecimalClass.functions)
+ LOG.info("Properties: {}", bigDecimalClass.memberProperties)
+ LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions)
+ }
+}
+
+class TestSubject {
+ companion object {
+ val name = "TestSubject"
+ }
+}
+
+object TestObject {
+ val answer = 42
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt
new file mode 100644
index 0000000000..17e9913731
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt
@@ -0,0 +1,88 @@
+package com.baeldung.kotlin.reflection
+
+import org.junit.Assert
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.nio.charset.Charset
+import kotlin.reflect.KMutableProperty
+import kotlin.reflect.full.starProjectedType
+
+class KMethodTest {
+
+ @Test
+ fun testCallMethod() {
+ val str = "Hello"
+ val lengthMethod = str::length
+
+ Assert.assertEquals(5, lengthMethod())
+ }
+
+ @Test
+ fun testReturnType() {
+ val str = "Hello"
+ val method = str::byteInputStream
+
+ Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType)
+ Assert.assertFalse(method.returnType.isMarkedNullable)
+ }
+
+ @Test
+ fun testParams() {
+ val str = "Hello"
+ val method = str::byteInputStream
+
+ method.isSuspend
+ Assert.assertEquals(1, method.parameters.size)
+ Assert.assertTrue(method.parameters[0].isOptional)
+ Assert.assertFalse(method.parameters[0].isVararg)
+ Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type)
+ }
+
+ @Test
+ fun testMethodDetails() {
+ val codePoints = String::codePoints
+ Assert.assertEquals("codePoints", codePoints.name)
+ Assert.assertFalse(codePoints.isSuspend)
+ Assert.assertFalse(codePoints.isExternal)
+ Assert.assertFalse(codePoints.isInline)
+ Assert.assertFalse(codePoints.isOperator)
+
+ val byteInputStream = String::byteInputStream
+ Assert.assertEquals("byteInputStream", byteInputStream.name)
+ Assert.assertFalse(byteInputStream.isSuspend)
+ Assert.assertFalse(byteInputStream.isExternal)
+ Assert.assertTrue(byteInputStream.isInline)
+ Assert.assertFalse(byteInputStream.isOperator)
+ }
+
+ val readOnlyProperty: Int = 42
+ lateinit var mutableProperty: String
+
+ @Test
+ fun testPropertyDetails() {
+ val roProperty = this::readOnlyProperty
+ Assert.assertEquals("readOnlyProperty", roProperty.name)
+ Assert.assertFalse(roProperty.isLateinit)
+ Assert.assertFalse(roProperty.isConst)
+ Assert.assertFalse(roProperty is KMutableProperty<*>)
+
+ val mProperty = this::mutableProperty
+ Assert.assertEquals("mutableProperty", mProperty.name)
+ Assert.assertTrue(mProperty.isLateinit)
+ Assert.assertFalse(mProperty.isConst)
+ Assert.assertTrue(mProperty is KMutableProperty<*>)
+ }
+
+ @Test
+ fun testProperty() {
+ val prop = this::mutableProperty
+
+ Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType)
+
+ prop.set("Hello")
+ Assert.assertEquals("Hello", prop.get())
+
+ prop.setter("World")
+ Assert.assertEquals("World", prop.getter())
+ }
+}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt
new file mode 100644
index 0000000000..f595d65bf2
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt
@@ -0,0 +1,19 @@
+package com.baeldung.kotlin.spek
+
+import com.baeldung.kotlin.junit5.Calculator
+import org.jetbrains.spek.api.dsl.describe
+import org.jetbrains.spek.api.dsl.it
+import org.jetbrains.spek.subject.SubjectSpek
+import org.junit.jupiter.api.Assertions.assertEquals
+
+class CalculatorSubjectTest5 : SubjectSpek({
+ subject { Calculator() }
+ describe("A calculator") {
+ describe("Addition") {
+ val result = subject.add(3, 5)
+ it("Produces the correct answer") {
+ assertEquals(8, result)
+ }
+ }
+ }
+})
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt
new file mode 100644
index 0000000000..3c49d916e4
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt
@@ -0,0 +1,32 @@
+package com.baeldung.kotlin.spek
+
+import com.baeldung.kotlin.junit5.Calculator
+import org.jetbrains.spek.api.Spek
+import org.jetbrains.spek.api.dsl.describe
+import org.jetbrains.spek.api.dsl.given
+import org.jetbrains.spek.api.dsl.it
+import org.jetbrains.spek.api.dsl.on
+import org.junit.jupiter.api.Assertions.assertEquals
+
+class CalculatorTest5 : Spek({
+ given("A calculator") {
+ val calculator = Calculator()
+ on("Adding 3 and 5") {
+ val result = calculator.add(3, 5)
+ it("Produces 8") {
+ assertEquals(8, result)
+ }
+ }
+ }
+
+ describe("A calculator") {
+ val calculator = Calculator()
+ describe("Addition") {
+ val result = calculator.add(3, 5)
+ it("Produces the correct answer") {
+ assertEquals(8, result)
+ }
+ }
+ }
+
+})
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt
new file mode 100644
index 0000000000..bbcb36e8bb
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt
@@ -0,0 +1,21 @@
+package com.baeldung.kotlin.spek
+
+import org.jetbrains.spek.api.Spek
+import org.jetbrains.spek.api.dsl.describe
+import org.jetbrains.spek.api.dsl.it
+import org.junit.jupiter.api.Assertions
+
+class DataDrivenTest5 : Spek({
+ describe("A data driven test") {
+ mapOf(
+ "hello" to "HELLO",
+ "world" to "WORLD"
+ ).forEach { input, expected ->
+ describe("Capitalising $input") {
+ it("Correctly returns $expected") {
+ Assertions.assertEquals(expected, input.toUpperCase())
+ }
+ }
+ }
+ }
+})
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt
new file mode 100644
index 0000000000..5aeee622e4
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt
@@ -0,0 +1,62 @@
+package com.baeldung.kotlin.spek
+
+import org.jetbrains.spek.api.Spek
+import org.jetbrains.spek.api.dsl.describe
+import org.jetbrains.spek.api.dsl.it
+
+class GroupTest5 : Spek({
+ describe("Outer group") {
+ beforeEachTest {
+ System.out.println("BeforeEachTest 0")
+ }
+ beforeGroup {
+ System.out.println("BeforeGroup 0")
+ }
+ afterEachTest {
+ System.out.println("AfterEachTest 0")
+ }
+ afterGroup {
+ System.out.println("AfterGroup 0")
+ }
+ describe("Inner group 1") {
+ beforeEachTest {
+ System.out.println("BeforeEachTest 1")
+ }
+ beforeGroup {
+ System.out.println("BeforeGroup 1")
+ }
+ afterEachTest {
+ System.out.println("AfterEachTest 1")
+ }
+ afterGroup {
+ System.out.println("AfterGroup 1")
+ }
+ it("Test 1") {
+ System.out.println("Test 1")
+ }
+ it("Test 2") {
+ System.out.println("Test 2")
+ }
+ }
+ describe("Inner group 2") {
+ beforeEachTest {
+ System.out.println("BeforeEachTest 2")
+ }
+ beforeGroup {
+ System.out.println("BeforeGroup 2")
+ }
+ afterEachTest {
+ System.out.println("AfterEachTest 2")
+ }
+ afterGroup {
+ System.out.println("AfterGroup 2")
+ }
+ it("Test 3") {
+ System.out.println("Test 3")
+ }
+ it("Test 4") {
+ System.out.println("Test 4")
+ }
+ }
+ }
+})
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt
new file mode 100644
index 0000000000..3af00c98ff
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt
@@ -0,0 +1,95 @@
+package com.baeldung.lambda
+
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import kotlin.test.assertEquals
+
+class LambdaTest {
+ @Test
+ fun whenCallingALambda_thenPerformTheAction() {
+ assertEquals(9, inferredType(3))
+ }
+
+ @Test
+ fun whenCallingAMoreComplicatedLambda_thenPerformTheAction() {
+ assertEquals("500", intToBiggerString(5))
+ }
+
+ @Test
+ fun whenPassingALambdaObject_thenCallTriggerLambda() {
+ val lambda = { arg: Double ->
+ arg == 4.329
+ }
+
+ val result = invokeLambda(lambda)
+
+ assertTrue(result)
+ }
+
+ @Test
+ fun whenPassingALambdaLiteral_thenCallTriggerLambda() {
+ val result = invokeLambda({
+ true
+ })
+
+ assertTrue(result)
+ }
+
+ @Test
+ fun whenPassingALambdaLiteralOutsideBrackets_thenCallTriggerLambda() {
+ val result = invokeLambda { arg -> arg.isNaN() }
+
+ assertFalse(result)
+ }
+
+ @Test
+ fun whenPassingAnAnonymousFunction_thenCallTriggerLambda() {
+ val result = invokeLambda(fun(arg: Double): Boolean {
+ return arg >= 0
+ })
+
+ assertTrue(result)
+ }
+
+ @Test
+ fun whenUsingLambda_thenCalculateGrade() {
+ val gradeCalculation = getCalculationLambda()
+
+ assertEquals(false, gradeCalculation(-40))
+ assertEquals("Pass", gradeCalculation(50))
+ }
+
+ @Test
+ fun whenUsingReturnStatementLambda_thenCalculateGrade() {
+ val gradeCalculation: Int.() -> String = getCalculationLambdaWithReturn()
+
+ assertEquals("Distinction", 80.gradeCalculation())
+ assertEquals("Error", 244_234_324.gradeCalculation())
+ }
+
+ @Test
+ fun whenUsingAnonymousFunction_thenCalculateGrade() {
+ val gradeCalculation = getCalculationAnonymousFunction()
+
+ assertEquals("Error", gradeCalculation(244_234_324))
+ assertEquals("Pass", gradeCalculation(50))
+ }
+
+ @Test
+ fun whenPassingAFunctionReference_thenCallTriggerLambda() {
+ val reference = Double::isFinite
+ val result = invokeLambda(reference)
+
+ assertTrue(result)
+ }
+
+ @Test
+ fun givenArray_whenMappingArray_thenPerformCalculationOnAllElements() {
+ val expected = listOf("100", "200", "300", "400", "500")
+ val actual = manyLambda(arrayOf(1, 2, 3, 4, 5))
+
+ assertEquals(expected, actual)
+ }
+
+}
\ No newline at end of file
diff --git a/couchbase/README.md b/couchbase/README.md
index f124a0192c..9b76609593 100644
--- a/couchbase/README.md
+++ b/couchbase/README.md
@@ -5,6 +5,7 @@
- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view)
+- [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase)
### Overview
This Maven project contains the Java code for the Couchbase entities and Spring services
diff --git a/couchbase/pom.xml b/couchbase/pom.xml
index c79ce853d0..c369a9e598 100644
--- a/couchbase/pom.xml
+++ b/couchbase/pom.xml
@@ -1,6 +1,6 @@
+ 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
couchbase-sdk
@@ -22,13 +22,11 @@
java-client
${couchbase.client.version}
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson-version}
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson-version}
-
org.springframework
@@ -52,7 +50,6 @@
-
org.springframework
@@ -60,7 +57,6 @@
${spring-framework.version}
test
-
org.apache.commons
diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
index e708922988..3100f0c70b 100644
--- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
+++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java
@@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.couchbase.client.java.Bucket;
@@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService {
private Cluster cluster;
private Map buckets = new ConcurrentHashMap<>();
+
+ @Autowired
+ public ClusterServiceImpl(Cluster cluster) {
+ this.cluster = cluster;
+ }
@PostConstruct
private void init() {
diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
index 459585d995..75a196ff5d 100644
--- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
+++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java
@@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService {
@Autowired
public TutorialBucketService(ClusterService clusterService) {
super(clusterService);
+ openBucket();
}
@Override
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java
new file mode 100644
index 0000000000..9e650752d2
--- /dev/null
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java
@@ -0,0 +1,24 @@
+package com.baeldung.couchbase.async.person;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+import com.couchbase.client.java.Cluster;
+import com.couchbase.client.java.CouchbaseCluster;
+import com.couchbase.client.java.env.CouchbaseEnvironment;
+import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
+
+@Configuration
+@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"})
+public class PersonCrudServiceIntegrationTestConfig {
+
+ @Bean
+ public Cluster cluster() {
+ CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
+ .connectTimeout(60000)
+ .build();
+ return CouchbaseCluster.create(env, "127.0.0.1");
+ }
+
+}
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
similarity index 90%
rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
index 565aaed5da..267071ab35 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java
@@ -1,27 +1,31 @@
package com.baeldung.couchbase.async.person;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-import javax.annotation.PostConstruct;
-
import org.apache.commons.lang3.RandomStringUtils;
+import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.couchbase.async.AsyncIntegrationTest;
-import com.baeldung.couchbase.async.person.Person;
-import com.baeldung.couchbase.async.person.PersonCrudService;
-import com.baeldung.couchbase.async.person.PersonDocumentConverter;
import com.baeldung.couchbase.async.service.BucketService;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.document.JsonDocument;
-public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class})
+public class PersonCrudServiceLiveTest extends AsyncIntegrationTest {
@Autowired
private PersonCrudService personService;
@@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
private Bucket bucket;
- @PostConstruct
- private void init() {
+ @Before
+ public void init() {
bucket = bucketService.getBucket();
}
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
similarity index 94%
rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
index d0db5d37a3..5f478ae788 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java
@@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public class ClusterServiceIntegrationTest extends AsyncIntegrationTest {
+public class ClusterServiceLiveTest extends AsyncIntegrationTest {
@Autowired
private ClusterService couchbaseService;
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
similarity index 98%
rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
index 00d462e32a..d260795ed3 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java
@@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.view.ViewResult;
import com.couchbase.client.java.view.ViewRow;
-public class StudentGradeServiceIntegrationTest {
- private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class);
+public class StudentGradeServiceLiveTest {
+ private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class);
static StudentGradeService studentGradeService;
static Set gradeIds = new HashSet<>();
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
similarity index 97%
rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
index 8112d7d222..602bb5b8a5 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java
@@ -1,5 +1,23 @@
package com.baeldung.couchbase.n1ql;
+import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
+import static com.couchbase.client.java.query.Select.select;
+import static com.couchbase.client.java.query.dsl.Expression.i;
+import static com.couchbase.client.java.query.dsl.Expression.s;
+import static com.couchbase.client.java.query.dsl.Expression.x;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.document.JsonDocument;
@@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.query.Statement;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
import rx.Observable;
-import java.util.List;
-import java.util.UUID;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-
-import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
-import static com.couchbase.client.java.query.Select.select;
-import static com.couchbase.client.java.query.dsl.Expression.*;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
-public class N1QLIntegrationTest {
+public class N1QLLiveTest {
@Autowired
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
similarity index 97%
rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
index ec15be1acc..493b326d49 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java
@@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.couchbase.spring.IntegrationTest;
-public class PersonCrudServiceIntegrationTest extends IntegrationTest {
+public class PersonCrudServiceLiveTest extends IntegrationTest {
private static final String CLARK_KENT = "Clark Kent";
private static final String SMALLVILLE = "Smallville";
diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
similarity index 94%
rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java
rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
index ead247dfbc..7a89a208f7 100644
--- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java
+++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java
@@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
-public class ClusterServiceIntegrationTest extends IntegrationTest {
+public class ClusterServiceLiveTest extends IntegrationTest {
@Autowired
private ClusterService couchbaseService;
diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar
index 4ad6933865..e19bce6e52 100644
Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ
diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml
index f9ae961f3a..dcd068089b 100644
--- a/custom-pmd/pom.xml
+++ b/custom-pmd/pom.xml
@@ -1,43 +1,46 @@
- 4.0.0
- org.baeldung.pmd
- custom-pmd
- 0.0.1
- jar
- custom-pmd
- http://maven.apache.org
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ org.baeldung.pmd
+ custom-pmd
+ 0.0.1
+ jar
+ custom-pmd
+ http://maven.apache.org
-
- UTF-8
- 3.7.0
- 6.0.1
-
-
-
-
- net.sourceforge.pmd
- pmd-core
- ${pmdVersion}
+
+
+ net.sourceforge.pmd
+ pmd-core
+ ${pmdVersion}
-
- net.sourceforge.pmd
- pmd-java
- ${pmdVersion}
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
+
+ net.sourceforge.pmd
+ pmd-java
+ ${pmdVersion}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+
+ UTF-8
+ 3.7.0
+ 6.0.1
+ 1.8
+ 1.8
+
+
diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java
index 4136165b6f..3b73f9c21c 100644
--- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java
+++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java
@@ -11,20 +11,20 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule {
private static List allowedEndings = Arrays.asList(
"IntegrationTest",
+ "IntTest",
"ManualTest",
"JdbcTest",
"LiveTest",
- "UnitTest");
+ "UnitTest",
+ "jmhTest");
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
String className = node.getImage();
Objects.requireNonNull(className);
- if (className.endsWith("Test") || className.endsWith("Tests")) {
- if (allowedEndings.stream()
- .noneMatch(className::endsWith)) {
- addViolation(data, node);
- }
+ if (className.endsWith("Tests")
+ || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
+ addViolation(data, node);
}
return data;
diff --git a/dagger/README.md b/dagger/README.md
new file mode 100644
index 0000000000..72cba3d3f2
--- /dev/null
+++ b/dagger/README.md
@@ -0,0 +1,3 @@
+### Relevant articles:
+
+- [Introduction to Dagger 2](http://www.baeldung.com/dagger-2)
diff --git a/dagger/pom.xml b/dagger/pom.xml
new file mode 100644
index 0000000000..f927ce42c4
--- /dev/null
+++ b/dagger/pom.xml
@@ -0,0 +1,54 @@
+
+
+ 4.0.0
+ dagger
+ dagger
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+
+ com.google.dagger
+ dagger
+ ${dagger.version}
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.6.1
+
+
+
+ com.google.dagger
+ dagger-compiler
+ 2.16
+
+
+
+
+
+
+
+
+ 4.12
+ 2.16
+
+
+
\ No newline at end of file
diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java
new file mode 100644
index 0000000000..5ec6607d67
--- /dev/null
+++ b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java
@@ -0,0 +1,45 @@
+package com.baeldung.dagger.intro;
+
+/**
+ * Brand of a {@link Car}.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class Brand {
+
+ /**
+ * The name of the brand.
+ */
+ private String name;
+
+ /**
+ * Instantiates a new Brand.
+ *
+ * @param name
+ * the {@link #name}
+ */
+ public Brand(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Gets the {@link #name}.
+ *
+ * @return the {@link #name}
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the {@link #name}.
+ *
+ * @param name
+ * the new {@link #name}
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Car.java b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java
new file mode 100644
index 0000000000..2ad81b8f6c
--- /dev/null
+++ b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java
@@ -0,0 +1,75 @@
+package com.baeldung.dagger.intro;
+
+import javax.inject.Inject;
+
+/**
+ * Represents a car.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class Car {
+
+ /**
+ * The car's engine.
+ */
+ private Engine engine;
+
+ /**
+ * The car's brand.
+ */
+ private Brand brand;
+
+ /**
+ * Instantiates a new Car.
+ *
+ * @param engine
+ * the {@link #engine}
+ * @param brand
+ * the {@link #brand}
+ */
+ @Inject
+ public Car(Engine engine, Brand brand) {
+ this.engine = engine;
+ this.brand = brand;
+ }
+
+ /**
+ * Gets the {@link #engine}.
+ *
+ * @return the {@link #engine}
+ */
+ public Engine getEngine() {
+ return engine;
+ }
+
+ /**
+ * Sets the {@link #engine}.
+ *
+ * @param engine
+ * the new {@link #engine}
+ */
+ public void setEngine(Engine engine) {
+ this.engine = engine;
+ }
+
+ /**
+ * Gets the {@link #brand}.
+ *
+ * @return the {@link #brand}
+ */
+ public Brand getBrand() {
+ return brand;
+ }
+
+ /**
+ * Sets the {@link #brand}.
+ *
+ * @param brand
+ * the new {@link #brand}
+ */
+ public void setBrand(Brand brand) {
+ this.brand = brand;
+ }
+
+}
diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java
new file mode 100644
index 0000000000..99e30625cd
--- /dev/null
+++ b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java
@@ -0,0 +1,24 @@
+package com.baeldung.dagger.intro;
+
+/**
+ * Engine of a {@link Car}.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class Engine {
+
+ /**
+ * Starts the engine.
+ */
+ public void start() {
+ System.out.println("Engine started");
+ }
+
+ /**
+ * Stops the engine.
+ */
+ public void stop() {
+ System.out.println("Engine stopped");
+ }
+}
diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java
new file mode 100644
index 0000000000..aeeaab636e
--- /dev/null
+++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java
@@ -0,0 +1,24 @@
+package com.baeldung.dagger.intro;
+
+import javax.inject.Singleton;
+
+import dagger.Component;
+
+/**
+ * Dagger component for building vehicles.
+ *
+ * @author Donato Rimenti
+ *
+ */
+@Singleton
+@Component(modules = VehiclesModule.class)
+public interface VehiclesComponent {
+
+ /**
+ * Builds a {@link Car}.
+ *
+ * @return a {@link Car}
+ */
+ public Car buildCar();
+
+}
\ No newline at end of file
diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java
new file mode 100644
index 0000000000..f6c6e4a108
--- /dev/null
+++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java
@@ -0,0 +1,37 @@
+package com.baeldung.dagger.intro;
+
+import javax.inject.Singleton;
+
+import dagger.Module;
+import dagger.Provides;
+
+/**
+ * Dagger module for providing vehicles components.
+ *
+ * @author Donato Rimenti
+ *
+ */
+@Module
+public class VehiclesModule {
+
+ /**
+ * Creates an {@link Engine}.
+ *
+ * @return an {@link Engine}
+ */
+ @Provides
+ public Engine provideEngine() {
+ return new Engine();
+ }
+
+ /**
+ * Creates a {@link Brand}.
+ *
+ * @return a {@link Brand}
+ */
+ @Provides
+ @Singleton
+ public Brand provideBrand() {
+ return new Brand("Baeldung");
+ }
+}
\ No newline at end of file
diff --git a/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java
new file mode 100644
index 0000000000..83e881ffe1
--- /dev/null
+++ b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.dagger.intro;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Unit test for building a {@link Car} using Dagger.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class DaggerUnitTest {
+
+ /**
+ * Builds two {@link Car} and checks that the fields are injected correctly.
+ */
+ @Test
+ public void givenGeneratedComponent_whenBuildingCar_thenDependenciesInjected() {
+ VehiclesComponent component = DaggerVehiclesComponent.create();
+
+ Car carOne = component.buildCar();
+ Car carTwo = component.buildCar();
+
+ Assert.assertNotNull(carOne);
+ Assert.assertNotNull(carTwo);
+ Assert.assertNotNull(carOne.getEngine());
+ Assert.assertNotNull(carTwo.getEngine());
+ Assert.assertNotNull(carOne.getBrand());
+ Assert.assertNotNull(carTwo.getBrand());
+ Assert.assertNotEquals(carOne.getEngine(), carTwo.getEngine());
+ Assert.assertEquals(carOne.getBrand(), carTwo.getBrand());
+ }
+
+}
diff --git a/data-structures/pom.xml b/data-structures/pom.xml
index 68174a41df..287e9f38aa 100644
--- a/data-structures/pom.xml
+++ b/data-structures/pom.xml
@@ -1,24 +1,26 @@
- 4.0.0
- com.baeldung
- data-structures
- 0.0.1-SNAPSHOT
+ 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
+ data-structures
+ 0.0.1-SNAPSHOT
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+
+
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
- ${exec-maven-plugin.version}
-
-
-
-
diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml
index 8ab7b1e4e4..8d9e8c6475 100644
--- a/deeplearning4j/pom.xml
+++ b/deeplearning4j/pom.xml
@@ -6,32 +6,29 @@
jar
1.0-SNAPSHOT
deeplearning4j
-
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
- UTF-8
- 1.8
- 1.8
- 0.9.1
-
-
org.nd4j
nd4j-native-platform
${dl4j.version}
-
org.deeplearning4j
deeplearning4j-core
${dl4j.version}
-
+
+ UTF-8
+ 0.9.1
+
+
\ No newline at end of file
diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml
index e81ad49a6d..7f4491117b 100644
--- a/deltaspike/pom.xml
+++ b/deltaspike/pom.xml
@@ -1,6 +1,6 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.baeldung
deltaspike
@@ -8,15 +8,7 @@
war
deltaspike
A starter Java EE 7 webapp which uses DeltaSpike
-
http://wildfly.org
-
-
- Apache License, Version 2.0
- repo
- http://www.apache.org/licenses/LICENSE-2.0.html
-
-
com.baeldung
@@ -24,38 +16,29 @@
1.0.0-SNAPSHOT
-
-
-
- UTF-8
-
- 3.7.4
- 1.7.2
-
-
- 1.0.2.Final
-
-
- 8.2.2.Final
-
-
- 2.6
- 1.1.3
-
-
+
+
+ Apache License, Version 2.0
+ repo
+ http://www.apache.org/licenses/LICENSE-2.0.html
+
+
+
+
+ redhat-repository-techpreview
+ https://maven.repository.redhat.com/techpreview/all/
+
+
-
org.wildfly.bom
@@ -71,31 +54,38 @@
pom
import
+
+ org.apache.deltaspike.distribution
+ distributions-bom
+ ${deltaspike.version}
+ pom
+ import
+
-
+
-
+
javax.enterprise
cdi-api
provided
-
+
org.jboss.spec.javax.annotation
jboss-annotations-api_1.2_spec
provided
-
org.jboss.resteasy
@@ -103,16 +93,16 @@
provided
-
+
org.hibernate.javax.persistence
hibernate-jpa-2.1-api
provided
-
+
org.jboss.spec.javax.ejb
jboss-ejb-api_3.2_spec
@@ -134,8 +124,8 @@
-
+
org.jboss.spec.javax.faces
jboss-jsf-api_2.2_spec
@@ -144,16 +134,16 @@
-
+
org.hibernate
hibernate-jpamodelgen
provided
-
+
org.hibernate
hibernate-validator-annotation-processor
@@ -161,8 +151,8 @@
-
+
org.jboss.arquillian.junit
arquillian-junit-container
@@ -184,14 +174,12 @@
org.apache.deltaspike.modules
deltaspike-data-module-api
- ${deltaspike.version}
compile
org.apache.deltaspike.modules
deltaspike-data-module-impl
- ${deltaspike.version}
runtime
@@ -208,19 +196,83 @@
querydsl-jpa
${querydsl.version}
+
+
+ org.apache.deltaspike.modules
+ deltaspike-test-control-module-api
+ test
+
+
+
+ org.apache.deltaspike.modules
+ deltaspike-test-control-module-impl
+ test
+
+
+
+ org.apache.deltaspike.cdictrl
+ deltaspike-cdictrl-weld
+ test
+
+
+
+ org.jboss.weld.se
+ weld-se-core
+ ${weld.version}
+ test
+
+
+
+ org.hibernate
+ hibernate-core
+ provided
+
+
+
+ org.jboss
+ jandex
+ 1.2.5.Final-redhat-1
+
+
+
+ com.h2database
+ h2
+ 1.4.197
+ test
+
+
+
+ org.hibernate
+ hibernate-entitymanager
+ provided
+
+
+
+
+ junit
+ junit
+ test
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ 3.5
+
+
-
+
${project.artifactId}
maven-war-plugin
${war.plugin.version}
-
+
false
@@ -252,33 +304,11 @@
-
-
- default
-
- true
-
-
-
-
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- true
-
-
-
-
-
-
-
-
-
+
+
arq-wildfly-managed
@@ -290,4 +320,26 @@
+
+
+
+
+ UTF-8
+ 3.7.4
+ 1.8.2
+
+ 1.0.2.Final
+
+ 8.2.1.Final
+ 2.1.2.Final
+
+ 2.6
+ 1.1.3
+ 1.8
+ 1.8
+
+
diff --git a/deltaspike/src/main/java/baeldung/controller/MemberController.java b/deltaspike/src/main/java/baeldung/controller/MemberController.java
index 7a9e9800f4..eba36355b7 100644
--- a/deltaspike/src/main/java/baeldung/controller/MemberController.java
+++ b/deltaspike/src/main/java/baeldung/controller/MemberController.java
@@ -16,6 +16,9 @@
*/
package baeldung.controller;
+import baeldung.model.Member;
+import baeldung.service.MemberRegistration;
+
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
@@ -24,9 +27,6 @@ import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
-import baeldung.model.Member;
-import baeldung.service.MemberRegistration;
-
// The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an
// EL name
// Read more about the @Model stereotype in this FAQ:
@@ -34,11 +34,9 @@ import baeldung.service.MemberRegistration;
@Model
public class MemberController {
- @Inject
- private FacesContext facesContext;
+ @Inject private FacesContext facesContext;
- @Inject
- private MemberRegistration memberRegistration;
+ @Inject private MemberRegistration memberRegistration;
@Produces
@Named
diff --git a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java
index 9189dbba74..6c2387012d 100644
--- a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java
+++ b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java
@@ -1,29 +1,18 @@
package baeldung.data;
-import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
-import javax.enterprise.inject.Default;
-import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.PersistenceUnit;
+import javax.persistence.PersistenceContext;
-@ApplicationScoped
public class EntityManagerProducer {
- @PersistenceUnit(unitName = "primary")
- private EntityManagerFactory entityManagerFactory;
- @Produces
- @Default
+ @PersistenceContext(unitName = "primary") private EntityManager entityManager;
+
@RequestScoped
+ @Produces
public EntityManager create() {
- return this.entityManagerFactory.createEntityManager();
+ return entityManager;
}
- public void dispose(@Disposes @Default EntityManager entityManager) {
- if (entityManager.isOpen()) {
- entityManager.close();
- }
- }
}
\ No newline at end of file
diff --git a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java
index c1f5fda31d..989bcea917 100644
--- a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java
+++ b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java
@@ -16,6 +16,8 @@
*/
package baeldung.data;
+import baeldung.model.Member;
+
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
@@ -25,13 +27,10 @@ import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
-import baeldung.model.Member;
-
@RequestScoped
public class MemberListProducer {
- @Inject
- private MemberRepository memberRepository;
+ @Inject private MemberRepository memberRepository;
private List members;
diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java
index 220388bcf0..e9c7e52f9c 100644
--- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java
+++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java
@@ -18,7 +18,10 @@ package baeldung.data;
import baeldung.model.Member;
import baeldung.model.QMember;
-import org.apache.deltaspike.data.api.*;
+import org.apache.deltaspike.data.api.AbstractEntityRepository;
+import org.apache.deltaspike.data.api.EntityManagerConfig;
+import org.apache.deltaspike.data.api.Query;
+import org.apache.deltaspike.data.api.Repository;
import java.util.List;
@@ -35,6 +38,9 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() {
final QMember member = QMember.member;
- return jpaQuery().from(member).orderBy(member.email.asc()).list(member);
+ return jpaQuery()
+ .from(member)
+ .orderBy(member.email.asc())
+ .list(member);
}
}
diff --git a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java
index 8cb00958ab..4bb8a629de 100644
--- a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java
+++ b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java
@@ -8,8 +8,7 @@ import javax.inject.Inject;
public class QueryDslRepositoryExtension implements QueryDslSupport, DelegateQueryHandler {
- @Inject
- private QueryInvocationContext context;
+ @Inject private QueryInvocationContext context;
@Override
public JPAQuery jpaQuery() {
diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java
index 41d30d9018..606def4f30 100644
--- a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java
+++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java
@@ -2,29 +2,20 @@ package baeldung.data;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
-import javax.enterprise.inject.Default;
-import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.PersistenceUnit;
+import javax.persistence.PersistenceContext;
@ApplicationScoped
public class SecondaryEntityManagerProducer {
- @PersistenceUnit(unitName = "secondary")
- private EntityManagerFactory entityManagerFactory;
+
+ @PersistenceContext(unitName = "secondary") private EntityManager entityManager;
@Produces
- @Default
@RequestScoped
@SecondaryPersistenceUnit
public EntityManager create() {
- return this.entityManagerFactory.createEntityManager();
+ return entityManager;
}
- public void dispose(@Disposes @Default EntityManager entityManager) {
- if (entityManager.isOpen()) {
- entityManager.close();
- }
- }
}
\ No newline at end of file
diff --git a/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java
new file mode 100644
index 0000000000..9ea6115f11
--- /dev/null
+++ b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java
@@ -0,0 +1,45 @@
+package baeldung.data;
+
+import baeldung.model.User;
+import org.apache.deltaspike.data.api.FirstResult;
+import org.apache.deltaspike.data.api.MaxResults;
+import org.apache.deltaspike.data.api.Repository;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Created by adam.
+ */
+@Repository(forEntity = User.class)
+public abstract class SimpleUserRepository {
+ public abstract Collection findAll();
+
+ public abstract Collection findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size);
+
+ public abstract Collection findTop2OrderByFirstNameAsc();
+
+ public abstract Collection findFirst2OrderByFirstNameAsc();
+
+ public abstract List findAllOrderByFirstNameAsc();
+
+ public abstract List findAllOrderByFirstNameAscLastNameDesc();
+
+ public abstract User findById(Long id);
+
+ public abstract Collection findByFirstName(String firstName);
+
+ public abstract User findAnyByLastName(String lastName);
+
+ public abstract Collection findAnyByFirstName(String firstName);
+
+ public abstract Collection findByFirstNameAndLastName(String firstName, String lastName);
+
+ public abstract Collection findByFirstNameOrLastName(String firstName, String lastName);
+
+ public abstract Collection findByAddress_city(String city);
+
+ public abstract int count();
+
+ public abstract void remove(User user);
+}
diff --git a/deltaspike/src/main/java/baeldung/data/UserRepository.java b/deltaspike/src/main/java/baeldung/data/UserRepository.java
new file mode 100644
index 0000000000..688e46f5fc
--- /dev/null
+++ b/deltaspike/src/main/java/baeldung/data/UserRepository.java
@@ -0,0 +1,31 @@
+package baeldung.data;
+
+import baeldung.model.User;
+import org.apache.deltaspike.data.api.AbstractEntityRepository;
+import org.apache.deltaspike.data.api.Query;
+import org.apache.deltaspike.data.api.Repository;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Created by adam.
+ */
+@Repository
+public abstract class UserRepository extends AbstractEntityRepository {
+
+ public List findByFirstName(String firstName) {
+ return typedQuery("select u from User u where u.firstName = ?1")
+ .setParameter(1, firstName)
+ .getResultList();
+ }
+
+ public abstract List findByLastName(String lastName);
+
+ @Query("select u from User u where u.firstName = ?1")
+ public abstract Collection findUsersWithFirstName(String firstName);
+
+ @Query(value = "select * from User where firstName = ?1", isNative = true)
+ public abstract Collection findUsersWithFirstNameNative(String firstName);
+
+}
diff --git a/deltaspike/src/main/java/baeldung/model/Address.java b/deltaspike/src/main/java/baeldung/model/Address.java
new file mode 100644
index 0000000000..ef0d461b9c
--- /dev/null
+++ b/deltaspike/src/main/java/baeldung/model/Address.java
@@ -0,0 +1,51 @@
+package baeldung.model;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Created by adam.
+ */
+@Entity
+public class Address {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+ private String street;
+ private String city;
+ private String postCode;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public String getPostCode() {
+ return postCode;
+ }
+
+ public void setPostCode(String postCode) {
+ this.postCode = postCode;
+ }
+}
diff --git a/deltaspike/src/main/java/baeldung/model/Member.java b/deltaspike/src/main/java/baeldung/model/Member.java
index e178dcf63a..d9b9b5caf1 100644
--- a/deltaspike/src/main/java/baeldung/model/Member.java
+++ b/deltaspike/src/main/java/baeldung/model/Member.java
@@ -16,22 +16,16 @@
*/
package baeldung.model;
-import java.io.Serializable;
+import org.hibernate.validator.constraints.Email;
+import org.hibernate.validator.constraints.NotEmpty;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
+import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
-
-import org.hibernate.validator.constraints.Email;
-import org.hibernate.validator.constraints.NotEmpty;
+import java.io.Serializable;
@SuppressWarnings("serial")
@Entity
diff --git a/deltaspike/src/main/java/baeldung/model/User.java b/deltaspike/src/main/java/baeldung/model/User.java
new file mode 100644
index 0000000000..5560ea0e7c
--- /dev/null
+++ b/deltaspike/src/main/java/baeldung/model/User.java
@@ -0,0 +1,52 @@
+package baeldung.model;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+/**
+ * Created by adam.
+ */
+@Entity
+public class User {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+ private String firstName;
+ private String lastName;
+ @OneToOne private Address address;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
diff --git a/deltaspike/src/main/resources/META-INF/beans.xml b/deltaspike/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..f462814752
--- /dev/null
+++ b/deltaspike/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,5 @@
+
+
diff --git a/deltaspike/src/test/java/baeldung/ValidatorProducer.java b/deltaspike/src/test/java/baeldung/ValidatorProducer.java
new file mode 100644
index 0000000000..6b895f771e
--- /dev/null
+++ b/deltaspike/src/test/java/baeldung/ValidatorProducer.java
@@ -0,0 +1,21 @@
+package baeldung;
+
+import javax.enterprise.inject.Produces;
+import javax.validation.Validation;
+import javax.validation.Validator;
+
+/**
+ * Created by adam.
+ */
+public class ValidatorProducer {
+
+ @Produces
+ public Validator createValidator() {
+ return Validation
+ .byDefaultProvider()
+ .configure()
+ .buildValidatorFactory()
+ .getValidator();
+ }
+
+}
diff --git a/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java
new file mode 100644
index 0000000000..139760d7fc
--- /dev/null
+++ b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java
@@ -0,0 +1,23 @@
+package baeldung.data;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Produces;
+import javax.enterprise.inject.Specializes;
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+
+/**
+ * Created by adam.
+ */
+public class TestEntityManagerProducer extends EntityManagerProducer {
+
+ @ApplicationScoped
+ @Produces
+ @Specializes
+ public EntityManager create() {
+ return Persistence
+ .createEntityManagerFactory("pu-test")
+ .createEntityManager();
+ }
+
+}
diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java
similarity index 65%
rename from deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java
rename to deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java
index 2b6cfe2b02..9d72d13b80 100644
--- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java
+++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java
@@ -16,19 +16,12 @@
*/
package baeldung.test;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.File;
-import java.util.logging.Logger;
-
-import javax.inject.Inject;
-
import baeldung.data.*;
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.junit.Arquillian;
import baeldung.model.Member;
import baeldung.service.MemberRegistration;
import baeldung.util.Resources;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
@@ -37,24 +30,39 @@ import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
+import javax.inject.Inject;
+import java.io.File;
+import java.util.logging.Logger;
+
+import static org.junit.Assert.assertNotNull;
+
@RunWith(Arquillian.class)
-public class MemberRegistrationIntegrationTest {
+public class MemberRegistrationLiveTest {
@Deployment
public static Archive> createTestArchive() {
- File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
+ File[] files = Maven
+ .resolver()
+ .loadPomFromFile("pom.xml")
+ .importRuntimeDependencies()
+ .resolve()
+ .withTransitivity()
+ .asFile();
- return ShrinkWrap.create(WebArchive.class, "test.war")
- .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class,
- SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class)
- .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml")
- .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files);
+ return ShrinkWrap
+ .create(WebArchive.class, "test.war")
+ .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, SecondaryEntityManagerProducer.class,
+ SecondaryEntityManagerResolver.class)
+ .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
+ .addAsResource("META-INF/apache-deltaspike.properties")
+ .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
+ .addAsWebInfResource("test-ds.xml")
+ .addAsWebInfResource("test-secondary-ds.xml")
+ .addAsLibraries(files);
}
- @Inject
- MemberRegistration memberRegistration;
+ @Inject MemberRegistration memberRegistration;
- @Inject
- Logger log;
+ @Inject Logger log;
@Test
public void testRegister() throws Exception {
diff --git a/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java
new file mode 100644
index 0000000000..2065338c77
--- /dev/null
+++ b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java
@@ -0,0 +1,133 @@
+package baeldung.test;
+
+import baeldung.data.SimpleUserRepository;
+import baeldung.model.User;
+import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import javax.persistence.EntityManager;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Created by adam.
+ */
+@RunWith(CdiTestRunner.class)
+public class SimpleUserRepositoryUnitTest {
+
+ @Inject private EntityManager entityManager;
+
+ @Inject private SimpleUserRepository simpleUserRepository;
+
+ @Test
+ public void givenFourUsersWhenFindAllShouldReturnFourUsers() {
+ assertThat(simpleUserRepository
+ .findAll()
+ .size(), equalTo(4));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() {
+ assertThat(simpleUserRepository
+ .findByFirstName("Adam")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenFindAnyByFirstNameShouldReturnTwoUsers() {
+ assertThat(simpleUserRepository
+ .findAnyByFirstName("Adam")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenCountByFirstNameShouldReturnSizeTwo() {
+ assertThat(simpleUserRepository.count(), equalTo(4));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenRemoveByFirstNameShouldReturnSizeTwo() {
+ simpleUserRepository.remove(entityManager.merge(simpleUserRepository.findById(1L)));
+ assertThat(entityManager.find(User.class, 1L), nullValue());
+ }
+
+ @Test
+ public void givenOneUserWithSpecifiedFirstNameAndLastNameWhenFindByFirstNameAndLastNameShouldReturnOneUser() {
+ assertThat(simpleUserRepository
+ .findByFirstNameAndLastName("Adam", "LastName1")
+ .size(), equalTo(1));
+ assertThat(simpleUserRepository
+ .findByFirstNameAndLastName("David", "LastName2")
+ .size(), equalTo(1));
+ }
+
+ @Test
+ public void givenOneUserWithSpecifiedLastNameWhenFindAnyByLastNameShouldReturnOneUser() {
+ assertThat(simpleUserRepository.findAnyByLastName("LastName1"), notNullValue());
+ }
+
+ @Test
+ public void givenOneUserWithSpecifiedAddressCityWhenFindByCityShouldReturnOneUser() {
+ assertThat(simpleUserRepository
+ .findByAddress_city("London")
+ .size(), equalTo(1));
+ }
+
+ @Test
+ public void givenUsersWithSpecifiedFirstOrLastNameWhenFindByFirstNameOrLastNameShouldReturnTwoUsers() {
+ assertThat(simpleUserRepository
+ .findByFirstNameOrLastName("David", "LastName1")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenUsersWhenFindAllOrderByFirstNameAscShouldReturnFirstAdamLastPeter() {
+ List users = simpleUserRepository.findAllOrderByFirstNameAsc();
+ assertThat(users
+ .get(0)
+ .getFirstName(), equalTo("Adam"));
+ assertThat(users
+ .get(3)
+ .getFirstName(), equalTo("Peter"));
+ }
+
+ @Test
+ public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() {
+ List users = simpleUserRepository.findAllOrderByFirstNameAscLastNameDesc();
+ assertThat(users
+ .get(0)
+ .getFirstName(), equalTo("Adam"));
+ assertThat(users
+ .get(3)
+ .getFirstName(), equalTo("Peter"));
+ }
+
+ @Test
+ public void givenUsersWhenFindTop2ShouldReturnTwoUsers() {
+ assertThat(simpleUserRepository
+ .findTop2OrderByFirstNameAsc()
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenUsersWhenFindFirst2ShouldReturnTwoUsers() {
+ assertThat(simpleUserRepository
+ .findFirst2OrderByFirstNameAsc()
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenPagesWithSizeTwoWhenFindAllOrderByFirstNameAscShouldReturnTwoPages() {
+ assertThat(simpleUserRepository
+ .findAllOrderByFirstNameAsc(0, 2)
+ .size(), equalTo(2));
+ assertThat(simpleUserRepository
+ .findAllOrderByFirstNameAsc(2, 4)
+ .size(), equalTo(2));
+ }
+
+}
diff --git a/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java
new file mode 100644
index 0000000000..bd07bf2730
--- /dev/null
+++ b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java
@@ -0,0 +1,55 @@
+package baeldung.test;
+
+import baeldung.data.UserRepository;
+import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Created by adam.
+ */
+@RunWith(CdiTestRunner.class)
+public class UserRepositoryUnitTest {
+
+ @Inject private UserRepository userRepository;
+
+ @Test
+ public void givenFourUsersWhenFindAllShouldReturnFourUsers() {
+ assertThat(userRepository
+ .findAll()
+ .size(), equalTo(4));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() {
+ assertThat(userRepository
+ .findByFirstName("Adam")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameShouldReturnTwoUsers() {
+ assertThat(userRepository
+ .findUsersWithFirstName("Adam")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameNativeShouldReturnTwoUsers() {
+ assertThat(userRepository
+ .findUsersWithFirstNameNative("Adam")
+ .size(), equalTo(2));
+ }
+
+ @Test
+ public void givenTwoUsersWithSpecifiedLastNameWhenFindByLastNameShouldReturnTwoUsers() {
+ assertThat(userRepository
+ .findByLastName("LastName3")
+ .size(), equalTo(2));
+ }
+}
diff --git a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties
index a861ad729a..787e58ade0 100644
--- a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties
+++ b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties
@@ -1 +1,3 @@
globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy
+org.apache.deltaspike.ProjectStage=UnitTest
+deltaspike.testcontrol.stop_container=false
\ No newline at end of file
diff --git a/deltaspike/src/test/resources/META-INF/beans.xml b/deltaspike/src/test/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..346b484f2f
--- /dev/null
+++ b/deltaspike/src/test/resources/META-INF/beans.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/deltaspike/src/test/resources/META-INF/test-persistence.xml b/deltaspike/src/test/resources/META-INF/persistence.xml
similarity index 53%
rename from deltaspike/src/test/resources/META-INF/test-persistence.xml
rename to deltaspike/src/test/resources/META-INF/persistence.xml
index bc9fbcbeef..ee69855138 100644
--- a/deltaspike/src/test/resources/META-INF/test-persistence.xml
+++ b/deltaspike/src/test/resources/META-INF/persistence.xml
@@ -11,6 +11,7 @@
+
java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS
@@ -18,4 +19,23 @@
+
+
+ org.hibernate.jpa.HibernatePersistenceProvider
+
+ baeldung.model.User
+ baeldung.model.Address
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/deltaspike/src/test/resources/arquillian.xml b/deltaspike/src/test/resources/arquillian.xml
index 14f9e53bbd..7f02023089 100644
--- a/deltaspike/src/test/resources/arquillian.xml
+++ b/deltaspike/src/test/resources/arquillian.xml
@@ -28,12 +28,4 @@
-
-
-
-
- target\wildfly-run\wildfly-10.0.0.Final
-
-
-
diff --git a/deltaspike/src/test/resources/import.sql b/deltaspike/src/test/resources/import.sql
new file mode 100644
index 0000000000..f6e06ecee4
--- /dev/null
+++ b/deltaspike/src/test/resources/import.sql
@@ -0,0 +1,6 @@
+INSERT INTO ADDRESS(ID, STREET, CITY, POSTCODE) VALUES (1, 'Oxford', 'London', 'N121');
+
+INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (1, 'Adam', 'LastName1', null);
+INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (2, 'David', 'LastName2', null);
+INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (3, 'Adam', 'LastName3', null);
+INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (4, 'Peter', 'LastName3', 1);
\ No newline at end of file
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 33eb7bb50a..cc914cff7e 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -1,11 +1,10 @@
+ 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
disruptor
0.1.0-SNAPSHOT
jar
-
disruptor
@@ -15,20 +14,17 @@
-
org.apache.commons
commons-lang3
${commons-lang3.version}
-
com.lmax
disruptor
${disruptor.version}
-
@@ -39,9 +35,7 @@
true
-
-
org.apache.maven.plugins
maven-dependency-plugin
@@ -58,7 +52,6 @@
-
org.apache.maven.plugins
maven-jar-plugin
@@ -72,7 +65,6 @@
-
org.apache.maven.plugins
maven-assembly-plugin
@@ -96,7 +88,6 @@
-
org.apache.maven.plugins
maven-shade-plugin
@@ -109,7 +100,7 @@
true
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
org.baeldung.executable.ExecutableMavenJar
@@ -117,7 +108,6 @@
-
com.jolira
onejar-maven-plugin
@@ -134,43 +124,13 @@
-
-
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
-
-
- json
-
-
-
-
-
-
-
-
3.5
3.3.6
-
6.10
3.6.1
diff --git a/dozer/pom.xml b/dozer/pom.xml
index 00ac2d5675..0b7f85ddb4 100644
--- a/dozer/pom.xml
+++ b/dozer/pom.xml
@@ -1,11 +1,9 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
-
com.baeldung
dozer
1.0
-
dozer
@@ -15,19 +13,16 @@
-
org.apache.commons
commons-lang3
${commons-lang3.version}
-
net.sf.dozer
dozer
${dozer.version}
-
diff --git a/drools/pom.xml b/drools/pom.xml
index 35f3f7331c..a060563eeb 100644
--- a/drools/pom.xml
+++ b/drools/pom.xml
@@ -2,18 +2,14 @@
4.0.0
-
drools
+
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
- 4.4.6
- 7.4.1.Final
- 3.13
-
+ com.baeldung
+ parent-spring-4
+ 0.0.1-SNAPSHOT
+ ../parent-spring-4
+
@@ -32,7 +28,6 @@
drools-decisiontables
${drools-version}
-
org.drools
drools-core
@@ -48,17 +43,17 @@
poi
${apache-poi-version}
-
org.apache.poi
poi-ooxml
${apache-poi-version}
-
-
- org.springframework
- spring-core
- 4.3.6.RELEASE
-
+
+
+ 4.4.6
+ 7.4.1.Final
+ 3.13
+
+
diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java
similarity index 95%
rename from drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java
rename to drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java
index f49d0b82de..fd49f94479 100644
--- a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java
+++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java
@@ -10,7 +10,7 @@ import com.baeldung.drools.model.Result;
import static junit.framework.TestCase.assertEquals;
-public class BackwardChainingTest {
+public class BackwardChainingIntegrationTest {
private Result result;
private KieSession ksession;
diff --git a/dubbo/pom.xml b/dubbo/pom.xml
index 866d1c49c9..81ff921f2a 100644
--- a/dubbo/pom.xml
+++ b/dubbo/pom.xml
@@ -1,6 +1,7 @@
4.0.0
+ dubbo
parent-modules
@@ -8,7 +9,29 @@
1.0.0-SNAPSHOT
- dubbo
+
+
+ com.alibaba
+ dubbo
+ ${dubbo.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+ org.apache.zookeeper
+ zookeeper
+ ${zookeeper.version}
+
+
+ com.101tec
+ zkclient
+ ${zkclient.version}
+
+
UTF-8
@@ -20,31 +43,4 @@
2.19.1
-
-
- com.alibaba
- dubbo
- ${dubbo.version}
-
-
- junit
- junit
- 4.12
- test
-
-
-
- org.apache.zookeeper
- zookeeper
- ${zookeeper.version}
-
-
-
- com.101tec
- zkclient
- ${zkclient.version}
-
-
-
-
diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml
index ca8ec55f12..88116f8003 100755
--- a/ejb/ejb-client/pom.xml
+++ b/ejb/ejb-client/pom.xml
@@ -1,7 +1,9 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
+ ejb-client
+ EJB3 Client Maven
com.baeldung.ejb
@@ -9,10 +11,6 @@
1.0-SNAPSHOT
- ejb-client
- EJB3 Client Maven
- EJB3 Client Maven
-
org.wildfly
@@ -25,7 +23,6 @@
ejb-remote
ejb
-
@@ -42,5 +39,5 @@
-
+
\ No newline at end of file
diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml
index beb182ff8b..b8f1f0dcc0 100755
--- a/ejb/ejb-remote/pom.xml
+++ b/ejb/ejb-remote/pom.xml
@@ -2,6 +2,8 @@
4.0.0
+ ejb-remote
+ ejb
com.baeldung.ejb
@@ -9,9 +11,6 @@
1.0-SNAPSHOT
- ejb-remote
- ejb
-
javax
@@ -21,7 +20,6 @@
-
@@ -70,7 +68,7 @@
org.wildfly.plugins
wildfly-maven-plugin
- 1.1.0.Alpha5
+ ${wildfly-maven-plugin.version}
127.0.0.1
9990
@@ -82,14 +80,12 @@
-
7.0
1.6.1
+ 1.1.0.Alpha5
-
-
-
+
\ No newline at end of file
diff --git a/ejb/ejb-session-beans/pom.xml b/ejb/ejb-session-beans/pom.xml
index 8d05389a95..6afd7f2c6d 100644
--- a/ejb/ejb-session-beans/pom.xml
+++ b/ejb/ejb-session-beans/pom.xml
@@ -1,21 +1,12 @@
- 4.0.0
-
- com.baeldung.ejb
- ejb
- 1.0-SNAPSHOT
-
- ejb-session-beans
-
-
- UTF-8
- 1.1.12.Final
- 2.2.6
- 1.1.12.Final
- 1.0.0.Final
- 4.12
- 7.0
-
+ 4.0.0
+ ejb-session-beans
+
+
+ com.baeldung.ejb
+ ejb
+ 1.0-SNAPSHOT
+
@@ -30,29 +21,23 @@
-
javax
javaee-api
${javaee-api.version}
provided
-
-
junit
junit
- 4.12
+ ${junit.version}
test
-
-
org.jboss.arquillian.junit
arquillian-junit-container
test
-
@@ -65,7 +50,7 @@
org.jboss.arquillian.container
arquillian-glassfish-embedded-3.1
- 1.0.0.CR4
+ ${arquillian-glassfish-embedded-3.1.version}
test
@@ -89,6 +74,16 @@
-
-
+
+
+ UTF-8
+ 1.1.12.Final
+ 2.2.6
+ 1.1.12.Final
+ 1.0.0.Final
+ 4.12
+ 7.0
+ 1.0.0.CR4
+
+
\ No newline at end of file
diff --git a/ejb/pom.xml b/ejb/pom.xml
index 78e40a7b7c..e61c2a0b7b 100755
--- a/ejb/pom.xml
+++ b/ejb/pom.xml
@@ -1,6 +1,6 @@
+ 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.ejb
ejb
@@ -15,6 +15,56 @@
1.0.0-SNAPSHOT
+
+ ejb-remote
+ ejb-client
+ ejb-session-beans
+
+
+
+
+
+ com.baeldung.ejb
+ ejb-remote
+ ${ejb-remote.version}
+ ejb
+
+
+ com.baeldung.ejb
+ ejb-session-beans
+ ${ejb-session-beans.version}
+ ejb
+
+
+ javax
+ javaee-api
+ ${javaee-api.version}
+ provided
+
+
+ org.wildfly
+ wildfly-ejb-client-bom
+ ${wildfly-ejb-client-bom.version}
+ pom
+ import
+
+
+
+
+
+
+
+
+ maven-ejb-plugin
+ ${maven-ejb-plugin.version}
+
+ ${ejbVersion}
+
+
+
+
+
+
jboss-public-repository-group
@@ -32,54 +82,20 @@
-
-
-
- com.baeldung.ejb
- ejb-remote
- 1.0-SNAPSHOT
- ejb
-
-
- com.baeldung.ejb
- ejb-session-beans
- 1.0-SNAPSHOT
- ejb
-
-
- javax
- javaee-api
- 7.0
- provided
-
+
+ UTF-8
+ UTF-8
+ 1.8
+ 2.5.7
+ 3.4.11
+ 0.10
+ 2.19.1
+ 1.0-SNAPSHOT
+ 1.0-SNAPSHOT
+ 7.0
+ 2.4
+ 3.2
+ 10.1.0.Final
+
-
- org.wildfly
- wildfly-ejb-client-bom
- 10.1.0.Final
- pom
- import
-
-
-
-
-
-
-
-
- maven-ejb-plugin
- 2.4
-
- 3.2
-
-
-
-
-
-
-
- ejb-remote
- ejb-client
- ejb-session-beans
-
\ No newline at end of file
diff --git a/ejb/wildfly/pom.xml b/ejb/wildfly/pom.xml
index 83dbacfa3d..ad73f4817e 100644
--- a/ejb/wildfly/pom.xml
+++ b/ejb/wildfly/pom.xml
@@ -1,85 +1,93 @@
- 4.0.0
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
- pom
-
- com.baeldung.ejb
- ejb
- 1.0-SNAPSHOT
-
-
- 1.8
- 1.8
- UTF-8
-
-
- widlfly-web
- wildfly-ear
- wildfly-jpa
- wildfly-ejb-interfaces
- wildfly-ejb
-
+ 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.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+ pom
+
+
+ com.baeldung.ejb
+ ejb
+ 1.0-SNAPSHOT
+
+
+
+ widlfly-web
+ wildfly-ear
+ wildfly-jpa
+ wildfly-ejb-interfaces
+ wildfly-ejb
+
+
+
+
+
+
+
+ javax
+ javaee-api
+ ${javaee-api.version}
+ provided
+
+
+
+ org.wildfly.bom
+ wildfly-javaee7
+ ${wildfly-javaee7.version}
+ import
+ pom
+
+
+
+ org.hibernate
+ hibernate-core
+ ${hibernate-core.version}
+ provided
+
+
+
+ com.baeldung.wildfly
+ wildlfy-ear
+ ${wildlfy.version}
+ ear
+
+
+
+ com.baeldung.wildfly
+ wildlfy-web
+ ${wildlfy.version}
+ war
+
+
+
+ com.baeldung.wildfly
+ wildlfy-jpa
+ ${wildlfy.version}
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb
+ ${wildlfy.version}
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb-interfaces
+ ${wildlfy.version}
+
+
+
+
+
+ 1.8
+ 1.8
+ UTF-8
+ 7.0
+ 10.1.0.Final
+ 5.2.3.Final
+ 0.0.1-SNAPSHOT
+
-
-
-
-
-
- javax
- javaee-api
- 7.0
- provided
-
-
-
- org.wildfly.bom
- wildfly-javaee7
- 10.1.0.Final
- import
- pom
-
-
-
- org.hibernate
- hibernate-core
- 5.2.3.Final
- provided
-
-
-
- com.baeldung.wildfly
- wildlfy-ear
- 0.0.1-SNAPSHOT
- ear
-
-
-
- com.baeldung.wildfly
- wildlfy-web
- 0.0.1-SNAPSHOT
- war
-
-
-
- com.baeldung.wildfly
- wildlfy-jpa
- 0.0.1-SNAPSHOT
-
-
-
- com.baeldung.wildfly
- wildfly-ejb
- 0.0.1-SNAPSHOT
-
-
-
- com.baeldung.wildfly
- wildfly-ejb-interfaces
- 0.0.1-SNAPSHOT
-
-
-
\ No newline at end of file
diff --git a/ejb/wildfly/widlfly-web/pom.xml b/ejb/wildfly/widlfly-web/pom.xml
index 2e316dedd9..a337e8ef60 100644
--- a/ejb/wildfly/widlfly-web/pom.xml
+++ b/ejb/wildfly/widlfly-web/pom.xml
@@ -1,39 +1,40 @@
- 4.0.0
-
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
-
- widlfly-web
- war
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ widlfly-web
+ war
-
-
-
- javax
- javaee-api
- 7.0
- provided
-
-
-
- com.baeldung.wildfly
- wildfly-jpa
- 0.0.1-SNAPSHOT
-
-
-
- com.baeldung.wildfly
- wildfly-ejb-interfaces
- 0.0.1-SNAPSHOT
-
-
-
- com.baeldung.wildfly
- wildfly-ejb
- 0.0.1-SNAPSHOT
-
-
+
+ com.baeldung.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ javax
+ javaee-api
+ ${javaee-api.version}
+ provided
+
+
+
+ com.baeldung.wildfly
+ wildfly-jpa
+ ${wildlfy.version}
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb-interfaces
+ ${wildlfy.version}
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb
+ ${wildlfy.version}
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-ear/pom.xml b/ejb/wildfly/wildfly-ear/pom.xml
index 6beb387227..f264594652 100644
--- a/ejb/wildfly/wildfly-ear/pom.xml
+++ b/ejb/wildfly/wildfly-ear/pom.xml
@@ -1,62 +1,63 @@
- 4.0.0
-
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
-
- wildfly-ear
- ear
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ wildfly-ear
+ ear
-
-
-
- com.baeldung.wildfly
- widlfly-web
- 0.0.1-SNAPSHOT
- war
-
-
-
- com.baeldung.wildfly
- wildfly-jpa
- 0.0.1-SNAPSHOT
-
-
-
- com.baeldung.wildfly
- wildfly-ejb
-
-
-
- com.baeldung.wildfly
- wildfly-ejb-interfaces
-
-
+
+ com.baeldung.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+
-
-
-
- maven-ear-plugin
- 2.10.1
-
- lib/
- 7
-
-
- com.baeldung.wildfly
- widlfly-web
- /wildfly
-
-
-
-
-
- org.wildfly.plugins
- wildfly-maven-plugin
- 1.2.0.Final
-
-
-
+
+
+
+ com.baeldung.wildfly
+ widlfly-web
+ ${wildlfy.version}
+ war
+
+
+
+ com.baeldung.wildfly
+ wildfly-jpa
+ ${wildlfy.version}
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb-interfaces
+
+
+
+
+
+
+ maven-ear-plugin
+ 2.10.1
+
+ lib/
+ 7
+
+
+ com.baeldung.wildfly
+ widlfly-web
+ /wildfly
+
+
+
+
+
+ org.wildfly.plugins
+ wildfly-maven-plugin
+ 1.2.0.Final
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-ejb-interfaces/pom.xml b/ejb/wildfly/wildfly-ejb-interfaces/pom.xml
index e4d2eee0c6..61a630b899 100644
--- a/ejb/wildfly/wildfly-ejb-interfaces/pom.xml
+++ b/ejb/wildfly/wildfly-ejb-interfaces/pom.xml
@@ -1,26 +1,32 @@
- 4.0.0
-
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
-
- wildfly-ejb-interfaces
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ wildfly-ejb-interfaces
+
+
+ com.baeldung.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ javax.ejb
+ javax.ejb-api
+ ${javax.ejb-api.version}
+ provided
+
+
+
+ com.baeldung.wildfly
+ wildfly-jpa
+ ${wildlfy.version}
+
+
+
+
+ 3.2
+
-
-
-
- javax.ejb
- javax.ejb-api
- 3.2
- provided
-
-
-
- com.baeldung.wildfly
- wildfly-jpa
- 0.0.1-SNAPSHOT
-
-
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-ejb/pom.xml b/ejb/wildfly/wildfly-ejb/pom.xml
index 9d4464dafa..900f93c0ba 100644
--- a/ejb/wildfly/wildfly-ejb/pom.xml
+++ b/ejb/wildfly/wildfly-ejb/pom.xml
@@ -1,49 +1,50 @@
- 4.0.0
-
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
-
- wildfly-ejb
- ejb
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ wildfly-ejb
+ ejb
-
-
-
- javax.ejb
- javax.ejb-api
- 3.2
- provided
-
-
-
- javax
- javaee-api
- provided
-
-
-
- org.hibernate
- hibernate-core
-
-
-
- com.baeldung.wildfly
- wildfly-ejb-interfaces
-
-
+
+ com.baeldung.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+
-
-
-
- org.apache.maven.plugins
- maven-ejb-plugin
-
- 3.2
-
-
-
-
+
+
+
+ javax.ejb
+ javax.ejb-api
+ 3.2
+ provided
+
+
+
+ javax
+ javaee-api
+ provided
+
+
+
+ org.hibernate
+ hibernate-core
+
+
+
+ com.baeldung.wildfly
+ wildfly-ejb-interfaces
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-ejb-plugin
+
+ 3.2
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-jpa/pom.xml b/ejb/wildfly/wildfly-jpa/pom.xml
index e6f8b32e17..18e86b1b31 100644
--- a/ejb/wildfly/wildfly-jpa/pom.xml
+++ b/ejb/wildfly/wildfly-jpa/pom.xml
@@ -1,20 +1,22 @@
- 4.0.0
-
- com.baeldung.wildfly
- wildfly-example
- 0.0.1-SNAPSHOT
-
- wildfly-jpa
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ wildfly-jpa
+
+
+ com.baeldung.wildfly
+ wildfly-example
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+ org.hibernate
+ hibernate-core
+ provided
+
+
-
-
-
-
- org.hibernate
- hibernate-core
- provided
-
-
\ No newline at end of file
diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml
index 1c8f5a1b4d..07842b8981 100644
--- a/enterprise-patterns/pom.xml
+++ b/enterprise-patterns/pom.xml
@@ -1,14 +1,10 @@
+ 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.enterprise.patterns
enterprise-patterns-parent
pom
-
- spring-dispatcher-servlet
-
com.baeldung
@@ -16,4 +12,8 @@
1.0.0-SNAPSHOT
+
+ spring-dispatcher-servlet
+
+
diff --git a/ethereum/README.md b/ethereum/README.md
index eb695e4bc3..d06ca09636 100644
--- a/ethereum/README.md
+++ b/ethereum/README.md
@@ -2,5 +2,5 @@
### Relevant Articles:
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
-- [Lightweight Web3](http://www.baeldung.com/lightweight-web3/)
-
+- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity)
+- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j)
diff --git a/feign/pom.xml b/feign/pom.xml
index 78e1bbcf4c..ffcde60c54 100644
--- a/feign/pom.xml
+++ b/feign/pom.xml
@@ -1,7 +1,8 @@
-
+
4.0.0
-
com.baeldung.feign
feign-client
@@ -12,13 +13,6 @@
..
-
- UTF-8
- 9.4.0
- 1.16.12
- 1.4.2.RELEASE
-
-
io.github.openfeign
@@ -60,4 +54,11 @@
+
+ UTF-8
+ 9.4.0
+ 1.16.12
+ 1.4.2.RELEASE
+
+
diff --git a/flips/pom.xml b/flips/pom.xml
index 77d1df1a8b..34cbab7035 100644
--- a/flips/pom.xml
+++ b/flips/pom.xml
@@ -1,55 +1,42 @@
4.0.0
-
flips
flips
0.0.1-SNAPSHOT
jar
-
flips
-
- parent-boot-5
+
+
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
-
- UTF-8
- 1.8
- 1.8
-
-
org.springframework.boot
spring-boot-starter-web
- 1.5.10.RELEASE
+ ${spring-boot-starter-web.version}
-
org.springframework.boot
spring-boot-starter-test
- 1.5.9.RELEASE
+ ${spring-boot-starter-test.version}
-
com.github.feature-flip
flips-web
- 1.0.1
+ ${flips-web.version}
-
org.projectlombok
lombok
- 1.16.18
+ ${lombok.version}
provided
-
-
-
@@ -67,4 +54,15 @@
+
+
+ UTF-8
+ 1.8
+ 1.8
+ 1.5.10.RELEASE
+ 1.5.9.RELEASE
+ 1.0.1
+ 1.16.18
+
+
diff --git a/flips/src/main/java/com/baeldung/flips/model/Foo.java b/flips/src/main/java/com/baeldung/flips/model/Foo.java
index d98abb79a9..be15bee15c 100644
--- a/flips/src/main/java/com/baeldung/flips/model/Foo.java
+++ b/flips/src/main/java/com/baeldung/flips/model/Foo.java
@@ -1,11 +1,12 @@
package com.baeldung.flips.model;
import lombok.Data;
+import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class Foo {
- private final String name;
- private final int id;
+ @NonNull private final String name;
+ @NonNull private final int id;
}
diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java
similarity index 96%
rename from flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java
rename to flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java
index 1b8c78e2a4..9dd4ef064a 100644
--- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java
+++ b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java
@@ -20,10 +20,10 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
"first.active.after=2999-03-15T00:00:00Z",
"logging.level.org.flips=info"
-})
+}, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
-public class FlipControllerTest {
+public class FlipControllerIntegrationTest {
@Autowired private MockMvc mvc;
diff --git a/flyway/pom.xml b/flyway/pom.xml
index 84009e4579..018f9b7f86 100644
--- a/flyway/pom.xml
+++ b/flyway/pom.xml
@@ -2,44 +2,33 @@
4.0.0
-
flyway
jar
-
flyway
Flyway Callbacks Demo
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
-
- UTF-8
- UTF-8
- 1.8
-
-
org.flywaydb
flyway-core
- 5.0.2
+ ${flyway-core.version}
-
org.springframework.boot
spring-boot-starter-jdbc
-
mysql
mysql-connector-java
- 6.0.3
+ ${mysql-connector-java.version}
-
com.h2database
h2
@@ -57,7 +46,7 @@
org.flywaydb
flyway-maven-plugin
- 5.0.2
+ ${flyway-maven-plugin.version}
com.h2database
@@ -73,4 +62,13 @@
+
+ UTF-8
+ UTF-8
+ 1.8
+ 5.0.2
+ 6.0.3
+ 5.0.2
+
+
diff --git a/geotools/pom.xml b/geotools/pom.xml
index edd3c4bf3a..9347d17fc1 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -1,24 +1,24 @@
+ 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
geotools
0.0.1-SNAPSHOT
jar
-
geotools
http://maven.apache.org
-
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
+
junit
junit
- 4.12
+ ${junit.version}
test
@@ -37,6 +37,7 @@
${geotools-swing.version}
+
maven2-repository.dev.java.net
@@ -57,7 +58,8 @@
http://repo.opengeo.org
-
+
+
15.2
15.2
15.2
diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml
index 0f1eff36f8..b6e54e33c1 100644
--- a/google-cloud/pom.xml
+++ b/google-cloud/pom.xml
@@ -1,6 +1,6 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
google-cloud
0.1-SNAPSHOT
@@ -18,7 +18,7 @@
com.google.cloud
google-cloud-storage
- 1.16.0
+ ${google-cloud-storage.version}
org.projectlombok
@@ -31,8 +31,8 @@
1.16.18
- 1.8
UTF-8
+ 1.16.0
diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml
new file mode 100644
index 0000000000..d96a589e32
--- /dev/null
+++ b/google-web-toolkit/pom.xml
@@ -0,0 +1,116 @@
+
+
+
+
+ 4.0.0
+ com.baeldung
+ google_web_toolkit
+ war
+ 1.0-SNAPSHOT
+ com.baeldung.Google_web_toolkit
+
+
+
+
+ 1.8
+ 1.8
+
+
+ UTF-8
+ UTF-8
+
+
+
+
+
+
+ com.google.gwt
+ gwt
+ 2.8.2
+ pom
+ import
+
+
+
+
+
+
+ com.google.gwt
+ gwt-servlet
+ runtime
+
+
+ com.google.gwt
+ gwt-user
+ provided
+
+
+ com.google.gwt
+ gwt-dev
+ provided
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
+
+
+
+ ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
+
+
+
+
+
+ net.ltgt.gwt.maven
+ gwt-maven-plugin
+ 1.0-rc-8
+
+
+
+ compile
+ test
+
+
+
+
+ com.baeldung.Google_web_toolkit
+ Google_web_toolkit
+ true
+
+ 1.8
+
+
+
+ -compileReport
+ -XcompilerMetrics
+
+
+ ${project.build.directory}/${project.build.finalName}
+ compile+runtime
+
+
+ Google_web_toolkit.html
+
+
+
+
+
+
+ maven-surefire-plugin
+ 2.17
+
+ true
+
+
+
+
+
+
diff --git a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml
new file mode 100644
index 0000000000..1d8ca819d9
--- /dev/null
+++ b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java b/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java
new file mode 100644
index 0000000000..ae0ae7da38
--- /dev/null
+++ b/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java
@@ -0,0 +1,108 @@
+package com.baeldung.client;
+
+import com.baeldung.shared.MessageService;
+import com.baeldung.shared.MessageServiceAsync;
+import com.google.gwt.core.client.EntryPoint;
+import com.google.gwt.core.client.GWT;
+import com.google.gwt.event.dom.client.ClickEvent;
+import com.google.gwt.event.dom.client.ClickHandler;
+import com.google.gwt.event.dom.client.KeyCodes;
+import com.google.gwt.event.dom.client.KeyUpEvent;
+import com.google.gwt.event.dom.client.KeyUpHandler;
+import com.google.gwt.user.client.rpc.AsyncCallback;
+import com.google.gwt.user.client.ui.Button;
+import com.google.gwt.user.client.ui.DialogBox;
+import com.google.gwt.user.client.ui.HTML;
+import com.google.gwt.user.client.ui.Label;
+import com.google.gwt.user.client.ui.RootPanel;
+import com.google.gwt.user.client.ui.TextBox;
+import com.google.gwt.user.client.ui.VerticalPanel;
+
+/**
+ * Entry point classes define onModuleLoad().
+ */
+public class Google_web_toolkit implements EntryPoint {
+ private final MessageServiceAsync messageServiceAsync = GWT.create(MessageService.class);
+
+ public void onModuleLoad() {
+ Button sendButton = new Button("Submit");
+ TextBox nameField = new TextBox();
+ nameField.setText("Hi there");
+
+ Label warningLabel = new Label();
+
+ sendButton.addStyleName("sendButton");
+
+ RootPanel.get("nameFieldContainer").add(nameField);
+ RootPanel.get("sendButtonContainer").add(sendButton);
+ RootPanel.get("errorLabelContainer").add(warningLabel);
+
+ Button closeButton = new Button("Thanks");
+ closeButton.getElement().setId("closeButton");
+
+ Label textToServerLabel = new Label();
+ HTML serverResponseLabel = new HTML();
+ VerticalPanel vPanel = new VerticalPanel();
+ vPanel.addStyleName("vPanel");
+ vPanel.add(new HTML("Sending message to the server:"));
+ vPanel.add(textToServerLabel);
+ vPanel.add(new HTML("Server replies: "));
+ vPanel.add(serverResponseLabel);
+ vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
+ vPanel.add(closeButton);
+ vPanel.setVisible(false);
+ RootPanel.get("serverResponseContainer").add(vPanel);
+
+ closeButton.addClickHandler(event -> {
+ sendButton.setEnabled(true);
+ sendButton.setFocus(true);
+ vPanel.setVisible(false);
+ });
+
+ class MyHandler implements ClickHandler, KeyUpHandler {
+
+ public void onClick(ClickEvent event) {
+ sendMessageToServer();
+ }
+
+ public void onKeyUp(KeyUpEvent event) {
+ if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
+ sendMessageToServer();
+ }
+ }
+
+ private void sendMessageToServer() {
+
+ warningLabel.setText("");
+ String textToServer = nameField.getText();
+ if (textToServer == null || textToServer.isEmpty()) {
+ warningLabel.setText("Please enter the message");
+ return;
+ }
+
+ sendButton.setEnabled(false);
+ textToServerLabel.setText(textToServer);
+ serverResponseLabel.setText("");
+ messageServiceAsync.sendMessage(textToServer, new AsyncCallback() {
+ public void onFailure(Throwable caught) {
+ serverResponseLabel.addStyleName("serverResponseLabelError");
+ serverResponseLabel.setHTML("server error occurred");
+ closeButton.setFocus(true);
+ }
+
+ public void onSuccess(String result) {
+ serverResponseLabel.removeStyleName("serverResponseLabelError");
+ serverResponseLabel.setHTML(result);
+ closeButton.setFocus(true);
+ vPanel.setVisible(true);
+ }
+ });
+ }
+ }
+
+ // Add a handler to send the name to the server
+ MyHandler handler = new MyHandler();
+ sendButton.addClickHandler(handler);
+ nameField.addKeyUpHandler(handler);
+ }
+}
diff --git a/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java b/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java
new file mode 100644
index 0000000000..41e2a4725c
--- /dev/null
+++ b/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java
@@ -0,0 +1,22 @@
+package com.baeldung.server;
+
+import com.baeldung.shared.MessageService;
+import com.google.gwt.user.server.rpc.RemoteServiceServlet;
+
+import java.time.LocalDateTime;
+
+/**
+ * The server-side implementation of the RPC service.
+ */
+@SuppressWarnings("serial")
+public class MessageServiceImpl extends RemoteServiceServlet implements MessageService {
+
+ public String sendMessage(String message) throws IllegalArgumentException {
+ if (message == null) {
+ throw new IllegalArgumentException("message is null");
+ }
+
+ return "Hello, " + message + "! Time received: " + LocalDateTime.now();
+ }
+
+}
diff --git a/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java
new file mode 100644
index 0000000000..2c74a5c00d
--- /dev/null
+++ b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java
@@ -0,0 +1,12 @@
+package com.baeldung.shared;
+
+import com.google.gwt.user.client.rpc.RemoteService;
+import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
+
+/**
+ * The client-side stub for the RPC service.
+ */
+@RemoteServiceRelativePath("greet")
+public interface MessageService extends RemoteService {
+ String sendMessage(String message) throws IllegalArgumentException;
+}
diff --git a/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java
new file mode 100644
index 0000000000..49d4a29b7b
--- /dev/null
+++ b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java
@@ -0,0 +1,10 @@
+package com.baeldung.shared;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+
+/**
+ * The async counterpart of MessageService.
+ */
+public interface MessageServiceAsync {
+ void sendMessage(String input, AsyncCallback callback) throws IllegalArgumentException;
+}
diff --git a/google-web-toolkit/src/main/webapp/Google_web_toolkit.css b/google-web-toolkit/src/main/webapp/Google_web_toolkit.css
new file mode 100644
index 0000000000..b02f219589
--- /dev/null
+++ b/google-web-toolkit/src/main/webapp/Google_web_toolkit.css
@@ -0,0 +1,31 @@
+/** Add css rules here for your application. */
+h1 {
+ font-size: 2em;
+ font-weight: bold;
+ color: #777777;
+ margin: 40px 0px 70px;
+ text-align: center;
+}
+
+.sendButton {
+ display: block;
+ font-size: 16pt;
+}
+
+/** Most GWT widgets already have a style name defined */
+.gwt-DialogBox {
+ width: 400px;
+}
+
+.vPanel {
+ margin: 5px;
+}
+
+.serverResponseLabelError {
+ color: red;
+}
+
+/** Set ids using widget.getElement().setId("idOfElement") */
+#closeButton {
+ margin: 15px 6px 6px;
+}
\ No newline at end of file
diff --git a/google-web-toolkit/src/main/webapp/Google_web_toolkit.html b/google-web-toolkit/src/main/webapp/Google_web_toolkit.html
new file mode 100644
index 0000000000..20bba68eff
--- /dev/null
+++ b/google-web-toolkit/src/main/webapp/Google_web_toolkit.html
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+ Sample GWT Application
+
+
+
+
+
+Sample GWT Application
+
+
+ Please enter your message:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/google-web-toolkit/src/main/webapp/WEB-INF/web.xml b/google-web-toolkit/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..820d3d9916
--- /dev/null
+++ b/google-web-toolkit/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+ greetServlet
+ com.baeldung.server.MessageServiceImpl
+
+
+
+ greetServlet
+ /google_web_toolkit/greet
+
+
+
+
+ Google_web_toolkit.html
+
+
+
diff --git a/google-web-toolkit/src/main/webapp/favicon.ico b/google-web-toolkit/src/main/webapp/favicon.ico
new file mode 100644
index 0000000000..858a707523
Binary files /dev/null and b/google-web-toolkit/src/main/webapp/favicon.ico differ
diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml
index c031ddc694..27d2cebf26 100644
--- a/graphql/graphql-java/pom.xml
+++ b/graphql/graphql-java/pom.xml
@@ -1,29 +1,33 @@
- 4.0.0
+ 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.graphql
+ graphql-java
+ 1.0
+ graphql-java
- com.baeldung.graphql
- graphql-java
- 1.0
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
- graphql-java
+
+
+ com.graphql-java
+ graphql-java-annotations
+ ${graphql-java-annotations.version}
+
+
+ io.ratpack
+ ratpack-core
+ ${ratpack-core.version}
+
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+ 3.0.3
+ 1.4.6
+
-
-
- com.graphql-java
- graphql-java-annotations
- 3.0.3
-
-
- io.ratpack
- ratpack-core
- 1.4.6
-
-
\ No newline at end of file
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 99d41172c7..fb8312e8df 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -1,23 +1,16 @@
4.0.0
-
grpc
grpc-demo
0.0.1-SNAPSHOT
jar
- grpc-demo
- http://maven.apache.org
-
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
- UTF-8
- 1.5.0
-
@@ -38,23 +31,24 @@
junit
junit
- 4.12
+ ${junit.version}
test
+
kr.motd.maven
os-maven-plugin
- 1.5.0.Final
+ ${os-maven-plugin.version}
org.xolstice.maven.plugins
protobuf-maven-plugin
- 0.5.0
+ ${protobuf-maven-plugin.version}
com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
@@ -75,4 +69,12 @@
+
+
+ UTF-8
+ 1.5.0
+ 1.5.0.Final
+ 0.5.0
+
+
diff --git a/gson/README.md b/gson/README.md
index 60c80477b1..bedfbd206c 100644
--- a/gson/README.md
+++ b/gson/README.md
@@ -6,3 +6,4 @@
### Relevant Articles:
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
+- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization)
diff --git a/gson/pom.xml b/gson/pom.xml
index 24162bb72b..9ef775122c 100644
--- a/gson/pom.xml
+++ b/gson/pom.xml
@@ -1,82 +1,74 @@
-
- 4.0.0
- com.baeldung
- gson
- 0.1-SNAPSHOT
+
+ 4.0.0
+ com.baeldung
+ gson
+ 0.1-SNAPSHOT
+ gson
- gson
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+
+
+ org.projectlombok
+ lombok
+ 1.16.10
+ provided
+
+
+ joda-time
+ joda-time
+ ${joda-time.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
-
+
+ gson
+
+
+ src/main/resources
+ true
+
+
+
-
-
-
- joda-time
- joda-time
- ${joda-time.version}
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
-
-
- com.google.code.gson
- gson
- ${gson.version}
-
-
-
-
-
- gson
-
-
- src/main/resources
- true
-
-
-
-
-
-
- 2.8.0
-
-
- 19.0
- 3.5
- 4.1
- 2.5
- 2.9.6
-
-
+
+
+ 2.8.0
+
+ 19.0
+ 3.5
+ 4.1
+ 2.5
+ 2.9.6
+
\ No newline at end of file
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java
new file mode 100644
index 0000000000..429cb9d1b5
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java
@@ -0,0 +1,11 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface Exclude {
+}
\ No newline at end of file
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java
new file mode 100644
index 0000000000..cc6c498458
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java
@@ -0,0 +1,13 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MyClass {
+ private long id;
+ private String name;
+ private String other;
+ private MySubClass subclass;
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java
new file mode 100644
index 0000000000..5d41f8a224
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java
@@ -0,0 +1,20 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import com.google.gson.annotations.Expose;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MyClassWithAnnotatedFields {
+
+ @Expose
+ private long id;
+ @Expose
+ private String name;
+ private String other;
+ @Expose
+ private MySubClassWithAnnotatedFields subclass;
+
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java
new file mode 100644
index 0000000000..ace3583013
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java
@@ -0,0 +1,16 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MyClassWithCustomAnnotatedFields {
+
+ private long id;
+ private String name;
+ @Exclude
+ private String other;
+ private MySubClassWithCustomAnnotatedFields subclass;
+
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java
new file mode 100644
index 0000000000..5e781a6287
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java
@@ -0,0 +1,15 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MyClassWithTransientFields {
+
+ private long id;
+ private String name;
+ private transient String other;
+ private MySubClassWithTransientFields subclass;
+
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java
new file mode 100644
index 0000000000..5adac0697e
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java
@@ -0,0 +1,12 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MySubClass {
+ private long id;
+ private String description;
+ private String otherVerboseInfo;
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java
new file mode 100644
index 0000000000..a0f7b5d277
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java
@@ -0,0 +1,15 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import com.google.gson.annotations.Expose;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MySubClassWithAnnotatedFields {
+
+ @Expose private long id;
+ @Expose private String description;
+ private String otherVerboseInfo;
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java
new file mode 100644
index 0000000000..f6aa4651b3
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java
@@ -0,0 +1,14 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MySubClassWithCustomAnnotatedFields {
+
+ private long id;
+ private String description;
+ @Exclude
+ private String otherVerboseInfo;
+}
diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java
new file mode 100644
index 0000000000..d4e31b0bc8
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java
@@ -0,0 +1,13 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class MySubClassWithTransientFields {
+
+ private long id;
+ private String description;
+ private transient String otherVerboseInfo;
+}
diff --git a/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java
new file mode 100644
index 0000000000..632d06946b
--- /dev/null
+++ b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java
@@ -0,0 +1,104 @@
+package org.baeldung.gson.serializationwithexclusions;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.gson.ExclusionStrategy;
+import com.google.gson.FieldAttributes;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+class SerializationWithExclusionsUnitTest {
+
+ final String expectedResult = "{\"id\":1,\"name\":\"foo\",\"subclass\":{\"id\":42,\"description\":\"the answer\"}}";
+
+ @Test
+ public void givenClassWithTransientFields_whenSerializing_thenCorrectWithoutTransientFields() {
+ MyClassWithTransientFields source = new MyClassWithTransientFields(1L, "foo", "bar", new MySubClassWithTransientFields(42L, "the answer", "Verbose field which we don't want to be serialized"));
+ String jsonString = new Gson().toJson(source);
+ assertEquals(expectedResult, jsonString);
+ }
+
+ @Test
+ public void givenClassAnnotated_whenSerializing_thenCorrectWithoutNotAnnotatedFields() {
+ MyClassWithAnnotatedFields source = new MyClassWithAnnotatedFields(1L, "foo", "bar", new MySubClassWithAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized"));
+ Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
+ .create();
+ String jsonString = gson.toJson(source);
+
+ assertEquals(expectedResult, jsonString);
+ }
+
+ @Test
+ public void givenExclusionStrategyByClassesAndFields_whenSerializing_thenFollowStrategy() {
+ MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized"));
+ ExclusionStrategy strategy = new ExclusionStrategy() {
+ @Override
+ public boolean shouldSkipField(FieldAttributes field) {
+ if (field.getDeclaringClass() == MyClass.class && field.getName()
+ .equals("other"))
+ return true;
+ if (field.getDeclaringClass() == MySubClass.class && field.getName()
+ .equals("otherVerboseInfo"))
+ return true;
+ return false;
+ }
+
+ @Override
+ public boolean shouldSkipClass(Class> clazz) {
+ return false;
+ }
+ };
+
+ Gson gson = new GsonBuilder().addSerializationExclusionStrategy(strategy)
+ .create();
+ String jsonString = gson.toJson(source);
+
+ assertEquals(expectedResult, jsonString);
+ }
+
+ @Test
+ public void givenExclusionStrategyByStartsWith_whenSerializing_thenFollowStrategy() {
+ MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized"));
+ ExclusionStrategy strategy = new ExclusionStrategy() {
+ @Override
+ public boolean shouldSkipClass(Class> clazz) {
+ return false;
+ }
+
+ @Override
+ public boolean shouldSkipField(FieldAttributes field) {
+ return field.getName().startsWith("other");
+ }
+ };
+ Gson gson = new GsonBuilder().setExclusionStrategies(strategy)
+ .create();
+ String jsonString = gson.toJson(source);
+
+ assertEquals(expectedResult, jsonString);
+ }
+
+ @Test
+ public void givenExclusionStrategyByCustomAnnotation_whenSerializing_thenFollowStrategy() {
+ MyClassWithCustomAnnotatedFields source = new MyClassWithCustomAnnotatedFields(1L, "foo", "bar", new MySubClassWithCustomAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized"));
+ ExclusionStrategy strategy = new ExclusionStrategy() {
+ @Override
+ public boolean shouldSkipClass(Class> clazz) {
+ return false;
+ }
+
+ @Override
+ public boolean shouldSkipField(FieldAttributes field) {
+ return field.getAnnotation(Exclude.class) != null;
+ }
+
+ };
+
+ Gson gson = new GsonBuilder().setExclusionStrategies(strategy)
+ .create();
+ String jsonString = gson.toJson(source);
+ assertEquals(expectedResult, jsonString);
+ }
+
+}
\ No newline at end of file
diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml
index f8dbf5657e..b3deb305f2 100644
--- a/guava-modules/guava-18/pom.xml
+++ b/guava-modules/guava-18/pom.xml
@@ -1,28 +1,20 @@
+ 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
guava-18
0.1.0-SNAPSHOT
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
- ../../
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
18.0
+
\ No newline at end of file
diff --git a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
similarity index 97%
rename from guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
index db82ea6da8..bd3a73c60f 100644
--- a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
+++ b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
@@ -11,7 +11,7 @@ import java.util.concurrent.ConcurrentHashMap;
import static org.hamcrest.CoreMatchers.equalTo;
-public class GuavaMiscUtilsTest {
+public class GuavaMiscUtilsUnitTest {
@Test
public void whenHashingData_shouldReturnCorrectHashCode() throws Exception {
int receivedData = 123;
diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml
index 4a23bf7aec..9eb20d5bbe 100644
--- a/guava-modules/guava-19/pom.xml
+++ b/guava-modules/guava-19/pom.xml
@@ -1,27 +1,18 @@
+ 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
guava-19
0.1.0-SNAPSHOT
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
- ../../
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
19.0
diff --git a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
similarity index 98%
rename from guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
index c7b8441b78..6f2d85bb04 100644
--- a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
+++ b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java
@@ -12,7 +12,7 @@ import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInA
import static org.hamcrest.core.AnyOf.anyOf;
import static org.junit.Assert.*;
-public class GuavaMiscUtilsTest {
+public class GuavaMiscUtilsUnitTest {
@Test
public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception {
diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml
index f5432fb7df..7038810d24 100644
--- a/guava-modules/guava-21/pom.xml
+++ b/guava-modules/guava-21/pom.xml
@@ -1,32 +1,28 @@
-
4.0.0
-
guava-21
1.0-SNAPSHOT
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
- ../../
-
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
+
-
- com.google.guava
- guava
- 21.0
-
-
org.jooq
jool
- 0.9.12
+ ${jool.version}
+
+ 21.0
+ 0.9.12
+
\ No newline at end of file
diff --git a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java
similarity index 98%
rename from guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java
rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java
index 866e09c6a0..e3d31d9404 100644
--- a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java
+++ b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java
@@ -13,7 +13,7 @@ import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
-public class ZipCollectionTest {
+public class ZipCollectionUnitTest {
private List names;
private List ages;
diff --git a/guava/README.md b/guava/README.md
index 08814fd8b5..bb4e225649 100644
--- a/guava/README.md
+++ b/guava/README.md
@@ -32,3 +32,4 @@
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
+- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
diff --git a/guava/pom.xml b/guava/pom.xml
index e2538d090b..b36506f87a 100644
--- a/guava/pom.xml
+++ b/guava/pom.xml
@@ -1,42 +1,31 @@
+ 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
guava
0.1.0-SNAPSHOT
-
guava
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
org.apache.commons
commons-collections4
${commons-collections4.version}
-
org.apache.commons
commons-lang3
${commons-lang3.version}
-
-
org.assertj
assertj-core
@@ -44,7 +33,13 @@
test
-
+
+
+ org.hamcrest
+ java-hamcrest
+ ${java-hamcrest.version}
+ test
+
@@ -65,6 +60,7 @@
3.6.1
+ 2.0.0.0
\ No newline at end of file
diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java
similarity index 97%
rename from guava/src/test/java/org/baeldung/guava/BloomFilterTest.java
rename to guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java
index d7c25b7c8d..ff3031a0cb 100644
--- a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java
+++ b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java
@@ -9,7 +9,7 @@ import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
-public class BloomFilterTest {
+public class BloomFilterUnitTest {
@Test
public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() {
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java
similarity index 94%
rename from guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java
rename to guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java
index 5e96f3597c..7293b1631e 100644
--- a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java
+++ b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java
@@ -7,7 +7,7 @@ import org.junit.Test;
import com.google.common.io.CountingOutputStream;
-public class GuavaCountingOutputStreamTest {
+public class GuavaCountingOutputStreamUnitTest {
public static final int MAX = 5;
@Test(expected = RuntimeException.class)
diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java b/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java
index 6b9cee1992..82b6b8c87c 100644
--- a/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java
+++ b/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java
@@ -12,6 +12,7 @@ import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
+import static org.hamcrest.Matchers.emptyIterable;
import java.util.Collections;
import java.util.List;
@@ -57,6 +58,12 @@ public class HamcrestExamplesUnitTest {
final List collection = Lists.newArrayList();
assertThat(collection, empty());
}
+
+ @Test
+ public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
+ final Iterable collection = Lists.newArrayList();
+ assertThat(collection, emptyIterable());
+ }
@Test
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {
diff --git a/guava/src/test/java/org/baeldung/hamcrest/README.md b/guava/src/test/java/org/baeldung/hamcrest/README.md
index 7266ecda3a..456108d78a 100644
--- a/guava/src/test/java/org/baeldung/hamcrest/README.md
+++ b/guava/src/test/java/org/baeldung/hamcrest/README.md
@@ -1,2 +1,3 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)
+- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers)
diff --git a/guest/core-java-9/pom.xml b/guest/core-java-9/pom.xml
index e37f696e33..f8e2dcce85 100644
--- a/guest/core-java-9/pom.xml
+++ b/guest/core-java-9/pom.xml
@@ -1,32 +1,40 @@
- 4.0.0
- com.stackify
- core-java-9
- 0.0.1-SNAPSHOT
-
+ 4.0.0
+ com.stackify
+ core-java-9
+ 0.0.1-SNAPSHOT
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
+
+
junit
junit
- 4.12
+ ${junit.version}
-
-
-
-
- maven-compiler-plugin
- 3.7.0
-
- 1.9
- 1.9
-
-
-
-
+
+
+
+
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+
+
+ 1.9
+ 1.9
+
+
\ No newline at end of file
diff --git a/guest/core-java/pom.xml b/guest/core-java/pom.xml
index ccad9b87cf..b3c6ba9564 100644
--- a/guest/core-java/pom.xml
+++ b/guest/core-java/pom.xml
@@ -1,26 +1,28 @@
- 4.0.0
- com.stackify
- core-java
- 0.0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.stackify
+ core-java
+ 0.0.1-SNAPSHOT
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
- junit
- junit
- 4.12
-
-
- org.apache.logging.log4j
- log4j-core
- ${log4j2.version}
-
+
+
+
+ junit
+ junit
+ ${junit.version}
+
+
+ org.apache.logging.log4j
+ log4j-core
+ ${log4j2.version}
+
org.hamcrest
hamcrest-core
@@ -39,9 +41,18 @@
${org.hamcrest.version}
test
-
-
- 2.8.2
- 1.3
-
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+
+ 2.8.2
+ 1.3
+ 3.6.1
+
+
\ No newline at end of file
diff --git a/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitamin.java b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitamin.java
new file mode 100644
index 0000000000..90cb49b321
--- /dev/null
+++ b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitamin.java
@@ -0,0 +1,50 @@
+package com.stackify.optionalparams;
+
+public class MultiVitamin {
+
+ private String name; // required
+ private int vitaminA; // in mcg
+ private int vitaminC; // in mg
+ private int calcium; // in mg
+ private int iron; // in mg
+
+ public MultiVitamin(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getVitaminA() {
+ return vitaminA;
+ }
+
+ public void setVitaminA(int vitaminA) {
+ this.vitaminA = vitaminA;
+ }
+
+ public int getVitaminC() {
+ return vitaminC;
+ }
+
+ public void setVitaminC(int vitaminC) {
+ this.vitaminC = vitaminC;
+ }
+
+ public int getCalcium() {
+ return calcium;
+ }
+
+ public void setCalcium(int calcium) {
+ this.calcium = calcium;
+ }
+
+ public int getIron() {
+ return iron;
+ }
+
+ public void setIron(int iron) {
+ this.iron = iron;
+ }
+}
\ No newline at end of file
diff --git a/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminAllowingNulls.java b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminAllowingNulls.java
new file mode 100644
index 0000000000..1d2a61354d
--- /dev/null
+++ b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminAllowingNulls.java
@@ -0,0 +1,38 @@
+package com.stackify.optionalparams;
+
+public class MultiVitaminAllowingNulls {
+
+ private String name; // required
+ private Integer vitaminA; // in mcg
+ private Integer vitaminC; // in mg
+ private Integer calcium; // in mg
+ private Integer iron; // in mg
+
+ public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) {
+ this.name = name;
+ this.vitaminA = vitaminA;
+ this.vitaminC = vitaminC;
+ this.calcium = calcium;
+ this.iron = iron;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Integer getVitaminA() {
+ return vitaminA;
+ }
+
+ public Integer getVitaminC() {
+ return vitaminC;
+ }
+
+ public Integer getCalcium() {
+ return calcium;
+ }
+
+ public Integer getIron() {
+ return iron;
+ }
+}
\ No newline at end of file
diff --git a/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminOverloading.java b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminOverloading.java
new file mode 100644
index 0000000000..e9dcb2509b
--- /dev/null
+++ b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminOverloading.java
@@ -0,0 +1,56 @@
+package com.stackify.optionalparams;
+
+public class MultiVitaminOverloading {
+
+ static final int DEFAULT_IRON_AMOUNT = 20;
+
+ private final String name; // required
+ private final int vitaminA; // in mcg
+ private final int vitaminC; // in mg
+ private final int calcium; // in mg
+ private final int iron; // in mg
+
+ public MultiVitaminOverloading(String name) {
+ this(name, 0);
+ }
+
+ public MultiVitaminOverloading(String name, int vitaminA) {
+ this(name, vitaminA, 0);
+ }
+
+ public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) {
+ this(name, vitaminA, vitaminC, 0);
+ }
+
+ public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) {
+ this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT);
+ }
+
+ public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) {
+ this.name = name;
+ this.vitaminA = vitaminA;
+ this.vitaminC = vitaminC;
+ this.calcium = calcium;
+ this.iron = iron;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getVitaminA() {
+ return vitaminA;
+ }
+
+ public int getVitaminC() {
+ return vitaminC;
+ }
+
+ public int getCalcium() {
+ return calcium;
+ }
+
+ public int getIron() {
+ return iron;
+ }
+}
\ No newline at end of file
diff --git a/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminStaticFactoryMethods.java b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminStaticFactoryMethods.java
new file mode 100644
index 0000000000..229a2f0004
--- /dev/null
+++ b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminStaticFactoryMethods.java
@@ -0,0 +1,52 @@
+package com.stackify.optionalparams;
+
+public class MultiVitaminStaticFactoryMethods {
+
+ static final int IRON_AMT_DEF = 20;
+ static final int IRON_AMT_MEN = 30;
+
+ static final int CALCIUM_AMT_DEF = 100;
+ static final int CALCIUM_AMT_WOMEN = 120;
+
+ private final String name; // required
+ private final int vitaminA; // in mcg
+ private final int vitaminC; // in mg
+ private final int calcium; // in mg
+ private final int iron; // in mg
+
+ public static MultiVitaminStaticFactoryMethods forMen(String name) {
+ return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN);
+ }
+
+ public static MultiVitaminStaticFactoryMethods forWomen(String name) {
+ return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF);
+ }
+
+ private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) {
+ this.name = name;
+ this.vitaminA = vitaminA;
+ this.vitaminC = vitaminC;
+ this.calcium = calcium;
+ this.iron = iron;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getVitaminA() {
+ return vitaminA;
+ }
+
+ public int getVitaminC() {
+ return vitaminC;
+ }
+
+ public int getCalcium() {
+ return calcium;
+ }
+
+ public int getIron() {
+ return iron;
+ }
+}
\ No newline at end of file
diff --git a/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminWithBuilder.java b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminWithBuilder.java
new file mode 100644
index 0000000000..8097074b86
--- /dev/null
+++ b/guest/core-java/src/main/java/com/stackify/optionalparams/MultiVitaminWithBuilder.java
@@ -0,0 +1,77 @@
+package com.stackify.optionalparams;
+
+public class MultiVitaminWithBuilder {
+
+ private final String name; // required
+ private final int vitaminA; // in mcg
+ private final int vitaminC; // in mg
+ private final int calcium; // in mg
+ private final int iron; // in mg
+
+ private MultiVitaminWithBuilder(MultiVitaminBuilder builder) {
+ this.name = builder.name;
+ this.vitaminA = builder.vitaminA;
+ this.vitaminC = builder.vitaminC;
+ this.calcium = builder.calcium;
+ this.iron = builder.iron;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getVitaminA() {
+ return vitaminA;
+ }
+
+ public int getVitaminC() {
+ return vitaminC;
+ }
+
+ public int getCalcium() {
+ return calcium;
+ }
+
+ public int getIron() {
+ return iron;
+ }
+
+ public static class MultiVitaminBuilder {
+
+ private static final int ZERO = 0;
+
+ private final String name; // required
+ private int vitaminA = ZERO;
+ private int vitaminC = ZERO;
+ private int calcium = ZERO;
+ private int iron = ZERO;
+
+ public MultiVitaminBuilder(String name) {
+ this.name = name;
+ }
+
+ public MultiVitaminBuilder withVitaminA(int vitaminA) {
+ this.vitaminA = vitaminA;
+ return this;
+ }
+
+ public MultiVitaminBuilder withVitaminC(int vitaminC) {
+ this.vitaminC = vitaminC;
+ return this;
+ }
+
+ public MultiVitaminBuilder withCalcium(int calcium) {
+ this.calcium = calcium;
+ return this;
+ }
+
+ public MultiVitaminBuilder withIron(int iron) {
+ this.iron = iron;
+ return this;
+ }
+
+ public MultiVitaminWithBuilder build() {
+ return new MultiVitaminWithBuilder(this);
+ }
+ }
+}
diff --git a/guest/core-java/src/test/java/com/stackify/optionalparams/OptionalParamsUnitTest.java b/guest/core-java/src/test/java/com/stackify/optionalparams/OptionalParamsUnitTest.java
new file mode 100644
index 0000000000..947ce83a90
--- /dev/null
+++ b/guest/core-java/src/test/java/com/stackify/optionalparams/OptionalParamsUnitTest.java
@@ -0,0 +1,96 @@
+package com.stackify.optionalparams;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.math.BigDecimal;
+
+import org.assertj.core.util.Arrays;
+import org.junit.Test;
+
+public class OptionalParamsUnitTest {
+
+ @Test
+ public void whenCreateMultiVitaminWithOverloading_thenOk() {
+ MultiVitaminOverloading multiVitamin = new MultiVitaminOverloading("Default Multivitamin");
+
+ assertThat(multiVitamin.getName()).isEqualTo("Default Multivitamin");
+ assertThat(multiVitamin.getVitaminA()).isEqualTo(0);
+ assertThat(multiVitamin.getVitaminC()).isEqualTo(0);
+ assertThat(multiVitamin.getCalcium()).isEqualTo(0);
+ assertThat(multiVitamin.getIron()).isEqualTo(MultiVitaminOverloading.DEFAULT_IRON_AMOUNT);
+ }
+
+ @Test
+ public void whenCreateMultiVitaminWithStaticFactoryMethods_thenOk() {
+ MultiVitaminStaticFactoryMethods mensMultiVitamin = MultiVitaminStaticFactoryMethods.forMen("Complete for Men");
+
+ assertThat(mensMultiVitamin.getName()).isEqualTo("Complete for Men");
+ assertThat(mensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_DEF);
+ assertThat(mensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_MEN);
+
+ MultiVitaminStaticFactoryMethods womensMultiVitamin = MultiVitaminStaticFactoryMethods.forWomen("Complete for Women");
+
+ assertThat(womensMultiVitamin.getName()).isEqualTo("Complete for Women");
+ assertThat(womensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_WOMEN);
+ assertThat(womensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_DEF);
+ }
+
+ @Test
+ public void whenCreateMultiVitaminWithBuilder_thenOk() {
+ MultiVitaminWithBuilder vitamin = new MultiVitaminWithBuilder.MultiVitaminBuilder("Maximum Strength")
+ .withCalcium(100)
+ .withIron(200)
+ .withVitaminA(50)
+ .withVitaminC(1000)
+ .build();
+
+ assertThat(vitamin.getName()).isEqualTo("Maximum Strength");
+ assertThat(vitamin.getCalcium()).isEqualTo(100);
+ assertThat(vitamin.getIron()).isEqualTo(200);
+ assertThat(vitamin.getVitaminA()).isEqualTo(50);
+ assertThat(vitamin.getVitaminC()).isEqualTo(1000);
+ }
+
+ @Test
+ public void whenCreateMutliVitaminWithAccessors_thenOk() {
+ MultiVitamin vitamin = new MultiVitamin("Generic");
+ vitamin.setVitaminA(50);
+ vitamin.setVitaminC(1000);
+ vitamin.setCalcium(100);
+ vitamin.setIron(200);
+
+ assertThat(vitamin.getName()).isEqualTo("Generic");
+ assertThat(vitamin.getCalcium()).isEqualTo(100);
+ assertThat(vitamin.getIron()).isEqualTo(200);
+ assertThat(vitamin.getVitaminA()).isEqualTo(50);
+ assertThat(vitamin.getVitaminC()).isEqualTo(1000);
+ }
+
+ @Test
+ public void whenCreateMultiVitaminWithNulls_thenOk() {
+ MultiVitamin vitamin = new MultiVitamin(null);
+
+ assertThat(vitamin.getName()).isNull();
+ }
+
+ public void varArgsDemo() {
+ Object[] args = Arrays.array(Long.valueOf(1), Integer.valueOf(2), BigDecimal.valueOf(3));
+
+ processVarArgsWithCastingAntiPattern(args);
+ }
+
+ private void processVarArgsWithCastingAntiPattern(Object... args) {
+ String message = "processing %s as %s";
+
+ // never do this sort of thing
+ for (Object arg : args) {
+ if (arg instanceof Long) {
+ System.out.println(String.format(message, arg, "Long"));
+ } else if (arg instanceof Integer) {
+ System.out.println(String.format(message, arg, "Integer"));
+ } else if (arg instanceof BigDecimal) {
+ System.out.println(String.format(message, arg, "BigDecimal"));
+ }
+ }
+ }
+}
diff --git a/guest/deep-jsf/pom.xml b/guest/deep-jsf/pom.xml
index bbb544443f..bd02b145d0 100644
--- a/guest/deep-jsf/pom.xml
+++ b/guest/deep-jsf/pom.xml
@@ -6,11 +6,11 @@
deep-jsf
0.0.1-SNAPSHOT
war
-
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
false
diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml
index c9ea232715..93ce207940 100644
--- a/guest/junit5-example/pom.xml
+++ b/guest/junit5-example/pom.xml
@@ -1,65 +1,64 @@
- 4.0.0
- junit5-example
- junit5-example
- 0.0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ junit5-example
+ junit5-example
+ 0.0.1-SNAPSHOT
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
- org.junit.jupiter
- junit-jupiter-engine
- 5.0.0-M4
-
-
- org.junit.jupiter
- junit-jupiter-params
- 5.0.0-M4
-
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ 5.0.0-M4
+
-
- org.junit.vintage
- junit-vintage-engine
- 4.12.0-M4
-
+
+ org.junit.vintage
+ junit-vintage-engine
+ 4.12.0-M4
+
-
- com.h2database
- h2
- 1.4.195
-
+
+ com.h2database
+ h2
+ 1.4.195
+
-
- org.apache.logging.log4j
- log4j-core
- 2.8.2
-
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.2
+
-
+
-
-
-
- maven-surefire-plugin
- 2.19.1
-
-
- org.junit.platform
- junit-platform-surefire-provider
- 1.0.0-M4
-
-
-
-
- math
-
-
-
-
-
+
+
+
+ maven-surefire-plugin
+ 2.19.1
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ 1.0.0-M4
+
+
+
+
+ math
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/log4j2-example/pom.xml b/guest/log4j2-example/pom.xml
index 26e026448f..760af88a06 100644
--- a/guest/log4j2-example/pom.xml
+++ b/guest/log4j2-example/pom.xml
@@ -1,51 +1,51 @@
- 4.0.0
- log4j2-example
- log4j2-example
- 0.0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ log4j2-example
+ log4j2-example
+ 0.0.1-SNAPSHOT
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
-
- org.apache.logging.log4j
- log4j-core
- ${log4j-core.version}
-
+
+
+
+ org.apache.logging.log4j
+ log4j-core
+ ${log4j-core.version}
+
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
- junit
- junit
- 4.12
-
-
+
+ junit
+ junit
+ 4.12
+
+
-
-
-
- src/main/resources/
-
- **/*.java
-
-
-
-
+
+
+
+ src/main/resources/
+
+ **/*.java
+
+
+
+
-
- 2.8.8.1
- 2.8.2
-
+
+ 2.8.8.1
+ 2.8.2
+
\ No newline at end of file
diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml
index 8240e45b6a..d913db26bd 100644
--- a/guest/logback-example/pom.xml
+++ b/guest/logback-example/pom.xml
@@ -1,32 +1,32 @@
- 4.0.0
- com.stackify
- logback-example
- 0.0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.stackify
+ logback-example
+ 0.0.1-SNAPSHOT
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
- ch.qos.logback
- logback-classic
- 1.2.3
-
+
+
+ ch.qos.logback
+ logback-classic
+ 1.2.3
+
-
- junit
- junit
- 4.12
-
+
+ junit
+ junit
+ 4.12
+
-
- org.codehaus.janino
- janino
- 3.0.7
-
-
+
+ org.codehaus.janino
+ janino
+ 3.0.7
+
+
\ No newline at end of file
diff --git a/guest/memory-leaks/pom.xml b/guest/memory-leaks/pom.xml
index 63d5af9474..0bb201dd2f 100644
--- a/guest/memory-leaks/pom.xml
+++ b/guest/memory-leaks/pom.xml
@@ -1,34 +1,36 @@
- 4.0.0
- com.baeldung
- memory-leaks
- 0.0.1-SNAPSHOT
-
+ 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
+ memory-leaks
+ 0.0.1-SNAPSHOT
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
- junit
- junit
- 4.12
-
-
-
-
-
- src/main/resources/
-
- **/*.java
-
-
-
- src/test/resources/
-
-
-
+
+
+ junit
+ junit
+ ${junit.version}
+
+
+
+
+
+
+ src/main/resources/
+
+ **/*.java
+
+
+
+ src/test/resources/
+
+
+
\ No newline at end of file
diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml
index 8540347e40..6e077fce56 100644
--- a/guest/remote-debugging/pom.xml
+++ b/guest/remote-debugging/pom.xml
@@ -2,7 +2,6 @@
4.0.0
-
com.stackify
java-remote-debugging
0.0.1-SNAPSHOT
@@ -11,28 +10,19 @@
org.springframework.boot
spring-boot-starter-parent
- 1.5.8.RELEASE
+ ${spring-boot-starter-parent.version}
-
- UTF-8
- UTF-8
- 1.8
-
-
-
org.springframework.boot
spring-boot-starter-web
-
org.springframework.boot
spring-boot-starter-tomcat
-
@@ -45,4 +35,10 @@
+
+ UTF-8
+ UTF-8
+ 1.5.8.RELEASE
+
+
diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
index 254272e1c0..e3c07ab38a 100644
--- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
+++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF
@@ -1,3 +1,2 @@
Manifest-Version: 1.0
Class-Path:
-
diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile
new file mode 100644
index 0000000000..211e8927a3
--- /dev/null
+++ b/guest/spring-boot-app/docker/Dockerfile
@@ -0,0 +1,16 @@
+# Alpine Linux with OpenJDK JRE
+FROM openjdk:8-jre-alpine
+RUN apk add --no-cache bash
+
+# copy fat WAR
+COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war
+
+# copy fat WAR
+COPY logback.xml /logback.xml
+
+COPY run.sh /run.sh
+
+# runs application
+#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"]
+
+ENTRYPOINT ["/run.sh"]
diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml
new file mode 100644
index 0000000000..7e03ddc827
--- /dev/null
+++ b/guest/spring-boot-app/docker/logback.xml
@@ -0,0 +1,15 @@
+
+
+
+
+ /var/log/Application/application.log
+ true
+
+ %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n
+
+
+
+
+
+
+
diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh
new file mode 100755
index 0000000000..aeecc29371
--- /dev/null
+++ b/guest/spring-boot-app/docker/run.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war
+
diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml
index ba57bbd5c5..c02eef7ef3 100644
--- a/guest/spring-boot-app/pom.xml
+++ b/guest/spring-boot-app/pom.xml
@@ -51,6 +51,22 @@
WebContent
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ com.stackify.Application
+ ${project.basedir}/docker
+
+
+
+
+
@@ -58,4 +74,4 @@
8.0.43
-
\ No newline at end of file
+
diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml
index 1f695a75a7..da4d27b14d 100644
--- a/guest/spring-mvc/pom.xml
+++ b/guest/spring-mvc/pom.xml
@@ -2,19 +2,17 @@
4.0.0
-
com.stackify.guest
spring-mvc
0.0.1-SNAPSHOT
jar
-
spring-mvc
Spring MVC sample project
org.springframework.boot
spring-boot-starter-parent
- 2.0.0.M5
+ ${spring-boot-starter-parent.version}
@@ -29,31 +27,10 @@
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
UTF-8
UTF-8
- 1.8
+ 2.0.0.M5
diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml
index c41637bfc2..793df750de 100644
--- a/guest/spring-security/pom.xml
+++ b/guest/spring-security/pom.xml
@@ -3,21 +3,19 @@
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
-
com.stackify.guest
spring-security
1.0-SNAPSHOT
+ spring-security
+ Spring Security Sample Project
org.springframework.boot
spring-boot-starter-parent
- 2.0.0.M6
+ ${spring-boot-starter-parent.version}
- spring-security
- Spring Security Sample Project
-
org.springframework.boot
@@ -30,7 +28,7 @@
org.thymeleaf
thymeleaf-spring5
- 3.0.8.RELEASE
+ ${thymeleaf-spring5.version}
org.springframework.boot
@@ -47,31 +45,11 @@
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
UTF-8
UTF-8
- 1.8
+ 3.0.8.RELEASE
+ 2.0.0.M6
\ No newline at end of file
diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml
index 42770edb2a..56173b1285 100644
--- a/guest/thread-pools/pom.xml
+++ b/guest/thread-pools/pom.xml
@@ -1,20 +1,27 @@
- 4.0.0
- com.stackify
- thread-pools
- 0.0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.stackify
+ thread-pools
+ 0.0.1-SNAPSHOT
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
-
-
- ch.qos.logback
- logback-classic
- 1.2.3
-
-
+
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback-classic.version}
+
+
+
+
+ 1.2.3
+
+
\ No newline at end of file
diff --git a/guest/tomcat-app/pom.xml b/guest/tomcat-app/pom.xml
index 2ea5190248..f3447b08c3 100644
--- a/guest/tomcat-app/pom.xml
+++ b/guest/tomcat-app/pom.xml
@@ -1,56 +1,54 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.stackify
tomcat-app
0.0.1-SNAPSHOT
war
-
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../
+ ../../
+
org.glassfish.jersey.containers
jersey-container-servlet
- 2.25.1
+ ${jersey-container-servlet.version}
org.glassfish.jersey.media
jersey-media-moxy
- 2.25.1
+ ${jersey-media-moxy.version}
io.rest-assured
rest-assured
- 3.0.3
+ ${rest-assured.version}
junit
junit
- 4.12
+ ${junit.version}
-
com.h2database
h2
- 1.4.195
+ ${h2database.version}
-
org.apache.logging.log4j
log4j-core
- 2.8.2
+ ${log4j-core.version}
-
net.bull.javamelody
javamelody-core
- 1.69.0
+ ${javamelody-core.version}
-
@@ -64,4 +62,15 @@
+
+
+ 1.2.3
+ 2.25.1
+ 1.4.195
+ 3.0.3
+ 2.8.2
+ 1.69.0
+ 2.25.1
+
+
\ No newline at end of file
diff --git a/guest/webservices/rest-client/pom.xml b/guest/webservices/rest-client/pom.xml
index b124e632a3..84f4eaf3c0 100644
--- a/guest/webservices/rest-client/pom.xml
+++ b/guest/webservices/rest-client/pom.xml
@@ -1,25 +1,32 @@
- 4.0.0
- com.stackify
- rest-client
- 0.0.1-SNAPSHOT
- war
-
+ 4.0.0
+ com.stackify
+ rest-client
+ 0.0.1-SNAPSHOT
+ war
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../../
+ ../../../
-
-
-
- maven-war-plugin
- 2.6
-
- WebContent
- false
-
-
-
-
+
+
+
+
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ WebContent
+ false
+
+
+
+
+
+
+ 2.6
+
+
\ No newline at end of file
diff --git a/guest/webservices/rest-server/pom.xml b/guest/webservices/rest-server/pom.xml
index a183d4110c..955afdd82c 100644
--- a/guest/webservices/rest-server/pom.xml
+++ b/guest/webservices/rest-server/pom.xml
@@ -1,48 +1,58 @@
- 4.0.0
- com.stackify
- rest-server
- 0.0.1-SNAPSHOT
- war
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.stackify
+ rest-server
+ 0.0.1-SNAPSHOT
+ war
+
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../../../
+ ../../../
-
-
- org.glassfish.jersey.containers
- jersey-container-servlet
- 2.25.1
-
-
- org.glassfish.jersey.media
- jersey-media-moxy
- 2.25.1
-
-
- io.rest-assured
- rest-assured
- 3.0.3
-
-
- junit
- junit
- 4.12
-
-
-
-
-
- maven-war-plugin
- 3.0.0
-
- WebContent
-
-
-
-
+
+
+ org.glassfish.jersey.containers
+ jersey-container-servlet
+ ${jersey-container-servlet.version}
+
+
+ org.glassfish.jersey.media
+ jersey-media-moxy
+ ${jersey-media-moxy.version}
+
+
+ io.rest-assured
+ rest-assured
+ ${rest-assured.version}
+
+
+ junit
+ junit
+ ${junit.version}
+
+
+
+
+
+
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ WebContent
+
+
+
+
+
+
+ 3.0.0
+ 2.25.1
+ 3.0.3
+ 2.25.1
+
+
\ No newline at end of file
diff --git a/guest/webservices/spring-rest-service/pom.xml b/guest/webservices/spring-rest-service/pom.xml
index 11082cf17b..74b76ee725 100644
--- a/guest/webservices/spring-rest-service/pom.xml
+++ b/guest/webservices/spring-rest-service/pom.xml
@@ -1,48 +1,59 @@
- 4.0.0
- com.stackify
- spring-rest-service
- 0.0.1-SNAPSHOT
- war
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.stackify
+ spring-rest-service
+ 0.0.1-SNAPSHOT
+ war
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.5.4.RELEASE
-
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ ${spring-boot-starter-parent.version}
+
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-hateoas
-
-
- io.springfox
- springfox-swagger2
- 2.7.0
-
-
- io.springfox
- springfox-swagger-ui
- 2.7.0
-
-
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-hateoas
+
+
+ io.springfox
+ springfox-swagger2
+ ${springfox-swagger2.version}
+
+
+ io.springfox
+ springfox-swagger-ui
+ ${springfox-swagger-ui.version}
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+
+
+ UTF-8
+ UTF-8
+ 1.5.4.RELEASE
+ 2.7.0
+ 2.7.0
+ 1.8
+ 1.8
+
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
- 1.8
- 1.8
-
-
-
-
\ No newline at end of file
diff --git a/guice/pom.xml b/guice/pom.xml
index 17b599a379..ba0ed39c4a 100644
--- a/guice/pom.xml
+++ b/guice/pom.xml
@@ -1,11 +1,12 @@
+ 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.examples.guice
guice
1.0-SNAPSHOT
jar
+ guice
com.baeldung
@@ -20,9 +21,10 @@
${guice.version}
+
UTF-8
4.1.0
- guice
+
diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml
deleted file mode 100644
index cf944804db..0000000000
--- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml
deleted file mode 100644
index 94bd63e068..0000000000
--- a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml
index 2811bf8b12..aa7faa07cf 100644
--- a/hazelcast/pom.xml
+++ b/hazelcast/pom.xml
@@ -1,5 +1,5 @@
+ 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
hazelcast
@@ -18,13 +18,11 @@
hazelcast
${hazelcast.version}
-
com.hazelcast
hazelcast-client
${hazelcast.version}
-
diff --git a/hbase/pom.xml b/hbase/pom.xml
index 5fe47fcdc7..ff4aa15130 100644
--- a/hbase/pom.xml
+++ b/hbase/pom.xml
@@ -1,14 +1,14 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ hbase
+
parent-modules
com.baeldung
1.0.0-SNAPSHOT
- 4.0.0
-
- hbase
@@ -34,5 +34,4 @@
1.3.1
-
\ No newline at end of file
diff --git a/hibernate5/README.md b/hibernate5/README.md
index 4b7912056a..afba239919 100644
--- a/hibernate5/README.md
+++ b/hibernate5/README.md
@@ -9,3 +9,7 @@
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
+- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
+- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
+- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
+
diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml
index a9dcf56c1c..6ed13b8ae4 100644
--- a/hibernate5/pom.xml
+++ b/hibernate5/pom.xml
@@ -1,27 +1,21 @@
- 4.0.0
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
- com.baeldung
- hibernate5
- 0.0.1-SNAPSHOT
- hibernate5
- http://maven.apache.org
-
- UTF-8
-
- 3.7.0
- 5.2.12.Final
- 6.0.6
- 2.2.3
-
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ 4.0.0
+ com.baeldung
+ hibernate5
+ 0.0.1-SNAPSHOT
+ hibernate5
+ http://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
org.hibernate
hibernate-core
@@ -30,18 +24,18 @@
junit
junit
- 4.12
+ ${junit.version}
org.assertj
assertj-core
- 3.8.0
+ ${assertj-core.version}
test
com.h2database
h2
- 1.4.196
+ ${h2database.version}
org.hibernate
@@ -58,8 +52,9 @@
mariaDB4j
${mariaDB4j.version}
-
-
+
+
+
hibernate5
@@ -68,4 +63,16 @@
+
+
+ UTF-8
+
+ 3.7.0
+ 5.2.12.Final
+ 6.0.6
+ 2.2.3
+ 1.4.196
+ 3.8.0
+
+
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
index 130edec8cc..23d7d2e201 100644
--- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -1,30 +1,14 @@
package com.baeldung.hibernate;
-import com.baeldung.hibernate.pojo.Employee;
-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.PolygonEntity;
-import com.baeldung.hibernate.pojo.Product;
-import com.baeldung.hibernate.pojo.Phone;
-import com.baeldung.hibernate.pojo.TemporalValues;
-import com.baeldung.hibernate.pojo.Course;
-import com.baeldung.hibernate.pojo.Student;
-import com.baeldung.hibernate.pojo.User;
-import com.baeldung.hibernate.pojo.UserProfile;
-import com.baeldung.hibernate.pojo.inheritance.Animal;
-import com.baeldung.hibernate.pojo.inheritance.Bag;
-import com.baeldung.hibernate.pojo.inheritance.Book;
-import com.baeldung.hibernate.pojo.inheritance.Car;
-import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
-import com.baeldung.hibernate.pojo.inheritance.MyProduct;
-import com.baeldung.hibernate.pojo.inheritance.Pen;
-import com.baeldung.hibernate.pojo.inheritance.Person;
-import com.baeldung.hibernate.pojo.inheritance.Pet;
-import com.baeldung.hibernate.pojo.inheritance.Vehicle;
-
+import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
+import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
+import com.baeldung.hibernate.pessimisticlocking.Individual;
+import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
+import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
+import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
+import com.baeldung.hibernate.pojo.*;
+import com.baeldung.hibernate.pojo.Person;
+import com.baeldung.hibernate.pojo.inheritance.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
@@ -82,6 +66,14 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
+ metadataSources.addAnnotatedClass(Individual.class);
+ metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
+ metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
+ metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
+ metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
+ metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
+ metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
+ metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
new file mode 100644
index 0000000000..f7b8e6bf6d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.jpabootstrap.application;
+
+import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
+import com.baeldung.hibernate.jpabootstrap.entities.User;
+import javax.persistence.EntityManager;
+
+public class Application {
+
+ public static void main(String[] args) {
+ EntityManager entityManager = getJpaEntityManager();
+ User user = entityManager.find(User.class, 1);
+ System.out.println(user);
+ entityManager.getTransaction().begin();
+ user.setName("John");
+ user.setEmail("john@domain.com");
+ entityManager.merge(user);
+ entityManager.getTransaction().commit();
+ entityManager.getTransaction().begin();
+ entityManager.persist(new User("Monica", "monica@domain.com"));
+ entityManager.getTransaction().commit();
+
+ // additional CRUD operations
+
+ }
+
+ private static class EntityManagerHolder {
+ private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
+ new Class[]{User.class}).getEntityManager();
+ }
+
+ public static EntityManager getJpaEntityManager() {
+ return EntityManagerHolder.ENTITY_MANAGER;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
new file mode 100644
index 0000000000..3852b44b64
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
@@ -0,0 +1,131 @@
+package com.baeldung.hibernate.jpabootstrap.config;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+import javax.sql.DataSource;
+import javax.persistence.SharedCacheMode;
+import javax.persistence.ValidationMode;
+import javax.persistence.spi.ClassTransformer;
+import javax.persistence.spi.PersistenceUnitInfo;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import org.hibernate.jpa.HibernatePersistenceProvider;
+
+public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
+
+ public static final String JPA_VERSION = "2.1";
+ private final String persistenceUnitName;
+ private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
+ private final List managedClassNames;
+ private final List mappingFileNames = new ArrayList<>();
+ private final Properties properties;
+ private DataSource jtaDataSource;
+ private DataSource nonjtaDataSource;
+ private final List transformers = new ArrayList<>();
+
+ public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) {
+ this.persistenceUnitName = persistenceUnitName;
+ this.managedClassNames = managedClassNames;
+ this.properties = properties;
+ }
+
+ @Override
+ public String getPersistenceUnitName() {
+ return persistenceUnitName;
+ }
+
+ @Override
+ public String getPersistenceProviderClassName() {
+ return HibernatePersistenceProvider.class.getName();
+ }
+
+ @Override
+ public PersistenceUnitTransactionType getTransactionType() {
+ return transactionType;
+ }
+
+ public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
+ this.jtaDataSource = jtaDataSource;
+ this.nonjtaDataSource = null;
+ transactionType = PersistenceUnitTransactionType.JTA;
+ return this;
+ }
+
+ @Override
+ public DataSource getJtaDataSource() {
+ return jtaDataSource;
+ }
+
+ public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
+ this.nonjtaDataSource = nonJtaDataSource;
+ this.jtaDataSource = null;
+ transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
+ return this;
+ }
+
+ @Override
+ public DataSource getNonJtaDataSource() {
+ return nonjtaDataSource;
+ }
+
+ @Override
+ public List getMappingFileNames() {
+ return mappingFileNames;
+ }
+
+ @Override
+ public List getJarFileUrls() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public URL getPersistenceUnitRootUrl() {
+ return null;
+ }
+
+ @Override
+ public List getManagedClassNames() {
+ return managedClassNames;
+ }
+
+ @Override
+ public boolean excludeUnlistedClasses() {
+ return false;
+ }
+
+ @Override
+ public SharedCacheMode getSharedCacheMode() {
+ return SharedCacheMode.UNSPECIFIED;
+ }
+
+ @Override
+ public ValidationMode getValidationMode() {
+ return ValidationMode.AUTO;
+ }
+
+ public Properties getProperties() {
+ return properties;
+ }
+
+ @Override
+ public String getPersistenceXMLSchemaVersion() {
+ return JPA_VERSION;
+ }
+
+ @Override
+ public ClassLoader getClassLoader() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+
+ @Override
+ public void addTransformer(ClassTransformer transformer) {
+ transformers.add(transformer);
+ }
+
+ @Override
+ public ClassLoader getNewTempClassLoader() {
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
new file mode 100644
index 0000000000..bc1932af6f
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
@@ -0,0 +1,69 @@
+package com.baeldung.hibernate.jpabootstrap.config;
+
+import com.mysql.cj.jdbc.MysqlDataSource;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.spi.PersistenceUnitInfo;
+import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
+import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
+
+public class JpaEntityManagerFactory {
+
+ private final String DB_URL = "jdbc:mysql://databaseurl";
+ private final String DB_USER_NAME = "username";
+ private final String DB_PASSWORD = "password";
+ private final Class[] entityClasses;
+
+ public JpaEntityManagerFactory(Class[] entityClasses) {
+ this.entityClasses = entityClasses;
+ }
+
+ public EntityManager getEntityManager() {
+ return getEntityManagerFactory().createEntityManager();
+ }
+
+ protected EntityManagerFactory getEntityManagerFactory() {
+ PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
+ Map configuration = new HashMap<>();
+ return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
+ .build();
+ }
+
+ protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
+ return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
+ }
+
+ protected List getEntityClassNames() {
+ return Arrays.asList(getEntities())
+ .stream()
+ .map(Class::getName)
+ .collect(Collectors.toList());
+ }
+
+ protected Properties getProperties() {
+ Properties properties = new Properties();
+ properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
+ properties.put("hibernate.id.new_generator_mappings", false);
+ properties.put("hibernate.connection.datasource", getMysqlDataSource());
+ return properties;
+ }
+
+ protected Class[] getEntities() {
+ return entityClasses;
+ }
+
+ protected DataSource getMysqlDataSource() {
+ MysqlDataSource mysqlDataSource = new MysqlDataSource();
+ mysqlDataSource.setURL(DB_URL);
+ mysqlDataSource.setUser(DB_USER_NAME);
+ mysqlDataSource.setPassword(DB_PASSWORD);
+ return mysqlDataSource;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
new file mode 100644
index 0000000000..86ca1dfa19
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
@@ -0,0 +1,45 @@
+package com.baeldung.hibernate.jpabootstrap.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "users")
+public class User {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+ private String name;
+ private String email;
+
+ public User(){}
+
+ public User(String name, String email) {
+ this.name = name;
+ this.email = email;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
new file mode 100644
index 0000000000..1af3e3e21b
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
@@ -0,0 +1,48 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import javax.persistence.*;
+
+@Entity
+public class OptimisticLockingCourse {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ @ManyToOne
+ @JoinTable(name = "optimistic_student_course")
+ private OptimisticLockingStudent student;
+
+ public OptimisticLockingCourse(Long id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public OptimisticLockingCourse() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public OptimisticLockingStudent getStudent() {
+ return student;
+ }
+
+ public void setStudent(OptimisticLockingStudent student) {
+ this.student = student;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
new file mode 100644
index 0000000000..b79212ae8d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
@@ -0,0 +1,70 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+public class OptimisticLockingStudent {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ private String lastName;
+ @Version
+ private Integer version;
+
+ @OneToMany(mappedBy = "student")
+ private List courses;
+
+ public OptimisticLockingStudent(Long id, String name, String lastName, List courses) {
+ this.id = id;
+ this.name = name;
+ this.lastName = lastName;
+ this.courses = courses;
+ }
+
+ public OptimisticLockingStudent() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public List getCourses() {
+ return courses;
+ }
+
+ public void setCourses(List courses) {
+ this.courses = courses;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java
new file mode 100644
index 0000000000..c889cb6127
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.Embeddable;
+
+@Embeddable
+public class Address {
+
+ private String country;
+ private String city;
+
+ public Address(String country, String city) {
+ this.country = country;
+ this.city = city;
+ }
+
+ public Address() {
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java
new file mode 100644
index 0000000000..cb73cbc958
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java
@@ -0,0 +1,58 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+public class Customer {
+
+ @Id
+ private Long customerId;
+ private String name;
+ private String lastName;
+ @ElementCollection
+ @CollectionTable(name = "customer_address")
+ private List addressList;
+
+ public Customer() {
+ }
+
+ public Customer(Long customerId, String name, String lastName, List addressList) {
+ this.customerId = customerId;
+ this.name = name;
+ this.lastName = lastName;
+ this.addressList = addressList;
+ }
+
+ public Long getCustomerId() {
+ return customerId;
+ }
+
+ public void setCustomerId(Long customerId) {
+ this.customerId = customerId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public List getAddressList() {
+ return addressList;
+ }
+
+ public void setAddressList(List addressList) {
+ this.addressList = addressList;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java
new file mode 100644
index 0000000000..e491c09eb5
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java
@@ -0,0 +1,49 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public class Individual {
+
+ @Id
+ private Long id;
+ private String name;
+ private String lastName;
+
+ public Individual(Long id, String name, String lastName) {
+ this.id = id;
+ this.name = name;
+ this.lastName = lastName;
+ }
+
+ public Individual() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java
new file mode 100644
index 0000000000..aea7d5fc87
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java
@@ -0,0 +1,47 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.*;
+
+@Entity
+public class PessimisticLockingCourse {
+
+ @Id
+ private Long courseId;
+ private String name;
+ @ManyToOne
+ @JoinTable(name = "student_course")
+ private PessimisticLockingStudent student;
+
+ public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
+ this.courseId = courseId;
+ this.name = name;
+ this.student = student;
+ }
+
+ public PessimisticLockingCourse() {
+ }
+
+ public Long getCourseId() {
+ return courseId;
+ }
+
+ public void setCourseId(Long courseId) {
+ this.courseId = courseId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public PessimisticLockingStudent getStudent() {
+ return student;
+ }
+
+ public void setStudent(PessimisticLockingStudent students) {
+ this.student = students;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java
new file mode 100644
index 0000000000..a1328cbdad
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java
@@ -0,0 +1,27 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.Entity;
+import java.math.BigDecimal;
+
+@Entity
+public class PessimisticLockingEmployee extends Individual {
+
+ private BigDecimal salary;
+
+ public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) {
+ super(id, name, lastName);
+ this.salary = salary;
+ }
+
+ public PessimisticLockingEmployee() {
+ super();
+ }
+
+ public BigDecimal getSalary() {
+ return salary;
+ }
+
+ public void setSalary(BigDecimal average) {
+ this.salary = average;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java
new file mode 100644
index 0000000000..e6c5f476b4
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java
@@ -0,0 +1,46 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+public class PessimisticLockingStudent {
+
+ @Id
+ private Long id;
+ private String name;
+ @OneToMany(mappedBy = "student")
+ private List courses;
+
+ public PessimisticLockingStudent(Long id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public PessimisticLockingStudent() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getCourses() {
+ return courses;
+ }
+
+ public void setCourses(List courses) {
+ this.courses = courses;
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
new file mode 100644
index 0000000000..68b51764e4
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
@@ -0,0 +1,134 @@
+package com.baeldung.hibernate.optimisticlocking;
+
+import com.baeldung.hibernate.HibernateUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+import javax.persistence.LockModeType;
+import javax.persistence.OptimisticLockException;
+import java.io.IOException;
+import java.util.Arrays;
+
+public class OptimisticLockingIntegrationTest {
+
+ @Before
+ public void setUp() throws IOException {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH");
+ OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course));
+ course.setStudent(student);
+ entityManager.persist(course);
+ entityManager.persist(student);
+ entityManager.getTransaction()
+ .commit();
+ entityManager.close();
+ }
+
+ @After
+ public void clean() throws IOException {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L);
+ OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L);
+ entityManager.remove(course);
+ entityManager.remove(student);
+ entityManager.getTransaction()
+ .commit();
+ entityManager.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+ em.refresh(student, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ @Test(expected = OptimisticLockException.class)
+ public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
+ em.lock(student, LockModeType.OPTIMISTIC);
+
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
+ em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
+ student2.setName("RICHARD");
+ em2.persist(student2);
+ em2.getTransaction()
+ .commit();
+ em2.close();
+
+ student.setName("JOHN");
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+ }
+
+ protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
+ String propertyFileName = "hibernate-pessimistic-locking.properties";
+ EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
+ .openSession();
+ entityManager.getTransaction()
+ .begin();
+
+ return entityManager;
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java
new file mode 100644
index 0000000000..f416c11d1f
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java
@@ -0,0 +1,151 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import com.baeldung.hibernate.HibernateUtil;
+import com.vividsolutions.jts.util.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.persistence.*;
+import java.io.IOException;
+import java.util.Arrays;
+
+public class BasicPessimisticLockingIntegrationTest {
+
+ @BeforeClass
+ public static void setUp() throws IOException {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN");
+ PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student);
+ student.setCourses(Arrays.asList(course));
+ entityManager.persist(course);
+ entityManager.persist(student);
+ entityManager.getTransaction()
+ .commit();
+ entityManager.close();
+ }
+
+ @Test
+ public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ @Test
+ public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ Query query = entityManager.createQuery("from Student where studentId = :studentId");
+ query.setParameter("studentId", 1L);
+ query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
+ query.getResultList();
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ Query query2 = entityManager2.createQuery("from Student where studentId = :studentId");
+ query2.setParameter("studentId", 1L);
+ query2.setLockMode(LockModeType.PESSIMISTIC_READ);
+ query2.getResultList();
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ @Test
+ public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
+ entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ);
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ @Test
+ public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
+ entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE);
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ @Test
+ public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
+ entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ);
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
+ resultStudent2.setName("Change");
+ entityManager2.persist(resultStudent2);
+ entityManager2.getTransaction()
+ .commit();
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ @Test
+ public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() {
+ try {
+ EntityManager entityManager = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
+ entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE);
+
+ EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
+ resultStudent2.setName("Change");
+ entityManager2.persist(resultStudent2);
+ entityManager2.getTransaction()
+ .commit();
+
+ entityManager.close();
+ entityManager2.close();
+ } catch (Exception e) {
+ Assert.isTrue(e instanceof PessimisticLockException);
+ }
+ }
+
+ protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
+ String propertyFileName = "hibernate-pessimistic-locking.properties";
+ EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
+ .openSession();
+ entityManager.getTransaction()
+ .begin();
+
+ return entityManager;
+ }
+
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java
new file mode 100644
index 0000000000..ac56ab7133
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java
@@ -0,0 +1,115 @@
+package com.baeldung.hibernate.pessimisticlocking;
+
+import com.baeldung.hibernate.HibernateUtil;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+import javax.persistence.LockModeType;
+import javax.persistence.PessimisticLockScope;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+public class PessimisticLockScopesIntegrationTest {
+
+ @Test
+ public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5));
+ em.persist(employee);
+ em.getTransaction()
+ .commit();
+ em.close();
+
+ // NORMAL SCOPE
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE);
+ em2.getTransaction()
+ .rollback();
+
+ // EXTENDED SCOPE
+ Map map = new HashMap<>();
+ map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+
+ EntityManager em3 = getEntityManagerWithOpenTransaction();
+ foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
+ em3.getTransaction()
+ .rollback();
+
+ em2.close();
+ em3.close();
+ }
+
+ @Test
+ public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ Address address = new Address("Poland", "Warsaw");
+ Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address));
+ em.persist(customer);
+ em.getTransaction()
+ .commit();
+ em.close();
+
+ // NORMAL SCOPE
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE);
+ em2.getTransaction()
+ .rollback();
+
+ // EXTENDED SCOPE
+ Map map = new HashMap<>();
+ map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+
+ EntityManager em3 = getEntityManagerWithOpenTransaction();
+ foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
+ em2.getTransaction()
+ .rollback();
+
+ em2.close();
+ em3.close();
+ }
+
+ @Test
+ public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
+ EntityManager em = getEntityManagerWithOpenTransaction();
+ PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE");
+ PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student);
+ student.setCourses(Arrays.asList(course));
+ em.persist(course);
+ em.persist(student);
+ em.getTransaction()
+ .commit();
+ em.close();
+
+ // NORMAL SCOPE
+ EntityManager em2 = getEntityManagerWithOpenTransaction();
+ PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE);
+ em2.getTransaction()
+ .rollback();
+
+ // EXTENDED SCOPE
+ Map map = new HashMap<>();
+ map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+
+ EntityManager em3 = getEntityManagerWithOpenTransaction();
+ foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
+ em3.getTransaction()
+ .rollback();
+
+ em2.close();
+ em3.close();
+ }
+
+ protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
+ String propertyFileName = "hibernate-pessimistic-locking.properties";
+ EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
+ .openSession();
+ entityManager.getTransaction()
+ .begin();
+
+ return entityManager;
+ }
+
+}
diff --git a/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties
new file mode 100644
index 0000000000..c76bd3358b
--- /dev/null
+++ b/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties
@@ -0,0 +1,8 @@
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
+hibernate.connection.username=sa
+hibernate.connection.autocommit=true
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
\ No newline at end of file
diff --git a/httpclient/pom.xml b/httpclient/pom.xml
index b7567e0c4b..2f9b511133 100644
--- a/httpclient/pom.xml
+++ b/httpclient/pom.xml
@@ -1,36 +1,26 @@
+ 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
httpclient
0.1-SNAPSHOT
-
httpclient
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
org.apache.commons
commons-lang3
${commons-lang3.version}
-
-
org.apache.httpcomponents
httpclient
@@ -42,7 +32,6 @@
-
org.apache.httpcomponents
fluent-hc
@@ -54,19 +43,16 @@
-
org.apache.httpcomponents
httpmime
${httpclient.version}
-
commons-codec
commons-codec
${commons-codec.version}
-
org.apache.httpcomponents
httpasyncclient
@@ -78,15 +64,12 @@
-
com.github.tomakehurst
wiremock
${wiremock.version}
test
-
-
@@ -97,7 +80,6 @@
true
-
@@ -136,22 +118,17 @@
-
19.0
3.5
1.10
4.1.2
-
2.5.1
-
4.4.5
4.5.3
-
1.6.1
-
\ No newline at end of file
diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java
index 7a75729ea5..c9956e5852 100644
--- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java
+++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java
@@ -24,6 +24,7 @@ import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@@ -89,7 +90,7 @@ public class HttpClientAuthLiveTest {
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
- final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
+ final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
final String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
@@ -129,7 +130,7 @@ public class HttpClientAuthLiveTest {
private String authorizationHeader(final String username, final String password) {
final String auth = username + ":" + password;
- final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
+ final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 19da678eb7..b17ca2bfd9 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -1,35 +1,17 @@
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
hystrix
1.0
hystrix
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-5
+ ../parent-boot-1
-
-
-
-
- 1.5.8
- 0.20.7
-
-
- 1.3
-
-
- 2.6
- 2.7
- 1.5.8
- 1.5.8
-
-
org.springframework.boot
@@ -59,7 +41,7 @@
hystrix-metrics-event-stream
${hystrix-metrics-event-stream.version}
-
com.netflix.rxjava
@@ -79,39 +61,17 @@
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*LiveTest.java
-
-
- **/*IntegrationTest.java
-
-
-
-
-
-
- json
-
-
-
-
-
-
-
+
+
+ 1.5.8
+ 0.20.7
+
+ 1.3
+
+ 2.6
+ 2.7
+ 1.5.8
+ 1.5.8
+
diff --git a/image-processing/pom.xml b/image-processing/pom.xml
index 2e4063964e..51444a7812 100644
--- a/image-processing/pom.xml
+++ b/image-processing/pom.xml
@@ -1,17 +1,11 @@
+ 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
image-processing
1.0-SNAPSHOT
-
- 1.3.5
- 1.51h
-
-
com.baeldung
parent-modules
@@ -40,17 +34,23 @@
commons-logging
-
+
com.twelvemonkeys.imageio
imageio-core
- 3.3.2
-
+ ${imageio.version}
+
com.twelvemonkeys.imageio
imageio-bmp
- 3.3.2
+ ${imageio.version}
+
+ 1.3.5
+ 1.51h
+ 3.3.2
+
+
\ No newline at end of file
diff --git a/immutables/pom.xml b/immutables/pom.xml
index 884ebc0c61..987dce934d 100644
--- a/immutables/pom.xml
+++ b/immutables/pom.xml
@@ -1,8 +1,7 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
immutables
1.0.0-SNAPSHOT
@@ -37,4 +36,5 @@
3.6.1
0.9.6
+
\ No newline at end of file
diff --git a/influxdb/README.md b/influxdb/README.md
index f2c421580e..a24b2a08ad 100644
--- a/influxdb/README.md
+++ b/influxdb/README.md
@@ -1,7 +1,8 @@
## Influx SDK Tutorial Project
### Relevant Article:
-- [Introduction to using InfluxDB with Java](http://www.baeldung.com/using-influxdb-with-java/)
+- [Using InfluxDB with Java](http://www.baeldung.com/java-influxdb)
+
### Overview
This Maven project contains the Java code for the article linked above.
diff --git a/influxdb/pom.xml b/influxdb/pom.xml
index 05a8e00fa0..92c47d2082 100644
--- a/influxdb/pom.xml
+++ b/influxdb/pom.xml
@@ -1,6 +1,6 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
influxdb
0.1-SNAPSHOT
@@ -28,17 +28,12 @@
${lombok.version}
provided
-
-
-
- 1.8
UTF-8
2.8
1.16.18
-
diff --git a/jackson/pom.xml b/jackson/pom.xml
index 2587e61ac1..ea66f27833 100644
--- a/jackson/pom.xml
+++ b/jackson/pom.xml
@@ -1,28 +1,20 @@
+ 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
jackson
0.1-SNAPSHOT
-
jackson
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
commons-io
commons-io
@@ -113,7 +105,6 @@
${assertj.version}
test
-
@@ -124,13 +115,11 @@
true
-
2.9.4
-
19.0
3.5
@@ -142,7 +131,6 @@
3.0.1
3.6.1
-
diff --git a/java-difference-date/pom.xml b/java-difference-date/pom.xml
index 7a1ee5f1eb..ad66623581 100644
--- a/java-difference-date/pom.xml
+++ b/java-difference-date/pom.xml
@@ -1,21 +1,19 @@
- 4.0.0
+ 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
+ java-difference-date
+ 0.0.1-SNAPSHOT
+ jar
+ java-difference-date
+ Difference between two dates in java
- com.baeldung
- java-difference-date
- 0.0.1-SNAPSHOT
- jar
-
- java-difference-date
- Difference between two dates in java
-
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
@@ -41,4 +39,5 @@
2.9.9
1.5.1
+
diff --git a/java-ee-8-security-api/README.md b/java-ee-8-security-api/README.md
new file mode 100644
index 0000000000..1735419236
--- /dev/null
+++ b/java-ee-8-security-api/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+ - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml
new file mode 100644
index 0000000000..7782fd0479
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml
@@ -0,0 +1,72 @@
+
+
+ 4.0.0
+
+ app-auth-basic-store-db
+ war
+
+
+ com.baeldung
+ java-ee-8-security-api
+ 1.0-SNAPSHOT
+
+
+
+ 1.4.197
+
+
+
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy
+ package
+
+ copy
+
+
+
+
+
+
+ com.h2database
+ h2
+ ${h2-version}
+ jar
+
+ ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global
+
+
+
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java
new file mode 100644
index 0000000000..32adbf1abb
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java
@@ -0,0 +1,22 @@
+package com.baeldung.javaee.security;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet("/admin")
+@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
+public class AdminServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
+ response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
+ response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java
new file mode 100644
index 0000000000..a16d944f5a
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java
@@ -0,0 +1,16 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
+import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition;
+
+@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm")
+@DatabaseIdentityStoreDefinition(
+ dataSourceLookup = "java:comp/env/jdbc/securityDS",
+ callerQuery = "select password from users where username = ?",
+ groupsQuery = "select GROUPNAME from groups where username = ?"
+)
+@ApplicationScoped
+public class AppConfig {
+}
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java
new file mode 100644
index 0000000000..3658826e4d
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java
@@ -0,0 +1,59 @@
+package com.baeldung.javaee.security;
+
+import javax.annotation.Resource;
+import javax.annotation.sql.DataSourceDefinition;
+import javax.inject.Inject;
+import javax.security.enterprise.identitystore.Pbkdf2PasswordHash;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+@DataSourceDefinition(
+ name = "java:comp/env/jdbc/securityDS",
+ className = "org.h2.jdbcx.JdbcDataSource",
+ url = "jdbc:h2:~/securityTest;MODE=Oracle"
+)
+@WebServlet(value = "/init", loadOnStartup = 0)
+public class DatabaseSetupServlet extends HttpServlet {
+
+ @Resource(lookup = "java:comp/env/jdbc/securityDS")
+ private DataSource dataSource;
+
+ @Inject
+ private Pbkdf2PasswordHash passwordHash;
+
+ @Override
+ public void init() throws ServletException {
+ super.init();
+ initdb();
+ }
+
+ private void initdb() {
+ executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS");
+ executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS");
+
+ executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))");
+ executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))");
+
+ executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')");
+ executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')");
+
+ executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')");
+ executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')");
+ executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')");
+ }
+
+ private void executeUpdate(DataSource dataSource, String query) {
+ try (Connection connection = dataSource.getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(query)) {
+ statement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java
new file mode 100644
index 0000000000..548b5f6d85
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java
@@ -0,0 +1,25 @@
+package com.baeldung.javaee.security;
+
+import javax.annotation.security.DeclareRoles;
+import javax.inject.Inject;
+import javax.security.enterprise.SecurityContext;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+@WebServlet("/user")
+@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"}))
+public class UserServlet extends HttpServlet {
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
+ response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
+ response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..c49adff459
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml
@@ -0,0 +1,9 @@
+
+
+
+ webProfile-8.0
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml
new file mode 100644
index 0000000000..35a90621ae
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml
@@ -0,0 +1,42 @@
+
+
+ 4.0.0
+
+ app-auth-custom-form-store-custom
+ war
+
+
+ com.baeldung
+ java-ee-8-security-api
+ 1.0-SNAPSHOT
+
+
+
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java
new file mode 100644
index 0000000000..bba9fa36ce
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java
@@ -0,0 +1,17 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.faces.annotation.FacesConfig;
+import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+
+
+@CustomFormAuthenticationMechanismDefinition(
+ loginToContinue = @LoginToContinue(
+ loginPage = "/login.xhtml",
+ errorPage = "/login-error.html"
+ )
+)
+@ApplicationScoped
+public class AppConfig {
+}
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java
new file mode 100644
index 0000000000..54219f9750
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java
@@ -0,0 +1,46 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.credential.UsernamePasswordCredential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStore;
+import java.util.*;
+
+import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
+
+@ApplicationScoped
+public class InMemoryIdentityStore4Authentication implements IdentityStore {
+
+ private Map users = new HashMap<>();
+
+ public InMemoryIdentityStore4Authentication() {
+ //Init users
+ // from a file or hardcoded
+ init();
+ }
+
+ private void init() {
+ //user1
+ users.put("user", "pass0");
+ //user2
+ users.put("admin", "pass1");
+ }
+
+ @Override
+ public int priority() {
+ return 70;
+ }
+
+ @Override
+ public Set validationTypes() {
+ return EnumSet.of(ValidationType.VALIDATE);
+ }
+
+ public CredentialValidationResult validate(UsernamePasswordCredential credential) {
+ String password = users.get(credential.getCaller());
+ if (password != null && password.equals(credential.getPasswordAsString())) {
+ return new CredentialValidationResult(credential.getCaller());
+ }
+ return INVALID_RESULT;
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java
new file mode 100644
index 0000000000..f088ab80b9
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java
@@ -0,0 +1,46 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStore;
+import java.util.*;
+
+@ApplicationScoped
+class InMemoryIdentityStore4Authorization implements IdentityStore {
+
+ private Map> userRoles = new HashMap<>();
+
+ public InMemoryIdentityStore4Authorization() {
+ //Init users
+ // from a file or hardcoded
+ init();
+ }
+
+ private void init() {
+ //user1
+ List roles = new ArrayList<>();
+ roles.add("USER_ROLE");
+ userRoles.put("user", roles);
+ //user2
+ roles = new ArrayList<>();
+ roles.add("USER_ROLE");
+ roles.add("ADMIN_ROLE");
+ userRoles.put("admin", roles);
+ }
+
+ @Override
+ public int priority() {
+ return 80;
+ }
+
+ @Override
+ public Set validationTypes() {
+ return EnumSet.of(ValidationType.PROVIDE_GROUPS);
+ }
+
+ @Override
+ public Set getCallerGroups(CredentialValidationResult validationResult) {
+ List roles = userRoles.get(validationResult.getCallerPrincipal().getName());
+ return new HashSet<>(roles);
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java
new file mode 100644
index 0000000000..f8ee83432a
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java
@@ -0,0 +1,81 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.RequestScoped;
+import javax.faces.annotation.FacesConfig;
+import javax.faces.application.FacesMessage;
+import javax.faces.context.FacesContext;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.SecurityContext;
+import javax.security.enterprise.credential.Credential;
+import javax.security.enterprise.credential.Password;
+import javax.security.enterprise.credential.UsernamePasswordCredential;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.validation.constraints.NotNull;
+
+import static javax.faces.application.FacesMessage.SEVERITY_ERROR;
+import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE;
+import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
+import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams;
+
+@FacesConfig
+@Named
+@RequestScoped
+public class LoginBean {
+
+ @Inject
+ private SecurityContext securityContext;
+
+ @Inject
+ private FacesContext facesContext;
+
+ @NotNull
+ private String username;
+
+ @NotNull
+ private String password;
+
+ public void login() {
+ Credential credential = new UsernamePasswordCredential(username, new Password(password));
+ AuthenticationStatus status = securityContext.authenticate(
+ getHttpRequestFromFacesContext(),
+ getHttpResponseFromFacesContext(),
+ withParams().credential(credential));
+ if (status.equals(SEND_CONTINUE)) {
+ facesContext.responseComplete();
+ } else if (status.equals(SEND_FAILURE)) {
+ facesContext.addMessage(null,
+ new FacesMessage(SEVERITY_ERROR, "Authentication failed", null));
+ }
+ }
+
+ private HttpServletRequest getHttpRequestFromFacesContext() {
+ return (HttpServletRequest) facesContext
+ .getExternalContext()
+ .getRequest();
+ }
+
+ private HttpServletResponse getHttpResponseFromFacesContext() {
+ return (HttpServletResponse) facesContext
+ .getExternalContext()
+ .getResponse();
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java
new file mode 100644
index 0000000000..fb9c944140
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java
@@ -0,0 +1,31 @@
+package com.baeldung.javaee.security;
+
+import javax.inject.Inject;
+import javax.security.enterprise.SecurityContext;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet("/welcome")
+@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE"))
+public class WelcomeServlet extends HttpServlet {
+
+ @Inject
+ private SecurityContext securityContext;
+
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ securityContext.hasAccessToWebResource("/protectedServlet", "GET");
+ resp.getWriter().write("" +
+ "Authentication type :" + req.getAuthType() + "\n" +
+ "Caller Principal :" + securityContext.getCallerPrincipal() + "\n" +
+ "User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" +
+ "User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" +
+ "");
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..c49adff459
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml
@@ -0,0 +1,9 @@
+
+
+
+ webProfile-8.0
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml
new file mode 100644
index 0000000000..2f4726a77e
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml
@@ -0,0 +1,7 @@
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..bd219bf983
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,27 @@
+
+
+
+
+ javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN
+ true
+
+
+
+ javax.faces.ENABLE_CDI_RESOLVER_CHAIN
+ true
+
+
+
+ Faces Servlet
+ javax.faces.webapp.FacesServlet
+ 1
+
+
+ Faces Servlet
+ *.xhtml
+
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html
new file mode 100644
index 0000000000..c540797b54
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html
@@ -0,0 +1,10 @@
+
+
+
+
+ Title
+
+
+Custom Form Authentication Error
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml
new file mode 100644
index 0000000000..48928b2513
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+ Custom Form-based Authentication
+
+
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml
new file mode 100644
index 0000000000..d1a18db626
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+ Welcome !!
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml
new file mode 100644
index 0000000000..32e20fb066
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml
@@ -0,0 +1,72 @@
+
+
+ 4.0.0
+
+ app-auth-custom-no-store
+ war
+
+
+ com.baeldung
+ java-ee-8-security-api
+ 1.0-SNAPSHOT
+
+
+
+ 1.4.197
+
+
+
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy
+ package
+
+ copy
+
+
+
+
+
+
+ com.h2database
+ h2
+ ${h2-version}
+ jar
+
+ ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global
+
+
+
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java
new file mode 100644
index 0000000000..bef9e20038
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java
@@ -0,0 +1,28 @@
+package com.baeldung.javaee.security;
+
+import javax.inject.Inject;
+import javax.security.enterprise.SecurityContext;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.security.Principal;
+
+@WebServlet("/admin")
+@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
+public class AdminServlet extends HttpServlet {
+
+ @Inject
+ SecurityContext securityContext;
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ response.getWriter().append("getCallerPrincipal :" + securityContext.getCallerPrincipal() + "\n");
+ response.getWriter().append("CustomPrincipal :" + securityContext.getPrincipalsByType(CustomPrincipal.class) + "\n");
+ response.getWriter().append("Principal :" + securityContext.getPrincipalsByType(Principal.class) + "\n");
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java
new file mode 100644
index 0000000000..e93360db4d
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java
@@ -0,0 +1,7 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+
+@ApplicationScoped
+public class AppConfig {
+}
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java
new file mode 100644
index 0000000000..9accf3c752
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java
@@ -0,0 +1,36 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashSet;
+
+@ApplicationScoped
+public class CustomAuthentication implements HttpAuthenticationMechanism {
+
+ @Override
+ public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse,
+ HttpMessageContext httpMessageContext) throws AuthenticationException {
+ String username = httpServletRequest.getParameter("username");
+ String password = httpServletRequest.getParameter("password");
+ //Mocking UserDetail, but in real life, we can find it from a database.
+ UserDetail userDetail = findByUserNameAndPassword(username, password);
+ if (userDetail != null) {
+ return httpMessageContext.notifyContainerAboutLogin(
+ new CustomPrincipal(userDetail),
+ new HashSet<>(userDetail.getRoles()));
+ }
+ return httpMessageContext.responseUnauthorized();
+ }
+
+ private UserDetail findByUserNameAndPassword(String username, String password) {
+ UserDetail userDetail = new UserDetail("uid_10", username, password);
+ userDetail.addRole("admin_role");
+ return userDetail;
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java
new file mode 100644
index 0000000000..5bd636ea62
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java
@@ -0,0 +1,22 @@
+package com.baeldung.javaee.security;
+
+import java.security.Principal;
+
+public class CustomPrincipal implements Principal {
+
+ private UserDetail userDetail;
+
+ public CustomPrincipal(UserDetail userDetail) {
+ this.userDetail = userDetail;
+ }
+
+ @Override
+ public String getName() {
+ return userDetail.getLogin();
+ }
+
+ @Override
+ public String toString() {
+ return this.getClass().getSimpleName() + ":" + getName();
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java
new file mode 100644
index 0000000000..68e1df33c8
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java
@@ -0,0 +1,38 @@
+package com.baeldung.javaee.security;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class UserDetail {
+ private String uid;
+ private String login;
+ private String password;
+ private List roles = new ArrayList<>();
+ //...
+
+ UserDetail(String uid, String login, String password) {
+ this.uid = uid;
+ this.login = login;
+ this.password = password;
+ }
+
+ public String getUid() {
+ return uid;
+ }
+
+ public String getLogin() {
+ return login;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public List getRoles() {
+ return roles;
+ }
+
+ public void addRole(String role) {
+ roles.add(role);
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..c49adff459
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml
@@ -0,0 +1,9 @@
+
+
+
+ webProfile-8.0
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html
new file mode 100644
index 0000000000..bd7263e0fb
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html
@@ -0,0 +1,10 @@
+
+
+
+
+ Title
+
+
+Authentication Error
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html
new file mode 100644
index 0000000000..3336eb5513
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html
@@ -0,0 +1,25 @@
+
+
+
+
+ Title
+
+
+
+ Form-based Authentication
+
+
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml
new file mode 100644
index 0000000000..570b36add5
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml
@@ -0,0 +1,50 @@
+
+
+ 4.0.0
+
+ app-auth-form-store-ldap
+ war
+
+
+ com.baeldung
+ java-ee-8-security-api
+ 1.0-SNAPSHOT
+
+
+
+
+ com.unboundid
+ unboundid-ldapsdk
+ 4.0.4
+
+
+
+
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java
new file mode 100644
index 0000000000..32adbf1abb
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java
@@ -0,0 +1,22 @@
+package com.baeldung.javaee.security;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet("/admin")
+@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
+public class AdminServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
+ response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
+ response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java
new file mode 100644
index 0000000000..6fd9672e8a
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java
@@ -0,0 +1,22 @@
+package com.baeldung.javaee.security;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+import javax.security.enterprise.identitystore.LdapIdentityStoreDefinition;
+
+@FormAuthenticationMechanismDefinition(
+ loginToContinue = @LoginToContinue(
+ loginPage = "/login.html",
+ errorPage = "/login-error.html"
+ )
+)
+@LdapIdentityStoreDefinition(
+ url = "ldap://localhost:10389",
+ callerBaseDn = "ou=caller,dc=baeldung,dc=com",
+ groupSearchBase = "ou=group,dc=baeldung,dc=com",
+ groupSearchFilter = "(&(member=%s)(objectClass=groupOfNames))"
+)
+@ApplicationScoped
+public class AppConfig {
+}
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java
new file mode 100644
index 0000000000..e55fe0d2a7
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java
@@ -0,0 +1,45 @@
+package com.baeldung.javaee.security;
+
+import com.unboundid.ldap.listener.InMemoryDirectoryServer;
+import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
+import com.unboundid.ldap.listener.InMemoryListenerConfig;
+import com.unboundid.ldap.sdk.LDAPException;
+import com.unboundid.ldif.LDIFReader;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+
+@WebServlet(value = "/init-ldap", loadOnStartup = 1)
+public class LdapSetupServlet extends HttpServlet {
+
+ private InMemoryDirectoryServer inMemoryDirectoryServer;
+
+ @Override
+ public void init() throws ServletException {
+ super.init();
+ initLdap();
+ System.out.println("@@@START_");
+ }
+
+ private void initLdap() {
+ try {
+ InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=baeldung,dc=com");
+ config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 10389));
+ config.setSchema(null);
+ inMemoryDirectoryServer = new InMemoryDirectoryServer(config);
+ inMemoryDirectoryServer.importFromLDIF(true,
+ new LDIFReader(this.getClass().getResourceAsStream("/users.ldif")));
+ inMemoryDirectoryServer.startListening();
+ } catch (LDAPException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void destroy() {
+ super.destroy();
+ inMemoryDirectoryServer.shutDown(true);
+ System.out.println("@@@END");
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java
new file mode 100644
index 0000000000..9f14cd8817
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java
@@ -0,0 +1,22 @@
+package com.baeldung.javaee.security;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+@WebServlet("/user")
+@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"}))
+public class UserServlet extends HttpServlet {
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
+ response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
+ response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
+ }
+}
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..c49adff459
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml
@@ -0,0 +1,9 @@
+
+
+
+ webProfile-8.0
+
+
+
+
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif
new file mode 100644
index 0000000000..538249aab7
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif
@@ -0,0 +1,47 @@
+dn: dc=baeldung,dc=com
+objectclass: top
+objectclass: dcObject
+objectclass: organization
+dc: baeldung
+o: baeldung
+
+dn: ou=caller,dc=baeldung,dc=com
+objectclass: top
+objectclass: organizationalUnit
+ou: caller
+
+dn: ou=group,dc=baeldung,dc=com
+objectclass: top
+objectclass: organizationalUnit
+ou: group
+
+dn: uid=admin,ou=caller,dc=baeldung,dc=com
+objectclass: top
+objectclass: uidObject
+objectclass: person
+uid: admin
+cn: Administrator
+sn: Admin
+userPassword: passadmin
+
+dn: uid=user,ou=caller,dc=baeldung,dc=com
+objectclass: top
+objectclass: uidObject
+objectclass: person
+uid: user
+cn: User
+sn: User
+userPassword: passuser
+
+dn: cn=admin_role,ou=group,dc=baeldung,dc=com
+objectclass: top
+objectclass: groupOfNames
+cn: admin_role
+member: uid=admin,ou=caller,dc=baeldung,dc=com
+
+dn: cn=user_role,ou=group,dc=baeldung,dc=com
+objectclass: top
+objectclass: groupOfNames
+cn: user_role
+member: uid=admin,ou=caller,dc=baeldung,dc=com
+member: uid=user,ou=caller,dc=baeldung,dc=com
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html
new file mode 100644
index 0000000000..bd7263e0fb
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html
@@ -0,0 +1,10 @@
+
+
+
+
+ Title
+
+
+Authentication Error
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html
new file mode 100644
index 0000000000..3336eb5513
--- /dev/null
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html
@@ -0,0 +1,25 @@
+
+
+
+
+ Title
+
+
+
+ Form-based Authentication
+
+
+
+
\ No newline at end of file
diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml
new file mode 100644
index 0000000000..cdc288f469
--- /dev/null
+++ b/java-ee-8-security-api/pom.xml
@@ -0,0 +1,73 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ java-ee-8-security-api
+ 1.0-SNAPSHOT
+ pom
+
+
+ 1.8
+ 1.8
+ UTF-8
+
+ 9080
+ 9443
+
+ 8.0
+ 2.3
+ 18.0.0.1
+ 1.4.197
+
+
+
+ app-auth-basic-store-db
+ app-auth-form-store-ldap
+ app-auth-custom-form-store-custom
+ app-auth-custom-no-store
+
+
+
+
+ javax
+ javaee-web-api
+ ${javaee-version}
+ provided
+
+
+
+
+
+
+ maven-war-plugin
+
+ false
+ pom.xml
+
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+ ${liberty-maven-plugin.version}
+
+
+
+ https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip
+
+
+ true
+ project
+ src/main/liberty/config/server.xml
+ true
+
+ ${defaultHttpPort}
+ ${defaultHttpsPort}
+
+
+
+
+
+
diff --git a/java-lite/pom.xml b/java-lite/pom.xml
index d7950487ca..7c0ed1c780 100644
--- a/java-lite/pom.xml
+++ b/java-lite/pom.xml
@@ -1,8 +1,7 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
org.baeldung
java-lite
1.0-SNAPSHOT
@@ -14,15 +13,40 @@
1.0.0-SNAPSHOT
-
- 9.4.8.v20171121
- 1.4.13
- 1.15
- 5.1.45
- 1.7.0
- 1.8.2
- 4.12
-
+
+
+ org.javalite
+ activeweb
+ ${activeweb.version}
+
+
+
+ mysql
+ mysql-connector-java
+ ${mysql.connector.java.version}
+
+
+
+ com.sun
+ tools
+ ${sun.tools.version}
+ system
+ ${java.home}/../lib/tools.jar
+
+
+
+ org.javalite
+ activeweb-testing
+ ${activeweb-testing.version}
+ test
+
+
+
+ junit
+ junit
+ ${junit.version}
+
+
@@ -69,39 +93,14 @@
-
-
- org.javalite
- activeweb
- ${activeweb.version}
-
-
-
- mysql
- mysql-connector-java
- ${mysql.connector.java.version}
-
-
-
- com.sun
- tools
- ${sun.tools.version}
- system
- ${java.home}/../lib/tools.jar
-
-
-
- org.javalite
- activeweb-testing
- 1.15
- test
-
-
-
- junit
- junit
- ${junit.version}
-
-
+
+ 9.4.8.v20171121
+ 1.4.13
+ 1.15
+ 5.1.45
+ 1.7.0
+ 1.8.2
+ 1.15
+
\ No newline at end of file
diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductUnitTest.java
similarity index 95%
rename from java-lite/src/test/java/app/models/ProductTest.java
rename to java-lite/src/test/java/app/models/ProductUnitTest.java
index 5e5c6e8845..416df67d0e 100644
--- a/java-lite/src/test/java/app/models/ProductTest.java
+++ b/java-lite/src/test/java/app/models/ProductUnitTest.java
@@ -4,7 +4,7 @@ import org.javalite.activejdbc.Base;
import org.junit.Assert;
import org.junit.Test;
-public class ProductTest {
+public class ProductUnitTest {
//@Test
public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() {
diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml
index 7c08968cbf..1543e24fbd 100644
--- a/java-rmi/pom.xml
+++ b/java-rmi/pom.xml
@@ -1,20 +1,19 @@
- 4.0.0
+ 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.rmi
+ java-rmi
+ 1.0-SNAPSHOT
+ jar
- com.baeldung.rmi
- java-rmi
- 1.0-SNAPSHOT
- jar
-
-
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
-
-
- UTF-8
-
-
+
+
+
+ UTF-8
+
+
diff --git a/java-spi/README.md b/java-spi/README.md
new file mode 100644
index 0000000000..d2658c42fe
--- /dev/null
+++ b/java-spi/README.md
@@ -0,0 +1,4 @@
+
+### Relevant Articles:
+
+- [Java Service Provider Interface](http://www.baeldung.com/java-spi)
diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml
index 27651533a9..2de650d1af 100644
--- a/java-spi/exchange-rate-api/pom.xml
+++ b/java-spi/exchange-rate-api/pom.xml
@@ -1,14 +1,16 @@
4.0.0
-
exchange-rate-api
jar
-
+
com.baeldung
java-spi
1.0.0-SNAPSHOT
+
+
+
diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml
index 7e64cf7438..b223cf7d95 100644
--- a/java-spi/exchange-rate-app/pom.xml
+++ b/java-spi/exchange-rate-app/pom.xml
@@ -1,14 +1,13 @@
4.0.0
-
exchange-rate-app
jar
com.baeldung
java-spi
- 1.0.0-SNAPSHOT
+ 1.0.0-SNAPSHOT
@@ -17,11 +16,6 @@
exchange-rate-api
1.0.0-SNAPSHOT
-
- com.baeldung
- exchange-rate-impl
- 1.0.0-SNAPSHOT
-
diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml
index ec22791351..435f40619e 100644
--- a/java-spi/exchange-rate-impl/pom.xml
+++ b/java-spi/exchange-rate-impl/pom.xml
@@ -1,7 +1,6 @@
4.0.0
-
exchange-rate-impl
jar
@@ -11,6 +10,27 @@
1.0.0-SNAPSHOT
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+ 3.1.0
+
+
+ copy-dependencies
+ package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/depends
+
+
+
+
+
+
com.baeldung
diff --git a/java-spi/pom.xml b/java-spi/pom.xml
index 9bcf6ab174..4b9500ffcd 100644
--- a/java-spi/pom.xml
+++ b/java-spi/pom.xml
@@ -1,7 +1,6 @@
4.0.0
-
java-spi
pom
diff --git a/java-vavr-stream/README.md b/java-vavr-stream/README.md
new file mode 100644
index 0000000000..64299cde11
--- /dev/null
+++ b/java-vavr-stream/README.md
@@ -0,0 +1,5 @@
+
+### Relevant Articles:
+
+- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams)
+
diff --git a/java-vavr-stream/pom.xml b/java-vavr-stream/pom.xml
index 25f0254626..093d8763e3 100644
--- a/java-vavr-stream/pom.xml
+++ b/java-vavr-stream/pom.xml
@@ -1,25 +1,29 @@
-
+
4.0.0
com.baeldung.samples
java-vavr-stream
1.0
jar
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
- UTF-8
- 1.8
- 1.8
-
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
io.vavr
vavr
- 0.9.2
+ ${io.vavr.version}
+
+
+ UTF-8
+ 0.9.2
+
+
\ No newline at end of file
diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml
index 402e3057c6..85078bd696 100644
--- a/java-websocket/pom.xml
+++ b/java-websocket/pom.xml
@@ -1,35 +1,35 @@
- 4.0.0
- com.baeldung
- java-websocket
- war
- 0.0.1-SNAPSHOT
- java-websocket Maven Webapp
- http://maven.apache.org
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ 4.0.0
+ com.baeldung
+ java-websocket
+ war
+ 0.0.1-SNAPSHOT
-
- UTF-8
-
-
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
+
-
-
- javax.websocket
- javax.websocket-api
- 1.1
- provided
-
-
- com.google.code.gson
- gson
- 2.8.0
-
-
+
+
+ javax.websocket
+ javax.websocket-api
+ ${javax.websocket-api.version}
+ provided
+
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
+
+
+ UTF-8
+ 1.1
+ 2.8.0
+
diff --git a/javafx/pom.xml b/javafx/pom.xml
index bcad64aca5..b2de708be1 100644
--- a/javafx/pom.xml
+++ b/javafx/pom.xml
@@ -1,15 +1,13 @@
-
+ 4.0.0
+ javafx
+
parent-modules
com.baeldung
1.0.0-SNAPSHOT
- 4.0.0
-
- javafx
-
\ No newline at end of file
diff --git a/javax-servlet-init-params/pom.xml b/javax-servlet-init-params/pom.xml
new file mode 100644
index 0000000000..4f766a7e2c
--- /dev/null
+++ b/javax-servlet-init-params/pom.xml
@@ -0,0 +1,56 @@
+
+
+ 4.0.0
+ com.baeldung.javax-servlet-init-params
+ javax-servlet-init-params
+ 1.0
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.assertj
+ assertj-core
+ 3.9.1
+ test
+
+
+ org.hamcrest
+ hamcrest-core
+ 1.3
+ test
+
+
+ org.mockito
+ mockito-core
+ 2.18.3
+ test
+
+
+ javax
+ javaee-web-api
+ 7.0
+ provided
+
+
+ jstl
+ jstl
+ 1.2
+
+
+ javax.el
+ el-api
+ 2.2
+
+
+
\ No newline at end of file
diff --git a/javax-servlet-init-params/src/main/java/com/baeldung/servlets/UserServlet.java b/javax-servlet-init-params/src/main/java/com/baeldung/servlets/UserServlet.java
new file mode 100644
index 0000000000..e195aa092a
--- /dev/null
+++ b/javax-servlet-init-params/src/main/java/com/baeldung/servlets/UserServlet.java
@@ -0,0 +1,49 @@
+package com.baeldung.servlets;
+
+import java.io.IOException;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebInitParam;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebServlet(name = "UserServlet", urlPatterns = {"/userServlet"}, initParams={
+ @WebInitParam(name="name", value="Not provided"),
+ @WebInitParam(name="email", value="Not provided")})
+public class UserServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ processRequest(request, response);
+ forwardRequest(request, response, "/WEB-INF/jsp/result.jsp");
+ }
+
+ protected void processRequest(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ request.setAttribute("name", getRequestParameter(request, "name"));
+ request.setAttribute("email", getRequestParameter(request, "email"));
+ request.setAttribute("province", getContextParameter("province"));
+ request.setAttribute("country", getContextParameter("country"));
+ }
+
+ protected String getRequestParameter(HttpServletRequest request, String name) {
+ String param = request.getParameter(name);
+ return !param.isEmpty() ? param : getInitParameter(name);
+ }
+
+ protected String getContextParameter(String name) {
+ return getServletContext().getInitParameter(name);
+ }
+
+ protected void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path)
+ throws ServletException, IOException {
+ request.getRequestDispatcher(path).forward(request, response);
+ }
+}
\ No newline at end of file
diff --git a/javax-servlet-init-params/src/main/webapp/WEB-INF/jsp/result.jsp b/javax-servlet-init-params/src/main/webapp/WEB-INF/jsp/result.jsp
new file mode 100644
index 0000000000..01cc54858e
--- /dev/null
+++ b/javax-servlet-init-params/src/main/webapp/WEB-INF/jsp/result.jsp
@@ -0,0 +1,16 @@
+<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
+<%@ page contentType="text/html" pageEncoding="UTF-8"%>
+
+
+
+
+ User Data
+
+
+ User Information
+ Name: ${name}
+ Email: ${email}
+ Province: ${province}
+ Country: ${country}
+
+
diff --git a/javax-servlet-init-params/src/main/webapp/WEB-INF/web.xml b/javax-servlet-init-params/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..1b801171b3
--- /dev/null
+++ b/javax-servlet-init-params/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,14 @@
+
+
+
+ province
+ Mendoza
+
+
+ country
+ Argentina
+
+
diff --git a/javax-servlet-init-params/src/main/webapp/index.jsp b/javax-servlet-init-params/src/main/webapp/index.jsp
new file mode 100644
index 0000000000..ca41942e5d
--- /dev/null
+++ b/javax-servlet-init-params/src/main/webapp/index.jsp
@@ -0,0 +1,19 @@
+<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
+<%@ page contentType="text/html" pageEncoding="UTF-8"%>
+
+
+
+ Context and Initialization Servlet Parameters
+
+
+
+ Please fill the form below:
+
+
+
diff --git a/javax-servlet-init-params/src/test/java/com/baeldung/test/UserServletUnitTest.java b/javax-servlet-init-params/src/test/java/com/baeldung/test/UserServletUnitTest.java
new file mode 100644
index 0000000000..ef3d877dd7
--- /dev/null
+++ b/javax-servlet-init-params/src/test/java/com/baeldung/test/UserServletUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.test;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class UserServletUnitTest {
+
+ private static HttpServletRequest request;
+ private static HttpServletResponse response;
+
+
+ @BeforeClass
+ public static void setUpHttpServletRequestMockInstance() {
+ request = mock(HttpServletRequest.class);
+ }
+
+ @BeforeClass
+ public static void setUpHttpServletResponsetMockInstance() {
+ response = mock(HttpServletResponse.class);
+ }
+
+ @Test
+ public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenCalledAtLeastOnce() {
+ request.getParameter("name");
+ verify(request, atLeast(1)).getParameter("name");
+ }
+
+ @Test
+ public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenOneAssertion() {
+ when(request.getParameter("name")).thenReturn("username");
+ assertThat(request.getParameter("name")).isEqualTo("username");
+ }
+
+ @Test
+ public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenCalledAtLeastOnce() {
+ response.getContentType();
+ verify(response, atLeast(1)).getContentType();
+ }
+
+ @Test
+ public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenOneAssertion() {
+ when(response.getContentType()).thenReturn("text/html");
+ assertThat(response.getContentType()).isEqualTo("text/html");
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/README.md b/javax-servlets/README.md
index ff2256b3c0..55ca1116aa 100644
--- a/javax-servlets/README.md
+++ b/javax-servlets/README.md
@@ -1,3 +1,7 @@
### Relevant Articles:
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
- [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp)
+- [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session)
+- [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet)
+- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file)
+- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response)
diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml
index a75af414cd..f64ce67a1f 100644
--- a/javax-servlets/pom.xml
+++ b/javax-servlets/pom.xml
@@ -1,48 +1,79 @@
- 4.0.0
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ javax-servlets
+ 1.0-SNAPSHOT
- javax-servlets
- 1.0-SNAPSHOT
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+
+
+ commons-fileupload
+ commons-fileupload
+ 1.3.3
+
+
+ commons-io
+ commons-io
+ 2.6
+
-
+
+
+ javax.servlet
+ javax.servlet-api
+ 4.0.1
+
+
+ javax.servlet.jsp.jstl
+ jstl-api
+ 1.2
+
+
+ javax.servlet.jsp
+ javax.servlet.jsp-api
+ 2.3.1
+
+
+ javax.servlet
+ jstl
+ 1.2
+
-
- javax.servlet
- javax.servlet-api
- ${javax.servlet.version}
-
-
- org.apache.httpcomponents
- httpclient
- ${org.apache.httpcomponents.version}
- test
-
-
- commons-logging
- commons-logging
-
-
-
-
-
- org.springframework
- spring-test
- 5.0.5.RELEASE
- test
-
-
-
-
- 3.1.0
- 4.5.3
-
+
+ org.apache.httpcomponents
+ httpclient
+ ${org.apache.httpcomponents.version}
+ test
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
+ org.springframework
+ spring-test
+ ${spring-test.version}
+ test
+
+
+
+ 4.5.3
+ 5.0.5.RELEASE
+ 2.8.2
+
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/Constants.java b/javax-servlets/src/main/java/com/baeldung/Constants.java
new file mode 100644
index 0000000000..90c64870ad
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/Constants.java
@@ -0,0 +1,11 @@
+package com.baeldung;
+
+public class Constants {
+
+ public static final String UPLOAD_DIRECTORY = "upload";
+ public static final String DEFAULT_FILENAME = "default.file";
+
+ public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
+ public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
+ public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
+}
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/model/Employee.java b/javax-servlets/src/main/java/com/baeldung/model/Employee.java
new file mode 100644
index 0000000000..698a598962
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/model/Employee.java
@@ -0,0 +1,72 @@
+package com.baeldung.model;
+
+public class Employee {
+
+ private int id;
+ private String name;
+ private String department;
+ private long salary;
+
+ public Employee(int id, String name, String department, long salary) {
+ super();
+ this.id = id;
+ this.name = name;
+ this.department = department;
+ this.salary = salary;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + id;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Employee other = (Employee) obj;
+ if (id != other.id)
+ return false;
+ return true;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDepartment() {
+ return department;
+ }
+
+ public void setDepartment(String department) {
+ this.department = department;
+ }
+
+ public long getSalary() {
+ return salary;
+ }
+
+ public void setSalary(long salary) {
+ this.salary = salary;
+ }
+
+}
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java
new file mode 100644
index 0000000000..b1a6621b24
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java
@@ -0,0 +1,32 @@
+package com.baeldung.servlets;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebServlet("/download")
+public class DownloadServlet extends HttpServlet {
+ private final int ARBITARY_SIZE = 1048;
+
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ resp.setContentType("text/plain");
+ resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
+
+ try (InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
+ OutputStream out = resp.getOutputStream()) {
+
+ byte[] buffer = new byte[ARBITARY_SIZE];
+
+ int numBytesRead;
+ while ((numBytesRead = in.read(buffer)) > 0) {
+ out.write(buffer, 0, numBytesRead);
+ }
+ }
+ }
+}
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java
new file mode 100644
index 0000000000..dbc1a010f7
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java
@@ -0,0 +1,34 @@
+package com.baeldung.servlets;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.baeldung.model.Employee;
+import com.google.gson.Gson;
+
+
+@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
+public class EmployeeServlet extends HttpServlet {
+
+ private Gson gson = new Gson();
+
+ @Override
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+
+ Employee employee = new Employee(1, "Karan", "IT", 5000);
+ String employeeJsonString = this.gson.toJson(employee);
+
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ response.setCharacterEncoding("UTF-8");
+ out.print(employeeJsonString);
+ out.flush();
+ }
+
+}
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java
new file mode 100644
index 0000000000..0008e837c0
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java
@@ -0,0 +1,34 @@
+package com.baeldung.servlets;
+
+import javax.servlet.annotation.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+import static javax.servlet.RequestDispatcher.*;
+
+@WebServlet(urlPatterns = "/errorHandler")
+public class ErrorHandlerServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ resp.setContentType("text/html; charset=utf-8");
+ try (PrintWriter writer = resp.getWriter()) {
+ writer.write("Error description ");
+ writer.write("Error description ");
+ writer.write("");
+ Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE)
+ .forEach(e ->
+ writer.write("" + e + ":" + req.getAttribute(e) + " ")
+ );
+ writer.write(" ");
+ writer.write("");
+ }
+
+ Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
+ if (IllegalArgumentException.class.isInstance(exception)) {
+ getServletContext().log("Error on an application argument", exception);
+ }
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java
new file mode 100644
index 0000000000..185edcf916
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java
@@ -0,0 +1,54 @@
+package com.baeldung.servlets;
+
+import com.baeldung.Constants;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.MultipartConfig;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.Part;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import static com.baeldung.Constants.UPLOAD_DIRECTORY;
+
+@WebServlet(
+ name = "MultiPartServlet",
+ urlPatterns = {"/multiPartServlet"}
+)
+@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
+public class MultipartServlet extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ private String getFileName(Part part) {
+ for (String content : part.getHeader("content-disposition").split(";")) {
+ if (content.trim().startsWith("filename"))
+ return content.substring(content.indexOf("=") + 2, content.length() - 1);
+ }
+ return Constants.DEFAULT_FILENAME;
+ }
+
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+
+ String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
+ File uploadDir = new File(uploadPath);
+ if (!uploadDir.exists())
+ uploadDir.mkdir();
+
+ try {
+ String fileName = "";
+ for (Part part : request.getParts()) {
+ fileName = getFileName(part);
+ part.write(uploadPath + File.separator + fileName);
+ }
+ request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
+ } catch (FileNotFoundException fne) {
+ request.setAttribute("message", "There was an error: " + fne.getMessage());
+ }
+ getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java
new file mode 100644
index 0000000000..c95bd2cec0
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java
@@ -0,0 +1,13 @@
+package com.baeldung.servlets;
+
+import javax.servlet.annotation.*;
+import javax.servlet.http.*;
+
+@WebServlet(urlPatterns = "/randomError")
+public class RandomErrorServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
+ throw new IllegalStateException("Random error");
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java
new file mode 100644
index 0000000000..4de7b20913
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java
@@ -0,0 +1,63 @@
+package com.baeldung.servlets;
+
+import javax.servlet.annotation.WebServlet;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import static com.baeldung.Constants.*;
+
+@WebServlet(
+ name = "UploadServlet",
+ urlPatterns = {"/uploadFile"}
+)
+public class UploadServlet extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+
+ if (ServletFileUpload.isMultipartContent(request)) {
+
+ DiskFileItemFactory factory = new DiskFileItemFactory();
+ factory.setSizeThreshold(MEMORY_THRESHOLD);
+ factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
+
+ ServletFileUpload upload = new ServletFileUpload(factory);
+ upload.setFileSizeMax(MAX_FILE_SIZE);
+ upload.setSizeMax(MAX_REQUEST_SIZE);
+ String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
+ File uploadDir = new File(uploadPath);
+ if (!uploadDir.exists()) {
+ uploadDir.mkdir();
+ }
+
+ try {
+ List formItems = upload.parseRequest(request);
+
+ if (formItems != null && formItems.size() > 0) {
+ for (FileItem item : formItems) {
+ if (!item.isFormField()) {
+ String fileName = new File(item.getName()).getName();
+ String filePath = uploadPath + File.separator + fileName;
+ File storeFile = new File(filePath);
+ item.write(storeFile);
+ request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
+ }
+ }
+ }
+ } catch (Exception ex) {
+ request.setAttribute("message", "There was an error: " + ex.getMessage());
+ }
+ getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
+ }
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java
new file mode 100644
index 0000000000..56cec546be
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java
@@ -0,0 +1,18 @@
+package com.baeldung.servlets;
+
+import java.io.IOException;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebServlet(name = "UploadWelcomeServlet", urlPatterns = "/uploadwelcome")
+public class UploadWelcomeServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ request.getRequestDispatcher("/upload.jsp").forward(request, response);
+ }
+}
diff --git a/javax-servlets/src/main/webapp/WEB-INF/web.xml b/javax-servlets/src/main/webapp/WEB-INF/web.xml
index 66934d8fd3..c9a06ac52d 100644
--- a/javax-servlets/src/main/webapp/WEB-INF/web.xml
+++ b/javax-servlets/src/main/webapp/WEB-INF/web.xml
@@ -1,7 +1,16 @@
-
-
+
+ 404
+ /error-404.html
+
+
+
+ java.lang.Exception
+ /errorHandler
+
\ No newline at end of file
diff --git a/javax-servlets/src/main/webapp/error-404.html b/javax-servlets/src/main/webapp/error-404.html
new file mode 100644
index 0000000000..b36fc44160
--- /dev/null
+++ b/javax-servlets/src/main/webapp/error-404.html
@@ -0,0 +1,14 @@
+
+
+
+
+ Error page
+
+
+
+Error: Page not found
+
+Go back home
+
+
+
\ No newline at end of file
diff --git a/javax-servlets/src/main/webapp/result.jsp b/javax-servlets/src/main/webapp/result.jsp
new file mode 100644
index 0000000000..2e985cb322
--- /dev/null
+++ b/javax-servlets/src/main/webapp/result.jsp
@@ -0,0 +1,13 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
+
+
+
+
+
+ Upload Result
+
+
+
+ ${message}
+
+
\ No newline at end of file
diff --git a/javax-servlets/src/main/webapp/sample.txt b/javax-servlets/src/main/webapp/sample.txt
new file mode 100644
index 0000000000..bab4636a96
--- /dev/null
+++ b/javax-servlets/src/main/webapp/sample.txt
@@ -0,0 +1 @@
+nice simple text file
\ No newline at end of file
diff --git a/javax-servlets/src/main/webapp/upload.jsp b/javax-servlets/src/main/webapp/upload.jsp
new file mode 100644
index 0000000000..f365484892
--- /dev/null
+++ b/javax-servlets/src/main/webapp/upload.jsp
@@ -0,0 +1,23 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
+
+
+
+
+
+ File Upload Demo
+
+
+
+ Apache FileUpload
+
+
+
+
+ Servlet Multipart
+
+
+
\ No newline at end of file
diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java
new file mode 100644
index 0000000000..4fe4908075
--- /dev/null
+++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java
@@ -0,0 +1,54 @@
+package com.baeldung.servlets;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.when;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import com.baeldung.model.Employee;
+import com.google.gson.Gson;
+
+
+@RunWith(MockitoJUnitRunner.class)
+public class EmployeeServletIntegrationTest {
+
+ @Mock
+ HttpServletRequest httpServletRequest;
+
+ @Mock
+ HttpServletResponse httpServletResponse;
+
+ Employee employee;
+
+ @Test
+ public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception {
+
+ //Given
+ int id = 1;
+ String name = "Karan Khanna";
+ String department = "IT";
+ long salary = 5000;
+ employee = new Employee(id, name, department, salary);
+
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ when(httpServletResponse.getWriter()).thenReturn(pw);
+
+ EmployeeServlet employeeServlet = new EmployeeServlet();
+ employeeServlet.doGet(httpServletRequest, httpServletResponse);
+
+ String employeeJsonString = sw.getBuffer().toString().trim();
+ Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class);
+ assertEquals(fetchedEmployee, employee);
+ }
+
+}
diff --git a/javaxval/bin/pom.xml b/javaxval/bin/pom.xml
index 68e65e4d02..a16072bb1a 100644
--- a/javaxval/bin/pom.xml
+++ b/javaxval/bin/pom.xml
@@ -1,5 +1,5 @@
+ 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
javaxval
@@ -7,7 +7,7 @@
-
+
javax.validation
validation-api
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index a05ee43aaf..5de77ed26b 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -1,19 +1,10 @@
+ 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
javaxval
0.1-SNAPSHOT
-
- 2.0.1.Final
- 6.0.7.Final
- 3.0.0
- 2.2.6
- 5.0.2.RELEASE
-
-
-
com.baeldung
parent-modules
@@ -21,25 +12,21 @@
-
org.hibernate
hibernate-validator
${hibernate-validator.version}
-
org.hibernate
hibernate-validator-annotation-processor
${hibernate-validator.version}
-
javax.el
javax.el-api
${javax.el-api.version}
-
org.glassfish.web
javax.el
@@ -55,7 +42,14 @@
spring-test
${org.springframework.version}
-
+
+ 2.0.1.Final
+ 6.0.7.Final
+ 3.0.0
+ 2.2.6
+ 5.0.2.RELEASE
+
+
\ No newline at end of file
diff --git a/jaxb/pom.xml b/jaxb/pom.xml
index 8c9a430929..f8e5ec0977 100644
--- a/jaxb/pom.xml
+++ b/jaxb/pom.xml
@@ -1,12 +1,11 @@
+ 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
jaxb
0.0.1-SNAPSHOT
jaxb
-
com.baeldung
parent-modules
@@ -19,30 +18,31 @@
jaxb-runtime
${jaxb.version}
-
org.glassfish.jaxb
jaxb-core
${jaxb.version}
-
com.sun.istack
istack-commons-runtime
- 3.0.2
+ ${istack-commons-runtime.version}
-
commons-io
commons-io
- 2.5
+ ${commons-io.version}
-
org.apache.commons
commons-lang3
- 3.5
+ ${commons-lang3.version}
+
+
+ javax.activation
+ activation
+ 1.1
@@ -60,7 +60,7 @@
org.eclipse.m2e
lifecycle-mapping
- 1.0.0
+ ${lifecycle-mapping-plugin.version}
@@ -75,7 +75,7 @@
-
+
@@ -116,13 +116,13 @@
-
@@ -133,6 +133,10 @@
2.3
+ 3.0.2
+ 2.5
+ 3.5
+ 1.0.0
\ No newline at end of file
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
index 0a3da677ce..26cd5814ac 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
@@ -1,48 +1,48 @@
-
-package com.baeldung.jaxb.gen;
-
-import javax.xml.bind.annotation.XmlRegistry;
-
-
-/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the com.baeldung.jaxb.gen package.
- * An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
- *
- */
-@XmlRegistry
-public class ObjectFactory {
-
-
- /**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
- *
- */
- public ObjectFactory() {
- }
-
- /**
- * Create an instance of {@link UserRequest }
- *
- */
- public UserRequest createUserRequest() {
- return new UserRequest();
- }
-
- /**
- * Create an instance of {@link UserResponse }
- *
- */
- public UserResponse createUserResponse() {
- return new UserResponse();
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import javax.xml.bind.annotation.XmlRegistry;
+
+
+/**
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the com.baeldung.jaxb.gen package.
+ *
An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
+ * provided in this class.
+ *
+ */
+@XmlRegistry
+public class ObjectFactory {
+
+
+ /**
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
+ *
+ */
+ public ObjectFactory() {
+ }
+
+ /**
+ * Create an instance of {@link UserRequest }
+ *
+ */
+ public UserRequest createUserRequest() {
+ return new UserRequest();
+ }
+
+ /**
+ * Create an instance of {@link UserResponse }
+ *
+ */
+ public UserResponse createUserResponse() {
+ return new UserResponse();
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
index 1c1abc61a6..4cfbeb8d46 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
@@ -1,87 +1,87 @@
-
-package com.baeldung.jaxb.gen;
-
-import java.io.Serializable;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- *
Java class for UserRequest complex type.
- *
- *
The following schema fragment specifies the expected content contained within this class.
- *
- *
- * <complexType name="UserRequest">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- *
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "UserRequest", propOrder = {
- "id",
- "name"
-})
-@XmlRootElement(name = "userRequest")
-public class UserRequest
- implements Serializable
-{
-
- private final static long serialVersionUID = -1L;
- protected int id;
- @XmlElement(required = true)
- protected String name;
-
- /**
- * Gets the value of the id property.
- *
- */
- public int getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- */
- public void setId(int value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the name property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getName() {
- return name;
- }
-
- /**
- * Sets the value of the name property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setName(String value) {
- this.name = value;
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import java.io.Serializable;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * Java class for UserRequest complex type.
+ *
+ *
The following schema fragment specifies the expected content contained within this class.
+ *
+ *
+ * <complexType name="UserRequest">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ *
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "UserRequest", propOrder = {
+ "id",
+ "name"
+})
+@XmlRootElement(name = "userRequest")
+public class UserRequest
+ implements Serializable
+{
+
+ private final static long serialVersionUID = -1L;
+ protected int id;
+ @XmlElement(required = true)
+ protected String name;
+
+ /**
+ * Gets the value of the id property.
+ *
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the value of the id property.
+ *
+ */
+ public void setId(int value) {
+ this.id = value;
+ }
+
+ /**
+ * Gets the value of the name property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the value of the name property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setName(String value) {
+ this.name = value;
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
index b80405e4a9..d86778403a 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
@@ -1,149 +1,149 @@
-
-package com.baeldung.jaxb.gen;
-
-import java.io.Serializable;
-import java.util.Calendar;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlSchemaType;
-import javax.xml.bind.annotation.XmlType;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-import org.w3._2001.xmlschema.Adapter1;
-
-
-/**
- * Java class for UserResponse complex type.
- *
- *
The following schema fragment specifies the expected content contained within this class.
- *
- *
- * <complexType name="UserResponse">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- *
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "UserResponse", propOrder = {
- "id",
- "name",
- "gender",
- "created"
-})
-@XmlRootElement(name = "userResponse")
-public class UserResponse
- implements Serializable
-{
-
- private final static long serialVersionUID = -1L;
- protected int id;
- @XmlElement(required = true)
- protected String name;
- @XmlElement(required = true)
- protected String gender;
- @XmlElement(required = true, type = String.class)
- @XmlJavaTypeAdapter(Adapter1 .class)
- @XmlSchemaType(name = "dateTime")
- protected Calendar created;
-
- /**
- * Gets the value of the id property.
- *
- */
- public int getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- */
- public void setId(int value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the name property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getName() {
- return name;
- }
-
- /**
- * Sets the value of the name property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setName(String value) {
- this.name = value;
- }
-
- /**
- * Gets the value of the gender property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getGender() {
- return gender;
- }
-
- /**
- * Sets the value of the gender property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setGender(String value) {
- this.gender = value;
- }
-
- /**
- * Gets the value of the created property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public Calendar getCreated() {
- return created;
- }
-
- /**
- * Sets the value of the created property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCreated(Calendar value) {
- this.created = value;
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import java.io.Serializable;
+import java.util.Calendar;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlSchemaType;
+import javax.xml.bind.annotation.XmlType;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import org.w3._2001.xmlschema.Adapter1;
+
+
+/**
+ * Java class for UserResponse complex type.
+ *
+ *
The following schema fragment specifies the expected content contained within this class.
+ *
+ *
+ * <complexType name="UserResponse">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ *
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "UserResponse", propOrder = {
+ "id",
+ "name",
+ "gender",
+ "created"
+})
+@XmlRootElement(name = "userResponse")
+public class UserResponse
+ implements Serializable
+{
+
+ private final static long serialVersionUID = -1L;
+ protected int id;
+ @XmlElement(required = true)
+ protected String name;
+ @XmlElement(required = true)
+ protected String gender;
+ @XmlElement(required = true, type = String.class)
+ @XmlJavaTypeAdapter(Adapter1 .class)
+ @XmlSchemaType(name = "dateTime")
+ protected Calendar created;
+
+ /**
+ * Gets the value of the id property.
+ *
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the value of the id property.
+ *
+ */
+ public void setId(int value) {
+ this.id = value;
+ }
+
+ /**
+ * Gets the value of the name property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the value of the name property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setName(String value) {
+ this.name = value;
+ }
+
+ /**
+ * Gets the value of the gender property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getGender() {
+ return gender;
+ }
+
+ /**
+ * Sets the value of the gender property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setGender(String value) {
+ this.gender = value;
+ }
+
+ /**
+ * Gets the value of the created property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public Calendar getCreated() {
+ return created;
+ }
+
+ /**
+ * Sets the value of the created property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCreated(Calendar value) {
+ this.created = value;
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
index 639d00179c..6384eab27f 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
@@ -1,2 +1,2 @@
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
-package com.baeldung.jaxb.gen;
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+package com.baeldung.jaxb.gen;
diff --git a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
index 54b3c360dc..b4865b5510 100644
--- a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
+++ b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
@@ -1,23 +1,23 @@
-
-package org.w3._2001.xmlschema;
-
-import java.util.Calendar;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
-
-public class Adapter1
- extends XmlAdapter
-{
-
-
- public Calendar unmarshal(String value) {
- return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
- }
-
- public String marshal(Calendar value) {
- if (value == null) {
- return null;
- }
- return (javax.xml.bind.DatatypeConverter.printDateTime(value));
- }
-
-}
+
+package org.w3._2001.xmlschema;
+
+import java.util.Calendar;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+
+public class Adapter1
+ extends XmlAdapter
+{
+
+
+ public Calendar unmarshal(String value) {
+ return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
+ }
+
+ public String marshal(Calendar value) {
+ if (value == null) {
+ return null;
+ }
+ return (javax.xml.bind.DatatypeConverter.printDateTime(value));
+ }
+
+}
diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties
new file mode 100644
index 0000000000..5bc2bfe4b9
--- /dev/null
+++ b/jaxb/src/main/resources/log4jstructuraldp.properties
@@ -0,0 +1,9 @@
+
+# Root logger
+log4j.rootLogger=INFO, file, stdout
+
+# Write to console
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
index b2dde85c0f..77b7f1a0b3 100644
--- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
+++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
@@ -44,7 +44,7 @@ public class JaxbIntegrationTest {
File bookFile = new File(this.getClass().getResource("/book.xml").getFile());
String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8");
String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8");
- Assert.assertEquals(sampleBookXML, marshallerBookXML);
+ Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", ""));
}
@Test
diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml
new file mode 100644
index 0000000000..605d531b16
--- /dev/null
+++ b/jaxb/src/test/resources/book.xml
@@ -0,0 +1,5 @@
+
+
+ Book1
+ 2016-12-16T17:28:49.718Z
+
diff --git a/jee-7/pom.xml b/jee-7/pom.xml
index f1d50f55c6..62e2132de5 100644
--- a/jee-7/pom.xml
+++ b/jee-7/pom.xml
@@ -1,427 +1,435 @@
- 4.0.0
+ 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
+ jee-7
+ 1.0-SNAPSHOT
+ war
+ JavaEE 7 Arquillian Archetype Sample
- com.baeldung
- jee-7
- 1.0-SNAPSHOT
- war
- JavaEE 7 Arquillian Archetype Sample
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+ ${maven.min.version}
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+
+
+ org.jboss.arquillian
+ arquillian-bom
+ ${arquillian_core.version}
+ import
+ pom
+
+
+ org.jboss.arquillian.extension
+ arquillian-drone-bom
+ ${arquillian-drone-bom.version}
+ pom
+ import
+
+
+
-
- 1.8
- 3.0.0
+
+
+ javax
+ javaee-api
+ ${javaee_api.version}
+ provided
+
- 7.0
- 1.1.11.Final
- 8.2.1.Final
- 1.7.0
- 1.4.6.Final
- 3.0.19.Final
- 4.1.1
- 1.0.4
- 1.13
- 2.25
- 1.0.0.Final
+
+ org.jboss.arquillian.junit
+ arquillian-junit-container
+ test
+
+
+ org.jboss.arquillian.graphene
+ graphene-webdriver
+ ${graphene-webdriver.version}
+ pom
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
- 2.6
- 4.2.3.RELEASE
-
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven
+ test
+ jar
+
-
- ${maven.min.version}
-
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven-archive
+ test
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ com.sun.faces
+ jsf-api
+ ${com.sun.faces.jsf.version}
+
+
+ com.sun.faces
+ jsf-impl
+ ${com.sun.faces.jsf.version}
+
+
+ javax.servlet
+ jstl
+ ${jstl.version}
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-api.version}
+
+
+ javax.servlet.jsp
+ jsp-api
+ ${jsp-api.version}
+ provided
+
+
+ taglibs
+ standard
+ ${taglibs.standard.version}
+
-
-
-
- org.jboss.arquillian
- arquillian-bom
- ${arquillian_core.version}
- import
- pom
-
-
- org.jboss.arquillian.extension
- arquillian-drone-bom
- 2.0.1.Final
- pom
- import
-
-
-
+
+ javax.mvc
+ javax.mvc-api
+ 20160715
+
+
+ org.glassfish.ozark
+ ozark
+ ${ozark.version}
+
-
-
- javax
- javaee-api
- ${javaee_api.version}
- provided
-
+
+ org.springframework.security
+ spring-security-web
+ ${org.springframework.security.version}
+
-
- org.jboss.arquillian.junit
- arquillian-junit-container
- test
-
-
- org.jboss.arquillian.graphene
- graphene-webdriver
- 2.1.0.Final
- pom
- test
-
-
- com.jayway.awaitility
- awaitility
- ${awaitility.version}
- test
-
+
+ org.springframework.security
+ spring-security-config
+ ${org.springframework.security.version}
+
+
+ org.springframework.security
+ spring-security-taglibs
+ ${org.springframework.security.version}
+
+
-
- org.jboss.shrinkwrap.resolver
- shrinkwrap-resolver-impl-maven
- test
- jar
-
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ webapp
+ false
+
+
+
+
-
- org.jboss.shrinkwrap.resolver
- shrinkwrap-resolver-impl-maven-archive
- test
-
-
- org.apache.httpcomponents
- httpclient
- 4.5
-
-
- commons-io
- commons-io
- 2.4
-
-
- com.sun.faces
- jsf-api
- 2.2.14
-
-
- com.sun.faces
- jsf-impl
- 2.2.14
-
-
- javax.servlet
- jstl
- 1.2
-
-
- javax.servlet
- javax.servlet-api
- 3.1.0
-
-
- javax.servlet.jsp
- jsp-api
- 2.2
- provided
-
-
- taglibs
- standard
- 1.1.2
-
+
+
+ wildfly-managed-arquillian
+
+ true
+
+
+ standalone-full.xml
+ ${project.build.directory}/wildfly-${version.wildfly}
+
+
+
+ io.undertow
+ undertow-websockets-jsr
+ ${undertow-websockets-jsr.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ ${resteasy.version}
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-managed
+ ${wildfly.version}
+ test
+
+
-
- javax.mvc
- javax.mvc-api
- 20160715
-
-
- org.glassfish.ozark
- ozark
- 20160715
-
+
+
+
+
+ maven-dependency-plugin
+ ${maven-dependency-plugin.version}
+
+ ${maven.test.skip}
+
+
+
+ unpack
+ process-test-classes
+
+ unpack
+
+
+
+
+ org.wildfly
+ wildfly-dist
+ ${wildfly.version}
+ zip
+ false
+ ${project.build.directory}
+
+
+
+
+
+
+
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ ${project.build.directory}/wildfly-${wildfly.version}
+
+
+
+
+
+
+
+
+ wildfly-remote-arquillian
+
+
+ io.undertow
+ undertow-websockets-jsr
+ ${undertow-websockets-jsr.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ ${resteasy.version}
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-remote
+ ${wildfly.version}
+ test
+
+
+
+
+ glassfish-embedded-arquillian
+
+
+ org.glassfish.main.extras
+ glassfish-embedded-all
+ ${glassfish-embedded-all.version}
+ test
+
+
+ org.glassfish
+ javax.json
+ ${javax.json.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-embedded-3.1
+ ${arquillian-glassfish.version}
+ test
+
+
+
+
+ glassfish-remote-arquillian
+
+
+ org.glassfish
+ javax.json
+ ${javax.json.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
+ ${jersey.version}
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-processing
+ ${jersey.version}
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-remote-3.1
+ ${arquillian-glassfish.version}
+ test
+
+
+
+
+ webdriver-chrome
+
+ true
+
+
+ chrome
+
+
+
+ webdriver-firefox
+
+ firefox
+
+
+
-
- org.springframework.security
- spring-security-web
- ${org.springframework.security.version}
-
+
+
+ bintray-mvc-spec-maven
+ bintray
+ http://dl.bintray.com/mvc-spec/maven
+
+ true
+
+
+ false
+
+
+
-
- org.springframework.security
- spring-security-config
- ${org.springframework.security.version}
-
-
- org.springframework.security
- spring-security-taglibs
- ${org.springframework.security.version}
-
-
+
+ 1.8
+ 3.0.0
+ 7.0
+ 1.1.11.Final
+ 8.2.1.Final
+ 1.7.0
+ 1.4.6.Final
+ 3.0.19.Final
+ 4.1.1
+ 1.0.4
+ 1.13
+ 2.25
+ 1.0.0.Final
+ 2.6
+ 4.2.3.RELEASE
+ 2.17
+ 1.1.2
+ 2.4
+ 2.2.14
+ 4.5
+ 2.0.1.Final
+ 3.1.0
+ 2.1.0.Final
+ 2.8
+ 1.2
+ 2.2
+ 20160715
+
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
- webapp
- false
-
-
-
-
-
-
-
-
- wildfly-managed-arquillian
-
- true
-
-
- standalone-full.xml
- ${project.build.directory}/wildfly-${version.wildfly}
-
-
-
- io.undertow
- undertow-websockets-jsr
- ${undertow-websockets-jsr.version}
- test
-
-
- org.jboss.resteasy
- resteasy-client
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-jaxb-provider
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-json-p-provider
- ${resteasy.version}
- test
-
-
- org.wildfly
- wildfly-arquillian-container-managed
- ${wildfly.version}
- test
-
-
-
-
-
-
- maven-dependency-plugin
- 2.8
-
- ${maven.test.skip}
-
-
-
- unpack
- process-test-classes
-
- unpack
-
-
-
-
- org.wildfly
- wildfly-dist
- ${wildfly.version}
- zip
- false
- ${project.build.directory}
-
-
-
-
-
-
-
- maven-surefire-plugin
- 2.17
-
-
- ${project.build.directory}/wildfly-${wildfly.version}
-
-
-
-
-
-
-
-
- wildfly-remote-arquillian
-
-
- io.undertow
- undertow-websockets-jsr
- ${undertow-websockets-jsr.version}
- test
-
-
- org.jboss.resteasy
- resteasy-client
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-jaxb-provider
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-json-p-provider
- ${resteasy.version}
- test
-
-
- org.wildfly
- wildfly-arquillian-container-remote
- ${wildfly.version}
- test
-
-
-
-
- glassfish-embedded-arquillian
-
-
- org.glassfish.main.extras
- glassfish-embedded-all
- ${glassfish-embedded-all.version}
- test
-
-
- org.glassfish
- javax.json
- ${javax.json.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-client
- ${tyrus.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-container-grizzly-client
- ${tyrus.version}
- test
-
-
- org.glassfish.jersey.core
- jersey-client
- ${jersey.version}
- test
-
-
- org.jboss.arquillian.container
- arquillian-glassfish-embedded-3.1
- ${arquillian-glassfish.version}
- test
-
-
-
-
- glassfish-remote-arquillian
-
-
- org.glassfish
- javax.json
- ${javax.json.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-client
- ${tyrus.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-container-grizzly-client
- ${tyrus.version}
- test
-
-
- org.glassfish.jersey.core
- jersey-client
- ${jersey.version}
- test
-
-
- org.glassfish.jersey.media
- jersey-media-json-jackson
- ${jersey.version}
- test
-
-
- org.glassfish.jersey.media
- jersey-media-json-processing
- ${jersey.version}
- test
-
-
- org.jboss.arquillian.container
- arquillian-glassfish-remote-3.1
- ${arquillian-glassfish.version}
- test
-
-
-
-
- webdriver-chrome
-
- true
-
-
- chrome
-
-
-
-
- webdriver-firefox
-
- firefox
-
-
-
-
-
-
- bintray-mvc-spec-maven
- bintray
- http://dl.bintray.com/mvc-spec/maven
-
- true
-
-
- false
-
-
-
diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml
index 3c9dbcc5a5..6a0dd05180 100644
--- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml
+++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml
@@ -1,52 +1,52 @@
- 4.0.0
- com.baeldung.javaeeannotations
- JavaEEAnnotationsSample
- 0.0.1-SNAPSHOT
- war
- JavaEEAnnotationsSample
- JavaEEAnnotationsSample
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
-
-
- javax.annotation
- javax.annotation-api
- 1.3
-
-
-
- javax.servlet
- javax.servlet-api
- 3.1.0
-
-
-
- javax.servlet.jsp
- jsp-api
- 2.1
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- 2.4
-
- src/main/webapp
- SpringFieldConstructorInjection
- false
-
-
-
-
- JavaEEAnnotationsSample
-
+ 4.0.0
+ com.baeldung.javaeeannotations
+ JavaEEAnnotationsSample
+ 0.0.1-SNAPSHOT
+ war
+ JavaEEAnnotationsSample
+ JavaEEAnnotationsSample
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.3
+
+
+
+ javax.servlet
+ javax.servlet-api
+ 3.1.0
+
+
+
+ javax.servlet.jsp
+ jsp-api
+ 2.1
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ 2.4
+
+ src/main/webapp
+ SpringFieldConstructorInjection
+ false
+
+
+
+
+ JavaEEAnnotationsSample
+
\ No newline at end of file
diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
similarity index 98%
rename from jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
index caeba95e45..0d6fd295e6 100644
--- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java
@@ -22,7 +22,7 @@ import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@RunWith(Arquillian.class)
-public class ConvListValIntegrationTest {
+public class ConvListValLiveTest {
@ArquillianResource
private URL deploymentUrl;
diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
similarity index 98%
rename from jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
index 0e4c91ad67..41dde6549d 100644
--- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
-public class AutomaticTimerBeanIntegrationTest {
+public class AutomaticTimerBeanLiveTest {
//the @AutomaticTimerBean has a method called every 10 seconds
//testing the difference ==> 100000
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
similarity index 96%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
index 13cd1729db..350c094f38 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticAtFixedRateTimerBeanIntegrationTest {
+public class ProgrammaticAtFixedRateTimerBeanLiveTest {
final static long TIMEOUT = 1000;
final static long TOLERANCE = 500l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
similarity index 97%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
index b90cb6d909..ad079c131b 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
@@ -19,7 +19,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticTimerBeanIntegrationTest {
+public class ProgrammaticTimerBeanLiveTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
similarity index 97%
rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
index e2e660f79b..974f0a285f 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java
@@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
-public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest {
+public class ProgrammaticWithFixedDelayTimerBeanLiveTest {
final static long TIMEOUT = 15000l;
final static long TOLERANCE = 1000l;
diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
similarity index 97%
rename from jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java
rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
index 580edade77..a4ed9ceb68 100644
--- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java
+++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java
@@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
-public class ScheduleTimerBeanIntegrationTest {
+public class ScheduleTimerBeanLiveTest {
private final static long TIMEOUT = 5000l;
private final static long TOLERANCE = 1000l;
diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml
index 15cf2f8e34..8c6d691b29 100644
--- a/jenkins/hello-world/pom.xml
+++ b/jenkins/hello-world/pom.xml
@@ -5,7 +5,7 @@
org.jenkins-ci.plugins
plugin
2.33
-
+
jenkins-hello-world
1.0-SNAPSHOT
diff --git a/jersey/pom.xml b/jersey/pom.xml
index 0c8b6b9281..b41ea1f340 100644
--- a/jersey/pom.xml
+++ b/jersey/pom.xml
@@ -1,63 +1,59 @@
- 4.0.0
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ 4.0.0
+ com.baeldung
+ jersey
+ 0.0.1-SNAPSHOT
+ war
- com.baeldung
- jersey
- 0.0.1-SNAPSHOT
- war
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+
+ org.glassfish.jersey.core
+ jersey-server
+ ${jersey.version}
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+
+
+ org.glassfish.jersey.bundles
+ jaxrs-ri
+ ${jersey.version}
+
+
+ org.slf4j
+ slf4j-api
+ ${slf4j.version}
+
+
-
- 2.26
- 1.7.25
- 3.2.0
-
+
+ jersey
+
+
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
+
+
-
- jersey
-
-
- maven-war-plugin
- ${maven-war-plugin.version}
-
- false
-
-
-
-
-
-
-
- org.glassfish.jersey.core
- jersey-server
- ${jersey.version}
-
-
- org.glassfish.jersey.core
- jersey-client
- ${jersey.version}
-
-
- org.glassfish.jersey.bundles
- jaxrs-ri
- ${jersey.version}
-
-
- org.slf4j
- slf4j-api
- ${slf4j.version}
-
-
-
-
-
+
+ 2.26
+ 1.7.25
+ 3.2.0
+
diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
similarity index 95%
rename from jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java
rename to jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
index 72ba4cc5b9..a6fd606e3f 100644
--- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
@@ -7,7 +7,7 @@ import org.junit.Ignore;
import org.junit.Test;
@Ignore
-public class JerseyClientTest {
+public class JerseyClientIntegrationTest {
private static int HTTP_OK = 200;
diff --git a/jgroups/pom.xml b/jgroups/pom.xml
index 0e5971875e..6340e41565 100644
--- a/jgroups/pom.xml
+++ b/jgroups/pom.xml
@@ -1,6 +1,6 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jgroups
0.1-SNAPSHOT
@@ -18,19 +18,18 @@
org.jgroups
jgroups
- 4.0.10.Final
+ ${jgroups.version}
-
commons-cli
commons-cli
- 1.4
+ ${commons-cli.version}
- 1.8
UTF-8
+ 4.0.10.Final
diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml
index 5fd7febd07..e5593bdbb9 100644
--- a/jhipster/jhipster-microservice/car-app/pom.xml
+++ b/jhipster/jhipster-microservice/car-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.car.app
@@ -47,8 +47,8 @@
3.1.3
v6.10.0
-
-
+
+
${project.build.directory}/test-results
0.0.20
@@ -454,7 +454,7 @@
-
+
@@ -657,9 +657,9 @@
src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml
org.h2.Driver
jdbc:h2:file:./target/h2db/db/carapp
-
+
carapp
-
+
hibernate:spring:com.car.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
true
debug
@@ -708,7 +708,7 @@
org.apache.maven.plugins
maven-war-plugin
-
+
@@ -747,7 +747,7 @@
org.apache.maven.plugins
maven-war-plugin
-
+
org.springframework.boot
diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml
index 359783ef81..3c21e0042f 100644
--- a/jhipster/jhipster-microservice/dealer-app/pom.xml
+++ b/jhipster/jhipster-microservice/dealer-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.dealer.app
@@ -47,8 +47,8 @@
3.1.3
v6.10.0
-
-
+
+
0.0.20
${project.build.directory}/test-results
@@ -679,7 +679,7 @@
-
+
diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml
index 32aa432279..42808e26ce 100644
--- a/jhipster/jhipster-microservice/gateway-app/pom.xml
+++ b/jhipster/jhipster-microservice/gateway-app/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../../parent-boot-5
+ ../../../parent-boot-1
com.gateway
@@ -49,8 +49,8 @@
3.1.3
v6.10.0
-
-
+
+
0.0.20
${project.build.directory}/test-results
@@ -736,7 +736,7 @@
-
+
diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml
index eb4c2ca2d3..c8c9578fd6 100644
--- a/jhipster/jhipster-monolithic/pom.xml
+++ b/jhipster/jhipster-monolithic/pom.xml
@@ -3,10 +3,10 @@
4.0.0
- parent-boot-5
+ parent-boot-1
com.baeldung
0.0.1-SNAPSHOT
- ../../parent-boot-5
+ ../../parent-boot-1
com.baeldung
@@ -51,8 +51,8 @@
v6.10.0
4.3.0
-
-
+
+
${project.build.directory}/test-results
0.0.20
@@ -63,21 +63,22 @@
src/main/webapp/content/**/*.*,
src/main/webapp/bower_components/**/*.*,
- src/main/webapp/i18n/*.js, target/www/**/*.*
+ src/main/webapp/i18n/*.js, target/www/**/*.*
+
S3437,UndocumentedApi,BoldAndItalicTagsCheck
-
src/main/webapp/app/**/*.*
Web:BoldAndItalicTagsCheck
-
src/main/java/**/*
squid:S3437
-
src/main/java/**/*
squid:UndocumentedApi
@@ -128,7 +129,7 @@
com.jayway.jsonpath
json-path
test
-
@@ -392,8 +393,8 @@
spring-boot:run
-
org.eclipse.m2e
@@ -412,7 +413,7 @@
-
+
@@ -426,7 +427,7 @@
-
+
@@ -483,11 +484,11 @@
target/gatling/results
src/test/gatling/bodies
src/test/gatling/simulations
-
true
-
@@ -533,13 +534,15 @@
You are running an older version of
Maven. JHipster requires at least Maven
- ${maven.version}
+ ${maven.version}
+