diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml
index 989f6e535451..a602cd11b933 100644
--- a/asciidoctor/pom.xml
+++ b/asciidoctor/pom.xml
@@ -35,7 +35,12 @@
src/docs/asciidoc
target/docs/asciidoc
+
+ ${project.basedir}/src/themes
+ custom
+
pdf
+ book
diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/asciidoctor/src/docs/asciidoc/test.adoc
index 5a86a00440ae..fec1f7358467 100644
--- a/asciidoctor/src/docs/asciidoc/test.adoc
+++ b/asciidoctor/src/docs/asciidoc/test.adoc
@@ -1,3 +1,13 @@
-== Introduction Section
+:icons: font
-Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#.
\ No newline at end of file
+
+= Generating book with AsciiDoctorj
+Baeldung
+
+[abstract]
+This is the actual content.
+
+== First Section
+
+This is first section of the book where you can include some nice icons like icon:comment[].
+You can also create http://www.baeldung.com[links]
diff --git a/asciidoctor/src/themes/custom-theme.yml b/asciidoctor/src/themes/custom-theme.yml
new file mode 100644
index 000000000000..a3c8c00510b3
--- /dev/null
+++ b/asciidoctor/src/themes/custom-theme.yml
@@ -0,0 +1,29 @@
+title_page:
+ align: left
+
+page:
+ layout: portrait
+ margin: [0.75in, 1in, 0.75in, 1in]
+ size: A4
+base:
+ font_color: #333333
+ line_height_length: 17
+ line_height: $base_line_height_length / $base_font_size
+link:
+ font_color: #009900
+
+header:
+ height: 0.5in
+ line_height: 1
+ recto_content:
+ center: '{document-title}'
+ verso_content:
+ center: '{document-title}'
+
+footer:
+ height: 0.5in
+ line_height: 1
+ recto_content:
+ right: '{chapter-title} | *{page-number}*'
+ verso_content:
+ left: '*{page-number}* | {chapter-title}'
\ No newline at end of file
diff --git a/aws/src/main/java/com/baeldung/s3/S3Application.java b/aws/src/main/java/com/baeldung/s3/S3Application.java
index fcbd7811b543..fdfb909f7368 100644
--- a/aws/src/main/java/com/baeldung/s3/S3Application.java
+++ b/aws/src/main/java/com/baeldung/s3/S3Application.java
@@ -1,9 +1,10 @@
package com.baeldung.s3;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.commons.io.FileUtils;
+
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
@@ -28,7 +29,7 @@ public class S3Application {
"",
""
);
- }
+ }
public static void main(String[] args) throws IOException {
//set-up the client
@@ -74,15 +75,7 @@ public static void main(String[] args) throws IOException {
//downloading an object
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
S3ObjectInputStream inputStream = s3object.getObjectContent();
- FileOutputStream fos = new FileOutputStream(new File("/Users/user/Desktop/hello.txt"));
-
- int read = 0;
- byte[] bytes = new byte[1024];
- while ((read = inputStream.read(bytes)) != -1) {
- fos.write(bytes, 0, read);
- }
- inputStream.close();
- fos.close();
+ FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt"));
//copying an object
awsService.copyObject(
diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/camel-api/src/main/java/com/baeldung/camel/Application.java
index f805385ff959..aadd37a3b422 100644
--- a/camel-api/src/main/java/com/baeldung/camel/Application.java
+++ b/camel-api/src/main/java/com/baeldung/camel/Application.java
@@ -13,14 +13,13 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
-import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@SpringBootApplication
@ComponentScan(basePackages="com.baeldung.camel")
-public class Application extends SpringBootServletInitializer {
+public class Application{
@Value("${server.port}")
String serverPort;
@@ -62,10 +61,12 @@ public void configure() {
.bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true");
/**
-The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
-By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
-You may want to use binding if you develop POJOs that maps to your REST services request and response types.
-This allows you, as a developer, to work with the POJOs in Java code.
+The Rest DSL supports automatic binding json/xml contents to/from
+POJOs using Camels Data Format.
+By default the binding mode is off, meaning there is no automatic
+binding happening for incoming and outgoing messages.
+You may want to use binding if you develop POJOs that maps to
+your REST services request and response types.
*/
rest("/api/").description("Teste REST Service")
diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml
new file mode 100644
index 000000000000..393aa69153e9
--- /dev/null
+++ b/core-java/hashcode/pom.xml
@@ -0,0 +1,39 @@
+
+
+ 4.0.0
+ com.baeldung.hashcode
+ hashcode
+ 1.0
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.25
+
+
+ org.slf4j
+ slf4j-simple
+ 1.7.25
+
+
+
\ No newline at end of file
diff --git a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java
new file mode 100644
index 000000000000..08c670c82f78
--- /dev/null
+++ b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java
@@ -0,0 +1,23 @@
+package com.baeldung.application;
+
+import com.baeldung.entities.User;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Application {
+
+ public static void main(String[] args) {
+ Map users = new HashMap<>();
+ User user1 = new User(1L, "John", "john@domain.com");
+ User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
+ User user3 = new User(3L, "Mary", "mary@domain.com");
+
+ users.put(user1, user1);
+ users.put(user2, user2);
+ users.put(user3, user3);
+
+ if (users.containsKey(user1)) {
+ System.out.print("User found in the collection");
+ }
+ }
+}
diff --git a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java
new file mode 100644
index 000000000000..a976233562dc
--- /dev/null
+++ b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java
@@ -0,0 +1,38 @@
+package com.baeldung.entities;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class User {
+
+ private final Logger logger = LoggerFactory.getLogger(User.class);
+ private long id;
+ private String name;
+ private String email;
+
+ public User(long id, String name, String email) {
+ this.id = id;
+ this.name = name;
+ this.email = email;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null) return false;
+ if (this.getClass() != o.getClass()) return false;
+ User user = (User) o;
+ return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ hash = 31 * hash + (int) id;
+ hash = 31 * hash + (name == null ? 0 : name.hashCode());
+ hash = 31 * hash + (email == null ? 0 : email.hashCode());
+ logger.info("hashCode() method called - Computed hash: " + hash);
+ return hash;
+ }
+ // getters and setters here
+}
diff --git a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java
new file mode 100644
index 000000000000..dcd853f451d9
--- /dev/null
+++ b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.application;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import static org.junit.Assert.assertEquals;
+
+public class ApplicationTest {
+
+ private ByteArrayOutputStream outContent;
+
+ @Before
+ public void setUpPrintStreamInstance() throws Exception {
+ this.outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @After
+ public void tearDownByteArrayOutputStream() throws Exception {
+ outContent = null;
+ }
+
+ @Test
+ public void main_NoInputState_TextPrintedToConsole() throws Exception {
+ Application.main(new String[]{});
+ assertEquals("User found in the collection", outContent.toString());
+ }
+}
\ No newline at end of file
diff --git a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java
new file mode 100644
index 000000000000..01f6085d7eac
--- /dev/null
+++ b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.entities;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class UserTest {
+
+ private User user;
+ private User comparisonUser;
+
+ @Before
+ public void setUpUserInstances() {
+ this.user = new User(1L, "test", "test@domain.com");
+ this.comparisonUser = this.user;
+ }
+
+ @After
+ public void tearDownUserInstances() {
+ user = null;
+ comparisonUser = null;
+ }
+
+ @Test
+ public void equals_EqualUserInstance_TrueAssertion(){
+ Assert.assertTrue(user.equals(comparisonUser));
+ }
+
+ @Test
+ public void hashCode_UserHash_TrueAssertion() {
+ Assert.assertEquals(1792276941, user.hashCode());
+ }
+}
\ No newline at end of file
diff --git a/core-java/pom.xml b/core-java/pom.xml
index ee0d6b4b4a38..73b1c22ed843 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -382,7 +382,7 @@
-
+
2.8.5
@@ -391,7 +391,7 @@
1.1.7
- 21.0
+ 22.0
3.5
1.55
1.10
@@ -408,7 +408,7 @@
1.3
4.12
- 1.10.19
+ 2.8.9
3.6.1
1.7.0
diff --git a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
index 171f308c1682..b77019eea5fe 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
@@ -1,6 +1,5 @@
package com.baeldung.concurrent.Scheduledexecutorservice;
-import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
@@ -12,32 +11,21 @@ public class ScheduledExecutorServiceDemo {
public void execute() {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
- ScheduledFuture> scheduledFuture = executorService.schedule(new Runnable() {
- @Override
- public void run() {
- // task details
- }
+ ScheduledFuture> scheduledFuture = executorService.schedule(() -> {
+ // Task
}, 1, TimeUnit.SECONDS);
- executorService.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- // task details
- }
+ executorService.scheduleAtFixedRate(() -> {
+ // Task
}, 1, 10, TimeUnit.SECONDS);
- executorService.scheduleWithFixedDelay(new Runnable() {
- @Override
- public void run() {
- // task details
- }
+ executorService.scheduleWithFixedDelay(() -> {
+ // Task
}, 1, 10, TimeUnit.SECONDS);
- Future future = executorService.schedule(new Callable() {
- @Override
- public String call() throws Exception {
- return "Hello World";
- }
+ Future future = executorService.schedule(() -> {
+ // Task
+ return "Hellow world";
}, 1, TimeUnit.SECONDS);
executorService.shutdown();
diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
index b2502018bbda..38633011bfd7 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
@@ -1,7 +1,7 @@
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
- int counter;
+ private volatile int counter;
public int getValue() {
return counter;
diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
index 55226f4f13ed..41e10789a6e4 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
@@ -3,7 +3,7 @@
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCounterWithoutLock {
- AtomicInteger counter = new AtomicInteger(0);
+ private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java
index e6075c933e89..a9b92d9f4a17 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java
@@ -4,24 +4,21 @@
public class CyclicBarrierExample {
- public void start() {
- CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
- @Override
- public void run() {
- System.out.println("All previous tasks are completed");
- }
- });
+ public void start() {
+ CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
+ // Task
+ System.out.println("All previous tasks are completed");
+ });
- Thread t1 = new Thread(new Task(cyclicBarrier), "T1");
- Thread t2 = new Thread(new Task(cyclicBarrier), "T2");
- Thread t3 = new Thread(new Task(cyclicBarrier), "T3");
-
- if (!cyclicBarrier.isBroken()) {
- t1.start();
- t2.start();
- t3.start();
- }
-
- }
+ Thread t1 = new Thread(new Task(cyclicBarrier), "T1");
+ Thread t2 = new Thread(new Task(cyclicBarrier), "T2");
+ Thread t3 = new Thread(new Task(cyclicBarrier), "T3");
+ if (!cyclicBarrier.isBroken()) {
+ t1.start();
+ t2.start();
+ t3.start();
+ }
+ }
}
+
diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java
index 4f7801e8c519..cc9ed105dcb6 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java
@@ -6,20 +6,19 @@
public class Task implements Runnable {
private CyclicBarrier barrier;
-
- public Task(CyclicBarrier barrier) {
- this.barrier = barrier;
- }
- @Override
- public void run() {
- try {
- System.out.println("Thread : "+ Thread.currentThread().getName() + " is waiting");
- barrier.await();
- System.out.println("Thread : "+ Thread.currentThread().getName() + " is released");
- } catch (InterruptedException | BrokenBarrierException e) {
- e.printStackTrace();
- }
- }
+ public Task(CyclicBarrier barrier) {
+ this.barrier = barrier;
+ }
+ @Override
+ public void run() {
+ try {
+ System.out.println("Thread : " + Thread.currentThread().getName() + " is waiting");
+ barrier.await();
+ System.out.println("Thread : " + Thread.currentThread().getName() + " is released");
+ } catch (InterruptedException | BrokenBarrierException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java
index 9392134bfb70..84998cb489c7 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java
@@ -6,11 +6,8 @@ public class ExecutorDemo {
public void execute() {
Executor executor = new Invoker();
- executor.execute(new Runnable() {
- @Override
- public void run() {
- // task to be performed
- }
+ executor.execute(()->{
+ // task to be performed
});
}
diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java
index 631ae140ab06..ae2b279d9a91 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java
@@ -10,15 +10,10 @@ public class ExecutorServiceDemo {
public void execute() {
- executor.execute(new Runnable() {
- @Override
- public void run() {
- // task details
- }
+ executor.submit(() -> {
+ new Task();
});
- executor.submit(new Task());
-
executor.shutdown();
executor.shutdownNow();
try {
diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java
index 89ce1a0a41d4..7cb611be0fca 100644
--- a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java
+++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java
@@ -1,6 +1,5 @@
package com.baeldung.concurrent.future;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -16,12 +15,10 @@ public String invoke() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
- Future future = executorService.submit(new Callable() {
- @Override
- public String call() throws Exception {
- Thread.sleep(10000l);
- return "Hello World";
- }
+ Future future = executorService.submit(() -> {
+ // Task
+ Thread.sleep(10000l);
+ return "Hellow world";
});
future.cancel(false);
diff --git a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java
index d672b9a4f5dc..a10499b36277 100644
--- a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java
+++ b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java
@@ -4,12 +4,12 @@
public class AppleProduct implements Serializable {
- private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
-// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
+ private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
+ // private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
public String headphonePort;
public String thunderboltPort;
- public String lighteningPort;
+ public String lightningPort;
public String getHeadphonePort() {
return headphonePort;
@@ -23,4 +23,8 @@ public static long getSerialVersionUID() {
return serialVersionUID;
}
+ public String getLightningPort() {
+ return lightningPort;
+ }
+
}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java
index 3ed2b8be1d9a..ad8e92989880 100644
--- a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java
+++ b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java
@@ -9,11 +9,12 @@ public class DeserializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
- String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
+ String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
System.out.println("Deserializing AppleProduct...");
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
+ System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort());
}
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
diff --git a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java
index 1dbcc40e6bfc..aa7f66659a64 100644
--- a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java
+++ b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java
@@ -13,6 +13,7 @@ public static void main(String[] args) throws ClassNotFoundException, IOExceptio
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
+ macBook.lightningPort = "lightningPort2020";
String serializedObj = serializeObjectToString(macBook);
System.out.println("Serialized AppleProduct object to string:");
diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java
new file mode 100644
index 000000000000..08c670c82f78
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java
@@ -0,0 +1,23 @@
+package com.baeldung.application;
+
+import com.baeldung.entities.User;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Application {
+
+ public static void main(String[] args) {
+ Map users = new HashMap<>();
+ User user1 = new User(1L, "John", "john@domain.com");
+ User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
+ User user3 = new User(3L, "Mary", "mary@domain.com");
+
+ users.put(user1, user1);
+ users.put(user2, user2);
+ users.put(user3, user3);
+
+ if (users.containsKey(user1)) {
+ System.out.print("User found in the collection");
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
new file mode 100644
index 000000000000..a976233562dc
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
@@ -0,0 +1,38 @@
+package com.baeldung.entities;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class User {
+
+ private final Logger logger = LoggerFactory.getLogger(User.class);
+ private long id;
+ private String name;
+ private String email;
+
+ public User(long id, String name, String email) {
+ this.id = id;
+ this.name = name;
+ this.email = email;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null) return false;
+ if (this.getClass() != o.getClass()) return false;
+ User user = (User) o;
+ return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ hash = 31 * hash + (int) id;
+ hash = 31 * hash + (name == null ? 0 : name.hashCode());
+ hash = 31 * hash + (email == null ? 0 : email.hashCode());
+ logger.info("hashCode() method called - Computed hash: " + hash);
+ return hash;
+ }
+ // getters and setters here
+}
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
index 1e1423f0b378..5e38eb6088cb 100644
--- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
@@ -4,7 +4,7 @@ public class Rectangle extends Shape {
private double width;
private double length;
- public Rectangle(double width, double length) {
+ Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java
index 09344902b7fe..d291ac0d3b0c 100644
--- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java
+++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java
@@ -1,11 +1,10 @@
package org.baeldung.executable;
-import javax.swing.JOptionPane;
+import javax.swing.*;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
-
}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java
similarity index 53%
rename from core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java
rename to core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java
index 1612c62513c9..e9b2e164ae5f 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java
@@ -7,31 +7,10 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
-import org.junit.Ignore;
import org.junit.Test;
-public class CounterTest {
+public class ThreadSafeCounterTest {
- /**
- * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling
- * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will
- * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads
- * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this
- * test by adding Ignore annotation.
- */
- @Test
- @Ignore
- public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException {
- ExecutorService service = Executors.newFixedThreadPool(3);
- UnsafeCounter unsafeCounter = new UnsafeCounter();
-
- IntStream.range(0, 1000)
- .forEach(count -> service.submit(unsafeCounter::increment));
- service.awaitTermination(100, TimeUnit.MILLISECONDS);
-
- assertEquals(1000, unsafeCounter.getValue());
- }
-
@Test
public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
@@ -55,4 +34,5 @@ public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws Interr
assertEquals(1000, safeCounter.getValue());
}
+
}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java
new file mode 100644
index 000000000000..cc7cc18bb505
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.concurrent.atomic;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.IntStream;
+
+import org.junit.Test;
+
+/**
+ * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling
+ * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will
+ * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads
+ * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this
+ * test from build by adding this in manual test
+ */
+public class ThreadUnsafeCounterManualTest {
+
+ @Test
+ public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException {
+ ExecutorService service = Executors.newFixedThreadPool(3);
+ UnsafeCounter unsafeCounter = new UnsafeCounter();
+
+ IntStream.range(0, 1000)
+ .forEach(count -> service.submit(unsafeCounter::increment));
+ service.awaitTermination(100, TimeUnit.MILLISECONDS);
+
+ assertEquals(1000, unsafeCounter.getValue());
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java
index 887e7e41da1c..d7c1ee17d4dc 100644
--- a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java
@@ -12,7 +12,7 @@
public class DeserializationUnitTest {
- private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
+ private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
private static long userDefinedSerialVersionUID = 1234567L;
@@ -25,20 +25,22 @@ public class DeserializationUnitTest {
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
-
+
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
-
+ macBook.lightningPort = "lightningPort2020";
+
// serializes the "AppleProduct" object
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
// deserializes the "AppleProduct" object
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
-
+
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
-
+ assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort));
+
}
/**
@@ -59,7 +61,6 @@ public void testDeserializeObj_compatible() throws IOException, ClassNotFoundExc
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
-
// attempts to deserialize the "AppleProduct" object
DeserializationUtility.deSerializeObjectFromString(serializedObj);
}
diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java
new file mode 100644
index 000000000000..dcd853f451d9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.application;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import static org.junit.Assert.assertEquals;
+
+public class ApplicationTest {
+
+ private ByteArrayOutputStream outContent;
+
+ @Before
+ public void setUpPrintStreamInstance() throws Exception {
+ this.outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @After
+ public void tearDownByteArrayOutputStream() throws Exception {
+ outContent = null;
+ }
+
+ @Test
+ public void main_NoInputState_TextPrintedToConsole() throws Exception {
+ Application.main(new String[]{});
+ assertEquals("User found in the collection", outContent.toString());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java
new file mode 100644
index 000000000000..01f6085d7eac
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.entities;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class UserTest {
+
+ private User user;
+ private User comparisonUser;
+
+ @Before
+ public void setUpUserInstances() {
+ this.user = new User(1L, "test", "test@domain.com");
+ this.comparisonUser = this.user;
+ }
+
+ @After
+ public void tearDownUserInstances() {
+ user = null;
+ comparisonUser = null;
+ }
+
+ @Test
+ public void equals_EqualUserInstance_TrueAssertion(){
+ Assert.assertTrue(user.equals(comparisonUser));
+ }
+
+ @Test
+ public void hashCode_UserHash_TrueAssertion() {
+ Assert.assertEquals(1792276941, user.hashCode());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
index 3c2d9904d4c3..0a0993a0d71a 100644
--- a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
@@ -63,6 +63,6 @@ public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyW
private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
- return Paths.get(classLoader.getResource(fileName).getPath());
+ return Paths.get(classLoader.getResource(fileName).toURI());
}
}
diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
similarity index 95%
rename from core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java
rename to core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
index 8948d1ebf78f..fe2747bceeea 100644
--- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
@@ -1,190 +1,190 @@
-package com.baeldung.money;
-
-import org.javamoney.moneta.FastMoney;
-import org.javamoney.moneta.Money;
-import org.javamoney.moneta.format.CurrencyStyle;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import javax.money.CurrencyUnit;
-import javax.money.Monetary;
-import javax.money.MonetaryAmount;
-import javax.money.UnknownCurrencyException;
-import javax.money.convert.CurrencyConversion;
-import javax.money.convert.MonetaryConversions;
-import javax.money.format.AmountFormatQueryBuilder;
-import javax.money.format.MonetaryAmountFormat;
-import javax.money.format.MonetaryFormats;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-public class JavaMoneyUnitTest {
-
- @Test
- public void givenCurrencyCode_whenString_thanExist() {
- CurrencyUnit usd = Monetary.getCurrency("USD");
-
- assertNotNull(usd);
- assertEquals(usd.getCurrencyCode(), "USD");
- assertEquals(usd.getNumericCode(), 840);
- assertEquals(usd.getDefaultFractionDigits(), 2);
- }
-
- @Test(expected = UnknownCurrencyException.class)
- public void givenCurrencyCode_whenNoExist_thanThrowsError() {
- Monetary.getCurrency("AAA");
- }
-
- @Test
- public void givenAmounts_whenStringified_thanEquals() {
- CurrencyUnit usd = Monetary.getCurrency("USD");
- MonetaryAmount fstAmtUSD = Monetary
- .getDefaultAmountFactory()
- .setCurrency(usd)
- .setNumber(200)
- .create();
- Money moneyof = Money.of(12, usd);
- FastMoney fastmoneyof = FastMoney.of(2, usd);
-
- assertEquals("USD", usd.toString());
- assertEquals("USD 200", fstAmtUSD.toString());
- assertEquals("USD 12", moneyof.toString());
- assertEquals("USD 2.00000", fastmoneyof.toString());
- }
-
- @Test
- public void givenCurrencies_whenCompared_thanNotequal() {
- MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
- Money oneEuro = Money.of(1, "EUR");
-
- assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
- assertTrue(oneDolar.equals(Money.of(1, "USD")));
- }
-
- @Test(expected = ArithmeticException.class)
- public void givenAmount_whenDivided_thanThrowsException() {
- MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
- oneDolar.divide(3);
- fail(); // if no exception
- }
-
- @Test
- public void givenAmounts_whenSummed_thanCorrect() {
- List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
-
- Money sumAmtCHF = (Money) monetaryAmounts
- .stream()
- .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
-
- assertEquals("CHF 111.35", sumAmtCHF.toString());
- }
-
- @Test
- public void givenArithmetic_whenStringified_thanEqualsAmount() {
- CurrencyUnit usd = Monetary.getCurrency("USD");
-
- Money moneyof = Money.of(12, usd);
- MonetaryAmount fstAmtUSD = Monetary
- .getDefaultAmountFactory()
- .setCurrency(usd)
- .setNumber(200.50)
- .create();
- MonetaryAmount oneDolar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
- Money subtractedAmount = Money
- .of(1, "USD")
- .subtract(fstAmtUSD);
- MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
- MonetaryAmount divideAmount = oneDolar.divide(0.25);
-
- assertEquals("USD", usd.toString());
- assertEquals("USD 1", oneDolar.toString());
- assertEquals("USD 200.5", fstAmtUSD.toString());
- assertEquals("USD 12", moneyof.toString());
- assertEquals("USD -199.5", subtractedAmount.toString());
- assertEquals("USD 0.25", multiplyAmount.toString());
- assertEquals("USD 4", divideAmount.toString());
- }
-
- @Test
- public void givenAmount_whenRounded_thanEquals() {
- MonetaryAmount fstAmtEUR = Monetary
- .getDefaultAmountFactory()
- .setCurrency("EUR")
- .setNumber(1.30473908)
- .create();
- MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
- assertEquals("EUR 1.30473908", fstAmtEUR.toString());
- assertEquals("EUR 1.3", roundEUR.toString());
- }
-
- @Test
- @Ignore("Currency providers are not always available")
- public void givenAmount_whenConversion_thenNotNull() {
- MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
-
- CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
-
- MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
-
- assertEquals("USD 1", oneDollar.toString());
- assertNotNull(convertedAmountUSDtoEUR);
- }
-
- @Test
- public void givenLocale_whenFormatted_thanEquals() {
- MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
- MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
- String usFormatted = formatUSD.format(oneDollar);
-
- assertEquals("USD 1", oneDollar.toString());
- assertNotNull(formatUSD);
- assertEquals("USD1.00", usFormatted);
- }
-
- @Test
- public void givenAmount_whenCustomFormat_thanEquals() {
- MonetaryAmount oneDollar = Monetary
- .getDefaultAmountFactory()
- .setCurrency("USD")
- .setNumber(1)
- .create();
-
- MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
- .of(Locale.US)
- .set(CurrencyStyle.NAME)
- .set("pattern", "00000.00 ¤")
- .build());
- String customFormatted = customFormat.format(oneDollar);
-
- assertNotNull(customFormat);
- assertEquals("USD 1", oneDollar.toString());
- assertEquals("00001.00 US Dollar", customFormatted);
- }
-}
+package com.baeldung.money;
+
+import org.javamoney.moneta.FastMoney;
+import org.javamoney.moneta.Money;
+import org.javamoney.moneta.format.CurrencyStyle;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import javax.money.CurrencyUnit;
+import javax.money.Monetary;
+import javax.money.MonetaryAmount;
+import javax.money.UnknownCurrencyException;
+import javax.money.convert.CurrencyConversion;
+import javax.money.convert.MonetaryConversions;
+import javax.money.format.AmountFormatQueryBuilder;
+import javax.money.format.MonetaryAmountFormat;
+import javax.money.format.MonetaryFormats;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class JavaMoneyUnitManualTest {
+
+ @Test
+ public void givenCurrencyCode_whenString_thanExist() {
+ CurrencyUnit usd = Monetary.getCurrency("USD");
+
+ assertNotNull(usd);
+ assertEquals(usd.getCurrencyCode(), "USD");
+ assertEquals(usd.getNumericCode(), 840);
+ assertEquals(usd.getDefaultFractionDigits(), 2);
+ }
+
+ @Test(expected = UnknownCurrencyException.class)
+ public void givenCurrencyCode_whenNoExist_thanThrowsError() {
+ Monetary.getCurrency("AAA");
+ }
+
+ @Test
+ public void givenAmounts_whenStringified_thanEquals() {
+ CurrencyUnit usd = Monetary.getCurrency("USD");
+ MonetaryAmount fstAmtUSD = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency(usd)
+ .setNumber(200)
+ .create();
+ Money moneyof = Money.of(12, usd);
+ FastMoney fastmoneyof = FastMoney.of(2, usd);
+
+ assertEquals("USD", usd.toString());
+ assertEquals("USD 200", fstAmtUSD.toString());
+ assertEquals("USD 12", moneyof.toString());
+ assertEquals("USD 2.00000", fastmoneyof.toString());
+ }
+
+ @Test
+ public void givenCurrencies_whenCompared_thanNotequal() {
+ MonetaryAmount oneDolar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+ Money oneEuro = Money.of(1, "EUR");
+
+ assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
+ assertTrue(oneDolar.equals(Money.of(1, "USD")));
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void givenAmount_whenDivided_thanThrowsException() {
+ MonetaryAmount oneDolar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+ oneDolar.divide(3);
+ fail(); // if no exception
+ }
+
+ @Test
+ public void givenAmounts_whenSummed_thanCorrect() {
+ List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
+
+ Money sumAmtCHF = (Money) monetaryAmounts
+ .stream()
+ .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
+
+ assertEquals("CHF 111.35", sumAmtCHF.toString());
+ }
+
+ @Test
+ public void givenArithmetic_whenStringified_thanEqualsAmount() {
+ CurrencyUnit usd = Monetary.getCurrency("USD");
+
+ Money moneyof = Money.of(12, usd);
+ MonetaryAmount fstAmtUSD = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency(usd)
+ .setNumber(200.50)
+ .create();
+ MonetaryAmount oneDolar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+ Money subtractedAmount = Money
+ .of(1, "USD")
+ .subtract(fstAmtUSD);
+ MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
+ MonetaryAmount divideAmount = oneDolar.divide(0.25);
+
+ assertEquals("USD", usd.toString());
+ assertEquals("USD 1", oneDolar.toString());
+ assertEquals("USD 200.5", fstAmtUSD.toString());
+ assertEquals("USD 12", moneyof.toString());
+ assertEquals("USD -199.5", subtractedAmount.toString());
+ assertEquals("USD 0.25", multiplyAmount.toString());
+ assertEquals("USD 4", divideAmount.toString());
+ }
+
+ @Test
+ public void givenAmount_whenRounded_thanEquals() {
+ MonetaryAmount fstAmtEUR = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("EUR")
+ .setNumber(1.30473908)
+ .create();
+ MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
+ assertEquals("EUR 1.30473908", fstAmtEUR.toString());
+ assertEquals("EUR 1.3", roundEUR.toString());
+ }
+
+ @Test
+ @Ignore("Currency providers are not always available")
+ public void givenAmount_whenConversion_thenNotNull() {
+ MonetaryAmount oneDollar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+
+ CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
+
+ MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
+
+ assertEquals("USD 1", oneDollar.toString());
+ assertNotNull(convertedAmountUSDtoEUR);
+ }
+
+ @Test
+ public void givenLocale_whenFormatted_thanEquals() {
+ MonetaryAmount oneDollar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+ MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
+ String usFormatted = formatUSD.format(oneDollar);
+
+ assertEquals("USD 1", oneDollar.toString());
+ assertNotNull(formatUSD);
+ assertEquals("USD1.00", usFormatted);
+ }
+
+ @Test
+ public void givenAmount_whenCustomFormat_thanEquals() {
+ MonetaryAmount oneDollar = Monetary
+ .getDefaultAmountFactory()
+ .setCurrency("USD")
+ .setNumber(1)
+ .create();
+
+ MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
+ .of(Locale.US)
+ .set(CurrencyStyle.NAME)
+ .set("pattern", "00000.00 �")
+ .build());
+ String customFormatted = customFormat.format(oneDollar);
+
+ assertNotNull(customFormat);
+ assertEquals("USD 1", oneDollar.toString());
+ assertEquals("00001.00 US Dollar", customFormatted);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java
new file mode 100644
index 000000000000..d267bd640681
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java
@@ -0,0 +1,69 @@
+package com.baeldung.stream;
+
+import static java.util.stream.Collectors.collectingAndThen;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toSet;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.IntStream;
+
+import org.junit.Test;
+
+import com.baeldung.stream.mycollectors.MyImmutableListCollector;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+public class StreamToImmutableTest {
+
+ @Test
+ public void whenUsingCollectingToImmutableSet_thenSuccess() {
+ Set mutableSet = new HashSet<>(Arrays.asList("a", "b", "c"));
+ mutableSet.add("test");
+ Set immutableSet = mutableSet.stream()
+ .collect(collectingAndThen(toSet(), ImmutableSet::copyOf));
+
+ System.out.println(immutableSet.getClass());
+ }
+
+ @Test
+ public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
+ List givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
+ List result = givenList.stream()
+ .collect(collectingAndThen(toList(), Collections::unmodifiableList));
+
+ System.out.println(result.getClass());
+ }
+
+ @Test
+ public void whenCollectToImmutableList_thenSuccess() {
+ List list = IntStream.range(0, 9)
+ .boxed()
+ .collect(ImmutableList.toImmutableList());
+
+ System.out.println(list.getClass());
+ }
+
+ @Test
+ public void whenCollectToMyImmutableListCollector_thenSuccess() {
+ List givenList = Arrays.asList("a", "b", "c", "d");
+ List result = givenList.stream()
+ .collect(MyImmutableListCollector.toImmutableList());
+
+ System.out.println(result.getClass());
+ }
+
+ @Test
+ public void whenPassingSupplier_thenSuccess() {
+ List givenList = Arrays.asList("a", "b", "c", "d");
+ List result = givenList.stream()
+ .collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
+
+ System.out.println(result.getClass());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java
new file mode 100644
index 000000000000..cf6b3601c393
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java
@@ -0,0 +1,22 @@
+package com.baeldung.stream.mycollectors;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+
+public class MyImmutableListCollector {
+
+ public static > Collector> toImmutableList(Supplier supplier) {
+ return Collector.of(supplier, List::add, (left, right) -> {
+ left.addAll(right);
+ return left;
+ }, Collections::unmodifiableList);
+ }
+
+ public static Collector, List> toImmutableList() {
+ return toImmutableList(ArrayList::new);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java
index ad8de82e1fc8..7b5f781620bd 100644
--- a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java
+++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java
@@ -41,4 +41,4 @@ public void whenAdjust_thenFourteenDaysAfterDate() {
assertEquals(fourteenDaysAfterDate, result.toString());
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java
index 5af286dbcaaa..1c16a5d435db 100644
--- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java
@@ -11,6 +11,7 @@
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
+import java.util.Locale;
import java.util.Scanner;
import org.junit.Test;
@@ -105,6 +106,7 @@ public void whenValidateInputUsingScanner_thenValidated() throws IOException {
public void whenScanString_thenCorrect() throws IOException {
final String input = "Hello 1 F 3.5";
final Scanner scanner = new Scanner(input);
+ scanner.useLocale(Locale.US);
assertEquals("Hello", scanner.next());
assertEquals(1, scanner.nextInt());
diff --git a/feign/README.md b/feign/README.md
index 149f7320d9b0..4d6964a73a42 100644
--- a/feign/README.md
+++ b/feign/README.md
@@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api
-###Relevant Articles:
+### Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign)
diff --git a/feign/pom.xml b/feign/pom.xml
index 9c3868c82f1b..78e1bbcf4c88 100644
--- a/feign/pom.xml
+++ b/feign/pom.xml
@@ -1,12 +1,9 @@
-
+
4.0.0
com.baeldung.feign
feign-client
- 1.0.0-SNAPSHOT
com.baeldung
diff --git a/jooby/conf/application.conf b/jooby/conf/application.conf
new file mode 100644
index 000000000000..2f89e0eb6b3c
--- /dev/null
+++ b/jooby/conf/application.conf
@@ -0,0 +1,2 @@
+#application.secret = 2o128940921eo298e21
+#db = /url/to/the/datastore
\ No newline at end of file
diff --git a/jooby/conf/logback.xml b/jooby/conf/logback.xml
new file mode 100644
index 000000000000..50733ee6d6c1
--- /dev/null
+++ b/jooby/conf/logback.xml
@@ -0,0 +1,42 @@
+
+
+
+
+ [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n
+
+
+
+
+ log/jooby.log
+
+ log/jooby.%d{yyyy-MM-dd}.log
+ 1mb
+ 7
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n
+
+
+
+
+ log/access.log
+
+ log/access.%d{yyyy-MM-dd}.log
+ 1mb
+ 7
+
+
+
+ %msg%n
+
+
+
+
+
+
+
+
+
+
+
diff --git a/jooby/pom.xml b/jooby/pom.xml
new file mode 100644
index 000000000000..1935c646eec5
--- /dev/null
+++ b/jooby/pom.xml
@@ -0,0 +1,56 @@
+
+
+ 4.0.0
+ jooby
+ com.baeldung.jooby
+ 1.0
+ jooby
+
+
+ org.jooby
+ modules
+ 1.1.3
+
+
+
+ 1.1.3
+ com.baeldung.jooby.App
+
+
+
+
+ org.jooby
+ jooby-netty
+
+
+ org.jooby
+ jooby-jedis
+ 1.1.3
+
+
+ ch.qos.logback
+ logback-classic
+
+
+ junit
+ junit
+ test
+
+
+ io.rest-assured
+ rest-assured
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+
+
+
+
+
diff --git a/jooby/public/form.html b/jooby/public/form.html
new file mode 100644
index 000000000000..a23620812a49
--- /dev/null
+++ b/jooby/public/form.html
@@ -0,0 +1,17 @@
+
+
+
+
+Insert title here
+
+
+
+
+
\ No newline at end of file
diff --git a/jooby/public/welcome.html b/jooby/public/welcome.html
new file mode 100644
index 000000000000..cd21fb19885d
--- /dev/null
+++ b/jooby/public/welcome.html
@@ -0,0 +1,10 @@
+
+
+
+
+Insert title here
+
+
+i m welcomed
+
+
\ No newline at end of file
diff --git a/jooby/src/etc/stork.yml b/jooby/src/etc/stork.yml
new file mode 100644
index 000000000000..f2f2790cd1e4
--- /dev/null
+++ b/jooby/src/etc/stork.yml
@@ -0,0 +1,41 @@
+# Name of application (make sure it has no spaces)
+name: "${project.artifactId}"
+
+# Display name of application (can have spaces)
+display_name: "${project.name}"
+
+# Type of launcher (CONSOLE or DAEMON)
+type: DAEMON
+
+# Java class to run
+main_class: "${application.class}"
+
+domain: "${project.groupId}"
+
+short_description: "${project.artifactId}"
+
+# Platform launchers to generate (WINDOWS, LINUX, MAC_OSX)
+# Linux launcher is suitable for Bourne shells (e.g. Linux/BSD)
+platforms: [ LINUX ]
+
+# Working directory for app
+# RETAIN will not change the working directory
+# APP_HOME will change the working directory to the home of the app
+# (where it was intalled) before running the main class
+working_dir_mode: RETAIN
+
+# Minimum version of java required (system will be searched for acceptable jvm)
+min_java_version: "1.8"
+
+# Min/max fixed memory (measured in MB)
+min_java_memory: 512
+max_java_memory: 512
+
+# Min/max memory by percentage of system
+#min_java_memory_pct: 10
+#max_java_memory_pct: 20
+
+# Try to create a symbolic link to java executable in /run with
+# the name of "-java" so that commands like "ps" will make it
+# easier to find your app
+symlink_java: true
diff --git a/jooby/src/main/java/com/baeldung/jooby/App.java b/jooby/src/main/java/com/baeldung/jooby/App.java
new file mode 100644
index 000000000000..94a24048c292
--- /dev/null
+++ b/jooby/src/main/java/com/baeldung/jooby/App.java
@@ -0,0 +1,95 @@
+package com.baeldung.jooby;
+
+import org.jooby.Jooby;
+import org.jooby.Mutant;
+import org.jooby.Session;
+import org.jooby.jedis.Redis;
+import org.jooby.jedis.RedisSessionStore;
+
+import com.baeldung.jooby.bean.Employee;
+
+public class App extends Jooby {
+
+ {
+ port(8080);
+ securePort(8443);
+ }
+
+ {
+ get("/", () -> "Hello World!");
+ }
+
+ {
+ get("/user/{id}", req -> "Hello user : " + req.param("id").value());
+ get("/user/:id", req -> "Hello user: " + req.param("id").value());
+ get("/uid:{id}", req -> "Hello User with id : uid" + req.param("id").value());
+ }
+
+ {
+ onStart(() -> {
+ System.out.println("starting app");
+ });
+
+ onStop(() -> {
+ System.out.println("stopping app");
+ });
+
+ onStarted(() -> {
+ System.out.println("app started");
+ });
+ }
+
+ {
+ get("/login", () -> "Hello from Baeldung");
+ }
+
+ {
+ post("/save", req -> {
+ Mutant token = req.param("token");
+ return token.intValue();
+ });
+ }
+
+ {
+ {
+ assets("/employee", "form.html");
+ }
+
+ post("/submitForm", req -> {
+ Employee employee = req.params(Employee.class);
+ // TODO
+ return "empoyee data saved successfullly";
+ });
+ }
+
+ {
+ get("/filter", (req, resp, chain) -> {
+ // TODO
+ // resp.send(...);
+ chain.next(req, resp);
+ });
+ get("/filter", (req, resp) -> {
+ resp.send("filter response");
+ });
+ }
+
+ {
+// cookieSession();
+
+// use(new Redis());
+//
+// session(RedisSessionStore.class);
+
+ get("/session", req -> {
+ Session session = req.session();
+ session.set("token", "value");
+ return session.get("token").value();
+ });
+ }
+
+ public static void main(final String[] args) {
+
+ run(App::new, args);
+ }
+
+}
diff --git a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java
new file mode 100644
index 000000000000..2c4a1038b5c7
--- /dev/null
+++ b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java
@@ -0,0 +1,16 @@
+package com.baeldung.jooby.bean;
+
+public class Employee {
+
+ String id;
+ String name;
+ String email;
+
+ public Employee(String id, String name, String email) {
+ super();
+ this.id = id;
+ this.name = name;
+ this.email = email;
+ }
+
+}
diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java
new file mode 100644
index 000000000000..a2c51bae70e3
--- /dev/null
+++ b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java
@@ -0,0 +1,22 @@
+package com.baeldung.jooby.mvc;
+
+import org.jooby.Result;
+import org.jooby.Results;
+import org.jooby.mvc.GET;
+import org.jooby.mvc.Path;
+
+@Path("/hello")
+public class GetController {
+
+ @GET
+ public String hello() {
+ return "Hello Baeldung";
+ }
+
+ @GET
+ @Path("/home")
+ public Result home() {
+ return Results.html("welcome").put("model", new Object());
+ }
+
+}
diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java
new file mode 100644
index 000000000000..df00e47da5e6
--- /dev/null
+++ b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java
@@ -0,0 +1,14 @@
+package com.baeldung.jooby.mvc;
+
+import org.jooby.mvc.POST;
+import org.jooby.mvc.Path;
+
+@Path("/submit")
+public class PostController {
+
+ @POST
+ public String hello() {
+ return "Submit Baeldung";
+ }
+
+}
diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppTest.java
new file mode 100644
index 000000000000..af2626c046af
--- /dev/null
+++ b/jooby/src/test/java/com/baeldung/jooby/AppTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.jooby;
+
+import static io.restassured.RestAssured.get;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertEquals;
+
+import org.jooby.test.JoobyRule;
+import org.jooby.test.MockRouter;
+import org.junit.ClassRule;
+import org.junit.Test;
+
+public class AppTest {
+
+ @ClassRule
+ public static JoobyRule app = new JoobyRule(new App());
+
+ @Test
+ public void given_defaultUrl_expect_fixedString() {
+ get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200)
+ .contentType("text/html;charset=UTF-8");
+ }
+
+ @Test
+ public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable {
+ String result = new MockRouter(new App()).get("/");
+ assertEquals("Hello World!", result);
+ }
+
+}
diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt
new file mode 100644
index 000000000000..d3167ce03311
--- /dev/null
+++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt
@@ -0,0 +1,3 @@
+package com.baeldung.destructuringdeclarations
+
+data class Person(var id: Int, var name: String, var age: Int)
\ No newline at end of file
diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt
new file mode 100644
index 000000000000..e3da9b46a453
--- /dev/null
+++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt
@@ -0,0 +1,3 @@
+package com.baeldung.destructuringdeclarations
+
+data class Result(val result: Int, val status: String)
\ No newline at end of file
diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt
new file mode 100644
index 000000000000..a5018d93c8a4
--- /dev/null
+++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt
@@ -0,0 +1,44 @@
+package com.baeldung.destructuringdeclarations
+
+import com.baeldung.destructuringdeclarations.Person
+
+fun main(args: Array) {
+
+ //2.1. Objects
+ val person = Person(1, "Jon Snow", 20)
+ val(id, name, age) = person
+
+ println(id) //1
+ println(name) //Jon Snow
+ println(age) //20
+
+ //2.2. Functions
+ fun getPersonInfo() = Person(2, "Ned Stark", 45)
+ val(idf, namef, agef) = getPersonInfo()
+
+ fun twoValuesReturn(): Pair {
+
+ // needed code
+
+ return Pair(1, "success")
+ }
+
+ // Now, to use this function:
+ val (result, status) = twoValuesReturn()
+
+ //2.3. Collections and For-loops
+ var map: HashMap = HashMap()
+ map.put(1, person)
+
+ for((key, value) in map){
+ println("Key: $key, Value: $value")
+ }
+
+ //2.4. Underscore and Destructuring in Lambdas
+ val (_, name2, age2) = person
+ val (id3, name3) = person
+
+ map.mapValues { entry -> "${entry.value}!" }
+ map.mapValues { (key, value) -> "$value!" }
+
+}
\ No newline at end of file
diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml
new file mode 100644
index 000000000000..94a9ca43f422
--- /dev/null
+++ b/libraries-data/pom.xml
@@ -0,0 +1,22 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+ libraries-data
+ libraries-data
+ jar
+
+
+ com.esotericsoftware
+ kryo
+ ${kryo.version}
+
+
+
+ 4.0.1
+
+
\ No newline at end of file
diff --git a/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java
new file mode 100644
index 000000000000..0e125e48a91c
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java
@@ -0,0 +1,16 @@
+package com.baeldung.kryo;
+
+import java.io.Serializable;
+
+public class ComplexClass implements Serializable{
+ private static final long serialVersionUID = 123456L;
+ private String name = "Bael";
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/libraries-data/src/main/java/com/baeldung/kryo/Person.java b/libraries-data/src/main/java/com/baeldung/kryo/Person.java
new file mode 100644
index 000000000000..f9be5cfd62f9
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/kryo/Person.java
@@ -0,0 +1,54 @@
+package com.baeldung.kryo;
+
+import com.esotericsoftware.kryo.DefaultSerializer;
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.KryoSerializable;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+import java.util.Date;
+
+@DefaultSerializer(PersonSerializer.class)
+public class Person implements KryoSerializable {
+ private String name = "John Doe";
+ private int age = 18;
+ private Date birthDate = new Date(933191282821L);
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ @Override
+ public void write(Kryo kryo, Output output) {
+ output.writeString(name);
+ output.writeLong(birthDate.getTime());
+ output.writeInt(age);
+ }
+
+ @Override
+ public void read(Kryo kryo, Input input) {
+ name = input.readString();
+ birthDate = new Date(input.readLong());
+ age = input.readInt();
+ }
+
+}
diff --git a/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java
new file mode 100644
index 000000000000..f5d01509a668
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java
@@ -0,0 +1,33 @@
+package com.baeldung.kryo;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.Serializer;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+import java.util.Date;
+
+public class PersonSerializer extends Serializer {
+
+ @Override
+ public void write(Kryo kryo, Output output, Person object) {
+ output.writeString(object.getName());
+ output.writeLong(object.getBirthDate()
+ .getTime());
+ }
+
+ @Override
+ public Person read(Kryo kryo, Input input, Class type) {
+ Person person = new Person();
+ person.setName(input.readString());
+ long birthDate = input.readLong();
+ person.setBirthDate(new Date(birthDate));
+ person.setAge(calculateAge(birthDate));
+ return person;
+ }
+
+ private int calculateAge(long birthDate) {
+ // Some custom logic
+ return 18;
+ }
+
+}
diff --git a/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java
new file mode 100644
index 000000000000..c124ca618db9
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java
@@ -0,0 +1,125 @@
+package com.baeldung.kryo;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.util.Date;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+import com.esotericsoftware.kryo.serializers.JavaSerializer;
+
+public class KryoUnitTest {
+
+ private Kryo kryo;
+ private Output output;
+ private Input input;
+
+ @Before
+ public void init() {
+ kryo = new Kryo();
+ try {
+ output = new Output(new FileOutputStream("file.dat"));
+ input = new Input(new FileInputStream("file.dat"));
+ } catch (FileNotFoundException ex) {
+ Logger.getLogger(KryoUnitTest.class.getName())
+ .log(Level.SEVERE, null, ex);
+ }
+ }
+
+ @Test
+ public void givenObject_whenSerializing_thenReadCorrectly() {
+ Object someObject = "Some string";
+
+ kryo.writeClassAndObject(output, someObject);
+ output.close();
+
+ Object theObject = kryo.readClassAndObject(input);
+ input.close();
+
+ assertEquals(theObject, "Some string");
+ }
+
+ @Test
+ public void givenObjects_whenSerializing_thenReadCorrectly() {
+ String someString = "Multiple Objects";
+ Date someDate = new Date(915170400000L);
+
+ kryo.writeObject(output, someString);
+ kryo.writeObject(output, someDate);
+ output.close();
+
+ String readString = kryo.readObject(input, String.class);
+ Date readDate = kryo.readObject(input, Date.class);
+ input.close();
+
+ assertEquals(readString, "Multiple Objects");
+ assertEquals(readDate.getTime(), 915170400000L);
+ }
+
+ @Test
+ public void givenPerson_whenSerializing_thenReadCorrectly() {
+ Person person = new Person();
+
+ kryo.writeObject(output, person);
+ output.close();
+
+ Person readPerson = kryo.readObject(input, Person.class);
+ input.close();
+
+ assertEquals(readPerson.getName(), "John Doe");
+ }
+
+ @Test
+ public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() {
+ Person person = new Person();
+ person.setAge(0);
+ kryo.register(Person.class, new PersonSerializer());
+
+ kryo.writeObject(output, person);
+ output.close();
+
+ Person readPerson = kryo.readObject(input, Person.class);
+ input.close();
+
+ assertEquals(readPerson.getName(), "John Doe");
+ assertEquals(readPerson.getAge(), 18);
+ }
+
+ @Test
+ public void givenPerson_whenCustomSerialization_thenReadCorrectly() {
+ Person person = new Person();
+
+ kryo.writeObject(output, person);
+ output.close();
+
+ Person readPerson = kryo.readObject(input, Person.class);
+ input.close();
+
+ assertEquals(readPerson.getName(), "John Doe");
+ assertEquals(readPerson.getAge(), 18);
+ }
+
+ @Test
+ public void givenJavaSerializable_whenSerializing_thenReadCorrectly() {
+ ComplexClass complexClass = new ComplexClass();
+ kryo.register(ComplexClass.class, new JavaSerializer());
+
+ kryo.writeObject(output, complexClass);
+ output.close();
+
+ ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class);
+ input.close();
+
+ assertEquals(readComplexObject.getName(), "Bael");
+ }
+
+}
diff --git a/libraries/README.md b/libraries/README.md
index 7970c0e99ec1..86baa39045bd 100644
--- a/libraries/README.md
+++ b/libraries/README.md
@@ -26,6 +26,8 @@
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
+- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
+- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 16f70cb17194..efdf20423a1f 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -1,633 +1,501 @@
-
- parent-modules
- com.baeldung
- 1.0.0-SNAPSHOT
-
- 4.0.0
-
- libraries
- libraries
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- org.apache.felix
- maven-bundle-plugin
- 3.3.0
- maven-plugin
-
-
-
- true
-
-
- maven-failsafe-plugin
- 2.20
-
-
- chromedriver
-
-
-
-
- net.serenity-bdd.maven.plugins
- serenity-maven-plugin
- ${serenity.plugin.version}
-
-
- serenity-reports
- post-integration-test
-
- aggregate
-
-
-
-
-
-
- org.datanucleus
- datanucleus-maven-plugin
- 5.0.2
-
- JDO
- ${basedir}/datanucleus.properties
- ${basedir}/log4j.properties
- true
- false
-
-
-
-
- process-classes
-
- enhance
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- 3.0.0
-
- false
- WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**
-
-
-
- com.vaadin
- vaadin-maven-plugin
- ${vaadin.plugin.version}
-
-
-
- update-theme
- update-widgetset
- compile
- compile-theme
-
-
-
-
-
- org.apache.maven.plugins
- maven-clean-plugin
- 3.0.0
-
-
-
- src/main/webapp/VAADIN/themes
-
- **/styles.css
- **/styles.scss.cache
-
-
-
-
-
-
- org.eclipse.jetty
- jetty-maven-plugin
- ${jetty.version}
-
- 2
- true
-
-
-
-
-
-
-
-
- vaadin-addons
- http://maven.vaadin.com/vaadin-addons
-
-
-
-
-
- com.vaadin
- vaadin-bom
- ${vaadin.version}
- pom
- import
-
-
-
-
-
-
-
- cglib
- cglib
- ${cglib.version}
-
-
- commons-beanutils
- commons-beanutils
- ${commons-beanutils.version}
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang.version}
-
-
- org.apache.commons
- commons-text
- ${commons-text.version}
-
-
- org.apache.commons
- commons-collections4
- ${commons.collections.version}
-
-
- org.jasypt
- jasypt
- ${jasypt.version}
-
-
- org.javatuples
- javatuples
- ${javatuples.version}
-
-
- org.javassist
- javassist
- ${javaassist.version}
-
-
-
- org.assertj
- assertj-core
- ${assertj.version}
-
-
- org.skyscreamer
- jsonassert
- ${jsonassert.version}
-
-
- org.javers
- javers-core
- ${javers.version}
-
-
- org.eclipse.jetty
- jetty-server
- ${jetty.version}
-
-
- org.eclipse.jetty
- jetty-servlet
- ${jetty.version}
-
-
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- commons-io
- commons-io
- ${commons.io.version}
-
-
- commons-chain
- commons-chain
- ${commons-chain.version}
-
-
- commons-dbutils
- commons-dbutils
- ${commons.dbutils.version}
-
-
- org.apache.flink
- flink-core
- ${flink.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.apache.flink
- flink-java
- ${flink.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.apache.flink
- flink-test-utils_2.10
- ${flink.version}
- test
-
-
- org.apache.commons
- commons-math3
- 3.6.1
-
-
- net.serenity-bdd
- serenity-core
- ${serenity.version}
- test
-
-
- net.serenity-bdd
- serenity-junit
- ${serenity.version}
- test
-
-
- net.serenity-bdd
- serenity-jbehave
- ${serenity.jbehave.version}
- test
-
-
- net.serenity-bdd
- serenity-rest-assured
- ${serenity.version}
- test
-
-
- net.serenity-bdd
- serenity-jira-requirements-provider
- ${serenity.jira.version}
- test
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
-
-
- org.datanucleus
- javax.jdo
- 3.2.0-m6
-
-
- org.datanucleus
- datanucleus-core
- 5.1.0-m1
-
-
- org.datanucleus
- datanucleus-api-jdo
- 5.1.0-m1
-
-
- org.datanucleus
- datanucleus-rdbms
- 5.1.0-m1
-
-
- org.datanucleus
- datanucleus-maven-plugin
- 5.0.2
-
-
- org.datanucleus
- datanucleus-xml
- 5.0.0-release
-
-
- net.openhft
- chronicle
- 3.6.4
-
-
- org.springframework
- spring-web
- 4.3.8.RELEASE
-
-
- net.serenity-bdd
- serenity-spring
- ${serenity.version}
- test
-
-
- net.serenity-bdd
- serenity-screenplay
- ${serenity.version}
- test
-
-
- net.serenity-bdd
- serenity-screenplay-webdriver
- ${serenity.version}
- test
-
-
- io.rest-assured
- spring-mock-mvc
- 3.0.3
- test
-
-
- org.multiverse
- multiverse-core
- ${multiverse.version}
-
-
- com.zaxxer
- HikariCP
- 2.6.1
- compile
-
-
- com.h2database
- h2
- ${h2.version}
-
-
- pl.pragmatists
- JUnitParams
- ${jUnitParams.version}
- test
-
-
- org.quartz-scheduler
- quartz
- 2.3.0
-
-
-
- one.util
- streamex
- 0.6.5
-
-
- org.jooq
- jool
- 0.9.12
-
-
- org.openjdk.jmh
- jmh-core
- 1.19
-
-
- org.openjdk.jmh
- jmh-generator-annprocess
- 1.19
-
-
- io.netty
- netty-all
- ${netty.version}
-
-
- junit
- junit
- ${junit.version}
- test
-
-
- info.debatty
- java-lsh
- ${java-lsh.version}
-
-
- au.com.dius
- pact-jvm-consumer-junit_2.11
- ${pact.version}
- test
-
-
- org.codehaus.groovy
- groovy-all
- 2.4.10
-
-
- org.awaitility
- awaitility
- ${awaitility.version}
- test
-
-
- org.awaitility
- awaitility-proxy
- ${awaitility.version}
- test
-
-
- org.hamcrest
- java-hamcrest
- ${org.hamcrest.java-hamcrest.version}
- test
-
-
-
- com.vaadin
- vaadin-server
-
-
- com.vaadin
- vaadin-client-compiled
-
-
- com.vaadin
- vaadin-themes
-
-
- com.vaadin
- vaadin-push
-
-
- org.seleniumhq.selenium
- selenium-java
- test
- 3.4.0
-
-
- org.seleniumhq.selenium
- htmlunit-driver
- 2.27
-
-
- org.eclipse.jetty.websocket
- websocket-server
- ${jetty.version}
-
-
- org.eclipse.jetty.websocket
- websocket-client
- ${jetty.version}
-
-
- org.eclipse.jetty.websocket
- websocket-api
- ${jetty.version}
-
-
- org.eclipse.jetty.websocket
- websocket-common
- ${jetty.version}
-
-
- org.eclipse.jetty
- jetty-continuation
- ${jetty.version}
-
-
- org.eclipse.jetty
- jetty-util
- ${jetty.version}
-
-
- org.seleniumhq.selenium
- selenium-api
- 3.4.0
- test
- jar
-
-
-
- net.agkn
- hll
- ${hll.version}
-
-
- net.bytebuddy
- byte-buddy
- ${bytebuddy.version}
-
-
- net.bytebuddy
- byte-buddy-agent
- ${bytebuddy.version}
-
-
-
- 0.7.0
- 3.2.4
- 3.5
- 1.1
- 1.9.3
- 1.2
- 1.9.2
- 1.2
- 3.21.0-GA
- 3.6.2
- 1.5.0
- 3.1.0
- 9.4.3.v20170317
- 4.5.3
- 2.5
- 1.6
- 1.4.196
- 9.4.2.v20170220
- 4.5.3
- 2.5
- 1.2.0
- 2.8.5
- 1.4.0
- 1.24.0
- 1.1.3-rc.5
- 1.4.0
- 1.1.0
- 4.1.10.Final
- 4.1
- 4.12
- 0.10
- 3.5.0
- 3.0.0
- 2.0.0.0
-
- 7.7.10
- 8.0.6
- mytheme
-
- 1.6.0
- 1.7.1
-
-
-
-
- vaadin-prerelease
-
- false
-
-
-
- vaadin-prereleases
- http://maven.vaadin.com/vaadin-prereleases
-
-
- vaadin-snapshots
- https://oss.sonatype.org/content/repositories/vaadin-snapshots/
-
- false
-
-
- true
-
-
-
-
-
- vaadin-prereleases
- http://maven.vaadin.com/vaadin-prereleases
-
-
- vaadin-snapshots
- https://oss.sonatype.org/content/repositories/vaadin-snapshots/
-
- false
-
-
- true
-
-
-
-
-
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+ libraries
+ libraries
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 3.3.0
+ maven-plugin
+
+
+ true
+
+
+ maven-failsafe-plugin
+ 2.20
+
+
+ chromedriver
+
+
+
+
+ net.serenity-bdd.maven.plugins
+ serenity-maven-plugin
+ ${serenity.plugin.version}
+
+
+ serenity-reports
+ post-integration-test
+
+ aggregate
+
+
+
+
+
+
+ org.datanucleus
+ datanucleus-maven-plugin
+ 5.0.2
+
+ JDO
+ ${basedir}/datanucleus.properties
+ ${basedir}/log4j.properties
+ true
+ false
+
+
+
+
+ process-classes
+
+ enhance
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 3.0.2
+
+
+ **/log4j.properties
+
+
+
+ com.baeldung.neuroph.NeurophXOR
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.18.1
+
+
+ test
+ test
+
+ test
+
+
+
+ test/java/com/baeldung/neuroph/XORTest.java
+
+
+
+
+
+
+
+
+
+
+
+ org.beykery
+ neuroph
+ ${neuroph.version}
+
+
+
+ cglib
+ cglib
+ ${cglib.version}
+
+
+ commons-beanutils
+ commons-beanutils
+ ${commons-beanutils.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang.version}
+
+
+ org.apache.commons
+ commons-text
+ ${commons-text.version}
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons.collections.version}
+
+
+ org.jasypt
+ jasypt
+ ${jasypt.version}
+
+
+ org.javatuples
+ javatuples
+ ${javatuples.version}
+
+
+ org.javassist
+ javassist
+ ${javaassist.version}
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+
+
+ org.skyscreamer
+ jsonassert
+ ${jsonassert.version}
+
+
+ org.javers
+ javers-core
+ ${javers.version}
+
+
+ org.eclipse.jetty
+ jetty-server
+ ${jetty.version}
+
+
+ org.eclipse.jetty
+ jetty-servlet
+ ${jetty.version}
+
+
+ io.specto
+ hoverfly-java
+ 0.8.0
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ commons-io
+ commons-io
+ ${commons.io.version}
+
+
+ commons-chain
+ commons-chain
+ ${commons-chain.version}
+
+
+ commons-dbutils
+ commons-dbutils
+ ${commons.dbutils.version}
+
+
+ org.apache.flink
+ flink-core
+ ${flink.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.apache.flink
+ flink-java
+ ${flink.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.apache.flink
+ flink-test-utils_2.10
+ ${flink.version}
+ test
+
+
+ org.apache.commons
+ commons-math3
+ 3.6.1
+
+
+ net.serenity-bdd
+ serenity-core
+ ${serenity.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-junit
+ ${serenity.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-jbehave
+ ${serenity.jbehave.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-rest-assured
+ ${serenity.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-jira-requirements-provider
+ ${serenity.jira.version}
+ test
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
+
+
+ org.datanucleus
+ javax.jdo
+ 3.2.0-m6
+
+
+ org.datanucleus
+ datanucleus-core
+ 5.1.0-m1
+
+
+ org.datanucleus
+ datanucleus-api-jdo
+ 5.1.0-m1
+
+
+ org.datanucleus
+ datanucleus-rdbms
+ 5.1.0-m1
+
+
+ org.datanucleus
+ datanucleus-maven-plugin
+ 5.0.2
+
+
+ org.datanucleus
+ datanucleus-xml
+ 5.0.0-release
+
+
+ net.openhft
+ chronicle
+ 3.6.4
+
+
+ org.springframework
+ spring-web
+ 4.3.8.RELEASE
+
+
+ net.serenity-bdd
+ serenity-spring
+ ${serenity.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-screenplay
+ ${serenity.version}
+ test
+
+
+ net.serenity-bdd
+ serenity-screenplay-webdriver
+ ${serenity.version}
+ test
+
+
+ io.rest-assured
+ spring-mock-mvc
+ 3.0.3
+ test
+
+
+ org.multiverse
+ multiverse-core
+ ${multiverse.version}
+
+
+ com.zaxxer
+ HikariCP
+ 2.6.1
+ compile
+
+
+ com.h2database
+ h2
+ ${h2.version}
+
+
+ pl.pragmatists
+ JUnitParams
+ ${jUnitParams.version}
+ test
+
+
+ org.quartz-scheduler
+ quartz
+ 2.3.0
+
+
+ one.util
+ streamex
+ 0.6.5
+
+
+ org.jooq
+ jool
+ 0.9.12
+
+
+ org.openjdk.jmh
+ jmh-core
+ 1.19
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ 1.19
+
+
+ io.netty
+ netty-all
+ ${netty.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+ info.debatty
+ java-lsh
+ ${java-lsh.version}
+
+
+ au.com.dius
+ pact-jvm-consumer-junit_2.11
+ ${pact.version}
+ test
+
+
+ org.codehaus.groovy
+ groovy-all
+ 2.4.10
+
+
+ org.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
+
+ org.awaitility
+ awaitility-proxy
+ ${awaitility.version}
+ test
+
+
+ org.hamcrest
+ java-hamcrest
+ ${org.hamcrest.java-hamcrest.version}
+ test
+
+
+ net.agkn
+ hll
+ ${hll.version}
+
+
+ net.bytebuddy
+ byte-buddy
+ ${bytebuddy.version}
+
+
+ net.bytebuddy
+ byte-buddy-agent
+ ${bytebuddy.version}
+
+
+ org.pcollections
+ pcollections
+ ${pcollections.version}
+
+
+
+ 0.7.0
+ 3.2.4
+ 3.5
+ 1.1
+ 1.9.3
+ 1.2
+ 1.9.2
+ 1.2
+ 3.21.0-GA
+ 3.6.2
+ 1.5.0
+ 3.1.0
+ 9.4.3.v20170317
+ 4.5.3
+ 2.5
+ 1.6
+ 1.4.196
+ 9.4.2.v20170220
+ 4.5.3
+ 2.5
+ 1.2.0
+ 2.8.5
+ 2.92
+ 1.4.0
+ 1.24.0
+ 1.1.3-rc.5
+ 1.4.0
+ 1.1.0
+ 4.1.10.Final
+ 4.1
+ 4.12
+ 0.10
+ 3.5.0
+ 3.0.0
+ 2.0.0.0
+ 1.6.0
+ 1.7.1
+ 2.1.2
+
diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
new file mode 100644
index 000000000000..fb6a01d4c144
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
@@ -0,0 +1,73 @@
+package com.baeldung.neuroph;
+
+import org.neuroph.core.Layer;
+import org.neuroph.core.NeuralNetwork;
+import org.neuroph.core.Neuron;
+import org.neuroph.core.data.DataSet;
+import org.neuroph.core.data.DataSetRow;
+import org.neuroph.nnet.learning.BackPropagation;
+import org.neuroph.util.ConnectionFactory;
+import org.neuroph.util.NeuralNetworkType;
+
+public class NeurophXOR {
+
+ public static NeuralNetwork assembleNeuralNetwork() {
+
+ Layer inputLayer = new Layer();
+ inputLayer.addNeuron(new Neuron());
+ inputLayer.addNeuron(new Neuron());
+
+ Layer hiddenLayerOne = new Layer();
+ hiddenLayerOne.addNeuron(new Neuron());
+ hiddenLayerOne.addNeuron(new Neuron());
+ hiddenLayerOne.addNeuron(new Neuron());
+ hiddenLayerOne.addNeuron(new Neuron());
+
+ Layer hiddenLayerTwo = new Layer();
+ hiddenLayerTwo.addNeuron(new Neuron());
+ hiddenLayerTwo.addNeuron(new Neuron());
+ hiddenLayerTwo.addNeuron(new Neuron());
+ hiddenLayerTwo.addNeuron(new Neuron());
+
+ Layer outputLayer = new Layer();
+ outputLayer.addNeuron(new Neuron());
+
+ NeuralNetwork ann = new NeuralNetwork();
+
+ ann.addLayer(0, inputLayer);
+ ann.addLayer(1, hiddenLayerOne);
+ ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1));
+ ann.addLayer(2, hiddenLayerTwo);
+ ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
+ ann.addLayer(3, outputLayer);
+ ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
+ ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false);
+
+ ann.setInputNeurons(inputLayer.getNeurons());
+ ann.setOutputNeurons(outputLayer.getNeurons());
+
+ ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON);
+ return ann;
+ }
+
+ public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
+ int inputSize = 2;
+ int outputSize = 1;
+ DataSet ds = new DataSet(inputSize, outputSize);
+
+ DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1});
+ ds.addRow(rOne);
+ DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0});
+ ds.addRow(rTwo);
+ DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0});
+ ds.addRow(rThree);
+ DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1});
+ ds.addRow(rFour);
+
+ BackPropagation backPropagation = new BackPropagation();
+ backPropagation.setMaxIterations(1000);
+
+ ann.learn(ds, backPropagation);
+ return ann;
+ }
+}
diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java
new file mode 100644
index 000000000000..430759f3a0d9
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java
@@ -0,0 +1,22 @@
+package com.baeldung.streamutils;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+
+import org.apache.commons.io.IOUtils;
+import org.springframework.util.StreamUtils;
+
+public class CopyStream {
+ public static String getStringFromInputStream(InputStream input) throws IOException {
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(input, writer, "UTF-8");
+ return writer.toString();
+ }
+
+ public InputStream getNonClosingInputStream() throws IOException {
+ InputStream in = new FileInputStream("src/test/resources/input.txt");
+ return StreamUtils.nonClosing(in);
+ }
+}
diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java
new file mode 100644
index 000000000000..6ee4a1ef3a4b
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java
@@ -0,0 +1,11 @@
+package com.baeldung.streamutils;
+
+import java.io.InputStream;
+
+import org.springframework.util.StreamUtils;
+
+public class DrainStream {
+ public InputStream getInputStream() {
+ return StreamUtils.emptyInput();
+ }
+}
diff --git a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss b/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss
deleted file mode 100644
index a5670b70c7ea..000000000000
--- a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss
+++ /dev/null
@@ -1,7 +0,0 @@
-/* This file is automatically managed and will be overwritten from time to time. */
-/* Do not manually edit this file. */
-
-/* Import and include this mixin into your project theme to include the addon themes */
-@mixin addons {
-}
-
diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java
new file mode 100644
index 000000000000..9f670af03c22
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java
@@ -0,0 +1,159 @@
+package com.baeldung.circularfifoqueue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.collections4.queue.CircularFifoQueue;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class CircularFifoQueueTest {
+
+ private static final int DEFAULT_SIZE = 32;
+
+ private static final int FIXED_SIZE = 5;
+
+ private static final int COLLECTION_SIZE = 7;
+
+ private static final String TEST_COLOR = "Red";
+
+ private static final String TEST_COLOR_BY_INDEX = "Blue";
+
+ @Test
+ public void whenUsingDefualtConstructor_correctSizeQueue() {
+ CircularFifoQueue bits = new CircularFifoQueue<>();
+
+ Assert.assertEquals(DEFAULT_SIZE, bits.maxSize());
+ }
+
+ @Test
+ public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(FIXED_SIZE, colors.maxSize());
+ }
+
+ @Test
+ public void whenUsingCollectionConstructor_correctSizeQueue() {
+ List days = new ArrayList<>();
+ days.add("Monday");
+ days.add("Tuesday");
+ days.add("Wednesday");
+ days.add("Thursday");
+ days.add("Friday");
+ days.add("Saturday");
+ days.add("Sunday");
+
+ CircularFifoQueue daysOfWeek = new CircularFifoQueue<>(days);
+
+ Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize());
+ }
+
+ @Test
+ public void givenAddElements_whenGetElement_correctElement() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1));
+ }
+
+ @Test
+ public void givenAddElements_whenPollElement_correctElement() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(TEST_COLOR, colors.poll());
+ }
+
+ @Test
+ public void givenAddElements_whenPeekQueue_correctElement() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(TEST_COLOR, colors.peek());
+ }
+
+ @Test
+ public void givenAddElements_whenElementQueue_correctElement() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(TEST_COLOR, colors.element());
+ }
+
+ @Test
+ public void givenAddElements_whenRemoveElement_correctElement() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(TEST_COLOR, colors.remove());
+ }
+
+ @Test
+ public void givenFullQueue_whenClearQueue_getIsEmpty() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ colors.clear();
+
+ Assert.assertEquals(true, colors.isEmpty());
+ }
+
+ @Test
+ public void givenFullQueue_whenCheckFull_getIsFull() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ Assert.assertEquals(false, colors.isFull());
+ }
+
+ @Test
+ public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() {
+ CircularFifoQueue colors = new CircularFifoQueue<>(5);
+ colors.add("Red");
+ colors.add("Blue");
+ colors.add("Green");
+ colors.offer("White");
+ colors.offer("Black");
+
+ colors.add("Orange");
+ colors.add("Violet");
+ colors.add("Pink");
+
+ Assert.assertEquals(true, colors.isAtFullCapacity());
+ }
+
+}
diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
index 10d408b467d3..4685d84781a2 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
@@ -4,14 +4,19 @@
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.TransformerUtils;
+import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
+import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
@@ -85,19 +90,12 @@ public void whenGetOnNullMap_thenMustReturnDefaultValue() {
@Test
public void whenInvertMap_thenMustReturnInvertedMap() {
Map invColorMap = MapUtils.invertMap(this.colorMap);
- assertEquals(this.colorMap.size(), invColorMap.size());
- MapIterator itColorMap
- = MapUtils.iterableMap(this.colorMap).mapIterator();
-
- while (itColorMap.hasNext()) {
- String colorMapKey = itColorMap.next();
- String colorMapValue = itColorMap.getValue();
-
- String invColorMapValue = MapUtils.getString(invColorMap, colorMapValue);
-
- assertTrue(invColorMapValue.equals(colorMapKey));
- }
+ int size = invColorMap.size();
+ Assertions.assertThat(invColorMap)
+ .hasSameSizeAs(colorMap)
+ .containsKeys(this.colorMap.values().toArray(new String[size]))
+ .containsValues(this.colorMap.keySet().toArray(new String[size]));
}
@Test(expected = IllegalArgumentException.class)
diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java
new file mode 100644
index 000000000000..bdaf4d7bd999
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java
@@ -0,0 +1,140 @@
+package com.baeldung.hoverfly;
+
+import static io.specto.hoverfly.junit.core.SimulationSource.dsl;
+import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service;
+import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes;
+import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath;
+import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.lang3.time.StopWatch;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.RequestEntity;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.RestTemplate;
+
+import io.specto.hoverfly.junit.core.SimulationSource;
+import io.specto.hoverfly.junit.rule.HoverflyRule;
+
+public class HoverflyApiTest {
+
+ private static final SimulationSource source = dsl(
+ service("http://www.baeldung.com")
+ .get("/api/courses/1")
+ .willReturn(success().body(
+ jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
+
+ .post("/api/courses")
+ .willReturn(success())
+
+ .andDelay(3, TimeUnit.SECONDS)
+ .forMethod("POST"),
+
+ service(matches("www.*dung.com"))
+ .get(startsWith("/api/student"))
+ .queryParam("page", any())
+ .willReturn(success())
+
+ .post(equalsTo("/api/student"))
+ .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
+ .willReturn(success())
+
+ .put("/api/student/1")
+ .body(matchesJsonPath("$.name"))
+ .willReturn(success())
+
+ .post("/api/student")
+ .body(equalsToXml("2John"))
+ .willReturn(success())
+
+ .put("/api/student/2")
+ .body(matchesXPath("/student/name"))
+ .willReturn(success()));
+
+ @ClassRule
+ public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
+ private final RestTemplate restTemplate = new RestTemplate();
+
+ @Test
+ public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
+ final ResponseEntity courseResponse = restTemplate.getForEntity(
+ "http://www.baeldung.com/api/courses/1", String.class);
+
+ assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
+ assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
+ }
+
+ @Test
+ public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
+ StopWatch stopWatch = new StopWatch();
+ stopWatch.start();
+ final ResponseEntity postResponse = restTemplate.postForEntity(
+ "http://www.baeldung.com/api/courses", null, Void.class);
+ stopWatch.stop();
+ long postTime = stopWatch.getTime();
+
+ assertEquals(HttpStatus.OK, postResponse.getStatusCode());
+ assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime));
+ }
+
+ @Test
+ public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
+ final ResponseEntity courseResponse = restTemplate.getForEntity(
+ "http://www.baeldung.com/api/student?page=3", Void.class);
+
+ assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
+ }
+
+ @Test
+ public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
+ final ResponseEntity postResponse = restTemplate.postForEntity(
+ "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
+
+ assertEquals(HttpStatus.OK, postResponse.getStatusCode());
+ }
+
+ @Test
+ public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
+ RequestEntity putRequest = RequestEntity
+ .put(new URI("http://www.baeldung.com/api/student/1"))
+ .body("{\"id\":\"1\",\"name\":\"Trevor\"}");
+
+ ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class);
+ assertEquals(HttpStatus.OK, putResponse.getStatusCode());
+ }
+
+ @Test
+ public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
+ final ResponseEntity postResponse = restTemplate.postForEntity(
+ "http://www.baeldung.com/api/student", "2John", Void.class);
+
+ assertEquals(HttpStatus.OK, postResponse.getStatusCode());
+ }
+
+
+ @Test
+ public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
+ RequestEntity putRequest = RequestEntity
+ .put(new URI("http://www.baeldung.com/api/student/2"))
+ .body(""
+ + "2Monica");
+
+ ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class);
+ assertEquals(HttpStatus.OK, putResponse.getStatusCode());
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java
new file mode 100644
index 000000000000..4a6ecf8e4655
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.neuroph;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.neuroph.core.NeuralNetwork;
+
+import static org.junit.Assert.*;
+
+public class XORTest {
+ private NeuralNetwork ann = null;
+
+ private void print(String input, double output, double actual) {
+ System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
+ }
+
+ @Before
+ public void annInit() {
+ ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
+ }
+
+ @Test
+ public void leftDisjunctTest() {
+ ann.setInput(0, 1);
+ ann.calculate();
+ print("0, 1", ann.getOutput()[0], 1.0);
+ assertEquals(ann.getOutput()[0], 1.0, 0.0);
+ }
+
+ @Test
+ public void rightDisjunctTest() {
+ ann.setInput(1, 0);
+ ann.calculate();
+ print("1, 0", ann.getOutput()[0], 1.0);
+ assertEquals(ann.getOutput()[0], 1.0, 0.0);
+ }
+
+ @Test
+ public void bothFalseConjunctTest() {
+ ann.setInput(0, 0);
+ ann.calculate();
+ print("0, 0", ann.getOutput()[0], 0.0);
+ assertEquals(ann.getOutput()[0], 0.0, 0.0);
+ }
+
+ @Test
+ public void bothTrueConjunctTest() {
+ ann.setInput(1, 1);
+ ann.calculate();
+ print("1, 1", ann.getOutput()[0], 0.0);
+ assertEquals(ann.getOutput()[0], 0.0, 0.0);
+ }
+
+ @After
+ public void annClose() {
+ ann = null;
+ }
+}
\ No newline at end of file
diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java
new file mode 100644
index 000000000000..23f9abf2f31e
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java
@@ -0,0 +1,90 @@
+package com.baeldung.pcollections;
+
+import org.junit.Test;
+import org.pcollections.*;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class PCollectionsUnitTest {
+
+ @Test
+ public void whenEmpty_thenCreateEmptyHashPMap() {
+ HashPMap pmap = HashTreePMap.empty();
+ assertEquals(pmap.size(), 0);
+ }
+
+ @Test
+ public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() {
+ HashPMap pmap1 = HashTreePMap.singleton("key1", "value1");
+ assertEquals(pmap1.size(), 1);
+ }
+
+ @Test
+ public void givenExistingHashMap_whenFrom_thenCreateHashPMap() {
+ Map map = new HashMap();
+ map.put("mkey1", "mval1");
+ map.put("mkey2", "mval2");
+
+ HashPMap pmap2 = HashTreePMap.from(map);
+ assertEquals(pmap2.size(), 2);
+ }
+
+ @Test
+ public void whenHashPMapMethods_thenPerformOperations() {
+
+ HashPMap pmap = HashTreePMap.empty();
+ HashPMap pmap0 = pmap.plus("key1", "value1");
+
+ Map map = new HashMap();
+ map.put("key2", "val2");
+ map.put("key3", "val3");
+
+ HashPMap pmap1 = pmap0.plusAll(map);
+ HashPMap pmap2 = pmap1.minus("key1");
+ HashPMap pmap3 = pmap2.minusAll(map.keySet());
+
+ assertEquals(pmap0.size(), 1);
+ assertEquals(pmap1.size(), 3);
+ assertFalse(pmap2.containsKey("key1"));
+ assertEquals(pmap3.size(), 0);
+ }
+
+ @Test
+ public void whenTreePVectorMethods_thenPerformOperations() {
+ TreePVector pVector = TreePVector.empty();
+
+ TreePVector pV1 = pVector.plus("e1");
+ TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
+ assertEquals(1, pV1.size());
+ assertEquals(4, pV2.size());
+
+ TreePVector pV3 = pV2.minus("e1");
+ TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
+ assertEquals(pV3.size(), 3);
+ assertEquals(pV4.size(), 0);
+
+ TreePVector pSub = pV2.subList(0, 2);
+ assertTrue(pSub.contains("e1") && pSub.contains("e2"));
+
+ TreePVector pVW = (TreePVector) pV2.with(0, "e10");
+ assertEquals(pVW.get(0), "e10");
+ }
+
+ @Test
+ public void whenMapPSetMethods_thenPerformOperations() {
+
+ MapPSet pSet = HashTreePSet.empty()
+ .plusAll(Arrays.asList("e1","e2","e3","e4"));
+ assertEquals(pSet.size(), 4);
+
+ MapPSet pSet1 = pSet.minus("e4");
+ assertFalse(pSet1.contains("e4"));
+ }
+
+}
diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java
new file mode 100644
index 000000000000..9a65075e5b00
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java
@@ -0,0 +1,100 @@
+package com.baeldung.streamutils;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.springframework.util.StreamUtils;
+
+import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
+
+public class CopyStreamTest {
+
+ @Test
+ public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
+ String inputFileName = "src/test/resources/input.txt";
+ String outputFileName = "src/test/resources/output.txt";
+ File outputFile = new File(outputFileName);
+ InputStream in = new FileInputStream(inputFileName);
+ OutputStream out = new FileOutputStream(outputFileName);
+
+ StreamUtils.copy(in, out);
+
+ assertTrue(outputFile.exists());
+ String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
+ String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
+ Assert.assertEquals(inputFileContent, outputFileContent);
+ }
+
+ @Test
+ public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
+ String inputFileName = "src/test/resources/input.txt";
+ String outputFileName = "src/test/resources/output.txt";
+ File outputFile = new File(outputFileName);
+ InputStream in = new FileInputStream(inputFileName);
+ OutputStream out = new FileOutputStream(outputFileName);
+
+ StreamUtils.copyRange(in, out, 1, 10);
+
+ assertTrue(outputFile.exists());
+ String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
+ String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
+ Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent);
+ }
+
+ @Test
+ public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
+ String string = "Should be copied to OutputStream.";
+ String outputFileName = "src/test/resources/output.txt";
+ File outputFile = new File(outputFileName);
+ OutputStream out = new FileOutputStream("src/test/resources/output.txt");
+
+ StreamUtils.copy(string, StandardCharsets.UTF_8, out);
+
+ assertTrue(outputFile.exists());
+ String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
+ Assert.assertEquals(outputFileContent, string);
+ }
+
+ @Test
+ public void whenCopyInputStreamToString_thenCorrect() throws IOException {
+ String inputFileName = "src/test/resources/input.txt";
+ InputStream is = new FileInputStream(inputFileName);
+ String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
+
+ String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
+ Assert.assertEquals(inputFileContent, content);
+ }
+
+ @Test
+ public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
+ String outputFileName = "src/test/resources/output.txt";
+ String string = "Should be copied to OutputStream.";
+ byte[] byteArray = string.getBytes();
+ OutputStream out = new FileOutputStream("src/test/resources/output.txt");
+
+ StreamUtils.copy(byteArray, out);
+ String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
+ Assert.assertEquals(outputFileContent, string);
+ }
+
+ @Test
+ public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
+ String inputFileName = "src/test/resources/input.txt";
+ InputStream in = new FileInputStream(inputFileName);
+ byte[] out = StreamUtils.copyToByteArray(in);
+
+ String content = new String(out);
+ String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
+ Assert.assertEquals(inputFileContent, content);
+ }
+
+}
diff --git a/libraries/src/test/resources/input.txt b/libraries/src/test/resources/input.txt
new file mode 100644
index 000000000000..811232fa1f52
--- /dev/null
+++ b/libraries/src/test/resources/input.txt
@@ -0,0 +1 @@
+This file is merely for testing.
\ No newline at end of file
diff --git a/libraries/src/test/resources/output.txt b/libraries/src/test/resources/output.txt
new file mode 100644
index 000000000000..34e1e27d5aa7
--- /dev/null
+++ b/libraries/src/test/resources/output.txt
@@ -0,0 +1 @@
+Should be copied to OutputStream.
\ No newline at end of file
diff --git a/mockito/pom.xml b/mockito/pom.xml
index c77d42f97d4c..19dd2f6468c1 100644
--- a/mockito/pom.xml
+++ b/mockito/pom.xml
@@ -41,7 +41,7 @@
org.powermock
- powermock-api-mockito
+ powermock-api-mockito2
${powermock.version}
test
@@ -65,7 +65,7 @@
3.5
- 1.6.6
+ 1.7.0
diff --git a/mockito2/pom.xml b/mockito2/pom.xml
index 523cfa816d09..a7c4683c3066 100644
--- a/mockito2/pom.xml
+++ b/mockito2/pom.xml
@@ -53,6 +53,6 @@
UTF-8
- 2.7.5
+ 2.8.9
diff --git a/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml
index 2ab35651f1d8..e350457f5426 100644
--- a/mocks/mock-comparisons/pom.xml
+++ b/mocks/mock-comparisons/pom.xml
@@ -13,7 +13,7 @@
mock-comparisons
- 1.10.19
+ 2.8.9
3.4
1.29
diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java
index 18bc2ae189a8..9d47b2f5d4d7 100644
--- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java
+++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java
@@ -7,7 +7,13 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.*;
+import org.mockito.ArgumentMatcher;
+import org.mockito.ArgumentMatchers;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
public class LoginControllerIntegrationTest {
@@ -41,50 +47,63 @@ public void assertThatNoMethodHasBeenCalled() {
public void assertTwoMethodsHaveBeenCalled() {
UserForm userForm = new UserForm();
userForm.username = "foo";
- Mockito.when(loginService.login(userForm)).thenReturn(true);
+ Mockito.when(loginService.login(userForm))
+ .thenReturn(true);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
- Mockito.verify(loginService).login(userForm);
- Mockito.verify(loginService).setCurrentUser("foo");
+ Mockito.verify(loginService)
+ .login(userForm);
+ Mockito.verify(loginService)
+ .setCurrentUser("foo");
}
@Test
public void assertOnlyOneMethodHasBeenCalled() {
UserForm userForm = new UserForm();
userForm.username = "foo";
- Mockito.when(loginService.login(userForm)).thenReturn(false);
+ Mockito.when(loginService.login(userForm))
+ .thenReturn(false);
String login = loginController.login(userForm);
Assert.assertEquals("KO", login);
- Mockito.verify(loginService).login(userForm);
+ Mockito.verify(loginService)
+ .login(userForm);
Mockito.verifyNoMoreInteractions(loginService);
}
@Test
public void mockExceptionThrowing() {
UserForm userForm = new UserForm();
- Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class);
+ Mockito.when(loginService.login(userForm))
+ .thenThrow(IllegalArgumentException.class);
String login = loginController.login(userForm);
Assert.assertEquals("ERROR", login);
- Mockito.verify(loginService).login(userForm);
+ Mockito.verify(loginService)
+ .login(userForm);
Mockito.verifyZeroInteractions(loginService);
}
@Test
public void mockAnObjectToPassAround() {
- UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock();
- Mockito.when(loginService.login(userForm)).thenReturn(true);
+ UserForm userForm = Mockito.when(Mockito.mock(UserForm.class)
+ .getUsername())
+ .thenReturn("foo")
+ .getMock();
+ Mockito.when(loginService.login(userForm))
+ .thenReturn(true);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
- Mockito.verify(loginService).login(userForm);
- Mockito.verify(loginService).setCurrentUser("foo");
+ Mockito.verify(loginService)
+ .login(userForm);
+ Mockito.verify(loginService)
+ .setCurrentUser("foo");
}
@Test
@@ -92,19 +111,22 @@ public void argumentMatching() {
UserForm userForm = new UserForm();
userForm.username = "foo";
// default matcher
- Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true);
+ Mockito.when(loginService.login(Mockito.any(UserForm.class)))
+ .thenReturn(true);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
- Mockito.verify(loginService).login(userForm);
+ Mockito.verify(loginService)
+ .login(userForm);
// complex matcher
- Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher() {
- @Override
- public boolean matches(Object argument) {
- return argument instanceof String && ((String) argument).startsWith("foo");
- }
- }));
+ Mockito.verify(loginService)
+ .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher() {
+ @Override
+ public boolean matches(String argument) {
+ return argument.startsWith("foo");
+ }
+ }));
}
@Test
@@ -114,12 +136,14 @@ public void partialMocking() {
UserForm userForm = new UserForm();
userForm.username = "foo";
// let service's login use implementation so let's mock DAO call
- Mockito.when(loginDao.login(userForm)).thenReturn(1);
+ Mockito.when(loginDao.login(userForm))
+ .thenReturn(1);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
// verify mocked call
- Mockito.verify(spiedLoginService).setCurrentUser("foo");
+ Mockito.verify(spiedLoginService)
+ .setCurrentUser("foo");
}
}
diff --git a/mockserver/pom.xml b/mockserver/pom.xml
index a3ca5459c973..8d3e97f12982 100644
--- a/mockserver/pom.xml
+++ b/mockserver/pom.xml
@@ -37,5 +37,18 @@
+
+
+
+ maven-surefire-plugin
+ 2.20
+
+
+ **/**LiveTest.java
+
+
+
+
+
\ No newline at end of file
diff --git a/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java
similarity index 94%
rename from mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java
rename to mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java
index aea1b8b278bd..e7b972f6a4e5 100644
--- a/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java
+++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java
@@ -5,9 +5,7 @@
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.*;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.integration.ClientAndProxy;
import org.mockserver.integration.ClientAndServer;
@@ -28,15 +26,13 @@
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.model.StringBody.exact;
-public class TestMockServer {
+public class MockServerLiveTest {
- private ClientAndProxy proxy;
- private ClientAndServer mockServer;
+ private static ClientAndServer mockServer;
- @Before
- public void startProxy() {
+ @BeforeClass
+ public static void startServer() {
mockServer = startClientAndServer(1080);
- proxy = startClientAndProxy(1090);
}
@@ -170,9 +166,8 @@ private void createExpectationForCallBack(){
);
}
- @After
- public void stopProxy() {
- proxy.stop();
+ @AfterClass
+ public static void stopServer() {
mockServer.stop();
}
}
diff --git a/pom.xml b/pom.xml
index f0a331e3bde9..3feba96d5a0d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -12,10 +12,13 @@
UTF-8
refs/heads/master
+ true
+ false
+ false
4.12
1.3
- 1.10.19
+ 2.8.9
1.7.21
1.1.7
@@ -25,7 +28,6 @@
- spring-activiti
aws
akka-streams
algorithms
@@ -91,6 +93,7 @@
jws
libraries
+ libraries-data
log-mdc
log4j
log4j2
@@ -125,6 +128,7 @@
spark-java
spring-5-mvc
+ spring-activiti
spring-akka
spring-amqp
spring-all
@@ -210,6 +214,7 @@
spring-zuul
spring-reactor
spring-vertx
+
testing
testng
@@ -327,11 +332,11 @@
-
+ 3.4
+
diff --git a/ratpack/pom.xml b/ratpack/pom.xml
index 8681f5fc1065..7a75ec50b729 100644
--- a/ratpack/pom.xml
+++ b/ratpack/pom.xml
@@ -1,55 +1,64 @@
- 4.0.0
- com.baeldung
- ratpack
- jar
- 1.0-SNAPSHOT
- ratpack
- 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
+ ratpack
+ jar
+ 1.0-SNAPSHOT
+ ratpack
+ http://maven.apache.org
-
- UTF-8
- 1.8
- 1.8
-
+
+ UTF-8
+ 1.8
+ 1.8
+ 1.4.6
+
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
-
-
-
- io.ratpack
- ratpack-core
- 1.4.5
-
-
- io.ratpack
- ratpack-hikari
- 1.4.5
-
-
- io.ratpack
- ratpack-test
- 1.4.5
-
-
- com.h2database
- h2
- 1.4.193
-
-
+
-
- ${project.artifactId}
-
-
- src/main/resources
-
-
-
+
+
+
+ io.ratpack
+ ratpack-spring-boot-starter
+ ${ratpack.version}
+ pom
+
+
+
+ io.ratpack
+ ratpack-core
+ ${ratpack.version}
+
+
+ io.ratpack
+ ratpack-hikari
+ ${ratpack.version}
+
+
+ io.ratpack
+ ratpack-test
+ ${ratpack.version}
+
+
+ com.h2database
+ h2
+ 1.4.193
+
+
+
+
+ ${project.artifactId}
+
+
+ src/main/resources
+
+
+
diff --git a/ratpack/src/main/java/com/baeldung/spring/ArticleList.java b/ratpack/src/main/java/com/baeldung/spring/ArticleList.java
new file mode 100644
index 000000000000..b4d50bb3d359
--- /dev/null
+++ b/ratpack/src/main/java/com/baeldung/spring/ArticleList.java
@@ -0,0 +1,11 @@
+package com.baeldung.spring;
+
+import java.util.List;
+
+/**
+ * @author aiet
+ */
+public interface ArticleList {
+
+ List articles();
+}
diff --git a/ratpack/src/main/java/com/baeldung/spring/Config.java b/ratpack/src/main/java/com/baeldung/spring/Config.java
new file mode 100644
index 000000000000..ec0d1787e65a
--- /dev/null
+++ b/ratpack/src/main/java/com/baeldung/spring/Config.java
@@ -0,0 +1,24 @@
+package com.baeldung.spring;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.Arrays;
+
+/**
+ * @author aiet
+ */
+@Configuration
+public class Config {
+
+ @Bean
+ public Content content() {
+ return () -> "hello baeldung!";
+ }
+
+ @Bean
+ public ArticleList articles() {
+ return () -> Arrays.asList("Introduction to Ratpack", "Ratpack Google Guice Integration", "Ratpack Spring Boot Integration");
+ }
+
+}
diff --git a/ratpack/src/main/java/com/baeldung/spring/Content.java b/ratpack/src/main/java/com/baeldung/spring/Content.java
new file mode 100644
index 000000000000..4d01c70cb9dd
--- /dev/null
+++ b/ratpack/src/main/java/com/baeldung/spring/Content.java
@@ -0,0 +1,10 @@
+package com.baeldung.spring;
+
+/**
+ * @author aiet
+ */
+public interface Content {
+
+ String body();
+
+}
diff --git a/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java b/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java
new file mode 100644
index 000000000000..7f3483d676ec
--- /dev/null
+++ b/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java
@@ -0,0 +1,46 @@
+package com.baeldung.spring;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+import ratpack.func.Action;
+import ratpack.handling.Chain;
+import ratpack.server.ServerConfig;
+import ratpack.spring.config.EnableRatpack;
+
+/**
+ * @author aiet
+ */
+@SpringBootApplication
+@EnableRatpack
+public class EmbedRatpackApp {
+
+ @Autowired private Content content;
+ @Autowired private ArticleList list;
+
+ @Bean
+ public Action hello() {
+ return chain -> chain.get("hello", ctx -> ctx.render(content.body()));
+ }
+
+ @Bean
+ public Action list() {
+ return chain -> chain.get("list", ctx -> ctx.render(list
+ .articles()
+ .toString()));
+ }
+
+ @Bean
+ public ServerConfig ratpackServerConfig() {
+ return ServerConfig
+ .builder()
+ .findBaseDir("public")
+ .build();
+ }
+
+ public static void main(String[] args) {
+ SpringApplication.run(EmbedRatpackApp.class, args);
+ }
+
+}
diff --git a/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java b/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java
new file mode 100644
index 000000000000..05ff00cbbd0d
--- /dev/null
+++ b/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java
@@ -0,0 +1,19 @@
+package com.baeldung.spring;
+
+import ratpack.server.RatpackServer;
+
+import static ratpack.spring.Spring.spring;
+
+public class EmbedSpringBootApp {
+
+ public static void main(String[] args) throws Exception {
+ RatpackServer.start(server -> server
+ .registry(spring(Config.class))
+ .handlers(chain -> chain.get(ctx -> ctx.render(ctx
+ .get(Content.class)
+ .body()))));
+ }
+
+}
+
+
diff --git a/ratpack/src/main/resources/public/index.html b/ratpack/src/main/resources/public/index.html
new file mode 100644
index 000000000000..d6573bfb7fe5
--- /dev/null
+++ b/ratpack/src/main/resources/public/index.html
@@ -0,0 +1,10 @@
+
+
+
+
+ Special Static Resource
+
+
+This page is static.
+
+
\ No newline at end of file
diff --git a/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java b/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java
new file mode 100644
index 000000000000..802fe75d5c4b
--- /dev/null
+++ b/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.spring;
+
+import org.junit.Test;
+import ratpack.test.MainClassApplicationUnderTest;
+
+import java.io.IOException;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+/**
+ * @author aiet
+ */
+public class EmbedRatpackAppIntegrationTest {
+
+ MainClassApplicationUnderTest appUnderTest = new MainClassApplicationUnderTest(EmbedRatpackApp.class);
+
+ @Test
+ public void whenSayHello_thenGotWelcomeMessage() {
+ assertEquals("hello baeldung!", appUnderTest
+ .getHttpClient()
+ .getText("/hello"));
+ }
+
+ @Test
+ public void whenRequestList_thenGotArticles() throws IOException {
+ assertEquals(3, appUnderTest
+ .getHttpClient()
+ .getText("/list")
+ .split(",").length);
+ }
+
+ @Test
+ public void whenRequestStaticResource_thenGotStaticContent() {
+ assertThat(appUnderTest
+ .getHttpClient()
+ .getText("/"), containsString("page is static"));
+ }
+
+}
diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml
index 3d2f1386df18..c5289b20a6ed 100644
--- a/spring-activiti/pom.xml
+++ b/spring-activiti/pom.xml
@@ -53,6 +53,23 @@
org.springframework.boot
spring-boot-maven-plugin
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ 3
+ true
+
+ **/*IntegrationTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+ **/JdbcTest.java
+ **/*LiveTest.java
+
+ true
+
+
diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java
index 3924d31f681f..fd184556c479 100644
--- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java
+++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java
@@ -1,9 +1,5 @@
package com.example.activitiwithspring;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
@@ -12,12 +8,15 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import java.util.List;
+import java.util.stream.Collectors;
+
@RestController
public class ActivitiController {
private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class);
+
@Autowired
private RuntimeService runtimeService;
@@ -28,32 +27,30 @@ public class ActivitiController {
public String startProcess() {
runtimeService.startProcessInstanceByKey("my-process");
return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery()
- .count();
+ .count();
}
@GetMapping("/get-tasks/{processInstanceId}")
public List getTasks(@PathVariable String processInstanceId) {
List usertasks = taskService.createTaskQuery()
- .processInstanceId(processInstanceId)
- .list();
-
- List tasks = usertasks.stream().map(task -> {
- TaskRepresentation taskRepresentation = new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId());
- return taskRepresentation;
- }).collect(Collectors.toList());
- return tasks;
+ .processInstanceId(processInstanceId)
+ .list();
+
+ return usertasks.stream()
+ .map(task -> new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()))
+ .collect(Collectors.toList());
}
@GetMapping("/complete-task-A/{processInstanceId}")
public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) {
Task task = taskService.createTaskQuery()
- .processInstanceId(processInstanceId)
- .singleResult();
+ .processInstanceId(processInstanceId)
+ .singleResult();
taskService.complete(task.getId());
logger.info("Task completed");
task = taskService.createTaskQuery()
- .processInstanceId(processInstanceId)
- .singleResult();
+ .processInstanceId(processInstanceId)
+ .singleResult();
return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId());
}
diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java
index e98b8ad7cab3..2cfacdcf0d49 100644
--- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java
+++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java
@@ -5,7 +5,6 @@
@SpringBootApplication
public class ActivitiWithSpringApplication {
-
public static void main(String[] args) {
SpringApplication.run(ActivitiWithSpringApplication.class, args);
}
diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java
similarity index 78%
rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java
rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java
index 31762076643d..baca58f6ffad 100644
--- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java
+++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java
@@ -1,10 +1,6 @@
package com.example.activitiwithspring;
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.List;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.junit.Before;
@@ -21,13 +17,16 @@
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest
-public class ActivitiControllerTest {
- private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerTest.class);
+public class ActivitiControllerIntegrationTest {
+ private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerIntegrationTest.class);
private MockMvc mockMvc;
@Autowired
@@ -39,10 +38,10 @@ public class ActivitiControllerTest {
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
- .build();
+ .build();
for (ProcessInstance instance : runtimeService.createProcessInstanceQuery()
- .list()) {
+ .list()) {
runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes");
}
}
@@ -51,21 +50,21 @@ public void setUp() {
public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
- .andReturn()
- .getResponse()
- .getContentAsString();
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 1", responseBody);
responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
- .andReturn()
- .getResponse()
- .getContentAsString();
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 2", responseBody);
responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
- .andReturn()
- .getResponse()
- .getContentAsString();
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 3", responseBody);
}
@@ -73,19 +72,19 @@ public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() t
public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
- .andReturn()
- .getResponse();
+ .andReturn()
+ .getResponse();
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
- .orderByProcessInstanceId()
- .desc()
- .list()
- .get(0);
+ .orderByProcessInstanceId()
+ .desc()
+ .list()
+ .get(0);
logger.info("process instance = " + pi.getId());
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId()))
- .andReturn()
- .getResponse()
- .getContentAsString();
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
ObjectMapper mapper = new ObjectMapper();
List tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class));
@@ -98,19 +97,19 @@ public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Ex
public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
- .andReturn()
- .getResponse();
+ .andReturn()
+ .getResponse();
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
- .orderByProcessInstanceId()
- .desc()
- .list()
- .get(0);
+ .orderByProcessInstanceId()
+ .desc()
+ .list()
+ .get(0);
logger.info("process instance = " + pi.getId());
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId()))
- .andReturn()
- .getResponse()
- .getContentAsString();
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
ObjectMapper mapper = new ObjectMapper();
TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class);
diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java
similarity index 84%
rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java
rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java
index da22c6c7fa80..7460c302d83a 100644
--- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java
+++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java
@@ -7,7 +7,7 @@
@RunWith(SpringRunner.class)
@SpringBootTest
-public class ActivitiWithSpringApplicationTests {
+public class ActivitiWithSpringApplicationIntegrationTest {
@Test
public void contextLoads() {
diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom/pom.xml
index 234404a6c042..cfce323eabb4 100644
--- a/spring-boot-property-exp/property-exp-custom/pom.xml
+++ b/spring-boot-property-exp/property-exp-custom/pom.xml
@@ -40,6 +40,15 @@
**/application*.properties
+
+ ${basedir}/src/main/resources
+ true
+
+ **/application*.yml
+ **/application*.yaml
+ **/application*.properties
+
+
@@ -53,6 +62,14 @@
true
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+ com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp
+
+
diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default/build.gradle
index f3c5f4a3780d..ec27de7c41f3 100644
--- a/spring-boot-property-exp/property-exp-default/build.gradle
+++ b/spring-boot-property-exp/property-exp-default/build.gradle
@@ -27,6 +27,10 @@ repositories {
mavenCentral()
}
+springBoot {
+ executable = true
+}
+
import org.apache.tools.ant.filters.ReplaceTokens
processResources {
with copySpec {
diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default/pom.xml
index 3629e56111a5..2544800e6a1e 100644
--- a/spring-boot-property-exp/property-exp-default/pom.xml
+++ b/spring-boot-property-exp/property-exp-default/pom.xml
@@ -30,4 +30,16 @@
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ true
+
+
+
+
+
diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java
index 8d5eb56bf430..660b461ab6b8 100644
--- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java
+++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java
@@ -14,15 +14,18 @@
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
@AutoConfigureMockMvc
-@TestPropertySource(properties = { "security.basic.enabled=false" })
+@TestPropertySource(properties = {"security.basic.enabled=false"})
public class SpringBootWithServletComponentIntegrationTest {
- @Autowired private ServletContext servletContext;
+ @Autowired
+ private ServletContext servletContext;
@Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
@@ -42,7 +45,8 @@ public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() {
.contains("echo servlet"));
}
- @Autowired private TestRestTemplate restTemplate;
+ @Autowired
+ private TestRestTemplate restTemplate;
@Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
@@ -59,7 +63,6 @@ public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() {
}
-
}
diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java
index 64507ad02c7d..31bb2ab195db 100644
--- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java
+++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java
@@ -14,17 +14,21 @@
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
@AutoConfigureMockMvc
-@TestPropertySource(properties = { "security.basic.enabled=false" })
+@TestPropertySource(properties = {"security.basic.enabled=false"})
public class SpringBootWithoutServletComponentIntegrationTest {
- @Autowired private ServletContext servletContext;
+ @Autowired
+ private ServletContext servletContext;
- @Autowired private TestRestTemplate restTemplate;
+ @Autowired
+ private TestRestTemplate restTemplate;
@Test
public void givenServletContext_whenAccessAttrs_thenNotFound() {
diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java
index dda9d69edd2b..e886042c8d65 100644
--- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java
+++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java
@@ -1,5 +1,8 @@
package com.baeldung.autoconfiguration;
+import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
+import com.baeldung.autoconfiguration.example.MyUser;
+import com.baeldung.autoconfiguration.example.MyUserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -7,13 +10,9 @@
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
-import com.baeldung.autoconfiguration.example.MyUser;
-import com.baeldung.autoconfiguration.example.MyUserRepository;
-
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AutoconfigurationApplication.class)
-@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" })
+@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"})
public class AutoconfigurationIntegrationTest {
@Autowired
diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java
index 530b8e9cb399..413f6980ce2c 100644
--- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java
+++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java
@@ -1,15 +1,5 @@
package com.baeldung.displayallbeans;
-import static org.assertj.core.api.BDDAssertions.then;
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -23,7 +13,15 @@
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
-import com.baeldung.displayallbeans.Application;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.BDDAssertions.then;
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@@ -46,10 +44,10 @@ public class DisplayBeanIntegrationTest {
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
ResponseEntity entity = this.testRestTemplate.getForEntity(
"http://localhost:" + this.port + "/displayallbeans", String.class);
-
+
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
-
+
@Test
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
@SuppressWarnings("rawtypes")
@@ -68,14 +66,14 @@ public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throw
List